title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
'qgis1.1', 'php_mapscript']
evenNicerPrint(foolist)
</code></pre>
<p>Desired result:</p>
<pre><code>exiv2-devel msvcrt
mingw-libs gdal-grass
tcltk-demos iconv
fcgi qgis-devel
netcdf qgis1.1
pdcurses-devel php_mapscript
</code></pre>
<p>thanks!</p>
| 6 | 2009-10-06T07:43:58Z | 1,525,926 | <pre><code>from itertools import izip_longest, islice
L = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
'qgis1.1', 'php_mapscript']
def columnize(sequence, columns=2):
size, remainder = divmod(len(sequence), columns)
if remainder:
size += 1
slices = [islice(sequence, pos, pos + size)
for pos in xrange(0, len(sequence), size)]
return izip_longest(fillvalue='', *slices)
for values in columnize(L):
print ' '.join(value.ljust(20) for value in values)
</code></pre>
| -1 | 2009-10-06T14:26:39Z | [
"python",
"printing"
] |
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
'qgis1.1', 'php_mapscript']
evenNicerPrint(foolist)
</code></pre>
<p>Desired result:</p>
<pre><code>exiv2-devel msvcrt
mingw-libs gdal-grass
tcltk-demos iconv
fcgi qgis-devel
netcdf qgis1.1
pdcurses-devel php_mapscript
</code></pre>
<p>thanks!</p>
| 6 | 2009-10-06T07:43:58Z | 25,048,690 | <p>This answer uses the same method in the answer by @Aaron Digulla, with slightly more pythonic syntax. It might make some of the above answers easier to understand.</p>
<pre><code>>>> for a,b,c in zip(foolist[::3],foolist[1::3],foolist[2::3]):
>>> print '{:<30}{:<30}{:<}'.format(a,b,c)
exiv2-devel mingw-libs tcltk-demos
fcgi netcdf pdcurses-devel
msvcrt gdal-grass iconv
qgis-devel qgis1.1 php_mapscript
</code></pre>
<p>This can be easily adapt to any number of columns or variable columns, which would lead to something like the answer by @gnibbler. The spacing can be adjusted for screen width. </p>
<hr>
<p>Update: Explanation as requested. </p>
<p><strong>Indexing</strong></p>
<p><code>foolist[::3]</code> selects every third element of <code>foolist</code>. <code>foolist[1::3]</code> selects every third element, starting at the second element ('1' because python uses zero-indexing). </p>
<pre><code>In [2]: bar = [1,2,3,4,5,6,7,8,9]
In [3]: bar[::3]
Out[3]: [1, 4, 7]
</code></pre>
<p><strong>zip</strong></p>
<p>Zipping lists (or other iterables) generates tuples of the elements of the the lists. For example: </p>
<pre><code>In [5]: zip([1,2,3],['a','b','c'],['x','y','z'])
Out[5]: [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z')]
</code></pre>
<p><strong>together</strong></p>
<p>Putting these ideas together we get our solution: </p>
<pre><code>for a,b,c in zip(foolist[::3],foolist[1::3],foolist[2::3]):
</code></pre>
<p>Here we first generate three "slices" of <code>foolist</code>, each indexed by every-third-element and offset by one. Individually they each contain only a third of the list. Now when we zip these slices and iterate, each iteration gives us three elements of <code>foolist</code>. </p>
<p>Which is what we wanted:</p>
<pre><code>In [11]: for a,b,c in zip(foolist[::3],foolist[1::3],foolist[2::3]):
....: print a,b,c
Out[11]: exiv2-devel mingw-libs tcltk-demos
fcgi netcdf pdcurses-devel
[etc]
</code></pre>
<p>Instead of: </p>
<pre><code>In [12]: for a in foolist:
....: print a
Out[12]: exiv2-devel
mingw-libs
[etc]
</code></pre>
| 7 | 2014-07-30T23:35:50Z | [
"python",
"printing"
] |
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
'qgis1.1', 'php_mapscript']
evenNicerPrint(foolist)
</code></pre>
<p>Desired result:</p>
<pre><code>exiv2-devel msvcrt
mingw-libs gdal-grass
tcltk-demos iconv
fcgi qgis-devel
netcdf qgis1.1
pdcurses-devel php_mapscript
</code></pre>
<p>thanks!</p>
| 6 | 2009-10-06T07:43:58Z | 27,299,462 | <p>Found this question as a met almost the same task. And I've created function to print list in multi columns with the number of columns as parameter. Maybe not so elegant as one-liner solutions, but it could be useful for someone.</p>
<p>However, it handles incomplete lists, ex.: it can print list of 11 in 3 rows.</p>
<p>Function splitted for better readability:</p>
<pre><code>def is_printable(my_list):
return len(my_list) > 0
def create_empty_list(columns):
result = []
for num in range(0, columns):
result.append([])
return result
def fill_empty_list(empty_list, my_list, columns):
column_depth = len(my_list) / columns if len(my_list) % columns == 0 else len(my_list) / columns + 1
item_index = 0
for column in range(0, columns):
while len(empty_list[column]) < column_depth:
if item_index < len(my_list):
empty_list[column].append(my_list[item_index])
else:
empty_list[column].append(" ") # last column could be incomplete, fill it with space
item_index += 1
def print_list_in_columns(my_list, columns=1):
if not is_printable(my_list):
print 'Nothing to print, sorry...'
return
column_width = 25 #(in symbols) Also can be calculated automatically
list_to_print = create_empty_list(columns)
fill_empty_list(list_to_print, my_list, columns)
iterators = ["it" + str(i) for i in range(0, columns)]
for iterators in zip(*list_to_print):
print ("".join(str.ljust(i, column_width) for i in iterators))
</code></pre>
<p>and the call part:</p>
<pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
'qgis1.1', 'php_mapscript']
print_list_in_columns(foolist, 2)
</code></pre>
| 0 | 2014-12-04T16:49:18Z | [
"python",
"printing"
] |
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
'qgis1.1', 'php_mapscript']
evenNicerPrint(foolist)
</code></pre>
<p>Desired result:</p>
<pre><code>exiv2-devel msvcrt
mingw-libs gdal-grass
tcltk-demos iconv
fcgi qgis-devel
netcdf qgis1.1
pdcurses-devel php_mapscript
</code></pre>
<p>thanks!</p>
| 6 | 2009-10-06T07:43:58Z | 30,861,871 | <p>Here's my solution. (<a href="https://gist.github.com/critiqjo/2ca84db26daaeb1715e1" rel="nofollow">Copy in GitHub gist</a>)</p>
<p>It takes terminal width as input and displays only as many columns that can be fit in it.</p>
<pre><code>def col_print(lines, term_width=80, indent=0, pad=2):
n_lines = len(lines)
if n_lines == 0:
return
col_width = max(len(line) for line in lines)
n_cols = int((term_width + pad - indent)/(col_width + pad))
n_cols = min(n_lines, max(1, n_cols))
col_len = int(n_lines/n_cols) + (0 if n_lines % n_cols == 0 else 1)
if (n_cols - 1) * col_len >= n_lines:
n_cols -= 1
cols = [lines[i*col_len : i*col_len + col_len] for i in range(n_cols)]
rows = list(zip(*cols))
rows_missed = zip(*[col[len(rows):] for col in cols[:-1]])
rows.extend(rows_missed)
for row in rows:
print(" "*indent + (" "*pad).join(line.ljust(col_width) for line in row))
</code></pre>
| 1 | 2015-06-16T07:57:54Z | [
"python",
"printing"
] |
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
'qgis1.1', 'php_mapscript']
evenNicerPrint(foolist)
</code></pre>
<p>Desired result:</p>
<pre><code>exiv2-devel msvcrt
mingw-libs gdal-grass
tcltk-demos iconv
fcgi qgis-devel
netcdf qgis1.1
pdcurses-devel php_mapscript
</code></pre>
<p>thanks!</p>
| 6 | 2009-10-06T07:43:58Z | 34,551,419 | <p>Here's a solution in python 3.4 that automatically detects terminal width and takes it into account. Tested on Linux and Mac.</p>
<pre><code>def column_print(list_to_print, column_width=40):
import os
term_height, term_width = os.popen('stty size', 'r').read().split()
total_columns = int(term_width) // column_width
total_rows = len(list_to_print) // total_columns
# ceil
total_rows = total_rows + 1 if len(list_to_print) % total_columns != 0 else total_rows
format_string = "".join(["{%d:<%ds}" % (c, column_width) \
for c in range(total_columns)])
for row in range(total_rows):
column_items = []
for column in range(total_columns):
# top-down order
list_index = row + column*total_rows
# left-right order
#list_index = row*total_columns + column
if list_index < len(list_to_print):
column_items.append(list_to_print[list_index])
else:
column_items.append("")
print(format_string.format(*column_items))
</code></pre>
| 0 | 2015-12-31T20:37:17Z | [
"python",
"printing"
] |
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
'qgis1.1', 'php_mapscript']
evenNicerPrint(foolist)
</code></pre>
<p>Desired result:</p>
<pre><code>exiv2-devel msvcrt
mingw-libs gdal-grass
tcltk-demos iconv
fcgi qgis-devel
netcdf qgis1.1
pdcurses-devel php_mapscript
</code></pre>
<p>thanks!</p>
| 6 | 2009-10-06T07:43:58Z | 36,085,705 | <p>Inspired by gimel's answer, <a href="http://stackoverflow.com/a/1524333/2352216">above</a>.</p>
<pre><code>import math
def list_columns(obj, cols=4, columnwise=True, gap=4):
"""
Print the given list in evenly-spaced columns.
Parameters
----------
obj : list
The list to be printed.
cols : int
The number of columns in which the list should be printed.
columnwise : bool, default=True
If True, the items in the list will be printed column-wise.
If False the items in the list will be printed row-wise.
gap : int
The number of spaces that should separate the longest column
item/s from the next column. This is the effective spacing
between columns based on the maximum len() of the list items.
"""
sobj = [str(item) for item in obj]
if cols > len(sobj): cols = len(sobj)
max_len = max([len(item) for item in sobj])
if columnwise: cols = int(math.ceil(float(len(sobj)) / float(cols)))
plist = [sobj[i: i+cols] for i in range(0, len(sobj), cols)]
if columnwise:
if not len(plist[-1]) == cols:
plist[-1].extend(['']*(len(sobj) - len(plist[-1])))
plist = zip(*plist)
printer = '\n'.join([
''.join([c.ljust(max_len + gap) for c in p])
for p in plist])
print printer
</code></pre>
<p>Results (the second one satisfies your request):</p>
<pre><code>>>> list_columns(foolist)
exiv2-devel fcgi msvcrt qgis-devel
mingw-libs netcdf gdal-grass qgis1.1
tcltk-demos pdcurses-devel iconv php_mapscript
>>> list_columns(foolist, cols=2)
exiv2-devel msvcrt
mingw-libs gdal-grass
tcltk-demos iconv
fcgi qgis-devel
netcdf qgis1.1
pdcurses-devel php_mapscript
>>> list_columns(foolist, columnwise=False)
exiv2-devel mingw-libs tcltk-demos fcgi
netcdf pdcurses-devel msvcrt gdal-grass
iconv qgis-devel qgis1.1 php_mapscript
>>> list_columns(foolist, gap=1)
exiv2-devel fcgi msvcrt qgis-devel
mingw-libs netcdf gdal-grass qgis1.1
tcltk-demos pdcurses-devel iconv php_mapscript
</code></pre>
| 3 | 2016-03-18T13:29:42Z | [
"python",
"printing"
] |
Does anyone know a way to scramble the elements in a list? | 1,524,160 | <pre><code>thelist = ['a','b','c','d']
</code></pre>
<p>How I can to scramble them in Python?</p>
| 5 | 2009-10-06T07:55:21Z | 1,524,176 | <p>Use the <a href="http://docs.python.org/library/random.html#random.shuffle"><code>random.shuffle()</code></a> function:</p>
<pre><code>random.shuffle(thelist)
</code></pre>
| 6 | 2009-10-06T07:59:16Z | [
"python",
"random"
] |
Does anyone know a way to scramble the elements in a list? | 1,524,160 | <pre><code>thelist = ['a','b','c','d']
</code></pre>
<p>How I can to scramble them in Python?</p>
| 5 | 2009-10-06T07:55:21Z | 1,524,180 | <p>Use the <code>shuffle</code> function from the <code>random</code> module:</p>
<pre><code>>>> from random import shuffle
>>> thelist = ['a','b','c','d']
>>> shuffle(thelist)
>>> thelist
['c', 'a', 'b', 'd']
</code></pre>
| 5 | 2009-10-06T07:59:44Z | [
"python",
"random"
] |
Does anyone know a way to scramble the elements in a list? | 1,524,160 | <pre><code>thelist = ['a','b','c','d']
</code></pre>
<p>How I can to scramble them in Python?</p>
| 5 | 2009-10-06T07:55:21Z | 1,524,181 | <pre><code>import random
random.shuffle(thelist)
</code></pre>
<p>Note, this shuffles the list in-place.</p>
| 9 | 2009-10-06T08:00:04Z | [
"python",
"random"
] |
Does anyone know a way to scramble the elements in a list? | 1,524,160 | <pre><code>thelist = ['a','b','c','d']
</code></pre>
<p>How I can to scramble them in Python?</p>
| 5 | 2009-10-06T07:55:21Z | 1,524,182 | <pre><code>>>> import random
>>> thelist = ['a', 'b', 'c', 'd']
>>> random.shuffle(thelist)
>>> thelist
['d', 'a', 'c', 'b']
</code></pre>
<p>Your result will (hopefully!) vary.</p>
| 12 | 2009-10-06T08:00:06Z | [
"python",
"random"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the other values? Can I just "ignore" the errors?</p>
<p>EDIT: I know how to do a simple try, except. However, Oftentimes when there is an error on #2, it will shoot to the except, and then NOT continue the rest of the code.'</p>
<p>EDIT: I understand that there is a "get" method. However, I'd like a GENERAL way of doing it...I won't always be using dictionaries.</p>
| 2 | 2009-10-06T08:07:41Z | 1,524,229 | <p>Ever heard of Try Catch and exception handling? You can readup on them <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">here</a></p>
<p>However, you should shy away from causing errors on purpose, why do you have code that you know will fail? </p>
| 0 | 2009-10-06T08:10:43Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the other values? Can I just "ignore" the errors?</p>
<p>EDIT: I know how to do a simple try, except. However, Oftentimes when there is an error on #2, it will shoot to the except, and then NOT continue the rest of the code.'</p>
<p>EDIT: I understand that there is a "get" method. However, I'd like a GENERAL way of doing it...I won't always be using dictionaries.</p>
| 2 | 2009-10-06T08:07:41Z | 1,524,232 | <p>The easiest option is to use <a href="http://docs.python.org/library/stdtypes.html#dict.get"><code>.get()</code></a>:</p>
<pre><code>l = dict.get('link')
t = dict.get('title')
d = dict.get('description')
k = dict.get('keyword')
</code></pre>
<p>The <code>t</code> variable will then contain <code>None</code> (you can use <code>dict.get('title', '')</code> if you want an empty string, for example). Another option would be to catch the <code>KeyError</code> exception.</p>
| 12 | 2009-10-06T08:11:19Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the other values? Can I just "ignore" the errors?</p>
<p>EDIT: I know how to do a simple try, except. However, Oftentimes when there is an error on #2, it will shoot to the except, and then NOT continue the rest of the code.'</p>
<p>EDIT: I understand that there is a "get" method. However, I'd like a GENERAL way of doing it...I won't always be using dictionaries.</p>
| 2 | 2009-10-06T08:07:41Z | 1,524,233 | <pre><code>t = dic.get('title')
</code></pre>
<p>won't produce the error. it's equivalent to:</p>
<pre><code>try:
t = dic['title']
except KeyError:
t = None
</code></pre>
<p>and please don't shadow built-in, don't use <code>dict</code> for a variable name. use something else.</p>
| 8 | 2009-10-06T08:11:26Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the other values? Can I just "ignore" the errors?</p>
<p>EDIT: I know how to do a simple try, except. However, Oftentimes when there is an error on #2, it will shoot to the except, and then NOT continue the rest of the code.'</p>
<p>EDIT: I understand that there is a "get" method. However, I'd like a GENERAL way of doing it...I won't always be using dictionaries.</p>
| 2 | 2009-10-06T08:07:41Z | 1,524,237 | <p>In this case, your best bet is to use</p>
<pre><code>l = dict.get('link', 'default')
t = dict.get('title', 'default')
</code></pre>
<p>etc.</p>
<p>Any values that weren't in the dictionary will be set to <code>'default'</code> (or whatever you choose). Of course, you'll have to deal with this later...</p>
| 1 | 2009-10-06T08:12:16Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the other values? Can I just "ignore" the errors?</p>
<p>EDIT: I know how to do a simple try, except. However, Oftentimes when there is an error on #2, it will shoot to the except, and then NOT continue the rest of the code.'</p>
<p>EDIT: I understand that there is a "get" method. However, I'd like a GENERAL way of doing it...I won't always be using dictionaries.</p>
| 2 | 2009-10-06T08:07:41Z | 1,524,240 | <p>Try/except/finally; see the <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">tutorial</a></p>
<p>However, the main question is; why are you assigning these to variables in the first place instead of accessing the dictionary?</p>
| 0 | 2009-10-06T08:13:13Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the other values? Can I just "ignore" the errors?</p>
<p>EDIT: I know how to do a simple try, except. However, Oftentimes when there is an error on #2, it will shoot to the except, and then NOT continue the rest of the code.'</p>
<p>EDIT: I understand that there is a "get" method. However, I'd like a GENERAL way of doing it...I won't always be using dictionaries.</p>
| 2 | 2009-10-06T08:07:41Z | 1,524,241 | <p>Use exceptions</p>
<pre><code>try:
l = dict['link']
t = dict['title']
d = dict['description']
k = dict['keyword']
except (RuntimeError, TypeError, NameError):
print ('something')
</code></pre>
| 0 | 2009-10-06T08:13:18Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the other values? Can I just "ignore" the errors?</p>
<p>EDIT: I know how to do a simple try, except. However, Oftentimes when there is an error on #2, it will shoot to the except, and then NOT continue the rest of the code.'</p>
<p>EDIT: I understand that there is a "get" method. However, I'd like a GENERAL way of doing it...I won't always be using dictionaries.</p>
| 2 | 2009-10-06T08:07:41Z | 1,524,770 | <p>If you want a way to consume exceptions and continue (though this is probably not a good idea) you could use a wrapper function such as:</p>
<pre><code>def consume_exception(func, args, exception):
try:
return func(*args)
except exception:
return None
</code></pre>
<p>Or something like that.</p>
<p>Then call</p>
<pre><code>l = consume_exception(dict.__getitem__, ['link'], KeyError)
t = consume_exception(dict.__getitem__, ['title'], KeyError)
...
</code></pre>
| 3 | 2009-10-06T10:26:45Z | [
"python"
] |
Why do I get encoding error in python warnings.formatwarning on format string? | 1,524,262 | <p>I get encoding error on this line:</p>
<pre><code>s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
</code></pre>
<p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128)</p>
<p>I tried to reproduce this error by passing all combinations of parameters to string format, but closest I got was "ascii decode" error (by passing unicode and high ascii string simultaneously, which forced conversion of string to unicode, using ascii decoder.</p>
<p>However, I did not manage to get "ascii encode" error. Anybody has an idea?</p>
| 5 | 2009-10-06T08:21:07Z | 1,524,278 | <p>One of the operands you are passing is not suitable for ASCII encoding - perhaps it contains either Unicode or Latin-1 characters. Change the format string to Unicode and see what happens.</p>
| 1 | 2009-10-06T08:25:26Z | [
"python",
"encoding",
"warnings"
] |
Why do I get encoding error in python warnings.formatwarning on format string? | 1,524,262 | <p>I get encoding error on this line:</p>
<pre><code>s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
</code></pre>
<p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128)</p>
<p>I tried to reproduce this error by passing all combinations of parameters to string format, but closest I got was "ascii decode" error (by passing unicode and high ascii string simultaneously, which forced conversion of string to unicode, using ascii decoder.</p>
<p>However, I did not manage to get "ascii encode" error. Anybody has an idea?</p>
| 5 | 2009-10-06T08:21:07Z | 1,524,374 | <p>This happens when Python tries to coerce an argument:</p>
<pre><code>s = u"\u00fc"
print str(s)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 0: ordinal not in range(128)
</code></pre>
<p>This happens because one of your arguments is an object (not a string of any kind) and Python calls <code>str()</code> on it. There are two solutions: Use a unicode string for the format (<code>s = u"%s..."</code>) or wrap each argument with <code>repr()</code>.</p>
| 8 | 2009-10-06T08:49:54Z | [
"python",
"encoding",
"warnings"
] |
Why do I get encoding error in python warnings.formatwarning on format string? | 1,524,262 | <p>I get encoding error on this line:</p>
<pre><code>s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
</code></pre>
<p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128)</p>
<p>I tried to reproduce this error by passing all combinations of parameters to string format, but closest I got was "ascii decode" error (by passing unicode and high ascii string simultaneously, which forced conversion of string to unicode, using ascii decoder.</p>
<p>However, I did not manage to get "ascii encode" error. Anybody has an idea?</p>
| 5 | 2009-10-06T08:21:07Z | 1,524,465 | <p>You are mixing unicode and str objects. </p>
<p>Explanation:
In Python 2.x, there are two kinds of objects that can contain text strings. str, and unicode. str is a string of bytes, so it can only contain characters between 0 and 255.
Unicode is a string of unicode characters.</p>
<p>You can convert between str and unicode with the "encode" and "decode" methods:</p>
<pre><code>>>> "thisisastring".decode('ascii')
u'thisisastring'
>>> u"This is ä string".encode('utf8')
'This is \xc3\xa4 string'
</code></pre>
<p>Note the encodings. Encodings are ways of representing unicode text as only strings of bytes. </p>
<p>If you try to add str and unicode together, Python will try to convert one to the other. But by default it will use ASCII as a encoding, which means a-z, A-Z, and some extra characters like <code>!"#$%&/()=?'{[]]}</code> etc. Anything else will fail.</p>
<p>You will at that point either get a encoding error or a decoding error, depending on if Python tries to convert the unicode to str or str to unicode. Usually it tries to decode, that is convert to unicode. But sometimes it decides not to but to coerce to string. I'm not entirely sure why.</p>
<p>Update:
The reason you get an encode error and not a decode error above is that <code>message</code> in the above code is neither str nor unicode. It's another object, that has a <strong>str</strong> method. Python therefore does str(message) before passing it in, and that fails, since the internally stores message is a unicode object that can't be coerced to ascii.</p>
<p><em>Or, more simply answered: It fails because warnings.warn() doesn't accept unicode messages.</em></p>
<p><strong>Now, the solution:</strong></p>
<p>Don't mix str and unicode. If you need to use unicode, and you apparently do, try to make sure all strings are unicode all the time. That's the only way to be sure you avoid this. This means that whenever you read in a string from disk, or a call to a function that may return anything else than pure ascii str, decode it to unicode as soon as possible.
And when you need to save it to disk or send it over a network or pass it in to a method that do not understand unicode, encode it to str as late as possible.</p>
<p>In this specific case, the problem is that you pass unicode to warnings.warn() and you can't do that. Pass a string. If you don't know what it is (as seems to be the case here) because it comes from somewhere else, your try/except solutions with a repr works fine, although doing a encode would be a possibility to.</p>
| 8 | 2009-10-06T09:12:28Z | [
"python",
"encoding",
"warnings"
] |
PyQt context menu | 1,524,349 | <p>I'm adding a contextmenu to a QTableWidget dynamically:</p>
<pre><code>playlistContenxt = QAction("Add to %s" % (currentItem.text()), self.musicTable)
playlistContenxt.setData(currentData)
self.connect(playlistContenxt, SIGNAL("triggered()"), self.addToPlaylistAction)
self.musicTable.addAction(playlistContenxt)
</code></pre>
<p>currentItem.text() is a playlist name thats being fetched from db, as you can see only one function (addToPlaylistAction) receives all triggers from different actions. On my addToPlaylistAction function, how do I determine which menu has been clicked?</p>
| 2 | 2009-10-06T08:44:15Z | 1,524,385 | <p>You can use <code>QAction.setData</code> to set some data, so that the slot knows which playlist to add to. Then from the slot you can call <code>self.sender()</code> to get the action that triggered the signal, and use <code>action.data()</code> to get the data back.</p>
| 2 | 2009-10-06T08:52:15Z | [
"python",
"qt",
"pyqt4"
] |
PyQt context menu | 1,524,349 | <p>I'm adding a contextmenu to a QTableWidget dynamically:</p>
<pre><code>playlistContenxt = QAction("Add to %s" % (currentItem.text()), self.musicTable)
playlistContenxt.setData(currentData)
self.connect(playlistContenxt, SIGNAL("triggered()"), self.addToPlaylistAction)
self.musicTable.addAction(playlistContenxt)
</code></pre>
<p>currentItem.text() is a playlist name thats being fetched from db, as you can see only one function (addToPlaylistAction) receives all triggers from different actions. On my addToPlaylistAction function, how do I determine which menu has been clicked?</p>
| 2 | 2009-10-06T08:44:15Z | 1,525,572 | <p>The correct way is to use <a href="http://doc.trolltech.com/4.5/qsignalmapper.html#details" rel="nofollow">signal mapper</a>: You can assign data to each of the senders and get a signal with that data.</p>
| 4 | 2009-10-06T13:24:40Z | [
"python",
"qt",
"pyqt4"
] |
Is an applet a proper solution for hardware detection and driver install? | 1,524,606 | <p>Can I use applets to inform me which hardware is installed on client system (fingerprint reader)? And if it is installed, can it tell me its version, so that it can download the proper plugin from a site? So that after everything is OK, the user can use his fingerprint reader to authenticate himself?</p>
| 0 | 2009-10-06T09:45:53Z | 1,524,622 | <p>Applet should be better if your application is not depended on IE.
If for IE only then use COM/ActiveX</p>
| 0 | 2009-10-06T09:50:28Z | [
"c#",
"python",
"ruby"
] |
How do I display images at different times on webpage | 1,524,713 | <p>I'm supposed to display images at certain times of the day on the webpage, Please can anyone tell me how to go about it</p>
| 1 | 2009-10-06T10:15:14Z | 1,524,724 | <p>You could make a Date object in javascript. Check the current time and depending on the time, you set the img src to whatever image you want for that time of day :) or hide the image through myimg.style.visibility = "hidden" if you dont want to display an image at that moment.</p>
| 0 | 2009-10-06T10:17:55Z | [
"python",
"django"
] |
How do I display images at different times on webpage | 1,524,713 | <p>I'm supposed to display images at certain times of the day on the webpage, Please can anyone tell me how to go about it</p>
| 1 | 2009-10-06T10:15:14Z | 1,524,740 | <p>The safest way is to do this on the server side, do not do this on the client side using javascript because clients may have different timezones.</p>
<p>for instance in PHP:</p>
<pre><code><style type="text/css"> #someimage{ position:absolute;left:200px;top:100px; }</style>
<?php
$h = intval(date('h'));
$m = intval(date('m'));
if($h==12 && $m==00){
echo '<img src="someimage.gif" id="someimg"/>';
}
?>
</code></pre>
<p>in python:</p>
<pre><code>#!/usr/bin/python
import time
localtime = time.localtime(time.time())
h = localtime[3]
m = localtime[4]
if h==12 and m==0: print "<img src='some.gif' id='someimg'/>"
</code></pre>
| 1 | 2009-10-06T10:21:02Z | [
"python",
"django"
] |
How do I display images at different times on webpage | 1,524,713 | <p>I'm supposed to display images at certain times of the day on the webpage, Please can anyone tell me how to go about it</p>
| 1 | 2009-10-06T10:15:14Z | 1,524,793 | <p>You'll need a template tag which checks the time of day and outputs the relevant HTML. How you do that depends on how you want to determine which image is for what time of day. For example, you could have a model which records a change_time and an image path, and the tag would get the image with the most recent change_time.</p>
<p>For instance:</p>
<pre><code>import datetime
@register.simple_tag
def image_change_by_time():
now = datetime.datetime.now().time()
image = Images.objects.filter(change_time__lte=now).order_by('-change_time')[0]
return mark_safe('<img src="%s">' % image.url.path)
</code></pre>
| 2 | 2009-10-06T10:31:35Z | [
"python",
"django"
] |
How do I display images at different times on webpage | 1,524,713 | <p>I'm supposed to display images at certain times of the day on the webpage, Please can anyone tell me how to go about it</p>
| 1 | 2009-10-06T10:15:14Z | 1,524,812 | <p>If you need to change the image before a page refresh, you could use jquery ajax call to get the correct image. jquery has some interval functionality which would allow this.</p>
| 0 | 2009-10-06T10:36:21Z | [
"python",
"django"
] |
How to fix encoding in Python Mechanize? | 1,525,295 | <p>here is the sample code:</p>
<pre><code>from mechanize import Browser
br = Browser()
page = br.open('http://hunters.tclans.ru/news.php?readmore=2')
br.form = br.forms().next()
print br.form
</code></pre>
<p>The problem is that server return incorrect encoding (windows-cp1251). How can I manually set the encoding of the current page in mechanize?</p>
<p>Error:</p>
<pre><code>Traceback (most recent call last):
File "/tmp/stackoverflow.py", line 5, in <module>
br.form = br.forms().next()
File "/usr/local/lib/python2.6/dist-packages/mechanize/_mechanize.py", line 426, in forms
return self._factory.forms()
File "/usr/local/lib/python2.6/dist-packages/mechanize/_html.py", line 559, in forms
self._forms_factory.forms())
File "/usr/local/lib/python2.6/dist-packages/mechanize/_html.py", line 225, in forms
_urlunparse=_rfc3986.urlunsplit,
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 967, in ParseResponseEx
_urlunparse=_urlunparse,
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 1104, in _ParseFileEx
fp.feed(data)
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 870, in feed
sgmllib.SGMLParser.feed(self, data)
File "/usr/lib/python2.6/sgmllib.py", line 104, in feed
self.goahead(0)
File "/usr/lib/python2.6/sgmllib.py", line 193, in goahead
self.handle_entityref(name)
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 751, in handle_entityref
'&%s;' % name, self._entitydefs, self._encoding))
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 238, in unescape
return re.sub(r"&#?[A-Za-z0-9]+?;", replace_entities, data)
File "/usr/lib/python2.6/re.py", line 151, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 230, in replace_entities
repl = repl.encode(encoding)
LookupError: unknown encoding: windows-cp1251
</code></pre>
| 5 | 2009-10-06T12:26:01Z | 1,525,660 | <p>I don't know about Mechanize, but you could hack <code>codecs</code> to accept wrong encoding names that have both âwindowsâ <em>and</em> âcpâ:</p>
<pre><code>>>> def fixcp(name):
... if name.lower().startswith('windows-cp'):
... try:
... return codecs.lookup(name[:8]+name[10:])
... except LookupError:
... pass
... return None
...
>>> codecs.register(fixcp)
>>> '\xcd\xe0\xef\xee\xec\xe8\xed\xe0\xe5\xec'.decode('windows-cp1251')
u'Ðапоминаем'
</code></pre>
| 3 | 2009-10-06T13:39:27Z | [
"python",
"encoding",
"mechanize"
] |
How to fix encoding in Python Mechanize? | 1,525,295 | <p>here is the sample code:</p>
<pre><code>from mechanize import Browser
br = Browser()
page = br.open('http://hunters.tclans.ru/news.php?readmore=2')
br.form = br.forms().next()
print br.form
</code></pre>
<p>The problem is that server return incorrect encoding (windows-cp1251). How can I manually set the encoding of the current page in mechanize?</p>
<p>Error:</p>
<pre><code>Traceback (most recent call last):
File "/tmp/stackoverflow.py", line 5, in <module>
br.form = br.forms().next()
File "/usr/local/lib/python2.6/dist-packages/mechanize/_mechanize.py", line 426, in forms
return self._factory.forms()
File "/usr/local/lib/python2.6/dist-packages/mechanize/_html.py", line 559, in forms
self._forms_factory.forms())
File "/usr/local/lib/python2.6/dist-packages/mechanize/_html.py", line 225, in forms
_urlunparse=_rfc3986.urlunsplit,
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 967, in ParseResponseEx
_urlunparse=_urlunparse,
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 1104, in _ParseFileEx
fp.feed(data)
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 870, in feed
sgmllib.SGMLParser.feed(self, data)
File "/usr/lib/python2.6/sgmllib.py", line 104, in feed
self.goahead(0)
File "/usr/lib/python2.6/sgmllib.py", line 193, in goahead
self.handle_entityref(name)
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 751, in handle_entityref
'&%s;' % name, self._entitydefs, self._encoding))
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 238, in unescape
return re.sub(r"&#?[A-Za-z0-9]+?;", replace_entities, data)
File "/usr/lib/python2.6/re.py", line 151, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 230, in replace_entities
repl = repl.encode(encoding)
LookupError: unknown encoding: windows-cp1251
</code></pre>
| 5 | 2009-10-06T12:26:01Z | 1,525,786 | <p>Fixed by setting</p>
<pre><code>br._factory.encoding = enc
br._factory._forms_factory.encoding = enc
br._factory._links_factory._encoding = enc
</code></pre>
<p>(note the underscores) after br.open()</p>
| 2 | 2009-10-06T14:00:47Z | [
"python",
"encoding",
"mechanize"
] |
Python: smarter way to calculate loan payments | 1,525,611 | <p>How to calculate the monthly fee on a loan?</p>
<p>Given is:</p>
<ul>
<li>a: an amount to loan.</li>
<li>b: the loan period (number of months).</li>
<li>c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every month).</li>
<li>d: the amount of money owed after the end of the period.</li>
</ul>
<p>This problem is a bit different than the usual since, the goal is not to have the loan payed after the lone period has ended, but to still owe an amount that is given. I have been able to find an algorithm so solve the problem if I wanted to pay the entire amount, but it will of cause not work for this problem where the goal is to end up owing a given amount rather than not owing anything.</p>
<p>I managed to make a solution to this problem by starting with an guess and then keep on improving that guess until it was close enough. I wondered however, if there is a better way to simply calculate this, rather than just guessing.</p>
<p><strong>Edit: Here's how I'm doing it now.</strong></p>
<pre><code>def find_payment(start, end, months, interest):
difference = start
guess = int(start / months * interest)
while True:
total = start
for month in range(1, months + 1):
ascribe = total * interest / 12
total = total + ascribe - guess
difference = total - end
# See if the guess was good enough.
if abs(difference) > start * 0.001:
if difference < 0:
if abs(difference) < guess:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
else:
mod = int(abs(difference) / start * guess)
if mod == 0:
mod = 1
guess -= mod
else:
mod = int(difference / start * guess)
if mod == 0:
mod = 1
guess += mod
else:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
</code></pre>
<p>evolution is just a function that displays how the loan would look like payment for payment and interest for interest, summing up total amount of interest paid etc.</p>
<p>An example would be if I wanted to find out the monthly payments for a loan starting with $100k and ending at $50k with an interest of 8% and a duration of 70 months, calling</p>
<pre><code>>>> find_payment(100000, 50000, 70, 0.08)
payment is 1363
</code></pre>
<p>In the above case I would end up owing 49935, and I went through the loop 5 times. The amount of times needed to go through the loop depends on how close I wont to get to the amount and it varies a bit.</p>
| 6 | 2009-10-06T13:30:59Z | 1,525,676 | <p>You can keep paying the interest of every month; then, you will alway owe the same amont.</p>
<pre><code>Owe_1 = a
Int_2 = Owe_1*(InterestRate/12)
Pay_2 = Int_2
Owe_2 = Owe_1 + Int_2 - Pay_2 # ==> Owe_1 + Int_2 - Int_2 = Owe_1
Int_3 = Owe_2*(InterestRate/12)
Pay_3 = Int_3
Owe_3 = Owe_2 + Int_3 - Pay_3 # ==> Owe_2 + Int_3 - Int_3 = Owe_2 = Owe_1
</code></pre>
| 0 | 2009-10-06T13:43:17Z | [
"python",
"algorithm",
"math",
"finance"
] |
Python: smarter way to calculate loan payments | 1,525,611 | <p>How to calculate the monthly fee on a loan?</p>
<p>Given is:</p>
<ul>
<li>a: an amount to loan.</li>
<li>b: the loan period (number of months).</li>
<li>c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every month).</li>
<li>d: the amount of money owed after the end of the period.</li>
</ul>
<p>This problem is a bit different than the usual since, the goal is not to have the loan payed after the lone period has ended, but to still owe an amount that is given. I have been able to find an algorithm so solve the problem if I wanted to pay the entire amount, but it will of cause not work for this problem where the goal is to end up owing a given amount rather than not owing anything.</p>
<p>I managed to make a solution to this problem by starting with an guess and then keep on improving that guess until it was close enough. I wondered however, if there is a better way to simply calculate this, rather than just guessing.</p>
<p><strong>Edit: Here's how I'm doing it now.</strong></p>
<pre><code>def find_payment(start, end, months, interest):
difference = start
guess = int(start / months * interest)
while True:
total = start
for month in range(1, months + 1):
ascribe = total * interest / 12
total = total + ascribe - guess
difference = total - end
# See if the guess was good enough.
if abs(difference) > start * 0.001:
if difference < 0:
if abs(difference) < guess:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
else:
mod = int(abs(difference) / start * guess)
if mod == 0:
mod = 1
guess -= mod
else:
mod = int(difference / start * guess)
if mod == 0:
mod = 1
guess += mod
else:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
</code></pre>
<p>evolution is just a function that displays how the loan would look like payment for payment and interest for interest, summing up total amount of interest paid etc.</p>
<p>An example would be if I wanted to find out the monthly payments for a loan starting with $100k and ending at $50k with an interest of 8% and a duration of 70 months, calling</p>
<pre><code>>>> find_payment(100000, 50000, 70, 0.08)
payment is 1363
</code></pre>
<p>In the above case I would end up owing 49935, and I went through the loop 5 times. The amount of times needed to go through the loop depends on how close I wont to get to the amount and it varies a bit.</p>
| 6 | 2009-10-06T13:30:59Z | 1,525,757 | <p>Perhaps the easiest way to think about this is to split the loan in two parts, one part which is to be repaid in full and another part where you don't pay off anything. You have already computed the monthly fee for the first part.</p>
| 4 | 2009-10-06T13:56:27Z | [
"python",
"algorithm",
"math",
"finance"
] |
Python: smarter way to calculate loan payments | 1,525,611 | <p>How to calculate the monthly fee on a loan?</p>
<p>Given is:</p>
<ul>
<li>a: an amount to loan.</li>
<li>b: the loan period (number of months).</li>
<li>c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every month).</li>
<li>d: the amount of money owed after the end of the period.</li>
</ul>
<p>This problem is a bit different than the usual since, the goal is not to have the loan payed after the lone period has ended, but to still owe an amount that is given. I have been able to find an algorithm so solve the problem if I wanted to pay the entire amount, but it will of cause not work for this problem where the goal is to end up owing a given amount rather than not owing anything.</p>
<p>I managed to make a solution to this problem by starting with an guess and then keep on improving that guess until it was close enough. I wondered however, if there is a better way to simply calculate this, rather than just guessing.</p>
<p><strong>Edit: Here's how I'm doing it now.</strong></p>
<pre><code>def find_payment(start, end, months, interest):
difference = start
guess = int(start / months * interest)
while True:
total = start
for month in range(1, months + 1):
ascribe = total * interest / 12
total = total + ascribe - guess
difference = total - end
# See if the guess was good enough.
if abs(difference) > start * 0.001:
if difference < 0:
if abs(difference) < guess:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
else:
mod = int(abs(difference) / start * guess)
if mod == 0:
mod = 1
guess -= mod
else:
mod = int(difference / start * guess)
if mod == 0:
mod = 1
guess += mod
else:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
</code></pre>
<p>evolution is just a function that displays how the loan would look like payment for payment and interest for interest, summing up total amount of interest paid etc.</p>
<p>An example would be if I wanted to find out the monthly payments for a loan starting with $100k and ending at $50k with an interest of 8% and a duration of 70 months, calling</p>
<pre><code>>>> find_payment(100000, 50000, 70, 0.08)
payment is 1363
</code></pre>
<p>In the above case I would end up owing 49935, and I went through the loop 5 times. The amount of times needed to go through the loop depends on how close I wont to get to the amount and it varies a bit.</p>
| 6 | 2009-10-06T13:30:59Z | 1,525,889 | <p>This is a basically a <a href="http://en.wikipedia.org/wiki/Mortgage%5Fcalculator">mortgage repayment calculation</a>. </p>
<p>Assuming that start is greater than end, and that interest is between 0 and 1 (i.e. 0.1 for 10% interest)</p>
<p>First consider the part of the payment you want to pay off.</p>
<pre><code>Principal = start - end
</code></pre>
<p>The monthly payment is given by:</p>
<pre><code>pay_a = (interest / 12) / (1 - (1+interest/12) ^ (-months))) * Principal
</code></pre>
<p>You then need to consider the extra interest. Which is just equal to the remaining principal times the monthly interest</p>
<pre><code>pay_b = interest / 12 * end
</code></pre>
<p>So the total payment is</p>
<pre><code>payment = (interest / 12) * (1 / (1 - (1+interest/12) ^ (-months))) * Principal + end)
</code></pre>
<p>On the example you gave of </p>
<pre><code>Start: 100000
End: 50000
Months: 70
Interest: 8%
pay_a = 896.20
pay_b = 333.33
Payment = 1229.54
</code></pre>
<p>When I tested these values in Excel, after 70 payments the remaing loan was 50,000. This is assuming you pay the interest on the notional before the payment is made each month.</p>
| 7 | 2009-10-06T14:22:32Z | [
"python",
"algorithm",
"math",
"finance"
] |
Python: smarter way to calculate loan payments | 1,525,611 | <p>How to calculate the monthly fee on a loan?</p>
<p>Given is:</p>
<ul>
<li>a: an amount to loan.</li>
<li>b: the loan period (number of months).</li>
<li>c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every month).</li>
<li>d: the amount of money owed after the end of the period.</li>
</ul>
<p>This problem is a bit different than the usual since, the goal is not to have the loan payed after the lone period has ended, but to still owe an amount that is given. I have been able to find an algorithm so solve the problem if I wanted to pay the entire amount, but it will of cause not work for this problem where the goal is to end up owing a given amount rather than not owing anything.</p>
<p>I managed to make a solution to this problem by starting with an guess and then keep on improving that guess until it was close enough. I wondered however, if there is a better way to simply calculate this, rather than just guessing.</p>
<p><strong>Edit: Here's how I'm doing it now.</strong></p>
<pre><code>def find_payment(start, end, months, interest):
difference = start
guess = int(start / months * interest)
while True:
total = start
for month in range(1, months + 1):
ascribe = total * interest / 12
total = total + ascribe - guess
difference = total - end
# See if the guess was good enough.
if abs(difference) > start * 0.001:
if difference < 0:
if abs(difference) < guess:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
else:
mod = int(abs(difference) / start * guess)
if mod == 0:
mod = 1
guess -= mod
else:
mod = int(difference / start * guess)
if mod == 0:
mod = 1
guess += mod
else:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
</code></pre>
<p>evolution is just a function that displays how the loan would look like payment for payment and interest for interest, summing up total amount of interest paid etc.</p>
<p>An example would be if I wanted to find out the monthly payments for a loan starting with $100k and ending at $50k with an interest of 8% and a duration of 70 months, calling</p>
<pre><code>>>> find_payment(100000, 50000, 70, 0.08)
payment is 1363
</code></pre>
<p>In the above case I would end up owing 49935, and I went through the loop 5 times. The amount of times needed to go through the loop depends on how close I wont to get to the amount and it varies a bit.</p>
| 6 | 2009-10-06T13:30:59Z | 31,782,045 | <p><strong>python code to calculate emi</strong></p>
<pre><code>class EMI_CALCULATOR(object):
# Data attributes
# Helps to calculate EMI
Loan_amount = None # assigning none values
Month_Payment = None # assigning none values
Interest_rate = None #assigning none values
Payment_period = None #assigning none values
def get_loan_amount(self):
#get the value of loan amount
self.Loan_amount = input("Enter The Loan amount(in rupees) :")
pass
def get_interest_rate(self):
# get the value of interest rate
self.Interest_rate = input("Enter The Interest rate(in percentage(%)) : ")
pass
def get_payment_period(self):
# get the payment period"
self.Payment_period = input("Enter The Payment period (in month): ")
pass
def calc_interest_rate(self):
# To calculate the interest rate"
self.get_interest_rate()
if self.Interest_rate > 1:
self.Interest_rate = (self.Interest_rate /100.0)
else:
print "You have not entered The interest rate correctly ,please try again "
pass
def calc_emi(self):
# To calculate the EMI"
try:
self.get_loan_amount() #input loan amount
self.get_payment_period() #input payment period
self.calc_interest_rate() #input interest rate and calculate the interest rate
except NameError:
print "You have not entered Loan amount (OR) payment period (OR) interest rate correctly,Please enter and try again. "
try:
self.Month_Payment = (self.Loan_amount*pow((self.Interest_rate/12)+1,
(self.Payment_period))*self.Interest_rate/12)/(pow(self.Interest_rate/12+1,
(self.Payment_period)) - 1)
except ZeroDivisionError:
print "ERROR!! ZERO DIVISION ERROR , Please enter The Interest rate correctly and Try again."
else:
print "Monthly Payment is : %r"%self.Month_Payment
pass
if __name__ == '__main__':# main method
Init = EMI_CALCULATOR() # creating instances
Init.calc_emi() #to calculate EMI
</code></pre>
<p>for more info visit : <a href="https://emilgeorgejames.wordpress.com/2015/07/29/python-emi-equated-monthly-installment-calculator/" rel="nofollow">https://emilgeorgejames.wordpress.com/2015/07/29/python-emi-equated-monthly-installment-calculator/</a> </p>
| 0 | 2015-08-03T07:50:20Z | [
"python",
"algorithm",
"math",
"finance"
] |
Python: smarter way to calculate loan payments | 1,525,611 | <p>How to calculate the monthly fee on a loan?</p>
<p>Given is:</p>
<ul>
<li>a: an amount to loan.</li>
<li>b: the loan period (number of months).</li>
<li>c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every month).</li>
<li>d: the amount of money owed after the end of the period.</li>
</ul>
<p>This problem is a bit different than the usual since, the goal is not to have the loan payed after the lone period has ended, but to still owe an amount that is given. I have been able to find an algorithm so solve the problem if I wanted to pay the entire amount, but it will of cause not work for this problem where the goal is to end up owing a given amount rather than not owing anything.</p>
<p>I managed to make a solution to this problem by starting with an guess and then keep on improving that guess until it was close enough. I wondered however, if there is a better way to simply calculate this, rather than just guessing.</p>
<p><strong>Edit: Here's how I'm doing it now.</strong></p>
<pre><code>def find_payment(start, end, months, interest):
difference = start
guess = int(start / months * interest)
while True:
total = start
for month in range(1, months + 1):
ascribe = total * interest / 12
total = total + ascribe - guess
difference = total - end
# See if the guess was good enough.
if abs(difference) > start * 0.001:
if difference < 0:
if abs(difference) < guess:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
else:
mod = int(abs(difference) / start * guess)
if mod == 0:
mod = 1
guess -= mod
else:
mod = int(difference / start * guess)
if mod == 0:
mod = 1
guess += mod
else:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
</code></pre>
<p>evolution is just a function that displays how the loan would look like payment for payment and interest for interest, summing up total amount of interest paid etc.</p>
<p>An example would be if I wanted to find out the monthly payments for a loan starting with $100k and ending at $50k with an interest of 8% and a duration of 70 months, calling</p>
<pre><code>>>> find_payment(100000, 50000, 70, 0.08)
payment is 1363
</code></pre>
<p>In the above case I would end up owing 49935, and I went through the loop 5 times. The amount of times needed to go through the loop depends on how close I wont to get to the amount and it varies a bit.</p>
| 6 | 2009-10-06T13:30:59Z | 35,393,533 | <p>This rather a detailed way but will give the whole payment as well</p>
<pre><code># Mortgage Loan that gives the balance and total payment per year
# Function that gives the monthly payment
def f1 (principle,annual_interest_rate,duration):
r = annual_interest_rate/1200
n = duration*12
a=principle*r*((1+r)**n)
b= (((1+r)**n)- 1)
if r > 0 :
MonthlyPayment = (a/b)
else :
MonthlyPayment = principle/n
return MonthlyPayment
# Function that gives the balance
def f2 (principle,annual_interest_rate,duration,number_of_payments):
r = annual_interest_rate/1200
n = duration*12
a= ((1+r)**n)
b= ((1+r)**number_of_payments)
c= (((1+r)**n)-1)
if r > 0 :
RemainingLoanBalance = principle*((a-b)/c)
else :
RemainingLoanBalance = principle*(1-(number_of_payments/n))
return RemainingLoanBalance
# Entering the required values
principle=float(input("Enter loan amount: "))
annual_interest_rate=float(input("Enter annual interest rate (percent): "))
duration=int(input("Enter loan duration in years: "))
# Output that returns all useful data needed
print ("LOAN AMOUNT:",principle,"INTEREST RATE (PERCENT):",annual_interest_rate)
print ("DURATION (YEARS):",duration,"MONTHLY PAYMENT:",int(f1(principle,annual_interest_rate,duration)))
k=duration+1
BALANCE=principle
total=0
for i in range (1,k):
TOTALPAYMENT= f1(BALANCE,annual_interest_rate,k-i)*12
total+= TOTALPAYMENT
BALANCE= f2(principle,annual_interest_rate,duration,12*i)
print("YEAR:",i,"BALANCE:",int(BALANCE),"TOTAL PAYMENT",int(total))
</code></pre>
| 0 | 2016-02-14T15:35:00Z | [
"python",
"algorithm",
"math",
"finance"
] |
Creating files on AppEngine | 1,525,625 | <p>I'm trying to store some data in a binary file:</p>
<pre><code>import os, pickle
o = some_object()
file = open('test', 'wb') #this causes the error
pickle.dump(o, file)
file.close()
</code></pre>
<p>I get this error: <strong>IOError: invalid mode: wb</strong></p>
<p>It doesn't work (neither on test server or GAE itself), apparantly because it does't have the write permission.</p>
<p>How can I create files on Appengine?</p>
| 0 | 2009-10-06T13:33:56Z | 1,525,638 | <p>I think the short answer is you shouldn't. I suggest you store this info in BigTable as a Blob and serve it up that way.</p>
| 1 | 2009-10-06T13:35:32Z | [
"python",
"google-app-engine",
"file",
"io"
] |
Creating files on AppEngine | 1,525,625 | <p>I'm trying to store some data in a binary file:</p>
<pre><code>import os, pickle
o = some_object()
file = open('test', 'wb') #this causes the error
pickle.dump(o, file)
file.close()
</code></pre>
<p>I get this error: <strong>IOError: invalid mode: wb</strong></p>
<p>It doesn't work (neither on test server or GAE itself), apparantly because it does't have the write permission.</p>
<p>How can I create files on Appengine?</p>
| 0 | 2009-10-06T13:33:56Z | 1,525,639 | <p>GAE is readonly, you can only store stuff in the datastore</p>
<p><a href="http://code.google.com/appengine/docs/python/runtime.html#The%5FSandbox" rel="nofollow">here is a link to the docs</a></p>
| 5 | 2009-10-06T13:35:33Z | [
"python",
"google-app-engine",
"file",
"io"
] |
Python, subprocess, devenv, why no output? | 1,525,696 | <p>I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output.</p>
<pre><code>p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
ret = p.returncode
</code></pre>
<p>Here, both <code>out</code> and <code>err</code> are always empty. This happens regardless of the build success as seen in <code>p.returncode</code>.</p>
| 6 | 2009-10-06T13:46:06Z | 1,525,720 | <p>That's probably because the software you're running doesn't write to <code>stdout</code> or <code>stderr</code>. Maybe it <a href="http://msdn.microsoft.com/en-us/library/ms687403%28VS.85%29.aspx" rel="nofollow">writes directly to the terminal/console</a>.</p>
<p>If that's the case you'll need some <a href="http://msdn.microsoft.com/en-us/library/ms684961%28VS.85%29.aspx" rel="nofollow">win32 api calls</a> to capture the output.</p>
| 0 | 2009-10-06T13:50:32Z | [
"python",
"subprocess"
] |
Python, subprocess, devenv, why no output? | 1,525,696 | <p>I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output.</p>
<pre><code>p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
ret = p.returncode
</code></pre>
<p>Here, both <code>out</code> and <code>err</code> are always empty. This happens regardless of the build success as seen in <code>p.returncode</code>.</p>
| 6 | 2009-10-06T13:46:06Z | 1,525,773 | <p>You should build the solution with <code>msbuild.exe</code> instead, which is designed to give feedback to stdout and stderr. <code>msbuild.exe</code> is located at</p>
<p><code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\msbuild.exe</code> (to build a VS2005 solution)
or <code>C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe</code> (to build a VS2008 solution)</p>
<p>Note that <code>msbuild.exe</code> does not take a <code>/build</code> switch like <code>devenv.exe</code>.</p>
| 2 | 2009-10-06T13:58:48Z | [
"python",
"subprocess"
] |
Python, subprocess, devenv, why no output? | 1,525,696 | <p>I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output.</p>
<pre><code>p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
ret = p.returncode
</code></pre>
<p>Here, both <code>out</code> and <code>err</code> are always empty. This happens regardless of the build success as seen in <code>p.returncode</code>.</p>
| 6 | 2009-10-06T13:46:06Z | 1,525,775 | <p>Probably your problem is the same that the pipe's buffer fills up. Check <a href="http://stackoverflow.com/questions/1445627/how-can-i-find-out-why-subprocess-popen-wait-waits-forever-if-stdoutpipe">this question</a> for a good answer.</p>
| -2 | 2009-10-06T13:59:09Z | [
"python",
"subprocess"
] |
Python, subprocess, devenv, why no output? | 1,525,696 | <p>I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output.</p>
<pre><code>p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
ret = p.returncode
</code></pre>
<p>Here, both <code>out</code> and <code>err</code> are always empty. This happens regardless of the build success as seen in <code>p.returncode</code>.</p>
| 6 | 2009-10-06T13:46:06Z | 1,646,191 | <p>Change it from 'devenv' to 'devenv.com'. Apparenty Popen looks for .EXEs first but the shell looks for .COMs first. Switching to 'devenv.com' worked for me.</p>
<p>devenv is significantly faster then msbuild for incremental builds. I just did a build with an up to date project, meaning nothing should happen.</p>
<p>devenv 23 seconds
msbuild 55 seconds.</p>
| 24 | 2009-10-29T19:59:25Z | [
"python",
"subprocess"
] |
creating a .mat file from python | 1,526,002 | <p>I have a variable <code>exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]</code>. I would like to create a mat file like the following </p>
<pre><code>>>
exon : [3*2 double] [2*2 double]
</code></pre>
<p>When I used the python code to do the same it is showing error message. here is my python code</p>
<pre><code>import scipy.io
exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]
scipy.io.savemat('/tmp/out.mat', mdict={'exon': (exon[0], exon[1])})
</code></pre>
<p>It will be great anyone can give a suggestion for the same.
thanks in advance
Vipin T S</p>
| 1 | 2009-10-06T14:38:51Z | 1,526,549 | <p>Sage is an open source mathematics software which aims at bundling together the python syntax and the python interpreter with other tools like Matlab, Octave, Mathematica, etc...</p>
<p>Maybe you want to have a look at it:</p>
<ul>
<li><a href="http://www.sagemath.org/doc/tutorial/index.html" rel="nofollow">http://www.sagemath.org/doc/tutorial/index.html</a></li>
<li><a href="http://www.sagemath.org/" rel="nofollow">http://www.sagemath.org/</a></li>
</ul>
| 1 | 2009-10-06T16:02:39Z | [
"python",
"scipy",
"mat-file"
] |
creating a .mat file from python | 1,526,002 | <p>I have a variable <code>exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]</code>. I would like to create a mat file like the following </p>
<pre><code>>>
exon : [3*2 double] [2*2 double]
</code></pre>
<p>When I used the python code to do the same it is showing error message. here is my python code</p>
<pre><code>import scipy.io
exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]
scipy.io.savemat('/tmp/out.mat', mdict={'exon': (exon[0], exon[1])})
</code></pre>
<p>It will be great anyone can give a suggestion for the same.
thanks in advance
Vipin T S</p>
| 1 | 2009-10-06T14:38:51Z | 1,644,090 | <p>You seem to want two different arrays linked to same variable name in Matlab. That is not possible. In MATLAB you can have cell arrays, or structs, which contain other arrays, but you cannot have just a tuple of arrays assigned to a single variable (which is what you have in mdict={'exon': (exon[0], exon<a href="http://docs.scipy.org/doc/scipy/reference/tutorial/io.html" rel="nofollow">1</a>)) - there is no concept of a tuple in Matlab.</p>
<p>You will also need to make your objects numpy arrays:</p>
<pre><code>import numpy as np
exon = [ np.array([[1, 2], [3, 4], [5, 6]]), np.array([[7, 8], [9, 10]]) ]
</code></pre>
<p>There is scipy documentation <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/io.html" rel="nofollow">here</a> with details of how to save different Matlab types, but assuming you want cell array:</p>
<pre><code>obj_arr = np.zeros((2,), dtype=np.object)
obj_arr[0] = exon[0]
obj_arr[1] = exon[1]
scipy.io.savemat('/tmp/out.mat', mdict={'exon': obj_arr})
</code></pre>
<p>this will result in the following at matlab:</p>
<p><img src="http://i.imgur.com/75kfqyE.png" alt="code result in matlab"></p>
<p>or possibly (untested):</p>
<pre><code>obj_arr = np.array(exon, dtype=np.object)
</code></pre>
| 6 | 2009-10-29T14:22:37Z | [
"python",
"scipy",
"mat-file"
] |
Sort string collection in Python using various locale settings | 1,526,109 | <p>I want to sort list of strings with respect to user language preference. I have a multilanguage Python webapp and what is the correct way to sort strings such way?</p>
<p>I know I can set up locale, like this:</p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, '')
</code></pre>
<p>But this should be done on application start (and doc says it is not thread-safe!), is it good idea to set it up in every thread according to current user (request) setting?</p>
<p>I would like something like function locale.strcoll(...) with additional parameter - language that is used for sorting.</p>
| 4 | 2009-10-06T14:54:05Z | 1,526,525 | <p>Given the documentation warnings, it seems you are on your own if you try to set locale diffrently in different threads.</p>
<p>If you can split your problem into one thread per locale, might you not as well split it into one subprocess per locale, using Python 2.6's multiprocessing?</p>
<p>It seems everything solving this must be a hack, you could even consider using the command-line program <code>sort (1)</code> invoked with different LC_ALL for different languages.</p>
| 0 | 2009-10-06T15:57:48Z | [
"python",
"google-app-engine",
"sorting",
"web-applications",
"collation"
] |
Sort string collection in Python using various locale settings | 1,526,109 | <p>I want to sort list of strings with respect to user language preference. I have a multilanguage Python webapp and what is the correct way to sort strings such way?</p>
<p>I know I can set up locale, like this:</p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, '')
</code></pre>
<p>But this should be done on application start (and doc says it is not thread-safe!), is it good idea to set it up in every thread according to current user (request) setting?</p>
<p>I would like something like function locale.strcoll(...) with additional parameter - language that is used for sorting.</p>
| 4 | 2009-10-06T14:54:05Z | 1,527,075 | <p>I would recommend <a href="http://pyicu.osafoundation.org/" rel="nofollow">pyICU</a> -- Python bindings for IBM's rich open-source <a href="http://www-01.ibm.com/software/globalization/icu/index.jsp" rel="nofollow">ICU</a> internationalization library. You make a Collator object e.g. with:</p>
<pre><code> collator = PyICU.Collator.createInstance(PyICU.Locale.getFrance())
</code></pre>
<p>and then you can sort e.g. a list of utf-8 encoded strings by the rules for French, e.g. by using <code>thelist.sort(cmp=collator.compare)</code>.</p>
<p>The only issue I had was that I found no good packaged, immediately usable version of PyICU plus ICU for MacOSX -- I ended up building and installing from sources: ICU's own sources, 3.6, from <a href="http://icu-project.org/download/3.6.html" rel="nofollow">here</a> -- there are binaries for Windows and several Unix versions there, but not for the Mac; PyICU 0.8.1 from <a href="http://pypi.python.org/pypi/PyICU/0.8.1" rel="nofollow">here</a>.</p>
<p>Net of these build/installation issues, and somewhat-scant docs for the Python bindings, ICU's really a godsend if you do any substantial amount of i18n-related work, and PyICU a very serviceable set of bindings to it!</p>
| 4 | 2009-10-06T17:50:30Z | [
"python",
"google-app-engine",
"sorting",
"web-applications",
"collation"
] |
Sort string collection in Python using various locale settings | 1,526,109 | <p>I want to sort list of strings with respect to user language preference. I have a multilanguage Python webapp and what is the correct way to sort strings such way?</p>
<p>I know I can set up locale, like this:</p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, '')
</code></pre>
<p>But this should be done on application start (and doc says it is not thread-safe!), is it good idea to set it up in every thread according to current user (request) setting?</p>
<p>I would like something like function locale.strcoll(...) with additional parameter - language that is used for sorting.</p>
| 4 | 2009-10-06T14:54:05Z | 1,539,883 | <p>You will want the latest possible ICU under your pyICU to get the best and most up to date data.</p>
| 1 | 2009-10-08T19:18:36Z | [
"python",
"google-app-engine",
"sorting",
"web-applications",
"collation"
] |
Sort string collection in Python using various locale settings | 1,526,109 | <p>I want to sort list of strings with respect to user language preference. I have a multilanguage Python webapp and what is the correct way to sort strings such way?</p>
<p>I know I can set up locale, like this:</p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, '')
</code></pre>
<p>But this should be done on application start (and doc says it is not thread-safe!), is it good idea to set it up in every thread according to current user (request) setting?</p>
<p>I would like something like function locale.strcoll(...) with additional parameter - language that is used for sorting.</p>
| 4 | 2009-10-06T14:54:05Z | 1,542,568 | <p>Another possible solution is to use SQL server that has good locale support (unfortunately, sqlite is not an option). Then I can put all data to temporary memory table and SELECT them with ORDER BY. IMO it should be better solution than trying to distribute locale settings to multiple processes as kaizer.se's answer recommends.</p>
| 0 | 2009-10-09T08:29:49Z | [
"python",
"google-app-engine",
"sorting",
"web-applications",
"collation"
] |
Operations for Long and Float in Python | 1,526,142 | <p>I'm trying to compute this:</p>
<pre><code>from scipy import *
3600**3400 * (exp(-3600)) / factorial(3400)
</code></pre>
<p>the error: unsupported long and float</p>
| 0 | 2009-10-06T14:57:49Z | 1,526,366 | <p>Well the error is coming about because you are trying to multiply</p>
<pre><code>3600**3400
</code></pre>
<p>which is a long with </p>
<pre><code>exp(-3600)
</code></pre>
<p>which is a float. </p>
<p>But regardless, the error you are receiving is disguising the true problem. It seems exp(-3600) is too big a number to fit in a float anyway. The python math library is fickle with large numbers, at best.</p>
| 0 | 2009-10-06T15:31:18Z | [
"python",
"floating-point",
"scipy",
"long-integer"
] |
Operations for Long and Float in Python | 1,526,142 | <p>I'm trying to compute this:</p>
<pre><code>from scipy import *
3600**3400 * (exp(-3600)) / factorial(3400)
</code></pre>
<p>the error: unsupported long and float</p>
| 0 | 2009-10-06T14:57:49Z | 1,526,443 | <p>Try using logarithms instead of working with the numbers directly. Since none of your operations are addition or subtraction, you could do the whole thing in logarithm form and convert back at the end.</p>
| 3 | 2009-10-06T15:44:22Z | [
"python",
"floating-point",
"scipy",
"long-integer"
] |
Operations for Long and Float in Python | 1,526,142 | <p>I'm trying to compute this:</p>
<pre><code>from scipy import *
3600**3400 * (exp(-3600)) / factorial(3400)
</code></pre>
<p>the error: unsupported long and float</p>
| 0 | 2009-10-06T14:57:49Z | 1,526,501 | <p>You could try using the <a href="http://docs.python.org/library/decimal.html" rel="nofollow">Decimal</a> object. Calculations will be slower but you won't have trouble with really small numbers.</p>
<pre><code>from decimal import Decimal
</code></pre>
<p>I don't know how Decimal interacts with the scipy module, however.</p>
<p>This <a href="http://www.mail-archive.com/numpy-discussion@scipy.org/msg17213.html" rel="nofollow">numpy discussion</a> might be relevant.</p>
| 1 | 2009-10-06T15:53:16Z | [
"python",
"floating-point",
"scipy",
"long-integer"
] |
Operations for Long and Float in Python | 1,526,142 | <p>I'm trying to compute this:</p>
<pre><code>from scipy import *
3600**3400 * (exp(-3600)) / factorial(3400)
</code></pre>
<p>the error: unsupported long and float</p>
| 0 | 2009-10-06T14:57:49Z | 1,527,121 | <p>Computing with numbers of such magnitude, you just can't use ordinary 64-bit-or-so floats, which is what Python's core runtime supports. Consider <a href="http://code.google.com/p/gmpy/" rel="nofollow"><code>gmpy</code></a> (do <strong>not</strong> get the sourceforge version, it's aeons out of date) -- with that, <code>math</code>, and some care...:</p>
<pre><code>>>> e = gmpy.mpf(math.exp(1))
>>> gmpy.mpz(3600)**3400 * (e**(-3600)) / gmpy.fac(3400)
mpf('2.37929475533825366213e-5')
</code></pre>
<p>(I'm biased about <code>gmpy</code>, of course, since I originated and still participate in that project, but I'd never make strong claims about its <em>floating point</em> abilities... I've been using it mostly for integer stuff... still, it <strong>does</strong> make this computation possible!-).</p>
| 2 | 2009-10-06T17:58:45Z | [
"python",
"floating-point",
"scipy",
"long-integer"
] |
Operations for Long and Float in Python | 1,526,142 | <p>I'm trying to compute this:</p>
<pre><code>from scipy import *
3600**3400 * (exp(-3600)) / factorial(3400)
</code></pre>
<p>the error: unsupported long and float</p>
| 0 | 2009-10-06T14:57:49Z | 1,528,704 | <p>exp(-3600) is too smale, factorial(3400) is too large: </p>
<pre><code>In [1]: from scipy import exp
In [2]: exp(-3600)
Out[2]: 0.0
In [3]: from scipy import factorial
In [4]: factorial(3400)
Out[4]: array(1.#INF)
</code></pre>
<p>What about calculate it step by step as a workaround(and it makes sense
to check the smallest and biggest intermediate result):</p>
<pre><code>from math import exp
output = 1
smallest = 1e100
biggest = 0
for i,j in izip(xrange(1, 1701), xrange(3400, 1699, -1)):
output = output * 3600 * exp(-3600/3400) / i
output = output * 3600 * exp(-3600/3400) / j
smallest = min(smallest, output)
biggest = max(biggest, output)
print "output: ", output
print "smallest: ", smallest
print "biggest: ", biggest
</code></pre>
<p>output is: </p>
<pre><code>output: 2.37929475534e-005
smallest: 2.37929475534e-005
biggest: 1.28724174494e+214
</code></pre>
| 0 | 2009-10-06T23:40:17Z | [
"python",
"floating-point",
"scipy",
"long-integer"
] |
Formatting date string in Python for dates prior to 1900? | 1,526,170 | <p>Can anyone explain the best way to format a date time string in Python where the date value is prior to the year 1900? <code>strftime</code> requires dates later than 1900.</p>
| 3 | 2009-10-06T15:03:08Z | 1,526,249 | <p>It's a bit cumbersome, but it works (at least in stable versions of python):</p>
<pre><code>>>> ts = datetime.datetime(1895, 10, 6, 16, 4, 5)
>>> '{0.year}-{0.month:{1}}-{0.day:{1}} {0.hour:{1}}:{0.minute:{1}}'.format(ts, '02')
'1895-10-06 16:04'
</code></pre>
<p>note that <code>str</code> would still produce a readable string: </p>
<pre><code>>>> str(ts)
'1895-10-06 16:04:05'
</code></pre>
<p><strong>edit</strong><br />
The closest possible way to emulate the default behaviour is to hard-code the dictionary such as:</p>
<pre><code>>>> d = {'%Y': '{0.year}', '%m': '{0.month:02}'} # need to include all the formats
>>> '{%Y}-{%m}'.format(**d).format(ts)
'1895-10'
</code></pre>
<p>You'll need to enclose all format specifiers into the curly braces with the simple regex:</p>
<pre><code>>>> re.sub('(%\w)', r'{\1}', '%Y-%m-%d %H sdf')
'{%Y}-{%m}-{%d} {%H} sdf'
</code></pre>
<p>and at the end we come to simple code:</p>
<pre><code>def ancient_fmt(ts, fmt):
fmt = fmt.replace('%%', '%')
fmt = re.sub('(%\w)', r'{\1}', fmt)
return fmt.format(**d).format(ts)
def main(ts, format):
if ts.year < 1900:
return ancient_format(ts, fmt)
else:
return ts.strftime(fmt)
</code></pre>
<p>where <code>d</code> is a global dictionary with keys corresponding to some specifiers in <a href="http://docs.python.org/library/datetime.html#strftime-behavior" rel="nofollow"><code>strftime</code> table</a>.</p>
<p><strong>edit 2</strong><br />
To clarify: this approach will work only for the following specifiers: <code>%Y, %m, %d, %H, %M, %S, %f</code>, i.e., those that are numeric, if you need textual information, you'd better off with babel or any other solution.</p>
| 3 | 2009-10-06T15:14:44Z | [
"python",
"datetime"
] |
Formatting date string in Python for dates prior to 1900? | 1,526,170 | <p>Can anyone explain the best way to format a date time string in Python where the date value is prior to the year 1900? <code>strftime</code> requires dates later than 1900.</p>
| 3 | 2009-10-06T15:03:08Z | 1,526,751 | <p>The <code>babel</code> internationalization library seems to have no problems with it. See the <a href="http://babel.edgewall.org/wiki/Documentation/0.9/dates.html" rel="nofollow">docs</a> for <code>babel.dates</code></p>
| 1 | 2009-10-06T16:43:32Z | [
"python",
"datetime"
] |
Formatting date string in Python for dates prior to 1900? | 1,526,170 | <p>Can anyone explain the best way to format a date time string in Python where the date value is prior to the year 1900? <code>strftime</code> requires dates later than 1900.</p>
| 3 | 2009-10-06T15:03:08Z | 1,527,779 | <p>The calendar is exactly the same every 400 years. Therefore it is sufficient to change year by multiple of 400 such as <code>year >= 1900</code> before calling <code>datetime.strftime()</code>.</p>
<p>The code shows what problems such approach has:</p>
<pre><code>#/usr/bin/env python2.6
import re
import warnings
from datetime import datetime
def strftime(datetime_, format, force=False):
"""`strftime()` that works for year < 1900.
Disregard calendars shifts.
>>> def f(fmt, force=False):
... return strftime(datetime(1895, 10, 6, 11, 1, 2), fmt, force)
>>> f('abc %Y %m %D')
'abc 1895 10 10/06/95'
>>> f('%X')
'11:01:02'
>>> f('%c') #doctest:+NORMALIZE_WHITESPACE
Traceback (most recent call last):
ValueError: '%c', '%x' produce unreliable results for year < 1900
use force=True to override
>>> f('%c', force=True)
'Sun Oct 6 11:01:02 1895'
>>> f('%x') #doctest:+NORMALIZE_WHITESPACE
Traceback (most recent call last):
ValueError: '%c', '%x' produce unreliable results for year < 1900
use force=True to override
>>> f('%x', force=True)
'10/06/95'
>>> f('%%x %%Y %Y')
'%x %Y 1895'
"""
year = datetime_.year
if year >= 1900:
return datetime_.strftime(format)
# make year larger then 1900 using 400 increment
assert year < 1900
factor = (1900 - year - 1) // 400 + 1
future_year = year + factor * 400
assert future_year > 1900
format = Specifier('%Y').replace_in(format, year)
result = datetime_.replace(year=future_year).strftime(format)
if any(f.ispresent_in(format) for f in map(Specifier, ['%c', '%x'])):
msg = "'%c', '%x' produce unreliable results for year < 1900"
if not force:
raise ValueError(msg + " use force=True to override")
warnings.warn(msg)
result = result.replace(str(future_year), str(year))
assert (future_year % 100) == (year % 100) # last two digits are the same
return result
class Specifier(str):
"""Model %Y and such in `strftime`'s format string."""
def __new__(cls, *args):
self = super(Specifier, cls).__new__(cls, *args)
assert self.startswith('%')
assert len(self) == 2
self._regex = re.compile(r'(%*{0})'.format(str(self)))
return self
def ispresent_in(self, format):
m = self._regex.search(format)
return m and m.group(1).count('%') & 1 # odd number of '%'
def replace_in(self, format, by):
def repl(m):
n = m.group(1).count('%')
if n & 1: # odd number of '%'
prefix = '%'*(n-1) if n > 0 else ''
return prefix + str(by) # replace format
else:
return m.group(0) # leave unchanged
return self._regex.sub(repl, format)
if __name__=="__main__":
import doctest; doctest.testmod()
</code></pre>
| 1 | 2009-10-06T20:01:59Z | [
"python",
"datetime"
] |
How do I memoize expensive calculations on Django model objects? | 1,526,191 | <p>I have several TextField columns on my UserProfile object which contain JSON objects. I've also defined a setter/getter property for each column which encapsulates the logic for serializing and deserializing the JSON into python datastructures.</p>
<p>The nature of this data ensures that it will be accessed many times by view and template logic within a single Request. To save on deserialization costs, I would like to memoize the python datastructures on read, invalidating on direct write to the property or save signal from the model object.</p>
<p>Where/How do I store the memo? I'm nervous about using instance variables, as I don't understand the magic behind how any particular UserProfile is instantiated by a query. Is <code>__init__</code> safe to use, or do I need to check the existence of the memo attribute via <code>hasattr()</code> at each read?</p>
<p>Here's an example of my current implementation:</p>
<pre><code>class UserProfile(Model):
text_json = models.TextField(default=text_defaults)
@property
def text(self):
if not hasattr(self, "text_memo"):
self.text_memo = None
self.text_memo = self.text_memo or simplejson.loads(self.text_json)
return self.text_memo
@text.setter
def text(self, value=None):
self.text_memo = None
self.text_json = simplejson.dumps(value)
</code></pre>
| 9 | 2009-10-06T15:06:48Z | 1,526,245 | <p>Generally, I use a pattern like this:</p>
<pre><code>def get_expensive_operation(self):
if not hasattr(self, '_expensive_operation'):
self._expensive_operation = self.expensive_operation()
return self._expensive_operation
</code></pre>
<p>Then you use the <code>get_expensive_operation</code> method to access the data.</p>
<p>However, in your particular case, I think you are approaching this in slightly the wrong way. You need to do the deserialization when the model is first loaded from the database, and serialize on save only. Then you can simply access the attributes as a standard Python dictionary each time. You can do this by defining a custom JSONField type, subclassing models.TextField, which overrides <code>to_python</code> and <code>get_db_prep_save</code>.</p>
<p>In fact someone's already done it: see <a href="http://www.djangosnippets.org/snippets/1478/">here</a>.</p>
| 16 | 2009-10-06T15:14:27Z | [
"python",
"django",
"django-models",
"memoization"
] |
How do I memoize expensive calculations on Django model objects? | 1,526,191 | <p>I have several TextField columns on my UserProfile object which contain JSON objects. I've also defined a setter/getter property for each column which encapsulates the logic for serializing and deserializing the JSON into python datastructures.</p>
<p>The nature of this data ensures that it will be accessed many times by view and template logic within a single Request. To save on deserialization costs, I would like to memoize the python datastructures on read, invalidating on direct write to the property or save signal from the model object.</p>
<p>Where/How do I store the memo? I'm nervous about using instance variables, as I don't understand the magic behind how any particular UserProfile is instantiated by a query. Is <code>__init__</code> safe to use, or do I need to check the existence of the memo attribute via <code>hasattr()</code> at each read?</p>
<p>Here's an example of my current implementation:</p>
<pre><code>class UserProfile(Model):
text_json = models.TextField(default=text_defaults)
@property
def text(self):
if not hasattr(self, "text_memo"):
self.text_memo = None
self.text_memo = self.text_memo or simplejson.loads(self.text_json)
return self.text_memo
@text.setter
def text(self, value=None):
self.text_memo = None
self.text_json = simplejson.dumps(value)
</code></pre>
| 9 | 2009-10-06T15:06:48Z | 2,634,701 | <p>You may be interested in a built-in django decorator <code>django.utils.functional.memoize</code>.</p>
<p>Django uses this to cache expensive operation like url resolving.</p>
| 22 | 2010-04-14T03:28:16Z | [
"python",
"django",
"django-models",
"memoization"
] |
Extracting data from a CSV file in Python | 1,526,607 | <p>I just got my data and it is given to me as a <code>csv</code> file.</p>
<p>It looks like this in data studio(where the file was taken).</p>
<pre><code>Counts frequency
300 1
302 5
303 7
</code></pre>
<p>Excel can't handle the computations so that's why I'm trying to load it in python(it has <code>scipy</code> :D).</p>
<p>I want to load the data in an array:</p>
<pre><code>Counts = [300, 302, 303]
frequency = [1, 5, 7]
</code></pre>
<p>How will I code this?</p>
| 0 | 2009-10-06T16:16:27Z | 1,526,618 | <p>Use the Python <a href="http://docs.python.org/library/csv" rel="nofollow">csv</a> module.</p>
| 9 | 2009-10-06T16:18:31Z | [
"python",
"csv"
] |
Extracting data from a CSV file in Python | 1,526,607 | <p>I just got my data and it is given to me as a <code>csv</code> file.</p>
<p>It looks like this in data studio(where the file was taken).</p>
<pre><code>Counts frequency
300 1
302 5
303 7
</code></pre>
<p>Excel can't handle the computations so that's why I'm trying to load it in python(it has <code>scipy</code> :D).</p>
<p>I want to load the data in an array:</p>
<pre><code>Counts = [300, 302, 303]
frequency = [1, 5, 7]
</code></pre>
<p>How will I code this?</p>
| 0 | 2009-10-06T16:16:27Z | 1,526,773 | <pre><code>import csv
counts = []
frequencies = []
for d in csv.DictReader(open('yourfile.csv'), delimiter='\t'):
counts.append(int(d['Counts']))
frequencies.append(int(d['frequency']))
print 'Counts = ', counts
print 'frequency = ', frequencies
</code></pre>
| 6 | 2009-10-06T16:47:09Z | [
"python",
"csv"
] |
How to deal with query parameter's encoding? | 1,526,965 | <p>I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.</p>
<p>For <a href="http://metaward.com/alias/add?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer%20Rat%20von%20Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">this example</a> has the character <code>ä</code> in utf-8 in the document (from the query string) but proceeds to send a <code>B\xe4ule</code> (which is either ISO-8859-1 or windows 1252) when you click submit. It also fires off a <a href="http://metaward.com/alias/parse?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer+Rat+von+Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">ajax request</a> which also fails from trying to decode the non-utf8 character.</p>
<p>An in django, my request.POST is really screwed up :</p>
<pre><code>>>> print request.POST
<QueryDict: {u'alias': [u'eu.wowarmory.com/character-sheet.xml?r=Der Rat von Dalaran&cn=B\ufffde']}>
</code></pre>
<p>How can I just make all these headaches go away and work in utf8?</p>
| 3 | 2009-10-06T17:27:51Z | 1,527,018 | <p>Although it's AFAIK not specified anywhere, all browsers use the character encoding of the HTML page, on which the form is embedded as the encoding for submitting the form back to the server. So if you want the URL parameters to be UTF-8-encoded, you have to make sure that the HTML page, on which the form is embedded, is also UTF-8 encoded.</p>
| 0 | 2009-10-06T17:38:32Z | [
"python",
"django",
"unicode",
"utf-8"
] |
How to deal with query parameter's encoding? | 1,526,965 | <p>I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.</p>
<p>For <a href="http://metaward.com/alias/add?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer%20Rat%20von%20Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">this example</a> has the character <code>ä</code> in utf-8 in the document (from the query string) but proceeds to send a <code>B\xe4ule</code> (which is either ISO-8859-1 or windows 1252) when you click submit. It also fires off a <a href="http://metaward.com/alias/parse?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer+Rat+von+Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">ajax request</a> which also fails from trying to decode the non-utf8 character.</p>
<p>An in django, my request.POST is really screwed up :</p>
<pre><code>>>> print request.POST
<QueryDict: {u'alias': [u'eu.wowarmory.com/character-sheet.xml?r=Der Rat von Dalaran&cn=B\ufffde']}>
</code></pre>
<p>How can I just make all these headaches go away and work in utf8?</p>
| 3 | 2009-10-06T17:27:51Z | 1,527,024 | <p>According to <a href="http://stackoverflow.com/questions/544071/get-non-utf-8-form-fields-as-utf-8-in-php">http://stackoverflow.com/questions/544071/get-non-utf-8-form-fields-as-utf-8-in-php</a>, you'll need to make sure the page itself is served up using UTF8 encoding. </p>
| 0 | 2009-10-06T17:39:52Z | [
"python",
"django",
"unicode",
"utf-8"
] |
How to deal with query parameter's encoding? | 1,526,965 | <p>I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.</p>
<p>For <a href="http://metaward.com/alias/add?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer%20Rat%20von%20Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">this example</a> has the character <code>ä</code> in utf-8 in the document (from the query string) but proceeds to send a <code>B\xe4ule</code> (which is either ISO-8859-1 or windows 1252) when you click submit. It also fires off a <a href="http://metaward.com/alias/parse?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer+Rat+von+Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">ajax request</a> which also fails from trying to decode the non-utf8 character.</p>
<p>An in django, my request.POST is really screwed up :</p>
<pre><code>>>> print request.POST
<QueryDict: {u'alias': [u'eu.wowarmory.com/character-sheet.xml?r=Der Rat von Dalaran&cn=B\ufffde']}>
</code></pre>
<p>How can I just make all these headaches go away and work in utf8?</p>
| 3 | 2009-10-06T17:27:51Z | 1,539,789 | <p>Since Django 1.0 all values you get from form submission are unicode objects, not bytestrings like in Django 0.96 and earlier. To get utf-8 from your values encode them with utf-8 codec:</p>
<pre><code>request.POST['somefield'].encode('utf-8')
</code></pre>
<p>To get query parameters decoded properly, they have to be properly encoded first:</p>
<pre><code>In [3]: urllib.quote('ä')
Out[3]: '%C3%A4'
</code></pre>
<p>I think your problem comes from bad encoding of query parameters.</p>
| 3 | 2009-10-08T18:59:36Z | [
"python",
"django",
"unicode",
"utf-8"
] |
How to deal with query parameter's encoding? | 1,526,965 | <p>I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.</p>
<p>For <a href="http://metaward.com/alias/add?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer%20Rat%20von%20Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">this example</a> has the character <code>ä</code> in utf-8 in the document (from the query string) but proceeds to send a <code>B\xe4ule</code> (which is either ISO-8859-1 or windows 1252) when you click submit. It also fires off a <a href="http://metaward.com/alias/parse?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer+Rat+von+Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">ajax request</a> which also fails from trying to decode the non-utf8 character.</p>
<p>An in django, my request.POST is really screwed up :</p>
<pre><code>>>> print request.POST
<QueryDict: {u'alias': [u'eu.wowarmory.com/character-sheet.xml?r=Der Rat von Dalaran&cn=B\ufffde']}>
</code></pre>
<p>How can I just make all these headaches go away and work in utf8?</p>
| 3 | 2009-10-06T17:27:51Z | 1,592,932 | <p>You should also add <code>accept-charset="UTF-8"</code> to the <code><form/></code> tag.</p>
| 1 | 2009-10-20T07:07:55Z | [
"python",
"django",
"unicode",
"utf-8"
] |
How to deal with query parameter's encoding? | 1,526,965 | <p>I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.</p>
<p>For <a href="http://metaward.com/alias/add?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer%20Rat%20von%20Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">this example</a> has the character <code>ä</code> in utf-8 in the document (from the query string) but proceeds to send a <code>B\xe4ule</code> (which is either ISO-8859-1 or windows 1252) when you click submit. It also fires off a <a href="http://metaward.com/alias/parse?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer+Rat+von+Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">ajax request</a> which also fails from trying to decode the non-utf8 character.</p>
<p>An in django, my request.POST is really screwed up :</p>
<pre><code>>>> print request.POST
<QueryDict: {u'alias': [u'eu.wowarmory.com/character-sheet.xml?r=Der Rat von Dalaran&cn=B\ufffde']}>
</code></pre>
<p>How can I just make all these headaches go away and work in utf8?</p>
| 3 | 2009-10-06T17:27:51Z | 1,673,377 | <p>Getting an utf-8 string from the submitted form should just be a matter of encoding the
unicode object:</p>
<p>next = request.POST['next'].encode('utf-8')</p>
<p>For the AJAX request, can you confirm that that request is also being sent as utf-8 and declared as utf-8 in the headers?</p>
| 0 | 2009-11-04T12:04:37Z | [
"python",
"django",
"unicode",
"utf-8"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played two<br />
He played knick-knack on my shoe<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played three<br />
He played knick-knack on my knee<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played four<br />
He played knick-knack on my door<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played five<br />
He played knick-knack on my hive<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played six<br />
He played knick-knack on my sticks<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played seven<br />
He played knick-knack up in heaven<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played eight<br />
He played knick-knack on my gate<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played nine<br />
He played knick-knack on my spine<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played ten<br />
He played knick-knack once again<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p><strong>This is what I have so far, but it doesn't do what I want it to do. I'm not sure how to phrase the while loop or get it to choose a single word from the list in order.</strong></p>
<pre><code>num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']
z=1
print "This old man, he played",(num)
print "He played knick-knack", (end)
print "Knick-knack paddywhack, give your dog a bone"
print "This old man came rolling home"
</code></pre>
| 0 | 2009-10-06T17:53:17Z | 1,527,128 | <p>Hint: You will need to use a loop</p>
<p>I would look at the <a href="http://docs.python.org/tutorial/controlflow.html" rel="nofollow">Python Flow Control</a> documentation. Also note the <code>range()</code> function.</p>
<p>You can grab the <em>n</em>'th element from an array like this:</p>
<pre><code>val = some_array[n]
</code></pre>
<p>And remember that in Python, arrays start counting at 0, not 1.</p>
| 5 | 2009-10-06T17:59:40Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played two<br />
He played knick-knack on my shoe<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played three<br />
He played knick-knack on my knee<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played four<br />
He played knick-knack on my door<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played five<br />
He played knick-knack on my hive<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played six<br />
He played knick-knack on my sticks<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played seven<br />
He played knick-knack up in heaven<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played eight<br />
He played knick-knack on my gate<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played nine<br />
He played knick-knack on my spine<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played ten<br />
He played knick-knack once again<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p><strong>This is what I have so far, but it doesn't do what I want it to do. I'm not sure how to phrase the while loop or get it to choose a single word from the list in order.</strong></p>
<pre><code>num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']
z=1
print "This old man, he played",(num)
print "He played knick-knack", (end)
print "Knick-knack paddywhack, give your dog a bone"
print "This old man came rolling home"
</code></pre>
| 0 | 2009-10-06T17:53:17Z | 1,527,133 | <p>I am not sure if I want to do your homework, but I will give you some hints: To me, this looks like a good place for a for loop. Use range, xrange, or enumerate.</p>
| 0 | 2009-10-06T18:00:26Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played two<br />
He played knick-knack on my shoe<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played three<br />
He played knick-knack on my knee<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played four<br />
He played knick-knack on my door<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played five<br />
He played knick-knack on my hive<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played six<br />
He played knick-knack on my sticks<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played seven<br />
He played knick-knack up in heaven<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played eight<br />
He played knick-knack on my gate<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played nine<br />
He played knick-knack on my spine<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played ten<br />
He played knick-knack once again<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p><strong>This is what I have so far, but it doesn't do what I want it to do. I'm not sure how to phrase the while loop or get it to choose a single word from the list in order.</strong></p>
<pre><code>num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']
z=1
print "This old man, he played",(num)
print "He played knick-knack", (end)
print "Knick-knack paddywhack, give your dog a bone"
print "This old man came rolling home"
</code></pre>
| 0 | 2009-10-06T17:53:17Z | 1,527,152 | <p>First, you probably want to say <code>z = 0</code> because arrays in Python (and most programming languages) are zero-indexed - the first element of <code>num</code> is <code>num[0]</code>, the second is <code>num[1]</code>, and so on. Though we don't really even need <code>z</code>. More on that later.</p>
<p>Second, I would change <code>num</code> and <code>end</code> to <code>nums</code> and <code>endings</code>. If we give them a plural name it's clearer that we're using a list. Also, lists aren't individual values, but a collection of values. We need to get an <em>element</em> of that collection in this case. We wouldn't say <code>(nums)</code> (or <code>(num)</code> if you keep it your way) - that gets the entire list. We would say <code>nums[x]</code> (or <code>num[x]</code>) which gets element <code>x</code> (remember that arrays are zero-indexed!), where <code>x</code> can be a number, a variable holding a number, or any arbitrary expression that evaluates to a number.</p>
<p>Third, you could use a <code>while</code> loop, but even better would be a <code>for</code> loop and the <code>range()</code> and <code>len()</code> functions. The syntax for <code>for</code> loops is:</p>
<pre><code>for x in y:
</code></pre>
<p>Where <code>x</code> is a temporary variable, and <code>y</code> is a list of items. The loop iterates over all the items in <code>y</code>, setting each one to <code>x</code> for the body of the loop. The <code>range()</code> function creates a list of numbers (which can be easily used as array indices, hint hint). The <code>len()</code> function takes a list and returns the length of the list. Combine these in the appropriate order to create a loop.</p>
| 0 | 2009-10-06T18:03:05Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played two<br />
He played knick-knack on my shoe<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played three<br />
He played knick-knack on my knee<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played four<br />
He played knick-knack on my door<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played five<br />
He played knick-knack on my hive<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played six<br />
He played knick-knack on my sticks<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played seven<br />
He played knick-knack up in heaven<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played eight<br />
He played knick-knack on my gate<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played nine<br />
He played knick-knack on my spine<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played ten<br />
He played knick-knack once again<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p><strong>This is what I have so far, but it doesn't do what I want it to do. I'm not sure how to phrase the while loop or get it to choose a single word from the list in order.</strong></p>
<pre><code>num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']
z=1
print "This old man, he played",(num)
print "He played knick-knack", (end)
print "Knick-knack paddywhack, give your dog a bone"
print "This old man came rolling home"
</code></pre>
| 0 | 2009-10-06T17:53:17Z | 1,527,235 | <p>Your rhyme encourages violence against the Irish. Nevertheless, here's some help. </p>
<p>Since the rhymes themselves have two parts, I've put each rhyme as a two part list, put together into a list of all those rhymes. </p>
<pre><code># List of rhymes, with each part of the rhyme as another list.
rhymes = ['one','on my thumb'],['two','on my shoe']
# The total amount of rhymes len(rhymes) lets us know when to stop...
count = 0
while count < len(rhymes):
print "This old man, he played "+rhymes[count][0]
print "He played knick-knack "+rhymes[count][1]
print "Knick-knack paddywhack, give your dog a bone"
print "This old man came rolling home \n"
count += 1
</code></pre>
| 0 | 2009-10-06T18:22:32Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played two<br />
He played knick-knack on my shoe<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played three<br />
He played knick-knack on my knee<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played four<br />
He played knick-knack on my door<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played five<br />
He played knick-knack on my hive<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played six<br />
He played knick-knack on my sticks<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played seven<br />
He played knick-knack up in heaven<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played eight<br />
He played knick-knack on my gate<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played nine<br />
He played knick-knack on my spine<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played ten<br />
He played knick-knack once again<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p><strong>This is what I have so far, but it doesn't do what I want it to do. I'm not sure how to phrase the while loop or get it to choose a single word from the list in order.</strong></p>
<pre><code>num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']
z=1
print "This old man, he played",(num)
print "He played knick-knack", (end)
print "Knick-knack paddywhack, give your dog a bone"
print "This old man came rolling home"
</code></pre>
| 0 | 2009-10-06T17:53:17Z | 1,527,279 | <p>first half shamelessly copied from from nailer's answer:</p>
<pre><code># List of rhymes, with each part of the rhyme as another list.
rhymes = ['one','on my thumb'],['two','on my shoe']
for number, position in rhymes:
# print your output in terms of number and position
</code></pre>
| 0 | 2009-10-06T18:29:00Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played two<br />
He played knick-knack on my shoe<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played three<br />
He played knick-knack on my knee<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played four<br />
He played knick-knack on my door<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played five<br />
He played knick-knack on my hive<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played six<br />
He played knick-knack on my sticks<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played seven<br />
He played knick-knack up in heaven<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played eight<br />
He played knick-knack on my gate<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played nine<br />
He played knick-knack on my spine<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played ten<br />
He played knick-knack once again<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p><strong>This is what I have so far, but it doesn't do what I want it to do. I'm not sure how to phrase the while loop or get it to choose a single word from the list in order.</strong></p>
<pre><code>num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']
z=1
print "This old man, he played",(num)
print "He played knick-knack", (end)
print "Knick-knack paddywhack, give your dog a bone"
print "This old man came rolling home"
</code></pre>
| 0 | 2009-10-06T17:53:17Z | 1,527,284 | <p>There is in fact a more Pythonic answer to your homework. Again, I can't give it to you directly, but as well as looking at the <a href="http://docs.python.org/tutorial/controlflow.html" rel="nofollow">loop documentation</a>, you might also want to look at <a href="http://docs.python.org/library/functions.html?highlight=zip#zip" rel="nofollow">zip</a>. You can do a lot in Python without directly using index variables.</p>
| 2 | 2009-10-06T18:29:44Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played two<br />
He played knick-knack on my shoe<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played three<br />
He played knick-knack on my knee<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played four<br />
He played knick-knack on my door<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played five<br />
He played knick-knack on my hive<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played six<br />
He played knick-knack on my sticks<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played seven<br />
He played knick-knack up in heaven<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played eight<br />
He played knick-knack on my gate<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played nine<br />
He played knick-knack on my spine<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p>This old man, he played ten<br />
He played knick-knack once again<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
<p><strong>This is what I have so far, but it doesn't do what I want it to do. I'm not sure how to phrase the while loop or get it to choose a single word from the list in order.</strong></p>
<pre><code>num = ['one','two','three','four','five','six','nine','ten']
end = ['on my thumb','on my shoe','on my knee','on my door','on my hive','on my sticks','up in heaven','on my gate','on my spine','once again']
z=1
print "This old man, he played",(num)
print "He played knick-knack", (end)
print "Knick-knack paddywhack, give your dog a bone"
print "This old man came rolling home"
</code></pre>
| 0 | 2009-10-06T17:53:17Z | 1,527,390 | <p>First, read up on tuples and lists in Python; then read up on the for loop.</p>
<p>I suggest that you use a tuple to store things that go together.</p>
<pre><code># define a list of tuples
lst = [ ("eggs", "an omelet"), ("bread", "a sandwich"), ("sugar", "cookies") ]
for ingredient, food in lst:
print "I need", ingredient, "to make", food + "."
</code></pre>
<p>If you run the above code, here is the output you will get:</p>
<pre><code>I need eggs to make an omelet.
I need bread to make a sandwich.
I need sugar to make cookies.
</code></pre>
<p>This is the Pythonic way to solve this problem. Here is another way, which I don't like as well:</p>
<pre><code>ingredients = ["eggs", "bread", "sugar"]
foods = ["an omelet", "a sandwich", "cookies"]
for i in range(len(ingredients)):
print "I need", ingredients[i], "to make", foods[i] + "."
</code></pre>
<p>This will print the same output as the previous example, but it's harder to work with. You need to make sure that the two lists stay synchronized. The whole "list of tuples" thing may seem weird, but it's actually much easier once you are used to it.</p>
<p>I suggest you get the book <a href="http://rads.stackoverflow.com/amzn/click/0596513984" rel="nofollow">Learning Python</a> and study that; it will teach you a lot and it is very clear.</p>
| 2 | 2009-10-06T18:55:20Z | [
"python"
] |
Python 3.1 RSS Parser? | 1,527,230 | <p>Anyone know of a good feed parser for python 3.1?
I was using feedparser for 2.5 but it doesn't seem to be ported to 3.1 yet, and it's apparently more complicated than just running 2to3.py on it.
Any help?</p>
| 8 | 2009-10-06T18:21:12Z | 1,568,072 | <p>You may take a look at the <a href="http://blog.ianbicking.org/2007/08/02/atom-models/" rel="nofollow">Atom Models</a> blog post by Ian Bicking. He proposes not to use any special "feed parsing" library because Atom and RSS are <strong>just XML</strong> so your model is really an XML tree, not some fancy class. You could try <a href="https://svn.openplans.org/svn/TaggerClient/trunk/taggerclient/atom.py" rel="nofollow">his code</a> under Python 3.</p>
| 4 | 2009-10-14T18:17:43Z | [
"python",
"rss",
"python-3.x",
"feeds"
] |
Python 3.1 RSS Parser? | 1,527,230 | <p>Anyone know of a good feed parser for python 3.1?
I was using feedparser for 2.5 but it doesn't seem to be ported to 3.1 yet, and it's apparently more complicated than just running 2to3.py on it.
Any help?</p>
| 8 | 2009-10-06T18:21:12Z | 1,568,128 | <p>Start porting <code>feedparser</code> to Python 3.1.</p>
| 0 | 2009-10-14T18:27:52Z | [
"python",
"rss",
"python-3.x",
"feeds"
] |
Python 3.1 RSS Parser? | 1,527,230 | <p>Anyone know of a good feed parser for python 3.1?
I was using feedparser for 2.5 but it doesn't seem to be ported to 3.1 yet, and it's apparently more complicated than just running 2to3.py on it.
Any help?</p>
| 8 | 2009-10-06T18:21:12Z | 4,282,679 | <p>I've been working on porting feedparser to Python 3, and I've published <a href="https://github.com/kurtmckee/feedparser/tree/py3/" rel="nofollow">a feedparser/Python 3 development branch</a> at GitHub with the results of that work so far.</p>
<p>There is also an open bug report about porting feedparser to Python 3, but since I'm a new user at StackOverflow, I'm currently limited to just a single link. You'll find the link to the bug report at the top of the GitHub page (it links to code.google.com).</p>
| 1 | 2010-11-26T05:12:43Z | [
"python",
"rss",
"python-3.x",
"feeds"
] |
Python 3.1 RSS Parser? | 1,527,230 | <p>Anyone know of a good feed parser for python 3.1?
I was using feedparser for 2.5 but it doesn't seem to be ported to 3.1 yet, and it's apparently more complicated than just running 2to3.py on it.
Any help?</p>
| 8 | 2009-10-06T18:21:12Z | 17,593,272 | <p><code>feedparser</code> is now available for Python 2.4 up to 3.3- <a href="https://code.google.com/p/feedparser/" rel="nofollow">https://code.google.com/p/feedparser/</a></p>
| 2 | 2013-07-11T12:22:15Z | [
"python",
"rss",
"python-3.x",
"feeds"
] |
Pylucene in Python 2.6 + MacOs Snow Leopard | 1,527,332 | <p>Greetings,
I'm trying to install Pylucene on my 32-bit python running on Snow Leopard. I compiled JCC with success. But I get warnings while making pylucene:</p>
<pre><code>ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__init__.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__wrap01__.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__wrap02__.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__wrap03__.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/functions.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/JArray.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/JObject.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/lucene.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/types.o, file is not of required architecture
ld: warning: in /Developer/SDKs/MacOSX10.4u.sdk/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/JCC-2.3-py2.6-macosx-10.3-fat.egg/libjcc.dylib, file is not of required architecture
ld: warning: in /Developer/SDKs/MacOSX10.4u.sdk/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/JCC-2.3-py2.6-macosx-10.3-fat.egg/libjcc.dylib, file is not of required architecture
build of complete
</code></pre>
<p>Then I try to import lucene:</p>
<pre><code>MacBookPro:~/tmp/trunk python
Python 2.6.3 (r263:75184, Oct 2 2009, 07:56:03)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pylucene
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pylucene
>>> import lucene
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/__init__.py", line 7, in <module>
import _lucene
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/_lucene.so, 2): Symbol not found: __Z8getVMEnvP7_object
Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/_lucene.so
Expected in: flat namespace
in /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/_lucene.so
>>>
</code></pre>
<p>Any hints? </p>
| 0 | 2009-10-06T18:40:29Z | 1,527,722 | <p>Hard to say for sure, but could be as simple as jcc not being installed in the same python location. To troubleshoot I would try using jcc directly first. These commands should work even without lucene:</p>
<pre><code>>>> import jcc
>>> jcc.initVM(jcc.CLASSPATH)
<jcc.JCCEnv object at 0x1004730d8>
>>> jcc._jcc.getVMEnv()
<jcc.JCCEnv object at 0x1004730f0>
</code></pre>
<p>And the module name is lucene, btw, not pylucene.</p>
| 0 | 2009-10-06T19:52:34Z | [
"python",
"osx",
"lucene",
"pylucene",
"jcc"
] |
Pylucene in Python 2.6 + MacOs Snow Leopard | 1,527,332 | <p>Greetings,
I'm trying to install Pylucene on my 32-bit python running on Snow Leopard. I compiled JCC with success. But I get warnings while making pylucene:</p>
<pre><code>ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__init__.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__wrap01__.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__wrap02__.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__wrap03__.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/functions.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/JArray.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/JObject.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/lucene.o, file is not of required architecture
ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/types.o, file is not of required architecture
ld: warning: in /Developer/SDKs/MacOSX10.4u.sdk/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/JCC-2.3-py2.6-macosx-10.3-fat.egg/libjcc.dylib, file is not of required architecture
ld: warning: in /Developer/SDKs/MacOSX10.4u.sdk/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/JCC-2.3-py2.6-macosx-10.3-fat.egg/libjcc.dylib, file is not of required architecture
build of complete
</code></pre>
<p>Then I try to import lucene:</p>
<pre><code>MacBookPro:~/tmp/trunk python
Python 2.6.3 (r263:75184, Oct 2 2009, 07:56:03)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pylucene
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pylucene
>>> import lucene
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/__init__.py", line 7, in <module>
import _lucene
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/_lucene.so, 2): Symbol not found: __Z8getVMEnvP7_object
Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/_lucene.so
Expected in: flat namespace
in /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/lucene-2.9.0-py2.6-macosx-10.6-i386.egg/lucene/_lucene.so
>>>
</code></pre>
<p>Any hints? </p>
| 0 | 2009-10-06T18:40:29Z | 4,857,266 | <p>I had to adjust line 44 to 49 in the Makefile to get pylucene to install correctly:</p>
<pre><code>PREFIX_PYTHON=/my/virtualenv
ANT=ant
PYTHON=$(PREFIX_PYTHON)/bin/python
# add .__main__ to default configuration!
# --arch depends on your architecture of course
JCC=$(PYTHON) -m jcc.__main__ --shared --arch x86_64
NUM_FILES=2
</code></pre>
<p>Hope that helps!</p>
| 1 | 2011-01-31T23:22:16Z | [
"python",
"osx",
"lucene",
"pylucene",
"jcc"
] |
How to do a Post Request in Python? | 1,527,337 | <p>Hi I'm sitting in a Greyhound Bus with Wifi and want to connect a second Device to the Network. But I have to accept an onscreen contract and the device does not have a browser.
To accept the contract the following form has to be accepted. The device has no CURL but all the standard python 2.6. libraries. </p>
<pre><code><form method="POST" name="wifi" id="wifi" action="http://192.168.100.1:5280/">
<input type="image" name="mode_login" value="Agree" src="btn_accept.gif" />
<input type="hidden" name="redirect" value="http://stackoverflow.com/">
</form>
</code></pre>
<p>How would I write a quick python script to accept the contract?</p>
| 6 | 2009-10-06T18:41:36Z | 1,527,561 | <p>I think this should do the trick:</p>
<pre><code>import urllib
data = urllib.urlencode({"mode_login":"Agree","redirect":"http://stackoverflow.com"})
result = urllib.urlopen("http://192.168.100.1:5280/",data).read()
print result
</code></pre>
| 2 | 2009-10-06T19:24:09Z | [
"python",
"networking",
"http-post"
] |
Constant instance variables? | 1,527,395 | <p>I use 'property' to ensure that changes to an objects instance variables are wrapped by methods where I need to. </p>
<p>What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a pid attribute that will frequently be accessed but should not be changed. </p>
<p>What's the most Pythonic way to handle someone attempting to modify that instance variable? </p>
<ul>
<li><p>Simply trust the user not to try and change
something they shouldn't? </p></li>
<li><p>Use property but raise an
exception if the instance variable is
changed? </p></li>
<li><p>Something else?</p></li>
</ul>
| 6 | 2009-10-06T18:56:00Z | 1,527,435 | <p>Maybe you can override <code>__setattr__</code>? In the line of,</p>
<pre><code>def __setattr__(self, name, value):
if self.__dict__.has_key(name):
raise TypeError, 'value is read only'
self.__dict__[name] = value
</code></pre>
| 1 | 2009-10-06T19:02:58Z | [
"python",
"properties",
"instance",
"setter",
"instance-variables"
] |
Constant instance variables? | 1,527,395 | <p>I use 'property' to ensure that changes to an objects instance variables are wrapped by methods where I need to. </p>
<p>What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a pid attribute that will frequently be accessed but should not be changed. </p>
<p>What's the most Pythonic way to handle someone attempting to modify that instance variable? </p>
<ul>
<li><p>Simply trust the user not to try and change
something they shouldn't? </p></li>
<li><p>Use property but raise an
exception if the instance variable is
changed? </p></li>
<li><p>Something else?</p></li>
</ul>
| 6 | 2009-10-06T18:56:00Z | 1,527,475 | <p>Prepend name of the variable with <code>__</code>, and create read-only property, Python will take care of exceptions, and variable itself will be protected from accidental overwrite.</p>
<pre><code>class foo(object):
def __init__(self, bar):
self.__bar = bar
@property
def bar(self):
return self.__bar
f = foo('bar')
f.bar # => bar
f.bar = 'baz' # AttributeError; would have to use f._foo__bar
</code></pre>
| 6 | 2009-10-06T19:08:31Z | [
"python",
"properties",
"instance",
"setter",
"instance-variables"
] |
Constant instance variables? | 1,527,395 | <p>I use 'property' to ensure that changes to an objects instance variables are wrapped by methods where I need to. </p>
<p>What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a pid attribute that will frequently be accessed but should not be changed. </p>
<p>What's the most Pythonic way to handle someone attempting to modify that instance variable? </p>
<ul>
<li><p>Simply trust the user not to try and change
something they shouldn't? </p></li>
<li><p>Use property but raise an
exception if the instance variable is
changed? </p></li>
<li><p>Something else?</p></li>
</ul>
| 6 | 2009-10-06T18:56:00Z | 1,527,494 | <p>Simply trusting the user is not necessarily a bad thing; if you are just writing a quick Python program to be used once and thrown away, you might very well just trust that the user not alter the pid field.</p>
<p>IMHO the most Pythonic way to enforce the read-only field is to use a property that raises an exception on an attempt to set the field.</p>
<p>So, IMHO you have good instincts about this stuff.</p>
| 3 | 2009-10-06T19:11:39Z | [
"python",
"properties",
"instance",
"setter",
"instance-variables"
] |
Constant instance variables? | 1,527,395 | <p>I use 'property' to ensure that changes to an objects instance variables are wrapped by methods where I need to. </p>
<p>What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a pid attribute that will frequently be accessed but should not be changed. </p>
<p>What's the most Pythonic way to handle someone attempting to modify that instance variable? </p>
<ul>
<li><p>Simply trust the user not to try and change
something they shouldn't? </p></li>
<li><p>Use property but raise an
exception if the instance variable is
changed? </p></li>
<li><p>Something else?</p></li>
</ul>
| 6 | 2009-10-06T18:56:00Z | 1,528,413 | <p>Simply use a property and a hidden attribute (prefixed with <em>one</em> underscore).</p>
<p>Simple properties are read-only!</p>
<pre><code>>>> class Test (object):
... @property
... def bar(self):
... return self._bar
...
>>> t = Test()
>>> t._bar = 2
>>> t.bar
2
>>> t.bar = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
</code></pre>
<p>Hiding with double underscore is not used to hide the implementation, but to make sure you don't collide with a subclass' attributes; consider a mixin for example, it has to be very careful!</p>
<p>If you just want to hide the attribute, use a single underscore. And as you see there is no extra magic to add -- if you don't define a set function, your property is just as read-only as the return value of a method.</p>
| 1 | 2009-10-06T22:24:49Z | [
"python",
"properties",
"instance",
"setter",
"instance-variables"
] |
How do I convert Perl's pack 'Nc*' format to struct.pack for Python? | 1,527,534 | <p>I'm trying to convert a Perl script to python, and it uses quite a few different packs. I've been able to figure out the lettering differences in the "templates" for each one, but I'm having an issue with understanding how to handle Perl's lack of length declaration.</p>
<p>example:</p>
<pre><code>pack('Nc*',$some_integer,$long_array_of_integers);
</code></pre>
<p>I don't see an analog for this "*" feature in struct.pack, on Python. Any ideas on how to convert this to Python?</p>
| 5 | 2009-10-06T19:18:42Z | 1,527,651 | <p>Perl's pack is using the '*' character similar to in regular expressions--meaning a wildcard for more of the same. Here, of course, it means more signed ints.</p>
<p>In Python, you'd just loop through the string and concat the pieces:</p>
<pre><code>result = struct.pack('>L', some_integer)
for c in long_array_of_integers:
result += struct.pack('b',c)
</code></pre>
| 1 | 2009-10-06T19:38:13Z | [
"python",
"perl",
"struct",
"pack"
] |
How do I convert Perl's pack 'Nc*' format to struct.pack for Python? | 1,527,534 | <p>I'm trying to convert a Perl script to python, and it uses quite a few different packs. I've been able to figure out the lettering differences in the "templates" for each one, but I'm having an issue with understanding how to handle Perl's lack of length declaration.</p>
<p>example:</p>
<pre><code>pack('Nc*',$some_integer,$long_array_of_integers);
</code></pre>
<p>I don't see an analog for this "*" feature in struct.pack, on Python. Any ideas on how to convert this to Python?</p>
| 5 | 2009-10-06T19:18:42Z | 1,527,660 | <p>How about this?</p>
<pre><code>struct.pack('>I', some_integer) + struct.pack('b'*len(long_array), *long_array)
</code></pre>
| 7 | 2009-10-06T19:39:30Z | [
"python",
"perl",
"struct",
"pack"
] |
How does Google Books work? Are there any open source alternatives? | 1,527,549 | <p>I have been asked to publish a complete book online similar way Google Books does? i.e. it's viewable and printable but not download-able. </p>
<p>Is the process is basically "high quality scanning"? are there any open source solution to "mass generation" of "watermark" on those high quality images. Suppose you have an original image. and when the user views it online, I re-create the image add watermark and some other text on top of the image "on-the-fly" are there such library exist in python off course :)</p>
<p>Any tips? If you have done this before please share.</p>
<p>Thanks</p>
| 0 | 2009-10-06T19:20:46Z | 1,527,572 | <p>Unfortunately Google uses a patented technique for scanning it's books, so you will probably have to stick to traditional methods.</p>
<blockquote>
<p>Google created some seriously nifty
infrared camera technology that
detects the three-dimensional shape
and angle of book pages when the book
is placed in the scanner. This
information is transmitted to the OCR
software, which adjusts for the
distortions and allows the OCR
software to read text more accurately.
No more broken bindings, no more
inefficient glass plates.</p>
</blockquote>
<p>Basically you will need to scan the book using an OCR application (tesseract is good), then I would generate a PDF/image from the scanned text, and finally add the watermark on top. The <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library</a> would seem to be the best tool for this.</p>
| 4 | 2009-10-06T19:26:01Z | [
"python",
"image-processing",
"watermark"
] |
How does Google Books work? Are there any open source alternatives? | 1,527,549 | <p>I have been asked to publish a complete book online similar way Google Books does? i.e. it's viewable and printable but not download-able. </p>
<p>Is the process is basically "high quality scanning"? are there any open source solution to "mass generation" of "watermark" on those high quality images. Suppose you have an original image. and when the user views it online, I re-create the image add watermark and some other text on top of the image "on-the-fly" are there such library exist in python off course :)</p>
<p>Any tips? If you have done this before please share.</p>
<p>Thanks</p>
| 0 | 2009-10-06T19:20:46Z | 1,527,576 | <p>Don't know much about Google Books, but <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library</a> can do watermarking (there's <a href="http://code.activestate.com/recipes/362879/" rel="nofollow">ASPN recipe</a> for that).</p>
| 1 | 2009-10-06T19:26:49Z | [
"python",
"image-processing",
"watermark"
] |
How does Google Books work? Are there any open source alternatives? | 1,527,549 | <p>I have been asked to publish a complete book online similar way Google Books does? i.e. it's viewable and printable but not download-able. </p>
<p>Is the process is basically "high quality scanning"? are there any open source solution to "mass generation" of "watermark" on those high quality images. Suppose you have an original image. and when the user views it online, I re-create the image add watermark and some other text on top of the image "on-the-fly" are there such library exist in python off course :)</p>
<p>Any tips? If you have done this before please share.</p>
<p>Thanks</p>
| 0 | 2009-10-06T19:20:46Z | 1,527,600 | <p>See the <a href="http://ask.slashdot.org/story/09/09/27/199251/Software-To-Flatten-a-Photographed-Book?art%5Fpos=1" rel="nofollow">slashdot</a> question on reproducing Google's photo + laser grid technique.</p>
| 0 | 2009-10-06T19:29:51Z | [
"python",
"image-processing",
"watermark"
] |
How to use JQuery and Django (ajax + HttpResponse)? | 1,527,641 | <p>Suppose I have an AJAX function:</p>
<pre><code>function callpage{
$.ajax({
method:"get",
url:"/abc/",
data:"x="+3
beforeSend:function() {},
success:function(html){
IF HTTPRESPONSE = "1" , ALERT SUCCESS!
}
});
return false;
}
}
</code></pre>
<p>When my "View" executes in Django, I want to return <code>HttpResponse('1')</code> or <code>'0'</code>.</p>
<p>How can I know if it was successful, and then make that alert?</p>
| 4 | 2009-10-06T19:37:05Z | 1,527,666 | <p>The typical workflow is to have the server return a JSON object as text, and then <a href="http://stackoverflow.com/questions/945015/alternatives-to-javascript-eval-for-parsing-json">interpret that object in the javascript</a>. In your case you could return the text {"httpresponse":1} from the server, or use the python json libary to generate that for you. </p>
<p>JQuery has a nice json-reader (I just read the docs, so there might be mistakes in my examples)</p>
<p>Javascript:</p>
<pre><code>$.getJSON("/abc/?x="+3,
function(data){
if (data["HTTPRESPONSE"] == 1)
{
alert("success")
}
});
</code></pre>
<p>Django</p>
<pre><code>#you might need to easy_install this
import json
def your_view(request):
# You can dump a lot of structured data into a json object, such as
# lists and touples
json_data = json.dumps({"HTTPRESPONSE":1})
# json data is just a JSON string now.
return HttpResponse(json_data, mimetype="application/json")
</code></pre>
<p>An alternative View suggested by Issy (cute because it follows the DRY principle)</p>
<pre><code>def updates_after_t(request, id):
response = HttpResponse()
response['Content-Type'] = "text/javascript"
response.write(serializers.serialize("json",
TSearch.objects.filter(pk__gt=id)))
return response
</code></pre>
| 15 | 2009-10-06T19:41:04Z | [
"jquery",
"python",
"django"
] |
How to use JQuery and Django (ajax + HttpResponse)? | 1,527,641 | <p>Suppose I have an AJAX function:</p>
<pre><code>function callpage{
$.ajax({
method:"get",
url:"/abc/",
data:"x="+3
beforeSend:function() {},
success:function(html){
IF HTTPRESPONSE = "1" , ALERT SUCCESS!
}
});
return false;
}
}
</code></pre>
<p>When my "View" executes in Django, I want to return <code>HttpResponse('1')</code> or <code>'0'</code>.</p>
<p>How can I know if it was successful, and then make that alert?</p>
| 4 | 2009-10-06T19:37:05Z | 1,604,495 | <p>Rather than do all this messy, low-level ajax and JSON stuff, consider using the <a href="http://malsup.com/jquery/taconite/" rel="nofollow">taconite plugin</a> for jQuery. You just make the call to the backend and it does the rest. It's well-documented and easy to debug -- especially if you are using Firebug with FF.</p>
| 2 | 2009-10-22T01:04:03Z | [
"jquery",
"python",
"django"
] |
Python 2.6.2, Django 1.0.3, Windows XP, Page not found: / | 1,527,678 | <p>I'm just starting to learn Python and Django and an unable to get the most basic app working. I've setup Python, added python to the Path environment variable, installed Django using install.py script.</p>
<p>I created an app by running the command </p>
<pre><code>django-admin.py startproject my_project
</code></pre>
<p>updated the settings.py file for a database</p>
<pre><code>DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'mysitedb'
</code></pre>
<p>Ran the command</p>
<pre><code>python manage.py syncdb
</code></pre>
<p>And finally, started everything up</p>
<pre><code>python manage.py runserver
</code></pre>
<p>To this point, everything looks to have run successfully. When I got to view <a href="http://localhost:8000/" rel="nofollow">http://localhost:8000/</a> I get the error "Page not found: /"</p>
<p>I originally installed Django version 1.1, but got the same error, so I removed it and tried the older version 1.0.3. Niether work. Any help would be appreciated.</p>
| 3 | 2009-10-06T19:43:58Z | 1,527,757 | <p>It sounds like you need to create some apps for your project and set up the urls. As you are just starting you'd be best following the tutorial right through to get a feel for it all.</p>
| 0 | 2009-10-06T19:58:33Z | [
"python",
"windows",
"django"
] |
Python 2.6.2, Django 1.0.3, Windows XP, Page not found: / | 1,527,678 | <p>I'm just starting to learn Python and Django and an unable to get the most basic app working. I've setup Python, added python to the Path environment variable, installed Django using install.py script.</p>
<p>I created an app by running the command </p>
<pre><code>django-admin.py startproject my_project
</code></pre>
<p>updated the settings.py file for a database</p>
<pre><code>DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'mysitedb'
</code></pre>
<p>Ran the command</p>
<pre><code>python manage.py syncdb
</code></pre>
<p>And finally, started everything up</p>
<pre><code>python manage.py runserver
</code></pre>
<p>To this point, everything looks to have run successfully. When I got to view <a href="http://localhost:8000/" rel="nofollow">http://localhost:8000/</a> I get the error "Page not found: /"</p>
<p>I originally installed Django version 1.1, but got the same error, so I removed it and tried the older version 1.0.3. Niether work. Any help would be appreciated.</p>
| 3 | 2009-10-06T19:43:58Z | 3,937,055 | <p>To complete this question - @artran's answer of changing the port </p>
<pre><code>python manage.py runserver 8001
</code></pre>
<p>will work. </p>
<p>When python runs the server, it automatically uses port 8000 (hence <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8000/</a>). It uses this port as to not tread on the toes of other applications using localhost ports. However, you may still have an application or service running through this port. As such using port 8001 or any other port you may consider free should work.</p>
<p>To repair this in the future, you need to run a program of which can finger all your ports and determine what application is using the :8000 port.</p>
| 2 | 2010-10-14T20:02:36Z | [
"python",
"windows",
"django"
] |
Python 2.6.2, Django 1.0.3, Windows XP, Page not found: / | 1,527,678 | <p>I'm just starting to learn Python and Django and an unable to get the most basic app working. I've setup Python, added python to the Path environment variable, installed Django using install.py script.</p>
<p>I created an app by running the command </p>
<pre><code>django-admin.py startproject my_project
</code></pre>
<p>updated the settings.py file for a database</p>
<pre><code>DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'mysitedb'
</code></pre>
<p>Ran the command</p>
<pre><code>python manage.py syncdb
</code></pre>
<p>And finally, started everything up</p>
<pre><code>python manage.py runserver
</code></pre>
<p>To this point, everything looks to have run successfully. When I got to view <a href="http://localhost:8000/" rel="nofollow">http://localhost:8000/</a> I get the error "Page not found: /"</p>
<p>I originally installed Django version 1.1, but got the same error, so I removed it and tried the older version 1.0.3. Niether work. Any help would be appreciated.</p>
| 3 | 2009-10-06T19:43:58Z | 5,188,887 | <p>You probably have <code>ADMIN_MEDIA_PREFIX = ""</code> in your settings. Django intercepts requests to this url and attempts to serve admin media, thus when you make it an empty string, it will attempt to intercept ALL requests, resulting in nothing working.</p>
| 0 | 2011-03-04T02:04:15Z | [
"python",
"windows",
"django"
] |
exit from ipython | 1,527,689 | <p>I like IPython a lot for working with the python interpreter. However, I continually find myself typing <code>exit</code> to exit, and get prompted "Type exit() to exit." </p>
<p>I know I can type Ctrl-D to exit, but is there a way I can type <code>exit</code> without parentheses and get IPython to exit? </p>
<p><strong>Update</strong>: Thanks to <a href="http://stackoverflow.com/users/17160/nosklo">nosklo</a>, this can be easily done by adding the following line to the main() function in your <code>ipy_user_conf.py</code>:</p>
<pre><code># type exit to exit
ip.ex("type(exit).__repr__ = lambda s: setattr(s.shell, 'exit_now', True) or ''")
</code></pre>
| 10 | 2009-10-06T19:45:21Z | 1,527,713 | <p><code>%exit</code>, or <code>%Exit</code>, if you have confirmation enabled and want to skip it.
You can alias it to e.g. <code>%e</code> by putting <code>execute __IPYTHON__.magic_e = __IPYTHON__.magic_exit</code> in your ipythonrc.</p>
| 3 | 2009-10-06T19:49:54Z | [
"python",
"interpreter",
"ipython"
] |
exit from ipython | 1,527,689 | <p>I like IPython a lot for working with the python interpreter. However, I continually find myself typing <code>exit</code> to exit, and get prompted "Type exit() to exit." </p>
<p>I know I can type Ctrl-D to exit, but is there a way I can type <code>exit</code> without parentheses and get IPython to exit? </p>
<p><strong>Update</strong>: Thanks to <a href="http://stackoverflow.com/users/17160/nosklo">nosklo</a>, this can be easily done by adding the following line to the main() function in your <code>ipy_user_conf.py</code>:</p>
<pre><code># type exit to exit
ip.ex("type(exit).__repr__ = lambda s: setattr(s.shell, 'exit_now', True) or ''")
</code></pre>
| 10 | 2009-10-06T19:45:21Z | 1,528,023 | <pre><code>>>> import sys
>>> class Quitter(object):
... def __repr__(self):
... sys.exit()
...
>>> exit = Quitter()
</code></pre>
<p>You can use it like this:</p>
<pre><code>>>> exit
</code></pre>
<p><strong>EDIT:</strong></p>
<p>I dont use <code>ipython</code> myself, but it seems to have some wierd <code>sys.exit</code> handler.
The solution I found is as follows:</p>
<pre><code>In [1]: type(exit).__repr__ = lambda s: setattr(s.shell, 'exit_now', True) or ''
</code></pre>
<p>Usage:</p>
<pre><code>In [2]: exit
</code></pre>
| 10 | 2009-10-06T20:48:33Z | [
"python",
"interpreter",
"ipython"
] |
exit from ipython | 1,527,689 | <p>I like IPython a lot for working with the python interpreter. However, I continually find myself typing <code>exit</code> to exit, and get prompted "Type exit() to exit." </p>
<p>I know I can type Ctrl-D to exit, but is there a way I can type <code>exit</code> without parentheses and get IPython to exit? </p>
<p><strong>Update</strong>: Thanks to <a href="http://stackoverflow.com/users/17160/nosklo">nosklo</a>, this can be easily done by adding the following line to the main() function in your <code>ipy_user_conf.py</code>:</p>
<pre><code># type exit to exit
ip.ex("type(exit).__repr__ = lambda s: setattr(s.shell, 'exit_now', True) or ''")
</code></pre>
| 10 | 2009-10-06T19:45:21Z | 4,515,356 | <p>At least in IPython 0.10, you should be able to set <strong>IPYTHON</strong>.rc.confirm_exit = False</p>
| 0 | 2010-12-23T02:17:58Z | [
"python",
"interpreter",
"ipython"
] |
Get records before and after current selection in Django query | 1,527,710 | <p>It sounds like an odd one but it's a really simple idea. I'm trying to make a simple Flickr for a website I'm building. This specific problem comes when I want to show a single photo (from my <code>Photo</code> model) on the page but I also want to show the image before it in the stream and the image after it.</p>
<p>If I were only sorting these streams by date, or was only sorting by ID, that might be simpler... But I'm not. I want to allow the user to sort and filter by a whole variety of methods. The sorting is simple. I've done that and I have a result-set, containing 0-many <code>Photo</code>s.</p>
<p>If I want a single <code>Photo</code>, I start off with that filtered/sorted/etc stream. From it I need to get the current <code>Photo</code>, the <code>Photo</code> before it and the <code>Photo</code> after it.</p>
<p>Here's what I'm looking at, at the moment.</p>
<pre><code>prev = None
next = None
photo = None
for i in range(1, filtered_queryset.count()):
if filtered_queryset[i].pk = desired_pk:
if i>1: prev = filtered_queryset[i-1]
if i<filtered_queryset.count(): next = filtered_queryset[i+1]
photo = filtered_queryset[i]
break
</code></pre>
<p>It just seems disgustingly messy. And inefficient. Oh my lord, so inefficient. Can anybody improve on it though?</p>
<p>Django queries are late-binding, so it would be nice to make use of that though I guess that might be impossible given my horrible restrictions.</p>
<p>Edit: it occurs to me that I can just chuck in some SQL to re-filter queryset. If there's a way of selecting something with its two (or one, or zero) closest neighbours with SQL, I'd love to know!</p>
| 1 | 2009-10-06T19:48:59Z | 1,528,013 | <p>I see the following possibilities:</p>
<ol>
<li><p>Your URL query parameters contain the sort/filtering information and some kind of 'item number', which is the item number <strong>within</strong> your filtered queryset. This is the simple case - previous and next are item number minus one and plus one respectively (plus some bounds checking)</p></li>
<li><p>You want the URL to be a permalink, and contain the photo primary key (or some unique ID). In this case, you are presumably storing the sorting/filtering in:</p>
<ul>
<li>in the URL as query parameters. In this case you don't have true permalinks, and so you may as well stick the item number in the URL as well, getting you back to option 1.</li>
<li>hidden fields in the page, and using POSTs for links instead of normal links. In this case, stick the item number in the hidden fields as well.</li>
<li>session data/cookies. This will break if the user has two tabs open with different sorts/filtering applied, but that might be a limitation you don't mind - after all, you have envisaged that they will probably just be using one tab and clicking through the list. In this case, store the item number in the session as well. You might be able to do something clever to "namespace" the item number for the case where they have multiple tabs open.</li>
</ul></li>
</ol>
<p>In short, store the item number wherever you are storing the filtering/sorting information.</p>
| 1 | 2009-10-06T20:44:43Z | [
"python",
"sql",
"django",
"django-models",
"django-queryset"
] |
Get records before and after current selection in Django query | 1,527,710 | <p>It sounds like an odd one but it's a really simple idea. I'm trying to make a simple Flickr for a website I'm building. This specific problem comes when I want to show a single photo (from my <code>Photo</code> model) on the page but I also want to show the image before it in the stream and the image after it.</p>
<p>If I were only sorting these streams by date, or was only sorting by ID, that might be simpler... But I'm not. I want to allow the user to sort and filter by a whole variety of methods. The sorting is simple. I've done that and I have a result-set, containing 0-many <code>Photo</code>s.</p>
<p>If I want a single <code>Photo</code>, I start off with that filtered/sorted/etc stream. From it I need to get the current <code>Photo</code>, the <code>Photo</code> before it and the <code>Photo</code> after it.</p>
<p>Here's what I'm looking at, at the moment.</p>
<pre><code>prev = None
next = None
photo = None
for i in range(1, filtered_queryset.count()):
if filtered_queryset[i].pk = desired_pk:
if i>1: prev = filtered_queryset[i-1]
if i<filtered_queryset.count(): next = filtered_queryset[i+1]
photo = filtered_queryset[i]
break
</code></pre>
<p>It just seems disgustingly messy. And inefficient. Oh my lord, so inefficient. Can anybody improve on it though?</p>
<p>Django queries are late-binding, so it would be nice to make use of that though I guess that might be impossible given my horrible restrictions.</p>
<p>Edit: it occurs to me that I can just chuck in some SQL to re-filter queryset. If there's a way of selecting something with its two (or one, or zero) closest neighbours with SQL, I'd love to know!</p>
| 1 | 2009-10-06T19:48:59Z | 1,528,122 | <p>You could try the following:</p>
<ol>
<li>Evaluate the filtered/sorted queryset and get the list of photo ids, which you hold in the session. These ids all match the filter/sort criteria.</li>
<li>Keep the current index into this list in the session too, and update it when the user moves to the previous/next photo. Use this index to get the prev/current/next ids to use in showing the photos.</li>
<li>When the filtering/sorting criteria change, re-evaluate the list and set the current index to a suitable value (e.g. 0 for the first photo in the new list).</li>
</ol>
| 1 | 2009-10-06T21:11:34Z | [
"python",
"sql",
"django",
"django-models",
"django-queryset"
] |
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper python regex to achieve that.</p>
| 0 | 2009-10-06T20:45:35Z | 1,528,055 | <p>You need a lot of escapes in your regular expression since <code>{</code>, <code>}</code> and <code>|</code> are special characters in them. A first step to extract the relevant parts of the string would be this:</p>
<pre><code>regex = re.compile(r'\{\{(.*?)\|(.*?)(?:\|(.*?))?\}\}')
regex.findall(line)
</code></pre>
<p>For the example this gives:</p>
<pre><code>[('bla', '123', '456'), ('bli', '789', '123'), ('blu', '789', '')]
</code></pre>
<p>Then you can continue with converting strings with digits into integers and removing empty strings like for the last match.</p>
| 1 | 2009-10-06T20:54:27Z | [
"python",
"regex"
] |
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper python regex to achieve that.</p>
| 0 | 2009-10-06T20:45:35Z | 1,528,061 | <pre><code>>>> re.findall(' {{(\w+)\|(\w+)(?:\|(\w+))?}} ', s)
[('bla', '123', '456'), ('bli', '789', '123'), ('blu', '789', '')]
</code></pre>
<p>if you still want number there you'd need to iterate over the output and convert it to the integer with <code>int</code>.</p>
| 1 | 2009-10-06T20:56:55Z | [
"python",
"regex"
] |
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper python regex to achieve that.</p>
| 0 | 2009-10-06T20:45:35Z | 1,528,087 | <pre><code>[re.split('\|', i) for i in re.findall("{{(.*?)}}", str)]
</code></pre>
<p>Returns:</p>
<pre><code>[['bla', '123', '456'], ['bli', '789', '123'], ['blu', '789']]
</code></pre>
<p>This method works regardless of the number of elements in the {{ }} blocks.</p>
| 0 | 2009-10-06T21:02:03Z | [
"python",
"regex"
] |
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper python regex to achieve that.</p>
| 0 | 2009-10-06T20:45:35Z | 1,528,088 | <p>To get the exact output you wrote, you need a regex and a split:</p>
<pre><code>import re
map(lambda s: s.split("|"), re.findall(r"\{\{([^}]*)\}\}", s))
</code></pre>
<p>To get it with the numbers converted, do this:</p>
<pre><code>toint = lambda x: int(x) if x.isdigit() else x
[map(toint, p.split("|")) for p in re.findall(r"\{\{([^}]*)\}\}", s)]
</code></pre>
| 0 | 2009-10-06T21:02:20Z | [
"python",
"regex"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.