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 list |
|---|---|---|---|---|---|---|---|---|---|
Populating a list/array by index in Python? | 869,778 | <p>Is this possible:</p>
<pre><code>myList = []
myList[12] = 'a'
myList[22] = 'b'
myList[32] = 'c'
myList[42] = 'd'
</code></pre>
<p>When I try, I get:</p>
<pre><code># IndexError: list assignment index out of range #
</code></pre>
| 20 | 2009-05-15T16:57:25Z | 869,819 | <p>Not without populating the other locations in the list with something (like <code>None</code> or an empty string). Trying to insert an element into a list using the code you wrote would result in an <code>IndexError</code>.</p>
<p>There's also <code>mylist.insert</code>, but this code:</p>
<pre><code>myList.insert(12,'a')
</code></pre>
<p>would just insert 'a' at the first unoccupied location in the list (which would be 0 using your example).</p>
<p>So, as I said, there has to be something in the list at indexes 0-11 before you can insert something at <code>myList[12]</code>.</p>
| 2 | 2009-05-15T17:03:32Z | [
"python",
"list"
] |
Populating a list/array by index in Python? | 869,778 | <p>Is this possible:</p>
<pre><code>myList = []
myList[12] = 'a'
myList[22] = 'b'
myList[32] = 'c'
myList[42] = 'd'
</code></pre>
<p>When I try, I get:</p>
<pre><code># IndexError: list assignment index out of range #
</code></pre>
| 20 | 2009-05-15T16:57:25Z | 869,894 | <p>If you don't know the size of the list ahead of time, you could use try/except and then Extend the list in the except:</p>
<pre><code>L = []
def add(i, s):
try:
L[i] = s
except IndexError:
L.extend([None]*(i-len(L)+1))
L[i] = s
add(12, 'a')
add(22, 'b')
</code></pre>
<p><strong>----- Update ---------------------------------------------</strong><br>
Per tgray's comment: If it is likely that your code will throw an Exception <em>most of the time</em>, you should check the length of the List every time, and avoid the Exceptions:</p>
<pre><code>L = []
def add(i, s):
size = len(L)
if i >= size:
L.extend([None]*(i-size+1))
L[i] = s
</code></pre>
| 2 | 2009-05-15T17:19:36Z | [
"python",
"list"
] |
Populating a list/array by index in Python? | 869,778 | <p>Is this possible:</p>
<pre><code>myList = []
myList[12] = 'a'
myList[22] = 'b'
myList[32] = 'c'
myList[42] = 'd'
</code></pre>
<p>When I try, I get:</p>
<pre><code># IndexError: list assignment index out of range #
</code></pre>
| 20 | 2009-05-15T16:57:25Z | 869,901 | <p>Here's a quick list wrapper that will auto-expand your list with zeros if you attempt to assign a value to a index past it's length.</p>
<pre><code>class defaultlist(list):
def __setitem__(self, index, value):
size = len(self)
if index >= size:
self.extend(0 for _ in range(size, index + 1))
list.__setitem__(self, index, value)
</code></pre>
<p>Now you can do this:</p>
<pre><code>>>> a = defaultlist([1,2,3])
>>> a[1] = 5
[1,5,3]
>>> a[5] = 10
[1,5,3,0,0,10]
</code></pre>
| 13 | 2009-05-15T17:20:46Z | [
"python",
"list"
] |
Populating a list/array by index in Python? | 869,778 | <p>Is this possible:</p>
<pre><code>myList = []
myList[12] = 'a'
myList[22] = 'b'
myList[32] = 'c'
myList[42] = 'd'
</code></pre>
<p>When I try, I get:</p>
<pre><code># IndexError: list assignment index out of range #
</code></pre>
| 20 | 2009-05-15T16:57:25Z | 20,031,992 | <p>Just in case someone needs, I figured out a soluction for my problem, I needed to <strong>calc a lot of factorials</strong>, some of them <strong>could be repeated</strong>, so here is my solution:</p>
<pre><code>factorials = {}
def calcFact(v):
try:
return factorials[v]
except KeyError:
factorials[v] = math.factorial(v)
return factorials[v]
</code></pre>
<p><strong>Testcase:</strong></p>
<pre><code>calcFact(99000)
calcFact(90900)
calcFact(90090)
calcFact(90009)
calcFact(90009) #repeated
calcFact(90009) #repeated
</code></pre>
<p><strong>Results:</strong></p>
<blockquote>
<p>Repeating mathematical calc: <strong>1.576</strong> s</p>
<p>Using the above code (a list to store repeated values): <strong>1.011</strong> s</p>
</blockquote>
| 1 | 2013-11-17T14:42:52Z | [
"python",
"list"
] |
Loop backwards using indices in Python? | 869,885 | <p>I am trying to loop from 100 to 0. How do I do this in Python?</p>
<p><code>for i in range (100,0)</code> doesn't work.</p>
| 92 | 2009-05-15T17:17:06Z | 869,902 | <p>Try <code>range(100,-1,-1)</code>, the 3rd argument being the increment to use (documented <a href="https://docs.python.org/library/functions.html#range">here</a>).</p>
| 146 | 2009-05-15T17:20:46Z | [
"python",
"loops"
] |
Loop backwards using indices in Python? | 869,885 | <p>I am trying to loop from 100 to 0. How do I do this in Python?</p>
<p><code>for i in range (100,0)</code> doesn't work.</p>
| 92 | 2009-05-15T17:17:06Z | 869,905 | <pre><code>for i in range(100, -1, -1)
</code></pre>
<p>and some slightly longer (and slower) solution:</p>
<pre><code>for i in reversed(range(101))
for i in range(101)[::-1]
</code></pre>
| 13 | 2009-05-15T17:21:39Z | [
"python",
"loops"
] |
Loop backwards using indices in Python? | 869,885 | <p>I am trying to loop from 100 to 0. How do I do this in Python?</p>
<p><code>for i in range (100,0)</code> doesn't work.</p>
| 92 | 2009-05-15T17:17:06Z | 869,914 | <p>In my opinion, this is the most readable:</p>
<pre><code>for i in reversed(xrange(101)):
print i,
</code></pre>
| 103 | 2009-05-15T17:24:09Z | [
"python",
"loops"
] |
Loop backwards using indices in Python? | 869,885 | <p>I am trying to loop from 100 to 0. How do I do this in Python?</p>
<p><code>for i in range (100,0)</code> doesn't work.</p>
| 92 | 2009-05-15T17:17:06Z | 1,750,432 | <p>Generally in Python, you can use negative indices to start from the back:</p>
<pre><code>numbers = [10, 20, 30, 40, 50]
for i in xrange(len(numbers)):
print numbers[-i - 1]
</code></pre>
<p>Result:</p>
<pre><code>50
40
30
20
10
</code></pre>
| 8 | 2009-11-17T17:26:02Z | [
"python",
"loops"
] |
Loop backwards using indices in Python? | 869,885 | <p>I am trying to loop from 100 to 0. How do I do this in Python?</p>
<p><code>for i in range (100,0)</code> doesn't work.</p>
| 92 | 2009-05-15T17:17:06Z | 6,807,504 | <p>Another solution:</p>
<pre><code>z = 10
for x in range (z):
y = z-x
print y
</code></pre>
<p>Result:</p>
<pre><code>10
9
8
7
6
5
4
3
2
1
</code></pre>
<p>Tip:
If you are using this method to count back indices in a list, you will want to -1 from the 'y' value, as your list indices will begin at 0.</p>
| 3 | 2011-07-24T14:48:06Z | [
"python",
"loops"
] |
Loop backwards using indices in Python? | 869,885 | <p>I am trying to loop from 100 to 0. How do I do this in Python?</p>
<p><code>for i in range (100,0)</code> doesn't work.</p>
| 92 | 2009-05-15T17:17:06Z | 24,374,584 | <p><code>for var in range(10,-1,-1)</code> works</p>
| 1 | 2014-06-23T20:15:58Z | [
"python",
"loops"
] |
Loop backwards using indices in Python? | 869,885 | <p>I am trying to loop from 100 to 0. How do I do this in Python?</p>
<p><code>for i in range (100,0)</code> doesn't work.</p>
| 92 | 2009-05-15T17:17:06Z | 24,617,809 | <p>I tried this in one of the codeacademy exercises (reversing chars in a string without using reversed nor :: -1)</p>
<pre><code>def reverse(text):
chars= []
l = len(text)
last = l-1
for i in range (l):
chars.append(text[last])
last-=1
result= ""
for c in chars:
result += c
return result
print reverse('hola')
</code></pre>
| 0 | 2014-07-07T18:55:05Z | [
"python",
"loops"
] |
Loop backwards using indices in Python? | 869,885 | <p>I am trying to loop from 100 to 0. How do I do this in Python?</p>
<p><code>for i in range (100,0)</code> doesn't work.</p>
| 92 | 2009-05-15T17:17:06Z | 30,311,352 | <p>Short and sweet. This was my solution when doing codeAcademy course. Prints a string in rev order. </p>
<pre><code>def reverse(text):
string = ""
for i in range(len(text)-1,-1,-1):
string += text[i]
return string
</code></pre>
| 2 | 2015-05-18T19:27:33Z | [
"python",
"loops"
] |
Loop backwards using indices in Python? | 869,885 | <p>I am trying to loop from 100 to 0. How do I do this in Python?</p>
<p><code>for i in range (100,0)</code> doesn't work.</p>
| 92 | 2009-05-15T17:17:06Z | 32,716,115 | <pre><code>a = 10
for i in sorted(range(a), reverse=True):
print i
</code></pre>
| 0 | 2015-09-22T11:50:33Z | [
"python",
"loops"
] |
BWSplitView and PyObjc | 869,912 | <p>I'm trying to use Brandon Walkin's BWSplitView from BWToolkit in a Cocoa PyObjc project. When I run the project I get the following error message:</p>
<pre><code>NSInvalidUnarchiveOperationException - *** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (BWSplitView)
</code></pre>
<p>Does this mean his toolkit is incompatible with a PyObc project, so I should just use the default interface builder views? BWToolkit seems pretty much perfect for my program, and I plan to use it elsewhere in my interface.</p>
| 3 | 2009-05-15T17:24:04Z | 869,993 | <p>I've fixed this using the following steps:<br />
1. Download and install <a href="http://github.com/jrydberg/pyobjc-bwtoolkitframework/tree/master" rel="nofollow">http://github.com/jrydberg/pyobjc-bwtoolkitframework/tree/master</a><br />
2. Ensure you have BWToolkit.framework installed in /System/Library/Frameworks (this can be done by redownloading BWToolkit and copying the folder across)<br />
3. Use import BWToolkitFramework in main.py</p>
| 0 | 2009-05-15T17:42:51Z | [
"python",
"cocoa",
"pyobjc",
"bwtoolkit"
] |
BWSplitView and PyObjc | 869,912 | <p>I'm trying to use Brandon Walkin's BWSplitView from BWToolkit in a Cocoa PyObjc project. When I run the project I get the following error message:</p>
<pre><code>NSInvalidUnarchiveOperationException - *** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (BWSplitView)
</code></pre>
<p>Does this mean his toolkit is incompatible with a PyObc project, so I should just use the default interface builder views? BWToolkit seems pretty much perfect for my program, and I plan to use it elsewhere in my interface.</p>
| 3 | 2009-05-15T17:24:04Z | 870,039 | <p>I suspect that you got that error because you had a BWSplitView in a nib/xib file that you were attempting to load. In order to unarchive the objects in a nib file, the runtime needs to be able to create instances of the archived classes (e.g. BWSplitView). The exception that's being thrown is because BWSplitView isn't available to the runtime. In an Objective-C app you would link to the BWToolkit framework and the dynamic linker would do the work of making BWSplitView available to the runtime. In a PyObjC app, you have to explicitly import classes that you want available to the runtime (that aren't linked behind the scenes for you, such as the Cocoa classes). Fortunately, BWToolkit has a bridge support file so you can import it directly (assuming it's in a standard framework location such as /Library/Frameworks). If you need to load a framework that does not have a bridge support file, you can use <code>objc.loadBundle</code> and then use <code>NSClassFromString</code> to get a class object.</p>
<p>On a side note, /System/Library/Frameworks is reserved for Apple-supplied system frameworks. You should not put third-party frameworks in that folder as Apple may wipe that folder at a system update (unlikely but possible). Thrid-party frameworks that are made available to all users on a system should be put in /Library/Frameworks, user-specific frameworks similarly in ~/Library/Frameworks and application specific frameworks in Contents/Frameworks, where within the application's app bundle.</p>
| 5 | 2009-05-15T17:51:02Z | [
"python",
"cocoa",
"pyobjc",
"bwtoolkit"
] |
BWSplitView and PyObjc | 869,912 | <p>I'm trying to use Brandon Walkin's BWSplitView from BWToolkit in a Cocoa PyObjc project. When I run the project I get the following error message:</p>
<pre><code>NSInvalidUnarchiveOperationException - *** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (BWSplitView)
</code></pre>
<p>Does this mean his toolkit is incompatible with a PyObc project, so I should just use the default interface builder views? BWToolkit seems pretty much perfect for my program, and I plan to use it elsewhere in my interface.</p>
| 3 | 2009-05-15T17:24:04Z | 1,768,125 | <p>We had a similar message:</p>
<pre><code>*** Terminating app due to uncaught exception âNSInvalidUnarchiveOperationExceptionâ, reason: â*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (MKMapView)â
</code></pre>
<p>In our case it was due to a stray entry in the "Framework Search Paths" setting under the target's build settings. When that entry was cleared, the problem went away.</p>
| 0 | 2009-11-20T03:20:31Z | [
"python",
"cocoa",
"pyobjc",
"bwtoolkit"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 870,003 | <p>In the Idle editor, you can just select the lines you want to indent and hit Tab.</p>
<p>I should note that this doesn't actually insert any tabs into your source, just spaces.</p>
| 3 | 2009-05-15T17:43:58Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 870,011 | <p>In IDLE I just use ctrl+] and ctrl+[ on a block of code.</p>
| 2 | 2009-05-15T17:46:27Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 870,030 | <p>Use VI and never program the same again. :^)</p>
| 1 | 2009-05-15T17:49:46Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 870,038 | <p>In TextMate, just highlight the lines you want to indent and use:</p>
<p><br />â + [
<br />or
<br />â + ] </p>
<p>To move the text in the appropriate direction.</p>
| 0 | 2009-05-15T17:50:59Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 870,910 | <p>PyDev, which you can find at <a href="http://pydev.sourceforge.net/" rel="nofollow">http://pydev.sourceforge.net/</a> has a "Code Formatter". It also has autoindent feature. It is a plugin for Eclipse which is freely available for Mac too.</p>
<p>Another option would be <a href="http://code.google.com/p/macvim/" rel="nofollow">http://code.google.com/p/macvim/</a> if you are familiar or invest time for Vim, which has lots of autoindent features not just for Python.</p>
<p>But, do not forget that, in Python, indentation changes the meaning of the program unlike C family languages. For example for C or C#, a utility program can beautify the code according to the "{" and "}" symbols. But, in Python that would be ambiguous since a program can not format the following:</p>
<pre><code>#Say we wrote the following and expect it to be formatted.
a = 1
for i in range(5):
print i
a = a + i
print a
</code></pre>
<p>Do you expect it to be</p>
<pre><code>a = 1
for i in range(5):
print i
a = a + i
print a #Will print 5
</code></pre>
<p>or</p>
<pre><code>a = 1
for i in range(5):
print i
a = a + i
print a #Will print 11
</code></pre>
<p>which are two different snippets.</p>
| 0 | 2009-05-15T21:15:21Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 871,192 | <p>[Funny ;-)] Dude, I told you that you would need one developer less if you had this new keyboard model
<img src="http://img22.imageshack.us/img22/7318/pythonkeyboard.jpg" alt="Pythonic keyboard" /></p>
| 1 | 2009-05-15T22:53:41Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 871,231 | <p>With emacs there's Python mode. In that mode you highlight and do:</p>
<pre><code>ctrl-c >
ctrl-c <
</code></pre>
| 2 | 2009-05-15T23:10:04Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 871,269 | <p>Vim: switch to visual mode, select the block, use > to indent (or < to unindent).</p>
<p>See also: <a href="http://stackoverflow.com/questions/235839/how-do-i-indent-multiple-lines-quickly-in-vi">http://stackoverflow.com/questions/235839/how-do-i-indent-multiple-lines-quickly-in-vi</a></p>
| 1 | 2009-05-15T23:35:32Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 871,294 | <p>If you are using vim there is a plugin specifically for this: <a href="http://vim.sourceforge.net/scripts/script.php?script%5Fid=30" rel="nofollow">Python_fn.vim</a> </p>
<p>It provides useful python functions (and menu equivalents):</p>
<pre><code>]t -- Jump to beginning of block
]e -- Jump to end of block
]v -- Select (Visual Line Mode) block
]< -- Shift block to left
]> -- Shift block to right
]# -- Comment selection
]u -- Uncomment selection
]c -- Select current/previous class
]d -- Select current/previous function
]<up> -- Jump to previous line with the same/lower indentation
]<down> -- Jump to next line with the same/lower indentation
</code></pre>
| 1 | 2009-05-15T23:46:59Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 871,329 | <p>I don't know what wacky planets everyone is coming from, but in most editors that don't date back to the stone age, indenting blocks of code typically only requires that a block of text be selected and Tab be pressed. On the flip side, Shift+Tab usually UNdents the block.</p>
<p>This is true for Visual Studio, Notepad2, e, Textmate, Slickedit, #Develop, etc. etc. etc.</p>
<p>If you're not doing large multi-file projects, I strongly recommend <a href="http://www.flos-freeware.ch/notepad2.html">Notepad2</a>. Its a very lightweight, free, easy-to-use notepad replacement with just enough code-centric features (line numbers, indentation guides, code highlighting, etc.)</p>
| 5 | 2009-05-16T00:18:29Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 871,482 | <p>In Komodo the Tab and Shift Tab both work as expected to indent and unindent large blocks of code.</p>
| 0 | 2009-05-16T01:52:52Z | [
"python",
"user-interface",
"indentation"
] |
Indentation in python GUI | 869,975 | <p>As i write code in python and suddenly feel like adding a new block in front of the code i have already written.... the indentation of the complete code is affected..
it is very tedious process to move to each line and change the indentation...is there any way to do auto indent or something...</p>
<p>eg:</p>
<pre><code>def somefunction:
x =5
return x
</code></pre>
<p>if i want to add a contrl block</p>
<p>eg:</p>
<pre><code>def somefunction:
if True:
x =5
return x
return 0
</code></pre>
<p>this small change of adding a control block took a lot of tab work....</p>
<p>is there a shortcut or sumthing to do this easily?</p>
| 2 | 2009-05-15T17:39:27Z | 871,562 | <p>In vim, you can enter:</p>
<p><code>>></code></p>
<p>to indent a line. If you enter:</p>
<p><code>5>></code></p>
<p>you indent the 5 lines at and below the cursor. <code>5<<</code> does the reverse.</p>
| 0 | 2009-05-16T02:54:09Z | [
"python",
"user-interface",
"indentation"
] |
Help translation PYTHON to VB.NET | 870,116 | <p>I am coding an application in VB.NET that sends sms.</p>
<p>Would you please post <strong>PYTHON->VB.NET</strong>
translation of this code and/or guidelines?</p>
<p>Thanks in advance!!!</p>
<pre><code>import threading
class MessageThread(threading.Thread):
def __init__(self,msg,no):
threading.Thread.__init__(self)
self.msg = msg # text message
self.no = no # mobile number
def run(self):
# function that sends "msg" to "no"
send_msg(msg,no)
# records of users are retrived from database
# and (msg,no) tuples are generated
records = [(msg1,no1),(msg2, no2),...(msgN,noN)]
thread_list = []
for each in records:
t = MessageThread(each)
thread_list.append(t)
for each in thread_list:
each.start()
for each in thread_list:
each.join()
</code></pre>
| 0 | 2009-05-15T18:13:27Z | 870,175 | <p>This is IronPython-code ("Python for .NET"), hence the source code uses the .NET-Framework just as VB and all classes (even <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx" rel="nofollow">System.Threading.Thread</a>) can be used in the same way shown.</p>
<p>Some tips:</p>
<p><code>MessageThread</code> derives from <code>Thread</code>, <code>msg</code> and <code>no</code> must be declared as class variables, <code>__init__</code> is the constructor, the <code>self</code>-parameter in the member functions isn't transcoded to VB (just leave it out). Use a <code>List<Thread></code> for <code>thread_list</code> and define a little structure for the tuples in <code>records</code>.</p>
| 0 | 2009-05-15T18:31:12Z | [
"python",
"vb.net",
"multithreading",
"translation"
] |
Help translation PYTHON to VB.NET | 870,116 | <p>I am coding an application in VB.NET that sends sms.</p>
<p>Would you please post <strong>PYTHON->VB.NET</strong>
translation of this code and/or guidelines?</p>
<p>Thanks in advance!!!</p>
<pre><code>import threading
class MessageThread(threading.Thread):
def __init__(self,msg,no):
threading.Thread.__init__(self)
self.msg = msg # text message
self.no = no # mobile number
def run(self):
# function that sends "msg" to "no"
send_msg(msg,no)
# records of users are retrived from database
# and (msg,no) tuples are generated
records = [(msg1,no1),(msg2, no2),...(msgN,noN)]
thread_list = []
for each in records:
t = MessageThread(each)
thread_list.append(t)
for each in thread_list:
each.start()
for each in thread_list:
each.join()
</code></pre>
| 0 | 2009-05-15T18:13:27Z | 870,303 | <p>This code creates a thread for every msg/no tuple and calls sendmsg. The first "for each ... each.start()" starts the thread (which only calls sendmsg) and the second "for each ... each.join()" waits for each thread to complete. Depending on the number of records, this could create a significant number of threads (what if you were sending 1000 SMS records) which is not necessarily efficient although it is asynchronous.</p>
<p>The code is relatively simple and pythonic, whereas for .NET you would probably want to use a <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool%28VS.80%29.aspx" rel="nofollow">ThreadPool</a> or <a href="http://msdn.microsoft.com/en-us/library/8xs8549b.aspx" rel="nofollow">BackgroundWorker</a> to do the sendmsg calls. You will need to create a .NET class that is equivalent to the tuple (msg,no), and probably put the sendmsg() function in the class itself. Then create .NET code to load the messages (which is not shown in the Python code). Typically you would use a generic List<> to hold the SMS records as well. Then the ThreadPool would queue all of the items and call sendmsg.</p>
<p>If you are trying to keep the code as equivalent to the original Python, then you should look at <a href="http://www.ironpython.com/" rel="nofollow">IronPython</a>.</p>
<p>(The underscore in sendmsg caused the text to use italics, so I removed the underscore in my response.)</p>
| 1 | 2009-05-15T19:00:01Z | [
"python",
"vb.net",
"multithreading",
"translation"
] |
Scheduling a JasperServer Report via SOAP using Python | 870,188 | <p>I was able to figure out how to run reports, download files, list folders, etc. on a JasperServer using Python with SOAPpy and xml.dom minidom.</p>
<p>Here's an example execute report request, which works:</p>
<pre><code>repositoryURL = 'http://user@pass:myjasperserver:8080/jasperserver/services/repository'
repositoryWSDL = repositoryURL + '?wsdl'
server = SOAPProxy(repositoryURL, repositoryWSDL)
print server._ns(repositoryWSDL).runReport('''
<request operationName="runReport" locale="en">
<argument name="RUN_OUTPUT_FORMAT">PDF</argument>
<resourceDescriptor name="" wsType="" uriString="/reports/baz">
<label>null</label>
<parameter name="foo">bar</parameter>
</resourceDescriptor>
</request>
''')
</code></pre>
<p>However, I'm having trouble formatting my requests properly for the "ReportScheduler" section of the server. I've consulted the documentation located here (<a href="http://jasperforge.org/espdocs/docsbrowse.php?id=74&type=docs&group%5Fid=112&fid=305">http://jasperforge.org/espdocs/docsbrowse.php?id=74&type=docs&group_id=112&fid=305</a>), and have tried model my requests after their samples with no luck (see page 27).</p>
<p>Here are two examples that I've tried, which both return the same error:</p>
<pre><code>schedulingURL = 'http://user@pass:myjasperserver:8080/jasperserver/services/ReportScheduler'
schedulingWSDL = schedulingURL + '?wsdl'
server = SOAPProxy(schedulingURL, schedulingWSDL)
# first request
print server._ns(schedulingWSDL).scheduleJob('''
<request operationName="scheduleJob" locale="en">
<job>
<reportUnitURI>/reports/baz</reportUnitURI>
<label>baz</label>
<description>baz</description>
<simpleTrigger>
<startDate>2009-05-15T15:45:00.000Z</startDate>
<occurenceCount>1</occurenceCount>
</simpleTrigger>
<baseOutputFilename>baz</baseOutputFilename>
<outputFormats>
<outputFormats>PDF</outputFormats>
</outputFormats>
<repositoryDestination>
<folderURI>/reports_generated</folderURI>
<sequentialFilenames>true</sequentialFilenames>
<overwriteFiles>false</overwriteFiles>
</repositoryDestination>
<mailNotification>
<toAddresses>my@email.com</toAddresses>
<subject>test</subject>
<messageText>test</messageText>
<resultSendType>SEND_ATTACHMENT</resultSendType>
</mailNotification>
</job>
</request>''')
# second request (trying different format here)
print server._ns(schedulingWSDL).scheduleJob('''
<ns1:scheduleJob soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://www.jasperforge.org/jasperserver/ws">
<job xsi:type="ns1:Job">
<reportUnitURI xsi:type="xsd:string">/reports/baz</reportUnitURI>
<username xsi:type="xsd:string" xsi:nil="true"/>
<label xsi:type="xsd:string">baz</label>
<description xsi:type="xsd:string">baz</description>
<simpleTrigger xsi:type="ns1:JobSimpleTrigger">
<timezone xsi:type="xsd:string" xsi:nil="true"/>
<startDate xsi:type="xsd:dateTime">2008-10-09T09:25:00.000Z</startDate>
<endDate xsi:type="xsd:dateTime" xsi:nil="true"/>
<occurrenceCount xsi:type="xsd:int">1</occurrenceCount>
<recurrenceInterval xsi:type="xsd:int" xsi:nil="true"/>
<recurrenceIntervalUnit xsi:type="ns1:IntervalUnit" xsi:nil="true"/>
</simpleTrigger>
<calendarTrigger xsi:type="ns1:JobCalendarTrigger" xsi:nil="true"/>
<parameters soapenc:arrayType="ns1:JobParameter[4]" xsi:type="soapenc:Array" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
</parameters>
<baseOutputFilename xsi:type="xsd:string">test</baseOutputFilename>
<outputFormats soapenc:arrayType="xsd:string[1]" xsi:type="soapenc:Array" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
<outputFormats xsi:type="xsd:string">PDF</outputFormats>
</outputFormats>
<outputLocale xsi:type="xsd:string" xsi:nil="true"/>
<repositoryDestination xsi:type="ns1:JobRepositoryDestination">
<folderURI xsi:type="xsd:string">/reports_generated</folderURI>
<sequentialFilenames xsi:type="xsd:boolean">false</sequentialFilenames>
<overwriteFiles xsi:type="xsd:boolean">false</overwriteFiles>
</repositoryDestination>
<mailNotification xsi:type="ns1:JobMailNotification" xsi:nil="true"/>
</job>
</ns1:scheduleJob>''')
</code></pre>
<p>Each of these requests result in errors:</p>
<pre><code>SOAPpy.Types.faultType: <Fault soapenv:Server.userException: org.xml.sax.SAXException:
Bad types (class java.lang.String -> class com.jaspersoft.jasperserver.ws.scheduling.Job):
<SOAPpy.Types.structType detail at 14743952>: {'hostname': 'myhost'}>
</code></pre>
<p>Any help/guidance would be appreciated. Thank you.</p>
| 6 | 2009-05-15T18:36:02Z | 1,898,176 | <p>I've had a lot of bad experiences with minidom. I recommend you use <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. I haven't had any experience with soap itself, so I can't speak to the rest of the issue. </p>
| 1 | 2009-12-13T23:22:34Z | [
"python",
"soap",
"jasper-reports"
] |
Scheduling a JasperServer Report via SOAP using Python | 870,188 | <p>I was able to figure out how to run reports, download files, list folders, etc. on a JasperServer using Python with SOAPpy and xml.dom minidom.</p>
<p>Here's an example execute report request, which works:</p>
<pre><code>repositoryURL = 'http://user@pass:myjasperserver:8080/jasperserver/services/repository'
repositoryWSDL = repositoryURL + '?wsdl'
server = SOAPProxy(repositoryURL, repositoryWSDL)
print server._ns(repositoryWSDL).runReport('''
<request operationName="runReport" locale="en">
<argument name="RUN_OUTPUT_FORMAT">PDF</argument>
<resourceDescriptor name="" wsType="" uriString="/reports/baz">
<label>null</label>
<parameter name="foo">bar</parameter>
</resourceDescriptor>
</request>
''')
</code></pre>
<p>However, I'm having trouble formatting my requests properly for the "ReportScheduler" section of the server. I've consulted the documentation located here (<a href="http://jasperforge.org/espdocs/docsbrowse.php?id=74&type=docs&group%5Fid=112&fid=305">http://jasperforge.org/espdocs/docsbrowse.php?id=74&type=docs&group_id=112&fid=305</a>), and have tried model my requests after their samples with no luck (see page 27).</p>
<p>Here are two examples that I've tried, which both return the same error:</p>
<pre><code>schedulingURL = 'http://user@pass:myjasperserver:8080/jasperserver/services/ReportScheduler'
schedulingWSDL = schedulingURL + '?wsdl'
server = SOAPProxy(schedulingURL, schedulingWSDL)
# first request
print server._ns(schedulingWSDL).scheduleJob('''
<request operationName="scheduleJob" locale="en">
<job>
<reportUnitURI>/reports/baz</reportUnitURI>
<label>baz</label>
<description>baz</description>
<simpleTrigger>
<startDate>2009-05-15T15:45:00.000Z</startDate>
<occurenceCount>1</occurenceCount>
</simpleTrigger>
<baseOutputFilename>baz</baseOutputFilename>
<outputFormats>
<outputFormats>PDF</outputFormats>
</outputFormats>
<repositoryDestination>
<folderURI>/reports_generated</folderURI>
<sequentialFilenames>true</sequentialFilenames>
<overwriteFiles>false</overwriteFiles>
</repositoryDestination>
<mailNotification>
<toAddresses>my@email.com</toAddresses>
<subject>test</subject>
<messageText>test</messageText>
<resultSendType>SEND_ATTACHMENT</resultSendType>
</mailNotification>
</job>
</request>''')
# second request (trying different format here)
print server._ns(schedulingWSDL).scheduleJob('''
<ns1:scheduleJob soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://www.jasperforge.org/jasperserver/ws">
<job xsi:type="ns1:Job">
<reportUnitURI xsi:type="xsd:string">/reports/baz</reportUnitURI>
<username xsi:type="xsd:string" xsi:nil="true"/>
<label xsi:type="xsd:string">baz</label>
<description xsi:type="xsd:string">baz</description>
<simpleTrigger xsi:type="ns1:JobSimpleTrigger">
<timezone xsi:type="xsd:string" xsi:nil="true"/>
<startDate xsi:type="xsd:dateTime">2008-10-09T09:25:00.000Z</startDate>
<endDate xsi:type="xsd:dateTime" xsi:nil="true"/>
<occurrenceCount xsi:type="xsd:int">1</occurrenceCount>
<recurrenceInterval xsi:type="xsd:int" xsi:nil="true"/>
<recurrenceIntervalUnit xsi:type="ns1:IntervalUnit" xsi:nil="true"/>
</simpleTrigger>
<calendarTrigger xsi:type="ns1:JobCalendarTrigger" xsi:nil="true"/>
<parameters soapenc:arrayType="ns1:JobParameter[4]" xsi:type="soapenc:Array" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
</parameters>
<baseOutputFilename xsi:type="xsd:string">test</baseOutputFilename>
<outputFormats soapenc:arrayType="xsd:string[1]" xsi:type="soapenc:Array" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
<outputFormats xsi:type="xsd:string">PDF</outputFormats>
</outputFormats>
<outputLocale xsi:type="xsd:string" xsi:nil="true"/>
<repositoryDestination xsi:type="ns1:JobRepositoryDestination">
<folderURI xsi:type="xsd:string">/reports_generated</folderURI>
<sequentialFilenames xsi:type="xsd:boolean">false</sequentialFilenames>
<overwriteFiles xsi:type="xsd:boolean">false</overwriteFiles>
</repositoryDestination>
<mailNotification xsi:type="ns1:JobMailNotification" xsi:nil="true"/>
</job>
</ns1:scheduleJob>''')
</code></pre>
<p>Each of these requests result in errors:</p>
<pre><code>SOAPpy.Types.faultType: <Fault soapenv:Server.userException: org.xml.sax.SAXException:
Bad types (class java.lang.String -> class com.jaspersoft.jasperserver.ws.scheduling.Job):
<SOAPpy.Types.structType detail at 14743952>: {'hostname': 'myhost'}>
</code></pre>
<p>Any help/guidance would be appreciated. Thank you.</p>
| 6 | 2009-05-15T18:36:02Z | 2,450,435 | <p>Without knowing anything at all about Jasper, I can guarantee you that you'll do better to replace your hardcoded SOAP requests with a simple client based on <a href="https://fedorahosted.org/suds/" rel="nofollow">the excellent suds library</a>. It abstracts away the SOAP and leaves you with squeaky-clean API access. </p>
<p><code>easy_install suds</code> and <a href="https://fedorahosted.org/suds/wiki/Documentation" rel="nofollow">the docs</a> should be enough to get you going.</p>
| 1 | 2010-03-15T20:58:53Z | [
"python",
"soap",
"jasper-reports"
] |
AuthSub with Text_db in google app engine | 870,192 | <p>I am trying to read a spreadsheet from app engine using text_db and authsub.</p>
<p>I read <a href="http://code.google.com/appengine/articles/gdata.html" rel="nofollow">http://code.google.com/appengine/articles/gdata.html</a> and got it to work. Then I read <a href="http://code.google.com/p/gdata-python-client/wiki/AuthSubWithTextDB" rel="nofollow">http://code.google.com/p/gdata-python-client/wiki/AuthSubWithTextDB</a> and I tried to merge the two in the file below (step4.py) but when I run it locally I get:</p>
<pre><code>Traceback (most recent call last):
File "/home/jmvidal/share/progs/googleapps/google_appengine/google/appengine/ext/webapp/__init__.py", line 498, in __call__
handler.get(*groups)
File "/home/jmvidal/share/progs/googleapps/google_appengine/glassboard/step4.py", line 56, in get
session_token = client._GetDocsClient().UpgradeToSessionToken(auth_token) #If I don't pass this argument I get a NonAuthSubToken
File "/home/jmvidal/share/progs/googleapps/google_appengine/glassboard/gdata/service.py", line 866, in UpgradeToSessionToken
self.SetAuthSubToken(self.upgrade_to_session_token(token))
File "/home/jmvidal/share/progs/googleapps/google_appengine/glassboard/gdata/service.py", line 885, in upgrade_to_session_token
headers={'Content-Type':'application/x-www-form-urlencoded'})
File "/home/jmvidal/share/progs/googleapps/google_appengine/glassboard/gdata/auth.py", line 678, in perform_request
return http_client.request(operation, url, data=data, headers=headers)
File "/home/jmvidal/share/progs/googleapps/google_appengine/glassboard/atom/http.py", line 163, in request
return connection.getresponse()
File "/home/jmvidal/share/progs/googleapps/google_appengine/google/appengine/dist/httplib.py", line 200, in getresponse
self._allow_truncated, self._follow_redirects)
File "/home/jmvidal/share/progs/googleapps/google_appengine/google/appengine/api/urlfetch.py", line 267, in fetch
raise DownloadError(str(e))
DownloadError: ApplicationError: 2 nonnumeric port: ''
</code></pre>
<p>Can anyone shed some light on this? Specifically, why is it that the original (step3.py from the first link) works but my call here to UpgradeToSessionToken fails?</p>
<pre><code># step4.py
#
# Trying to read spreadsheets from app engine using text_db and authsub.
#
# Merge of this code
# http://code.google.com/p/gdata-python-client/wiki/AuthSubWithTextDB
# with this one
# http://code.google.com/appengine/articles/gdata.html (step 3)
import wsgiref.handlers
import cgi
from google.appengine.ext import webapp
from google.appengine.api import users
import atom.url
import gdata.service
import gdata.alt.appengine
import gdata.spreadsheet.text_db
import settings
class Fetcher(webapp.RequestHandler):
def get(self):
# Write our pages title
self.response.out.write("""<html><head><title>
Google Data Feed Fetcher: read Google Data API Atom feeds</title>""")
self.response.out.write('</head><body>')
next_url = atom.url.Url('http', settings.HOST_NAME, path='/step4')
# Allow the user to sign in or sign out
if users.get_current_user():
self.response.out.write('<a href="%s">Sign Out</a><br>' % (
users.create_logout_url(str(next_url))))
else:
self.response.out.write('<a href="%s">Sign In</a><br>' % (
users.create_login_url(str(next_url))))
# Initialize a client to talk to Google Data API services.
# client = gdata.service.GDataService()
# auth_url = client.GenerateAuthSubURL(
# next_url,
# ('http://docs.google.com/feeds/',), secure=False, session=True)
client = gdata.spreadsheet.text_db.DatabaseClient()
auth_url = client._GetDocsClient().GenerateAuthSubURL(
next_url,
('http://spreadsheets.google.com/feeds/','http://docs.google.com/feeds/documents/'), secure=False, session=True)
gdata.alt.appengine.run_on_appengine(client)
feed_url = self.request.get('feed_url')
session_token = None
# Find the AuthSub token and upgrade it to a session token.
auth_token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri)
if auth_token:
# Upgrade the single-use AuthSub token to a multi-use session token.
client._GetDocsClient().SetAuthSubToken(auth_token)
session_token = client._GetDocsClient().UpgradeToSessionToken(auth_token) #If I don't pass this argument I get a NonAuthSubToken
client._GetSpreadsheetsClient().SetAuthSubToken(client._GetDocsClient().GetAuthSubToken())
# session_token = client.upgrade_to_session_token(auth_token)
if session_token and users.get_current_user():
# If there is a current user, store the token in the datastore and
# associate it with the current user. Since we told the client to
# run_on_appengine, the add_token call will automatically store the
# session token if there is a current_user.
client.token_store.add_token(session_token)
elif session_token:
# Since there is no current user, we will put the session token
# in a property of the client. We will not store the token in the
# datastore, since we wouldn't know which user it belongs to.
# Since a new client object is created with each get call, we don't
# need to worry about the anonymous token being used by other users.
client.current_token = session_token
self.response.out.write('<div id="main">')
self.fetch_feed(client, feed_url)
self.response.out.write('</div>')
self.response.out.write(
'<div id="sidebar"><div id="scopes"><h4>Request a token</h4><ul>')
self.response.out.write('<li><a href="%s">Google Documents</a></li>' % (auth_url))
self.response.out.write('</ul></div><br/><div id="tokens">')
def fetch_feed(self, client, feed_url):
# Attempt to fetch the feed.
if not feed_url:
self.response.out.write(
'No feed_url was specified for the app to fetch.<br/>')
example_url = atom.url.Url('http', settings.HOST_NAME, path='/step4',
params={'feed_url':
'http://docs.google.com/feeds/documents/private/full'}
).to_string()
self.response.out.write('Here\'s an example query which will show the'
' XML for the feed listing your Google Documents <a '
'href="%s">%s</a>' % (example_url, example_url))
return
try:
response = client.Get(feed_url, converter=str)
self.response.out.write(cgi.escape(response))
except gdata.service.RequestError, request_error:
# If fetching fails, then tell the user that they need to login to
# authorize this app by logging in at the following URL.
if request_error[0]['status'] == 401:
# Get the URL of the current page so that our AuthSub request will
# send the user back to here.
next = atom.url.Url('http', settings.HOST_NAME, path='/step4',
params={'feed_url': feed_url})
# If there is a current user, we can request a session token, otherwise
# we should ask for a single use token.
auth_sub_url = client.GenerateAuthSubURL(next, feed_url,
secure=False, session=True)
self.response.out.write('<a href="%s">' % (auth_sub_url))
self.response.out.write(
'Click here to authorize this application to view the feed</a>')
else:
self.response.out.write(
'Something went wrong, here is the error object: %s ' % (
str(request_error[0])))
def main():
application = webapp.WSGIApplication([('/.*', Fetcher),], debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
</code></pre>
| 1 | 2009-05-15T18:36:34Z | 870,343 | <p>As always, I figure out the answer only after giving up and asking for help.</p>
<p>we need to add two more calls to run_on_appengine (to register the two clients that the text_db client has):</p>
<pre><code>gdata.alt.appengine.run_on_appengine(client)
gdata.alt.appengine.run_on_appengine(client._GetDocsClient())
gdata.alt.appengine.run_on_appengine(client._GetSpreadsheetsClient()) here
</code></pre>
<p>I would have expected the first call to run_on_appengine to result in the two other calls, but I guess not.</p>
<p>Oh, and change the auth_url line to:</p>
<pre><code>auth_url = client._GetDocsClient().GenerateAuthSubURL(
next_url,scope='http://spreadsheets.google.com/feeds/ http://docs.google.com/feeds/documents/', secure=False, session=True)
</code></pre>
<p>Passing the scope urls in a list caused a "token does not have the correct scope" error.</p>
| 1 | 2009-05-15T19:10:42Z | [
"python",
"google-app-engine",
"authentication",
"gdata-api"
] |
SOAPpy - reserved word in named parameter list | 870,455 | <p>I'm using SOAPpy to access a SOAP Webservice. This call to the function findPathwaysByText works just fine:</p>
<pre><code>server.findPathwaysByText (query= 'WP619', species = 'Mus musculus')
</code></pre>
<p>However, this call to the function login does not:</p>
<pre><code>server.login (user='amarillion', pass='*****')
</code></pre>
<p>Because pass is a reserved word, python won't run this. Is there a workaround?</p>
| 3 | 2009-05-15T19:37:54Z | 870,473 | <p>You can say</p>
<pre><code>server.login(user='amarillion', **{'pass': '*****'})
</code></pre>
<p>The double-asterix syntax here applies keyword arguments. Here's a simple example that shows what's happening:</p>
<pre><code>def f(a, b):
return a + b
kwargs = {"a": 5, "b": 6}
return f(**kwargs) # same as saying f(a=5, b=6)
</code></pre>
| 1 | 2009-05-15T19:42:09Z | [
"python",
"soap",
"soappy",
"reserved-words"
] |
SOAPpy - reserved word in named parameter list | 870,455 | <p>I'm using SOAPpy to access a SOAP Webservice. This call to the function findPathwaysByText works just fine:</p>
<pre><code>server.findPathwaysByText (query= 'WP619', species = 'Mus musculus')
</code></pre>
<p>However, this call to the function login does not:</p>
<pre><code>server.login (user='amarillion', pass='*****')
</code></pre>
<p>Because pass is a reserved word, python won't run this. Is there a workaround?</p>
| 3 | 2009-05-15T19:37:54Z | 870,482 | <p>You could try:</p>
<pre><code>d = {'user':'amarillion', 'pass':'*****' }
server.login(**d)
</code></pre>
<p>This passes in the given dictionary as though they were keyword arguments (the **)</p>
| 5 | 2009-05-15T19:43:14Z | [
"python",
"soap",
"soappy",
"reserved-words"
] |
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned? | 870,520 | <p>Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'.</p>
<p>How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive.</p>
<p>I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The <code>.match</code> function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit.</p>
<p>If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?</p>
| 20 | 2009-05-15T19:48:02Z | 870,558 | <pre><code>s = 'ASDjifjASFJ7364'
s_lowercase = ''.join(filter(lambda c: c.islower(), s))
print s_lowercase #print 'jifj'
</code></pre>
| 4 | 2009-05-15T19:53:32Z | [
"python",
"filter",
"whitelist"
] |
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned? | 870,520 | <p>Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'.</p>
<p>How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive.</p>
<p>I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The <code>.match</code> function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit.</p>
<p>If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?</p>
| 20 | 2009-05-15T19:48:02Z | 870,559 | <pre><code>s = 'Agh#$%#%2341- -!zdrkfd'
print ''.join(c for c in s if c.islower())
</code></pre>
<p>String objects are iterable; there is no need to "explode" the string into a list. You can put whatever condition you want in the list comprehension, and it will filter characters accordingly.</p>
<p>You could also implement this using a regex, but this will only hide the loop. The regular expressions library will still have to loop through the characters of the string in order to filter them.</p>
| 17 | 2009-05-15T19:53:36Z | [
"python",
"filter",
"whitelist"
] |
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned? | 870,520 | <p>Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'.</p>
<p>How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive.</p>
<p>I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The <code>.match</code> function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit.</p>
<p>If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?</p>
| 20 | 2009-05-15T19:48:02Z | 870,565 | <p>I'd use a regex. For lowercase match [a-z].</p>
| 1 | 2009-05-15T19:54:27Z | [
"python",
"filter",
"whitelist"
] |
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned? | 870,520 | <p>Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'.</p>
<p>How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive.</p>
<p>I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The <code>.match</code> function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit.</p>
<p>If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?</p>
| 20 | 2009-05-15T19:48:02Z | 870,582 | <pre><code>>>> s = 'Agh#$%#%2341- -!zdrkfd'
>>> ''.join(i for i in s if i in 'qwertyuiopasdfghjklzxcvbnm')
'ghzdrkfd'
</code></pre>
| 4 | 2009-05-15T19:57:34Z | [
"python",
"filter",
"whitelist"
] |
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned? | 870,520 | <p>Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'.</p>
<p>How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive.</p>
<p>I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The <code>.match</code> function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit.</p>
<p>If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?</p>
| 20 | 2009-05-15T19:48:02Z | 870,588 | <p>Using a regular expression is easy enough, especially for this scenario:</p>
<pre><code>>>> import re
>>> s = 'ASDjifjASFJ7364'
>>> re.sub(r'[^a-z]+', '', s)
'jifj'
</code></pre>
<p>If you plan on doing this many times, it is best to compile the regular expression before hand:</p>
<pre><code>>>> import re
>>> s = 'ASDjifjASFJ7364'
>>> r = re.compile(r'[^a-z]+')
>>> r.sub('', s)
'jifj'
</code></pre>
| 5 | 2009-05-15T19:58:27Z | [
"python",
"filter",
"whitelist"
] |
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned? | 870,520 | <p>Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'.</p>
<p>How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive.</p>
<p>I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The <code>.match</code> function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit.</p>
<p>If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?</p>
| 20 | 2009-05-15T19:48:02Z | 870,624 | <pre><code>import string
print "".join([c for c in "Agh#$%#%2341- -!zdrkfd" if c in string.lowercase])
</code></pre>
| 0 | 2009-05-15T20:04:29Z | [
"python",
"filter",
"whitelist"
] |
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned? | 870,520 | <p>Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'.</p>
<p>How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive.</p>
<p>I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The <code>.match</code> function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit.</p>
<p>If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?</p>
| 20 | 2009-05-15T19:48:02Z | 870,748 | <p>If you are looking for efficiency. Using the <a href="http://docs.python.org/library/stdtypes.html#str.translate">translate</a> function is the fastest you can get.</p>
<p>It can be used to quickly replace characters and/or delete them.</p>
<pre><code>import string
delete_table = string.maketrans(
string.ascii_lowercase, ' ' * len(string.ascii_lowercase)
)
table = string.maketrans('', '')
"Agh#$%#%2341- -!zdrkfd".translate(table, delete_table)
</code></pre>
<p><strong>In python 2.6:</strong> you don't need the second table anymore</p>
<pre><code>import string
delete_table = string.maketrans(
string.ascii_lowercase, ' ' * len(string.ascii_lowercase)
)
"Agh#$%#%2341- -!zdrkfd".translate(None, delete_table)
</code></pre>
<p>This is method is way faster than any other. Of course you need to store the delete_table somewhere and use it. But even if you don't store it and build it every time, it is still going to be faster than other suggested methods so far.</p>
<p>To confirm my claims here are the results:</p>
<pre><code>for i in xrange(10000):
''.join(c for c in s if c.islower())
real 0m0.189s
user 0m0.176s
sys 0m0.012s
</code></pre>
<p>While running the regular expression solution:</p>
<pre><code>for i in xrange(10000):
re.sub(r'[^a-z]', '', s)
real 0m0.172s
user 0m0.164s
sys 0m0.004s
</code></pre>
<p><strong>[Upon request]</strong> If you pre-compile the regular expression:</p>
<pre><code>r = re.compile(r'[^a-z]')
for i in xrange(10000):
r.sub('', s)
real 0m0.166s
user 0m0.144s
sys 0m0.008s
</code></pre>
<p>Running the translate method the same number of times took:</p>
<pre><code>real 0m0.075s
user 0m0.064s
sys 0m0.012s
</code></pre>
| 30 | 2009-05-15T20:35:58Z | [
"python",
"filter",
"whitelist"
] |
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned? | 870,520 | <p>Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'.</p>
<p>How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive.</p>
<p>I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The <code>.match</code> function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit.</p>
<p>If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?</p>
| 20 | 2009-05-15T19:48:02Z | 870,847 | <p>Here's one solution if you are specifically interested in working on strings:</p>
<pre><code> s = 'Agh#$%#%2341- -!zdrkfd'
lowercase_chars = [chr(i) for i in xrange(ord('a'), ord('z') + 1)]
whitelist = set(lowercase_chars)
filtered_list = [c for c in s if c in whitelist]
</code></pre>
<p>The whitelist is actually a set (not a list) for efficiency.</p>
<p>If you need a string, use join():</p>
<pre><code>filtered_str = ''.join(filtered_list)
</code></pre>
<p><hr /></p>
<p>filter() is a more generic solution. From the documentation (<a href="http://docs.python.org/library/functions.html" rel="nofollow">http://docs.python.org/library/functions.html</a>):</p>
<blockquote>
<p>filter(function, iterable)</p>
<p>Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.</p>
</blockquote>
<p>This would be one way of using filter():</p>
<pre><code>filtered_list = filter(lambda c: c.islower(), s)
</code></pre>
| 1 | 2009-05-15T20:59:53Z | [
"python",
"filter",
"whitelist"
] |
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned? | 870,520 | <p>Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'.</p>
<p>How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive.</p>
<p>I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The <code>.match</code> function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit.</p>
<p>If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?</p>
| 20 | 2009-05-15T19:48:02Z | 29,925,445 | <pre><code>import string
print filter(string.lowercase.__contains__, "lowerUPPER")
print filter("123".__contains__, "a1b2c3")
</code></pre>
| 0 | 2015-04-28T16:54:47Z | [
"python",
"filter",
"whitelist"
] |
Pythonic way to split comma separated numbers into pairs | 870,652 | <p>I'd like to split a comma separated value into pairs:</p>
<pre><code>>>> s = '0,1,2,3,4,5,6,7,8,9'
>>> pairs = # something pythonic
>>> pairs
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
</code></pre>
<p>What would <em># something pythonic</em> look like?</p>
<p>How would you detect and handle a string with an odd set of numbers?</p>
| 17 | 2009-05-15T20:10:32Z | 870,677 | <p>Something like:</p>
<pre><code>zip(t[::2], t[1::2])
</code></pre>
<p>Full example:</p>
<pre><code>>>> s = ','.join(str(i) for i in range(10))
>>> s
'0,1,2,3,4,5,6,7,8,9'
>>> t = [int(i) for i in s.split(',')]
>>> t
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> p = zip(t[::2], t[1::2])
>>> p
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>>>
</code></pre>
<p>If the number of items is odd, the last element will be ignored. Only complete pairs will be included.</p>
| 44 | 2009-05-15T20:15:55Z | [
"python",
"tuples"
] |
Pythonic way to split comma separated numbers into pairs | 870,652 | <p>I'd like to split a comma separated value into pairs:</p>
<pre><code>>>> s = '0,1,2,3,4,5,6,7,8,9'
>>> pairs = # something pythonic
>>> pairs
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
</code></pre>
<p>What would <em># something pythonic</em> look like?</p>
<p>How would you detect and handle a string with an odd set of numbers?</p>
| 17 | 2009-05-15T20:10:32Z | 870,682 | <p>How about this:</p>
<pre><code>>>> x = '0,1,2,3,4,5,6,7,8,9'.split(',')
>>> def chunker(seq, size):
... return (tuple(seq[pos:pos + size]) for pos in xrange(0, len(seq), size))
...
>>> list(chunker(x, 2))
[('0', '1'), ('2', '3'), ('4', '5'), ('6', '7'), ('8', '9')]
</code></pre>
<p>This will also nicely handle uneven amounts:</p>
<pre><code>>>> x = '0,1,2,3,4,5,6,7,8,9,10'.split(',')
>>> list(chunker(x, 2))
[('0', '1'), ('2', '3'), ('4', '5'), ('6', '7'), ('8', '9'), ('10',)]
</code></pre>
<p>P.S. I had this code stashed away and I just realized where I got it from. There's two very similar questions in stackoverflow about this:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></li>
<li><a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></li>
</ul>
<p>There's also this gem from the <a href="http://docs.python.org/library/itertools.html#recipes" rel="nofollow">Recipes</a> section of <code>itertools</code>: </p>
<pre><code>def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
</code></pre>
| 8 | 2009-05-15T20:16:32Z | [
"python",
"tuples"
] |
Pythonic way to split comma separated numbers into pairs | 870,652 | <p>I'd like to split a comma separated value into pairs:</p>
<pre><code>>>> s = '0,1,2,3,4,5,6,7,8,9'
>>> pairs = # something pythonic
>>> pairs
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
</code></pre>
<p>What would <em># something pythonic</em> look like?</p>
<p>How would you detect and handle a string with an odd set of numbers?</p>
| 17 | 2009-05-15T20:10:32Z | 870,692 | <p>This will ignore the last number in an odd list:</p>
<pre><code>n = [int(x) for x in s.split(',')]
print zip(n[::2], n[1::2])
</code></pre>
<p>This will pad the shorter list by 0 in an odd list:</p>
<pre><code>import itertools
n = [int(x) for x in s.split(',')]
print list(itertools.izip_longest(n[::2], n[1::2], fillvalue=0))
</code></pre>
<p><a href="http://docs.python.org/library/itertools.html#itertools.izip%5Flongest" rel="nofollow">izip_longest</a> is available in Python 2.6.</p>
| 2 | 2009-05-15T20:20:54Z | [
"python",
"tuples"
] |
Pythonic way to split comma separated numbers into pairs | 870,652 | <p>I'd like to split a comma separated value into pairs:</p>
<pre><code>>>> s = '0,1,2,3,4,5,6,7,8,9'
>>> pairs = # something pythonic
>>> pairs
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
</code></pre>
<p>What would <em># something pythonic</em> look like?</p>
<p>How would you detect and handle a string with an odd set of numbers?</p>
| 17 | 2009-05-15T20:10:32Z | 870,724 | <p>A more general option, that also works on iterators and allows for combining any number of items:</p>
<pre><code> def n_wise(seq, n):
return zip(*([iter(seq)]*n))
</code></pre>
<p>Replace zip with itertools.izip if you want to get a lazy iterator instead of a list.</p>
| 8 | 2009-05-15T20:29:28Z | [
"python",
"tuples"
] |
Pythonic way to split comma separated numbers into pairs | 870,652 | <p>I'd like to split a comma separated value into pairs:</p>
<pre><code>>>> s = '0,1,2,3,4,5,6,7,8,9'
>>> pairs = # something pythonic
>>> pairs
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
</code></pre>
<p>What would <em># something pythonic</em> look like?</p>
<p>How would you detect and handle a string with an odd set of numbers?</p>
| 17 | 2009-05-15T20:10:32Z | 1,429,822 | <p>A solution much like FogleBirds, but using an iterator (a generator expression) instead of list comprehension.</p>
<pre><code>s = '0,1,2,3,4,5,6,7,8,9'
# generator expression creating an iterator yielding numbers
iterator = (int(i) for i in s.split(','))
# use zip to create pairs
# (will ignore last item if odd number of items)
# Note that zip() returns a list in Python 2.x,
# in Python 3 it returns an iterator
pairs = zip(iterator, iterator)
</code></pre>
<p>Both list comprehensions and generator expressions would probably be considered quite "pythonic".</p>
| 4 | 2009-09-15T21:53:29Z | [
"python",
"tuples"
] |
How to generate a file with DDL in the engine's SQL dialect in SQLAlchemy? | 870,925 | <p>Suppose I have an <code>engine</code> pointing at MySQL database:</p>
<pre><code>engine = create_engine('mysql://arthurdent:answer42@localhost/dtdb', echo=True)
</code></pre>
<p>I can populate <code>dtdb</code> with tables, FKs, etc by:</p>
<pre><code>metadata.create_all(engine)
</code></pre>
<p>Is there an easy way to generate the SQL file that contains all the DDL statements instead of actually applying these DDL statements to <code>dtdb</code>?</p>
<p>So far I have resorted to capturing SQLAlchemy log output produced by <code>echo=True</code>, and editing it by hand. But that's just too painful.</p>
<p>It looks like SA has pretty elaborate schema management API, but I haven't seen examples of simply streaming the schema definitions as text.</p>
| 7 | 2009-05-15T21:19:13Z | 870,958 | <p>The quick answer is in the <a href="http://docs.sqlalchemy.org/en/rel_0_8/faq.html#how-can-i-get-the-create-table-drop-table-output-as-a-string">SQLAlchemy 0.8 FAQ</a>.</p>
<p>In SQLAlchemy 0.8 you need to do</p>
<pre><code>engine = create_engine(
'mssql+pyodbc://./MyDb',
strategy='mock',
executor= lambda sql, *multiparams, **params: print (sql.compile(dialect=engine.dialect)))
</code></pre>
<p>In SQLAlchemy 0.9 the syntax is simplified.</p>
<pre><code>engine = create_engine(
'mssql+pyodbc://./MyDb',
strategy='mock',
executor= lambda sql, *multiparams, **params: print (sql)
</code></pre>
<p>The longer answer is that capturing the output still has some slight issues. Like with the encoding of literals of types. But this hasn't been a big enough of an issue for anyone to step up and scratch their itch. You could always let SQLAlchemy programmatically create an empty database and dump the SQL from there.</p>
<p>The more difficult problem is the handling of schema migrations. This is where <a href="http://code.google.com/p/sqlalchemy-migrate/">SQLAlchemy-migrate</a> can help you.</p>
| 13 | 2009-05-15T21:33:37Z | [
"python",
"sqlalchemy"
] |
Django: Overriding __init__ for Custom Forms | 871,037 | <p>I am making a custom form object in Django which has an overrided __init__ method. The purpose of overriding the method is to dynamically generate drop-down boxes based on the new parameters.</p>
<p>For example,</p>
<pre><code>class TicketForm(forms.Form):
Type = Type.GetTicketTypeField()
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, label_suffix=':', empty_permitted=False,
ticket=None):
if ticket:
self.__class__.State = State.GetTicketStateField(ticket.Type)
super(forms.BaseForm, self ).__init__(data=data, files=files,
auto_id=auto_id, prefix=prefix, initial=initial,
label_suffix=label_suffix, empty_permitted=empty_permitted)
</code></pre>
<p>This solution does not work. It appears that the fields are created before the __init__ is called. I would assume this problem would be pretty common. What would be the Django way of handling these classes of problems.</p>
| 14 | 2009-05-15T22:00:04Z | 871,082 | <p>You can dynamically modify your form by using the <code>self.fields</code> dict. Something like this may work for you:</p>
<pre><code>class TicketForm(forms.Form):
Type = Type.GetTicketTypeField()
def __init__(self, ticket, *args, **kwargs):
super(TicketForm, self).__init__(*args, **kwargs)
self.fields['state'] = State.GetTicketStateField(ticket.Type)
</code></pre>
| 25 | 2009-05-15T22:13:03Z | [
"python",
"django"
] |
Django: Overriding __init__ for Custom Forms | 871,037 | <p>I am making a custom form object in Django which has an overrided __init__ method. The purpose of overriding the method is to dynamically generate drop-down boxes based on the new parameters.</p>
<p>For example,</p>
<pre><code>class TicketForm(forms.Form):
Type = Type.GetTicketTypeField()
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, label_suffix=':', empty_permitted=False,
ticket=None):
if ticket:
self.__class__.State = State.GetTicketStateField(ticket.Type)
super(forms.BaseForm, self ).__init__(data=data, files=files,
auto_id=auto_id, prefix=prefix, initial=initial,
label_suffix=label_suffix, empty_permitted=empty_permitted)
</code></pre>
<p>This solution does not work. It appears that the fields are created before the __init__ is called. I would assume this problem would be pretty common. What would be the Django way of handling these classes of problems.</p>
| 14 | 2009-05-15T22:00:04Z | 871,084 | <p>I found a solution <a href="http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/" rel="nofollow">here</a>. If there is a better solution, please post a reply.</p>
<pre><code>class TicketForm(forms.Form):
Type = Type.GetTicketTypeField()
def __init__(self, ticket=None, *args, **kwargs):
super(TicketForm, self ).__init__(*args, **kwargs)
if ticket:
self.fields['State'] = State.GetTicketStateField(ticket.Type)
</code></pre>
| 2 | 2009-05-15T22:14:05Z | [
"python",
"django"
] |
escape problem in django templates | 871,163 | <p>Let's say that I have this string:</p>
<pre><code>s = '<p>Hello!</p>'
</code></pre>
<p>When I pass this variable to a template, I want it to be rendered as raw html. Looking at the docs I see that I can either use the safe filter:</p>
<pre><code>{{s|safe}}
</code></pre>
<p>or disable autoescape:</p>
<pre><code>{%autoescape off}
{{s}}
{%endautoescape%}
</code></pre>
<p>or inside the python code declare it safe:</p>
<pre><code>from django.utils.safestring import mark_safe
s = mark_safe(s)
</code></pre>
<p>None of these options are working for me. Whatever I do, the string is displayed as:</p>
<pre><code><p>Hello!</p>
</code></pre>
<p>I must be missing something, just couldn't figure out what. Is there some security setting somewhere that disallows escaping?</p>
<p>EDIT: Bizarre, the problem seems to be gone after I have restarted the computer.</p>
| 8 | 2009-05-15T22:43:45Z | 871,197 | <p>You pretty much covered it, those are indeed all the ways to disable autoescaping.</p>
<p>Are you sure the value you are talking about is actually <code>s = '<p>Hello!</p>'</code>?</p>
<p>My hunch is that you have additional escaping somewhere in that string...</p>
| 2 | 2009-05-15T22:56:45Z | [
"python",
"html",
"django",
"django-templates",
"rendering"
] |
escape problem in django templates | 871,163 | <p>Let's say that I have this string:</p>
<pre><code>s = '<p>Hello!</p>'
</code></pre>
<p>When I pass this variable to a template, I want it to be rendered as raw html. Looking at the docs I see that I can either use the safe filter:</p>
<pre><code>{{s|safe}}
</code></pre>
<p>or disable autoescape:</p>
<pre><code>{%autoescape off}
{{s}}
{%endautoescape%}
</code></pre>
<p>or inside the python code declare it safe:</p>
<pre><code>from django.utils.safestring import mark_safe
s = mark_safe(s)
</code></pre>
<p>None of these options are working for me. Whatever I do, the string is displayed as:</p>
<pre><code><p>Hello!</p>
</code></pre>
<p>I must be missing something, just couldn't figure out what. Is there some security setting somewhere that disallows escaping?</p>
<p>EDIT: Bizarre, the problem seems to be gone after I have restarted the computer.</p>
| 8 | 2009-05-15T22:43:45Z | 2,109,545 | <p>Look at the HTML source code, is it escaped!??? I don't think so. It should be printing letter by letter, just like this:</p>
<pre><code><
p
>
H
E
L
L
O
<
/
>
</code></pre>
| -3 | 2010-01-21T13:37:43Z | [
"python",
"html",
"django",
"django-templates",
"rendering"
] |
escape problem in django templates | 871,163 | <p>Let's say that I have this string:</p>
<pre><code>s = '<p>Hello!</p>'
</code></pre>
<p>When I pass this variable to a template, I want it to be rendered as raw html. Looking at the docs I see that I can either use the safe filter:</p>
<pre><code>{{s|safe}}
</code></pre>
<p>or disable autoescape:</p>
<pre><code>{%autoescape off}
{{s}}
{%endautoescape%}
</code></pre>
<p>or inside the python code declare it safe:</p>
<pre><code>from django.utils.safestring import mark_safe
s = mark_safe(s)
</code></pre>
<p>None of these options are working for me. Whatever I do, the string is displayed as:</p>
<pre><code><p>Hello!</p>
</code></pre>
<p>I must be missing something, just couldn't figure out what. Is there some security setting somewhere that disallows escaping?</p>
<p>EDIT: Bizarre, the problem seems to be gone after I have restarted the computer.</p>
| 8 | 2009-05-15T22:43:45Z | 4,405,279 | <p>I think you should write as follows</p>
<pre><code>{{s|escape|safe}}
</code></pre>
<p>it is ok for me</p>
| 5 | 2010-12-10T03:04:01Z | [
"python",
"html",
"django",
"django-templates",
"rendering"
] |
XPath - How can I query for a parent node satisfying an attribute presence condition? | 871,188 | <p>I need to query a node to determine if it has a parent node that contains a specified attribute. For instance:</p>
<pre><code><a b="value">
<b/>
</a>
</code></pre>
<p>From b as my focus element, I'd like to execute an XPath query:</p>
<pre><code>..[@b]
</code></pre>
<p>that would return element <strong>a</strong>. The returned element <em>must</em> be the parent node of <strong>a</strong>, and should not contain any of <strong>a</strong>'s siblings. </p>
<p>The lxml.etree library states that this is an invalid XPath expression.</p>
| 1 | 2009-05-15T22:52:42Z | 871,209 | <p>I don't know about the lxml.etree library but <code>..[@b]</code> is <strike>fully valid XPath</strike> (<strong>Update</strong>: see Ben Blank's comment). Identical to <code>parent::a[@b]</code>, it will return context at the <code>a</code> element.</p>
| 1 | 2009-05-15T23:00:38Z | [
"python",
"xml",
"xpath"
] |
XPath - How can I query for a parent node satisfying an attribute presence condition? | 871,188 | <p>I need to query a node to determine if it has a parent node that contains a specified attribute. For instance:</p>
<pre><code><a b="value">
<b/>
</a>
</code></pre>
<p>From b as my focus element, I'd like to execute an XPath query:</p>
<pre><code>..[@b]
</code></pre>
<p>that would return element <strong>a</strong>. The returned element <em>must</em> be the parent node of <strong>a</strong>, and should not contain any of <strong>a</strong>'s siblings. </p>
<p>The lxml.etree library states that this is an invalid XPath expression.</p>
| 1 | 2009-05-15T22:52:42Z | 871,222 | <p>You can't combine the <code>.</code> or <code>..</code> shorthands with a predicate. Instead, you'll need to use the full <code>parent::</code> axis. The following should work for you:</p>
<pre><code>parent::*[@b]
</code></pre>
<p>This will select the parent node (regardless of its local name), IFF it has a "b" attribute.</p>
| 4 | 2009-05-15T23:05:54Z | [
"python",
"xml",
"xpath"
] |
Python program using os.pipe and os.fork() issue | 871,447 | <p>I've recently needed to write a script that performs an <strong>os.fork()</strong> to split into two processes. The child process becomes a server process and passes data back to the parent process using a pipe created with <strong>os.pipe()</strong>. The child closes the <code>'r'</code> end of the pipe and the parent closes the <code>'w'</code> end of the pipe, as usual. I convert the returns from pipe() into file objects with <strong>os.fdopen</strong>. </p>
<p>The problem I'm having is this: The process successfully forks, and the child becomes a server. Everything works great and the child dutifully writes data to the open <code>'w'</code> end of the pipe. Unfortunately the parent end of the pipe does two strange things:<br>
A) It blocks on the <code>read()</code> operation on the <code>'r'</code> end of the pipe.<br>
Secondly, it fails to read any data that was put on the pipe unless the <code>'w'</code> end is entirely closed.</p>
<p>I immediately thought that buffering was the problem and added <strong>pipe.flush()</strong> calls, but these didn't help. </p>
<p>Can anyone shed some light on why the data doesn't appear until the writing end is fully closed? And is there a strategy to make the <code>read()</code> call non blocking?</p>
<p>This is my first Python program that forked or used pipes, so forgive me if I've made a simple mistake. </p>
| 10 | 2009-05-16T01:36:53Z | 871,503 | <p>The "parent" vs. "child" part of fork in a Python application is silly. It's a legacy from 16-bit unix days. It's an affectation from a day when fork/exec and exec were Important Things to make the most of a tiny little processor.</p>
<p>Break your Python code into two separate parts: parent and child.</p>
<p>The parent part should use <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> to run the child part. </p>
<p>A fork and exec may happen somewhere in there -- but you don't need to care.</p>
| -8 | 2009-05-16T02:05:01Z | [
"python",
"pipe",
"fork"
] |
Python program using os.pipe and os.fork() issue | 871,447 | <p>I've recently needed to write a script that performs an <strong>os.fork()</strong> to split into two processes. The child process becomes a server process and passes data back to the parent process using a pipe created with <strong>os.pipe()</strong>. The child closes the <code>'r'</code> end of the pipe and the parent closes the <code>'w'</code> end of the pipe, as usual. I convert the returns from pipe() into file objects with <strong>os.fdopen</strong>. </p>
<p>The problem I'm having is this: The process successfully forks, and the child becomes a server. Everything works great and the child dutifully writes data to the open <code>'w'</code> end of the pipe. Unfortunately the parent end of the pipe does two strange things:<br>
A) It blocks on the <code>read()</code> operation on the <code>'r'</code> end of the pipe.<br>
Secondly, it fails to read any data that was put on the pipe unless the <code>'w'</code> end is entirely closed.</p>
<p>I immediately thought that buffering was the problem and added <strong>pipe.flush()</strong> calls, but these didn't help. </p>
<p>Can anyone shed some light on why the data doesn't appear until the writing end is fully closed? And is there a strategy to make the <code>read()</code> call non blocking?</p>
<p>This is my first Python program that forked or used pipes, so forgive me if I've made a simple mistake. </p>
| 10 | 2009-05-16T01:36:53Z | 871,509 | <p><a href="http://www.myelin.co.nz/post/2003/3/13/" rel="nofollow">Here's</a> some example code for doing just this.</p>
| 2 | 2009-05-16T02:09:02Z | [
"python",
"pipe",
"fork"
] |
Python program using os.pipe and os.fork() issue | 871,447 | <p>I've recently needed to write a script that performs an <strong>os.fork()</strong> to split into two processes. The child process becomes a server process and passes data back to the parent process using a pipe created with <strong>os.pipe()</strong>. The child closes the <code>'r'</code> end of the pipe and the parent closes the <code>'w'</code> end of the pipe, as usual. I convert the returns from pipe() into file objects with <strong>os.fdopen</strong>. </p>
<p>The problem I'm having is this: The process successfully forks, and the child becomes a server. Everything works great and the child dutifully writes data to the open <code>'w'</code> end of the pipe. Unfortunately the parent end of the pipe does two strange things:<br>
A) It blocks on the <code>read()</code> operation on the <code>'r'</code> end of the pipe.<br>
Secondly, it fails to read any data that was put on the pipe unless the <code>'w'</code> end is entirely closed.</p>
<p>I immediately thought that buffering was the problem and added <strong>pipe.flush()</strong> calls, but these didn't help. </p>
<p>Can anyone shed some light on why the data doesn't appear until the writing end is fully closed? And is there a strategy to make the <code>read()</code> call non blocking?</p>
<p>This is my first Python program that forked or used pipes, so forgive me if I've made a simple mistake. </p>
| 10 | 2009-05-16T01:36:53Z | 871,515 | <p>Using </p>
<p><code>fcntl.fcntl(readPipe, fcntl.F_SETFL, os.O_NONBLOCK)</code></p>
<p>Before invoking the read() solved both problems. The read() call is no longer blocking and the data is appearing after just a flush() on the writing end.</p>
| 5 | 2009-05-16T02:14:38Z | [
"python",
"pipe",
"fork"
] |
Python program using os.pipe and os.fork() issue | 871,447 | <p>I've recently needed to write a script that performs an <strong>os.fork()</strong> to split into two processes. The child process becomes a server process and passes data back to the parent process using a pipe created with <strong>os.pipe()</strong>. The child closes the <code>'r'</code> end of the pipe and the parent closes the <code>'w'</code> end of the pipe, as usual. I convert the returns from pipe() into file objects with <strong>os.fdopen</strong>. </p>
<p>The problem I'm having is this: The process successfully forks, and the child becomes a server. Everything works great and the child dutifully writes data to the open <code>'w'</code> end of the pipe. Unfortunately the parent end of the pipe does two strange things:<br>
A) It blocks on the <code>read()</code> operation on the <code>'r'</code> end of the pipe.<br>
Secondly, it fails to read any data that was put on the pipe unless the <code>'w'</code> end is entirely closed.</p>
<p>I immediately thought that buffering was the problem and added <strong>pipe.flush()</strong> calls, but these didn't help. </p>
<p>Can anyone shed some light on why the data doesn't appear until the writing end is fully closed? And is there a strategy to make the <code>read()</code> call non blocking?</p>
<p>This is my first Python program that forked or used pipes, so forgive me if I've made a simple mistake. </p>
| 10 | 2009-05-16T01:36:53Z | 871,565 | <p>I see you have solved the problem of blocking i/o and buffering.</p>
<p>A note if you decide to try a different approach: subprocess is the equivalent / a replacement for the fork/exec idiom. It seems like that's not what you're doing: you have just a fork (not an exec) and exchanging data between the two processes -- in this case the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow"><code>multiprocessing</code></a> module (in Python 2.6+) would be a better fit. </p>
| 4 | 2009-05-16T02:56:06Z | [
"python",
"pipe",
"fork"
] |
Python program using os.pipe and os.fork() issue | 871,447 | <p>I've recently needed to write a script that performs an <strong>os.fork()</strong> to split into two processes. The child process becomes a server process and passes data back to the parent process using a pipe created with <strong>os.pipe()</strong>. The child closes the <code>'r'</code> end of the pipe and the parent closes the <code>'w'</code> end of the pipe, as usual. I convert the returns from pipe() into file objects with <strong>os.fdopen</strong>. </p>
<p>The problem I'm having is this: The process successfully forks, and the child becomes a server. Everything works great and the child dutifully writes data to the open <code>'w'</code> end of the pipe. Unfortunately the parent end of the pipe does two strange things:<br>
A) It blocks on the <code>read()</code> operation on the <code>'r'</code> end of the pipe.<br>
Secondly, it fails to read any data that was put on the pipe unless the <code>'w'</code> end is entirely closed.</p>
<p>I immediately thought that buffering was the problem and added <strong>pipe.flush()</strong> calls, but these didn't help. </p>
<p>Can anyone shed some light on why the data doesn't appear until the writing end is fully closed? And is there a strategy to make the <code>read()</code> call non blocking?</p>
<p>This is my first Python program that forked or used pipes, so forgive me if I've made a simple mistake. </p>
| 10 | 2009-05-16T01:36:53Z | 872,637 | <p>Are you using read() without specifying a size, or treating the pipe as an iterator (<code>for line in f</code>)? If so, that's probably the source of your problem - read() is defined to read until the end of the file before returning, rather than just read what is available for reading. That will mean it will block until the child calls close().</p>
<p>In the example code linked to, this is OK - the parent is acting in a blocking manner, and just using the child for isolation purposes. If you want to continue, then either use non-blocking IO as in the code you posted (but be prepared to deal with half-complete data), or read in chunks (eg r.read(size) or r.readline()) which will block only until a specific size / line has been read. (you'll still need to call flush on the child)</p>
<p>It looks like treating the pipe as an iterator is using some further buffer as well, for "<code>for line in r:</code>" may not give you what you want if you need each line to be immediately consumed. It may be possible to disable this, but just specifying 0 for the buffer size in fdopen doesn't seem sufficient.</p>
<p>Heres some sample code that should work:</p>
<pre><code>import os, sys, time
r,w=os.pipe()
r,w=os.fdopen(r,'r',0), os.fdopen(w,'w',0)
pid = os.fork()
if pid: # Parent
w.close()
while 1:
data=r.readline()
if not data: break
print "parent read: " + data.strip()
else: # Child
r.close()
for i in range(10):
print >>w, "line %s" % i
w.flush()
time.sleep(1)
</code></pre>
| 10 | 2009-05-16T15:30:19Z | [
"python",
"pipe",
"fork"
] |
Simple List of All Java Standard Classes and Methods? | 871,812 | <p>I'm building a very simple Java parser, to look for some specific usage models. This is in no way lex/yacc or any other form of interpreter/compiler for puposes of running the code. </p>
<p>When I encounter a word or a set of two words separated by a dot ("word.word"), I would like to know if that's a standard Java class (and method), e.g. "Integer", or some user defined name. I'm not interested in whether the proper classes were included/imported in the code (i.e. if the code compiles well), and the extreme cases of user defined classes that override the names of standard Java classes also does not interest me. In other words: I'm okay with false negative, I'm only interesting in being "mostly" right.</p>
<p>If there a place wher I could find a simple list of all the names of all Java standard classes and methods, in the form easily saved into a text file or database? (J2SE is okay, but J2EE is better). I'm familiar with <a href="http://java.sun.com/j2se/">http://java.sun.com/j2se/</a> etc, but it seems I need a terrible amount of manual work to extract all the names from there. Also, the most recent JDK is not neccesary, I can live with 1.4 or 1.5. </p>
<p>Clarification: I'm not working in Java but in Python, so I can't use Java-specific commands in my parsing mechanism.</p>
<p>Thanks</p>
| 6 | 2009-05-16T05:58:52Z | 871,818 | <p>What's wrong with the <a href="http://java.sun.com/javase/6/docs/api/allclasses-frame.html" rel="nofollow">javadoc</a>? The <a href="http://java.sun.com/javase/6/docs/api/allclasses-frame.html" rel="nofollow">index</a> lists all classes, methods, and static variables. You can probably grep for parenthesis.</p>
| 1 | 2009-05-16T06:03:45Z | [
"java",
"python",
"parsing"
] |
Simple List of All Java Standard Classes and Methods? | 871,812 | <p>I'm building a very simple Java parser, to look for some specific usage models. This is in no way lex/yacc or any other form of interpreter/compiler for puposes of running the code. </p>
<p>When I encounter a word or a set of two words separated by a dot ("word.word"), I would like to know if that's a standard Java class (and method), e.g. "Integer", or some user defined name. I'm not interested in whether the proper classes were included/imported in the code (i.e. if the code compiles well), and the extreme cases of user defined classes that override the names of standard Java classes also does not interest me. In other words: I'm okay with false negative, I'm only interesting in being "mostly" right.</p>
<p>If there a place wher I could find a simple list of all the names of all Java standard classes and methods, in the form easily saved into a text file or database? (J2SE is okay, but J2EE is better). I'm familiar with <a href="http://java.sun.com/j2se/">http://java.sun.com/j2se/</a> etc, but it seems I need a terrible amount of manual work to extract all the names from there. Also, the most recent JDK is not neccesary, I can live with 1.4 or 1.5. </p>
<p>Clarification: I'm not working in Java but in Python, so I can't use Java-specific commands in my parsing mechanism.</p>
<p>Thanks</p>
| 6 | 2009-05-16T05:58:52Z | 871,820 | <p>To get all classes and methods you can look at the index on
<a href="http://java.sun.com/javase/6/docs/api/index-files/index-1.html" rel="nofollow">http://java.sun.com/javase/6/docs/api/index-files/index-1.html</a></p>
<p>This will be 10's of thousands classes and method which can be overwhelming.</p>
<p>I suggest instead you use auto-complete in your IDE. This will show you all the matching classes/methods appropriate based on context.
e.g. say you have a variable</p>
<p>long time = System.</p>
<p>This will show you all the methods in System which return a long value, such as</p>
<p>long time = System.nanoTime();</p>
<p>Even if you know a lot of the method/classes, this can save you a lot of typing.</p>
| 1 | 2009-05-16T06:06:25Z | [
"java",
"python",
"parsing"
] |
Simple List of All Java Standard Classes and Methods? | 871,812 | <p>I'm building a very simple Java parser, to look for some specific usage models. This is in no way lex/yacc or any other form of interpreter/compiler for puposes of running the code. </p>
<p>When I encounter a word or a set of two words separated by a dot ("word.word"), I would like to know if that's a standard Java class (and method), e.g. "Integer", or some user defined name. I'm not interested in whether the proper classes were included/imported in the code (i.e. if the code compiles well), and the extreme cases of user defined classes that override the names of standard Java classes also does not interest me. In other words: I'm okay with false negative, I'm only interesting in being "mostly" right.</p>
<p>If there a place wher I could find a simple list of all the names of all Java standard classes and methods, in the form easily saved into a text file or database? (J2SE is okay, but J2EE is better). I'm familiar with <a href="http://java.sun.com/j2se/">http://java.sun.com/j2se/</a> etc, but it seems I need a terrible amount of manual work to extract all the names from there. Also, the most recent JDK is not neccesary, I can live with 1.4 or 1.5. </p>
<p>Clarification: I'm not working in Java but in Python, so I can't use Java-specific commands in my parsing mechanism.</p>
<p>Thanks</p>
| 6 | 2009-05-16T05:58:52Z | 871,879 | <blockquote>
<p>When I encounter a word or a set of two words separated by a dot ("word.word"), I would like to know if that's a standard Java class (and method), e.g. "Integer", or some user defined name.</p>
</blockquote>
<p>If thats what you're after, you could do without a (limited) list of Java Classes by using some simple reflection:
<a href="http://java.sun.com/developer/technicalArticles/ALT/Reflection/" rel="nofollow">http://java.sun.com/developer/technicalArticles/ALT/Reflection/</a></p>
<pre><code>try {
Class.forName("word.word");
System.out.println("This is a valid class!");
} catch (ClassNotFoundException e) {
System.out.println("This is not a valid class.");
}
</code></pre>
<p>Something like this should be enough for your purposes, with he added benefit of not being limited to a subset of classes, and extensible by any libraries on the classpath.</p>
| 0 | 2009-05-16T07:16:18Z | [
"java",
"python",
"parsing"
] |
Simple List of All Java Standard Classes and Methods? | 871,812 | <p>I'm building a very simple Java parser, to look for some specific usage models. This is in no way lex/yacc or any other form of interpreter/compiler for puposes of running the code. </p>
<p>When I encounter a word or a set of two words separated by a dot ("word.word"), I would like to know if that's a standard Java class (and method), e.g. "Integer", or some user defined name. I'm not interested in whether the proper classes were included/imported in the code (i.e. if the code compiles well), and the extreme cases of user defined classes that override the names of standard Java classes also does not interest me. In other words: I'm okay with false negative, I'm only interesting in being "mostly" right.</p>
<p>If there a place wher I could find a simple list of all the names of all Java standard classes and methods, in the form easily saved into a text file or database? (J2SE is okay, but J2EE is better). I'm familiar with <a href="http://java.sun.com/j2se/">http://java.sun.com/j2se/</a> etc, but it seems I need a terrible amount of manual work to extract all the names from there. Also, the most recent JDK is not neccesary, I can live with 1.4 or 1.5. </p>
<p>Clarification: I'm not working in Java but in Python, so I can't use Java-specific commands in my parsing mechanism.</p>
<p>Thanks</p>
| 6 | 2009-05-16T05:58:52Z | 871,896 | <p>If you just want to create a list of all classes in Java and their methods (so that you can populate a database or an XML file), you may want to write an Eclipse-plugin that looks at the entire JavaCore model, and scans all of its classes (e.g., by searching all subtypes of Object). Then enumerate all the methods. You can do that technically to any library by including it in your context.</p>
| 1 | 2009-05-16T07:25:01Z | [
"java",
"python",
"parsing"
] |
Simple List of All Java Standard Classes and Methods? | 871,812 | <p>I'm building a very simple Java parser, to look for some specific usage models. This is in no way lex/yacc or any other form of interpreter/compiler for puposes of running the code. </p>
<p>When I encounter a word or a set of two words separated by a dot ("word.word"), I would like to know if that's a standard Java class (and method), e.g. "Integer", or some user defined name. I'm not interested in whether the proper classes were included/imported in the code (i.e. if the code compiles well), and the extreme cases of user defined classes that override the names of standard Java classes also does not interest me. In other words: I'm okay with false negative, I'm only interesting in being "mostly" right.</p>
<p>If there a place wher I could find a simple list of all the names of all Java standard classes and methods, in the form easily saved into a text file or database? (J2SE is okay, but J2EE is better). I'm familiar with <a href="http://java.sun.com/j2se/">http://java.sun.com/j2se/</a> etc, but it seems I need a terrible amount of manual work to extract all the names from there. Also, the most recent JDK is not neccesary, I can live with 1.4 or 1.5. </p>
<p>Clarification: I'm not working in Java but in Python, so I can't use Java-specific commands in my parsing mechanism.</p>
<p>Thanks</p>
| 6 | 2009-05-16T05:58:52Z | 871,901 | <p>IBM had a tool for creating XML from JavaDocs, if I am not mistaken:
<a href="http://www.ibm.com/developerworks/xml/library/x-tipjdoc/index.html" rel="nofollow">http://www.ibm.com/developerworks/xml/library/x-tipjdoc/index.html</a></p>
| 1 | 2009-05-16T07:26:22Z | [
"java",
"python",
"parsing"
] |
Simple List of All Java Standard Classes and Methods? | 871,812 | <p>I'm building a very simple Java parser, to look for some specific usage models. This is in no way lex/yacc or any other form of interpreter/compiler for puposes of running the code. </p>
<p>When I encounter a word or a set of two words separated by a dot ("word.word"), I would like to know if that's a standard Java class (and method), e.g. "Integer", or some user defined name. I'm not interested in whether the proper classes were included/imported in the code (i.e. if the code compiles well), and the extreme cases of user defined classes that override the names of standard Java classes also does not interest me. In other words: I'm okay with false negative, I'm only interesting in being "mostly" right.</p>
<p>If there a place wher I could find a simple list of all the names of all Java standard classes and methods, in the form easily saved into a text file or database? (J2SE is okay, but J2EE is better). I'm familiar with <a href="http://java.sun.com/j2se/">http://java.sun.com/j2se/</a> etc, but it seems I need a terrible amount of manual work to extract all the names from there. Also, the most recent JDK is not neccesary, I can live with 1.4 or 1.5. </p>
<p>Clarification: I'm not working in Java but in Python, so I can't use Java-specific commands in my parsing mechanism.</p>
<p>Thanks</p>
| 6 | 2009-05-16T05:58:52Z | 871,924 | <p>There's also an option to either parse <code>classlist</code> file from jre/lib folder or open the <code>jsse.jar</code> file, list all classes there and make a list of them in dot-separated form by yourself.</p>
| 1 | 2009-05-16T07:41:11Z | [
"java",
"python",
"parsing"
] |
Using exec() with recursive functions | 871,887 | <p>I want to execute some Python code, typed at runtime, so I get the string and call</p>
<blockquote>
<p>exec(pp, globals(), locals())</p>
</blockquote>
<p>where <strong>pp</strong> is the string. It works fine, except for recursive calls, e. g., for example, this code is OK:</p>
<pre><code>def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
while True:
horse()
</code></pre>
<p>But this one is not:</p>
<pre><code>def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
horse()
horse()
</code></pre>
<blockquote>
<p>NameError: global name 'horse' is not
defined</p>
</blockquote>
<p>Is there a way to run recursive code as well?</p>
<p>UPDATE</p>
<pre><code>a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
</code></pre>
<p>Works if put on the top-level. But if moved inside a function:</p>
<pre><code>def fn1():
a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
fn1()
</code></pre>
<p>the same error occurs: NameError: global name 'rec' is not defined</p>
| 5 | 2009-05-16T07:21:25Z | 871,906 | <p>It works for me:</p>
<pre><code>a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
5
6
7
8
9
10
</code></pre>
<p>All I can say is that there is probably a bug in your code.</p>
<p><strong>Edit</strong></p>
<p>Here you go</p>
<pre><code>def fn1():
glob = {}
a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a, glob)
fn1()
</code></pre>
| 4 | 2009-05-16T07:30:48Z | [
"python",
"recursion",
"exec"
] |
Using exec() with recursive functions | 871,887 | <p>I want to execute some Python code, typed at runtime, so I get the string and call</p>
<blockquote>
<p>exec(pp, globals(), locals())</p>
</blockquote>
<p>where <strong>pp</strong> is the string. It works fine, except for recursive calls, e. g., for example, this code is OK:</p>
<pre><code>def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
while True:
horse()
</code></pre>
<p>But this one is not:</p>
<pre><code>def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
horse()
horse()
</code></pre>
<blockquote>
<p>NameError: global name 'horse' is not
defined</p>
</blockquote>
<p>Is there a way to run recursive code as well?</p>
<p>UPDATE</p>
<pre><code>a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
</code></pre>
<p>Works if put on the top-level. But if moved inside a function:</p>
<pre><code>def fn1():
a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
fn1()
</code></pre>
<p>the same error occurs: NameError: global name 'rec' is not defined</p>
| 5 | 2009-05-16T07:21:25Z | 871,956 | <p>"NameError: global name 'rec' is not defined" means it's looking for rec in the global scope, not the local scope. Looks like it's defining rec in the local scope but then attempting to execute in the global. Try printing locals() and globals() in side the string you're executing.</p>
<p><a href="http://www.python.org/doc/2.5.2/ref/exec.html" rel="nofollow">More info.</a></p>
| 0 | 2009-05-16T08:05:53Z | [
"python",
"recursion",
"exec"
] |
Using exec() with recursive functions | 871,887 | <p>I want to execute some Python code, typed at runtime, so I get the string and call</p>
<blockquote>
<p>exec(pp, globals(), locals())</p>
</blockquote>
<p>where <strong>pp</strong> is the string. It works fine, except for recursive calls, e. g., for example, this code is OK:</p>
<pre><code>def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
while True:
horse()
</code></pre>
<p>But this one is not:</p>
<pre><code>def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
horse()
horse()
</code></pre>
<blockquote>
<p>NameError: global name 'horse' is not
defined</p>
</blockquote>
<p>Is there a way to run recursive code as well?</p>
<p>UPDATE</p>
<pre><code>a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
</code></pre>
<p>Works if put on the top-level. But if moved inside a function:</p>
<pre><code>def fn1():
a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
fn1()
</code></pre>
<p>the same error occurs: NameError: global name 'rec' is not defined</p>
| 5 | 2009-05-16T07:21:25Z | 871,983 | <p>This works for me (added <code>global rec</code>). <code>rec(5)</code> calls the local <code>rec</code>, but <code>rec(n+1)</code> calls a global rec (which doesn't exist) without it.</p>
<pre><code>def fn1():
a = """global rec
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
</code></pre>
| 3 | 2009-05-16T08:30:27Z | [
"python",
"recursion",
"exec"
] |
Using exec() with recursive functions | 871,887 | <p>I want to execute some Python code, typed at runtime, so I get the string and call</p>
<blockquote>
<p>exec(pp, globals(), locals())</p>
</blockquote>
<p>where <strong>pp</strong> is the string. It works fine, except for recursive calls, e. g., for example, this code is OK:</p>
<pre><code>def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
while True:
horse()
</code></pre>
<p>But this one is not:</p>
<pre><code>def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
horse()
horse()
</code></pre>
<blockquote>
<p>NameError: global name 'horse' is not
defined</p>
</blockquote>
<p>Is there a way to run recursive code as well?</p>
<p>UPDATE</p>
<pre><code>a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
</code></pre>
<p>Works if put on the top-level. But if moved inside a function:</p>
<pre><code>def fn1():
a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
fn1()
</code></pre>
<p>the same error occurs: NameError: global name 'rec' is not defined</p>
| 5 | 2009-05-16T07:21:25Z | 872,082 | <p>This surprised me too at first, and seems to be an odd corner case where exec is acting neither quite like a top-level definition, or a definition within an enclosing function. It looks like what is happening is that the function definition is being executed in the locals() dict you pass in. However, the defined function does not actually have access to this locals dict.</p>
<p>Normally, if you define a function at the toplevel, locals and globals are the same, so functions are visible within because they can see the function in the globals.</p>
<p>When a function is defined within another function's scope, python will notice that it is accessed within the function, and create a closure so that "horse" maps to the binding in the outer scope.</p>
<p>Here, it's a weird halfway case. exec is acting as if the definitions are at top-level, so no closures are created. However, since locals is not the same as globals, the definition doesn't go where the function can access it - its defined only in the inaccessible outer locals dict.</p>
<p>There are a couple of things you could do:</p>
<ol>
<li>Use the same dictionary for both locals and globals. ie "<code>exec s in locals(),locals()</code>" (or better, just use your own dict). Providing only a globals() dict has the same effect - ie "<code>exec s in mydict</code>"
#</li>
<li><p>Put the func inside its own function, so that a closure is created. eg</p>
<pre><code>s="""
def go():
def factorial(x):
if x==0: return 1
return x*factorial(x-1)
print factorial(10)
go()"""
</code></pre></li>
<li><p>Force the function to go into globals() rather than locals by putting a "global funcname" directive, as suggested by <a href="http://stackoverflow.com/questions/871887/using-exec-with-recursive-functions/871983#871983">stephan's answer</a></p></li>
</ol>
| 4 | 2009-05-16T09:45:06Z | [
"python",
"recursion",
"exec"
] |
Python vs. C# Twitter API libraries | 872,054 | <p>I have experience with both .NET(5yrs) and Python(1yr) and I want to create a simple web project with Twitter as the backbone. I have experience with AppEngine, and have always wanted to try Azure. I'm going to make extensive use of sending and parsing tweets from lots of users at a time, and since I've set a short deadline for this I'd like to take the shortest path possible. So does anyone have any experience with both of these, or have any advice?</p>
<p>A quick look at the twitter API libraries(<a href="http://apiwiki.twitter.com/Libraries">http://apiwiki.twitter.com/Libraries</a>) gave me this for python:</p>
<ul>
<li>python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API.</li>
<li>python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client.</li>
<li>twitty-twister by Dustin Sallings. A Twisted interface to Twitter.</li>
</ul>
<p>and this for C#:</p>
<ul>
<li>Yedda Twitter Library by Yedda. Every Twitter API method has an equivalent .NET method in this wrapper library.</li>
<li>TwitterooCore API by Eric Willis/RareEdge Design Group. Binary .NET library that can be used in any .NET project. </li>
<li>Twitterizer originally by DigitallyBorn, but now open source. Written for .NET 2.0.</li>
<li>tweet# by Daniel Crenna. "100% coverage of the REST and Search APIs".</li>
</ul>
| 12 | 2009-05-16T09:27:26Z | 872,066 | <p>The best advice is to use whatever language you are most comfortable with.</p>
<p>Myself and a colleague have recently re-written our Twitter web-app's entire back-end with a C# service, and the decision for us came down to which library best suited the purpose. A number of the libraries have varying 'features', some are more complete than others: we decided which to select based purely on trying them out, and seeing which were the best-optimised, and made our job easiest.</p>
<p>I would make a recommendation for a C# library, but the playing field changes so very quickly, and we've changed implementations a couple of times, as Twitter has deprecated various aspects of their API, and some have updated more quickly than others.</p>
| 4 | 2009-05-16T09:35:35Z | [
"c#",
"python",
"api",
"twitter"
] |
Python vs. C# Twitter API libraries | 872,054 | <p>I have experience with both .NET(5yrs) and Python(1yr) and I want to create a simple web project with Twitter as the backbone. I have experience with AppEngine, and have always wanted to try Azure. I'm going to make extensive use of sending and parsing tweets from lots of users at a time, and since I've set a short deadline for this I'd like to take the shortest path possible. So does anyone have any experience with both of these, or have any advice?</p>
<p>A quick look at the twitter API libraries(<a href="http://apiwiki.twitter.com/Libraries">http://apiwiki.twitter.com/Libraries</a>) gave me this for python:</p>
<ul>
<li>python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API.</li>
<li>python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client.</li>
<li>twitty-twister by Dustin Sallings. A Twisted interface to Twitter.</li>
</ul>
<p>and this for C#:</p>
<ul>
<li>Yedda Twitter Library by Yedda. Every Twitter API method has an equivalent .NET method in this wrapper library.</li>
<li>TwitterooCore API by Eric Willis/RareEdge Design Group. Binary .NET library that can be used in any .NET project. </li>
<li>Twitterizer originally by DigitallyBorn, but now open source. Written for .NET 2.0.</li>
<li>tweet# by Daniel Crenna. "100% coverage of the REST and Search APIs".</li>
</ul>
| 12 | 2009-05-16T09:27:26Z | 872,219 | <p>I would put my vote in for this twitter library; <a href="http://code.google.com/p/python-twitter/" rel="nofollow">http://code.google.com/p/python-twitter/</a></p>
<p>I've used it in 10+ projects that I can think of and its been very good. I've actually been using the dev version in a number of projects too and found it stable and has many more features.</p>
| 4 | 2009-05-16T11:17:24Z | [
"c#",
"python",
"api",
"twitter"
] |
Python vs. C# Twitter API libraries | 872,054 | <p>I have experience with both .NET(5yrs) and Python(1yr) and I want to create a simple web project with Twitter as the backbone. I have experience with AppEngine, and have always wanted to try Azure. I'm going to make extensive use of sending and parsing tweets from lots of users at a time, and since I've set a short deadline for this I'd like to take the shortest path possible. So does anyone have any experience with both of these, or have any advice?</p>
<p>A quick look at the twitter API libraries(<a href="http://apiwiki.twitter.com/Libraries">http://apiwiki.twitter.com/Libraries</a>) gave me this for python:</p>
<ul>
<li>python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API.</li>
<li>python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client.</li>
<li>twitty-twister by Dustin Sallings. A Twisted interface to Twitter.</li>
</ul>
<p>and this for C#:</p>
<ul>
<li>Yedda Twitter Library by Yedda. Every Twitter API method has an equivalent .NET method in this wrapper library.</li>
<li>TwitterooCore API by Eric Willis/RareEdge Design Group. Binary .NET library that can be used in any .NET project. </li>
<li>Twitterizer originally by DigitallyBorn, but now open source. Written for .NET 2.0.</li>
<li>tweet# by Daniel Crenna. "100% coverage of the REST and Search APIs".</li>
</ul>
| 12 | 2009-05-16T09:27:26Z | 872,603 | <p>You can use both .NET and Python ... IronPython. IronPython will work with Yedda. [1]</p>
| 0 | 2009-05-16T15:10:35Z | [
"c#",
"python",
"api",
"twitter"
] |
Python vs. C# Twitter API libraries | 872,054 | <p>I have experience with both .NET(5yrs) and Python(1yr) and I want to create a simple web project with Twitter as the backbone. I have experience with AppEngine, and have always wanted to try Azure. I'm going to make extensive use of sending and parsing tweets from lots of users at a time, and since I've set a short deadline for this I'd like to take the shortest path possible. So does anyone have any experience with both of these, or have any advice?</p>
<p>A quick look at the twitter API libraries(<a href="http://apiwiki.twitter.com/Libraries">http://apiwiki.twitter.com/Libraries</a>) gave me this for python:</p>
<ul>
<li>python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API.</li>
<li>python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client.</li>
<li>twitty-twister by Dustin Sallings. A Twisted interface to Twitter.</li>
</ul>
<p>and this for C#:</p>
<ul>
<li>Yedda Twitter Library by Yedda. Every Twitter API method has an equivalent .NET method in this wrapper library.</li>
<li>TwitterooCore API by Eric Willis/RareEdge Design Group. Binary .NET library that can be used in any .NET project. </li>
<li>Twitterizer originally by DigitallyBorn, but now open source. Written for .NET 2.0.</li>
<li>tweet# by Daniel Crenna. "100% coverage of the REST and Search APIs".</li>
</ul>
| 12 | 2009-05-16T09:27:26Z | 872,611 | <p>I am using <a href="http://mike.verdone.ca/twitter/" rel="nofollow">this python library</a> for one of my project.</p>
<p>It's really easy to use and yet very powerful.</p>
| 0 | 2009-05-16T15:16:07Z | [
"c#",
"python",
"api",
"twitter"
] |
Python vs. C# Twitter API libraries | 872,054 | <p>I have experience with both .NET(5yrs) and Python(1yr) and I want to create a simple web project with Twitter as the backbone. I have experience with AppEngine, and have always wanted to try Azure. I'm going to make extensive use of sending and parsing tweets from lots of users at a time, and since I've set a short deadline for this I'd like to take the shortest path possible. So does anyone have any experience with both of these, or have any advice?</p>
<p>A quick look at the twitter API libraries(<a href="http://apiwiki.twitter.com/Libraries">http://apiwiki.twitter.com/Libraries</a>) gave me this for python:</p>
<ul>
<li>python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API.</li>
<li>python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client.</li>
<li>twitty-twister by Dustin Sallings. A Twisted interface to Twitter.</li>
</ul>
<p>and this for C#:</p>
<ul>
<li>Yedda Twitter Library by Yedda. Every Twitter API method has an equivalent .NET method in this wrapper library.</li>
<li>TwitterooCore API by Eric Willis/RareEdge Design Group. Binary .NET library that can be used in any .NET project. </li>
<li>Twitterizer originally by DigitallyBorn, but now open source. Written for .NET 2.0.</li>
<li>tweet# by Daniel Crenna. "100% coverage of the REST and Search APIs".</li>
</ul>
| 12 | 2009-05-16T09:27:26Z | 926,485 | <p><a href="http://linqtotwitter.codeplex.com/" rel="nofollow">LINQ to Twitter</a> is available too, covers the entire Twitter API, and works with VB, C#, and Delphi Prism.</p>
<p>Joe</p>
| 3 | 2009-05-29T15:07:59Z | [
"c#",
"python",
"api",
"twitter"
] |
Python vs. C# Twitter API libraries | 872,054 | <p>I have experience with both .NET(5yrs) and Python(1yr) and I want to create a simple web project with Twitter as the backbone. I have experience with AppEngine, and have always wanted to try Azure. I'm going to make extensive use of sending and parsing tweets from lots of users at a time, and since I've set a short deadline for this I'd like to take the shortest path possible. So does anyone have any experience with both of these, or have any advice?</p>
<p>A quick look at the twitter API libraries(<a href="http://apiwiki.twitter.com/Libraries">http://apiwiki.twitter.com/Libraries</a>) gave me this for python:</p>
<ul>
<li>python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API.</li>
<li>python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client.</li>
<li>twitty-twister by Dustin Sallings. A Twisted interface to Twitter.</li>
</ul>
<p>and this for C#:</p>
<ul>
<li>Yedda Twitter Library by Yedda. Every Twitter API method has an equivalent .NET method in this wrapper library.</li>
<li>TwitterooCore API by Eric Willis/RareEdge Design Group. Binary .NET library that can be used in any .NET project. </li>
<li>Twitterizer originally by DigitallyBorn, but now open source. Written for .NET 2.0.</li>
<li>tweet# by Daniel Crenna. "100% coverage of the REST and Search APIs".</li>
</ul>
| 12 | 2009-05-16T09:27:26Z | 1,100,307 | <p>python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client.</p>
<p>is my python library of choice. it's fairly straightforward. </p>
| 0 | 2009-07-08T20:15:04Z | [
"c#",
"python",
"api",
"twitter"
] |
Python vs. C# Twitter API libraries | 872,054 | <p>I have experience with both .NET(5yrs) and Python(1yr) and I want to create a simple web project with Twitter as the backbone. I have experience with AppEngine, and have always wanted to try Azure. I'm going to make extensive use of sending and parsing tweets from lots of users at a time, and since I've set a short deadline for this I'd like to take the shortest path possible. So does anyone have any experience with both of these, or have any advice?</p>
<p>A quick look at the twitter API libraries(<a href="http://apiwiki.twitter.com/Libraries">http://apiwiki.twitter.com/Libraries</a>) gave me this for python:</p>
<ul>
<li>python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API.</li>
<li>python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client.</li>
<li>twitty-twister by Dustin Sallings. A Twisted interface to Twitter.</li>
</ul>
<p>and this for C#:</p>
<ul>
<li>Yedda Twitter Library by Yedda. Every Twitter API method has an equivalent .NET method in this wrapper library.</li>
<li>TwitterooCore API by Eric Willis/RareEdge Design Group. Binary .NET library that can be used in any .NET project. </li>
<li>Twitterizer originally by DigitallyBorn, but now open source. Written for .NET 2.0.</li>
<li>tweet# by Daniel Crenna. "100% coverage of the REST and Search APIs".</li>
</ul>
| 12 | 2009-05-16T09:27:26Z | 1,288,970 | <p>I have a bit of experience with the Twitter API (I'm Digitallyborn, author of Twitterizer).</p>
<p>I would say go with what is easiest to you. There are a lot of great libraries out there for every language.</p>
| 0 | 2009-08-17T16:21:37Z | [
"c#",
"python",
"api",
"twitter"
] |
Visual Editor for Django Templates? | 872,065 | <p>Is there a tool out there for visually building Django templates?</p>
<p>Thanks</p>
| 16 | 2009-05-16T09:34:04Z | 873,728 | <p>I haven't tried it personally, but a co-worker uses the free <a href="http://www.activestate.com/komodo%5Fedit/features/" rel="nofollow">ActiveState Komodo Edit</a> to edit Django templates, and the page I linked claims support for Django template editing.</p>
<p>There's also <a href="http://code.google.com/p/netbeans-django/" rel="nofollow">netbeans-django</a> that is building a Django plugin for Netbeans, but no idea how complete or how well it works.</p>
<p>I've read that TextMate has a "Django bundle" for editing code and templates if you're on a Mac.</p>
| 6 | 2009-05-17T01:51:48Z | [
"python",
"django",
"django-templates"
] |
Visual Editor for Django Templates? | 872,065 | <p>Is there a tool out there for visually building Django templates?</p>
<p>Thanks</p>
| 16 | 2009-05-16T09:34:04Z | 874,222 | <p>There's no WYSIWYG tool like Dreamweaver. But highligting is possible. I am using Kate to edit my templates.</p>
<p>For instance when you comment in Django template it inserts <code>{% comment %}</code>.</p>
| 2 | 2009-05-17T09:19:03Z | [
"python",
"django",
"django-templates"
] |
Visual Editor for Django Templates? | 872,065 | <p>Is there a tool out there for visually building Django templates?</p>
<p>Thanks</p>
| 16 | 2009-05-16T09:34:04Z | 875,985 | <p>Kind of an oblique answer, but if being able to use tools like Dreamweaver on your templates is important to you, you may find you like Genshi better than Django Templates, and it's easy enough to switch your template engine. </p>
<p>Genshi is an XML templating language that is one of the inheritors of the Zope TAL family. Your template file <em>is</em> a valid XML file, so you can open it in any XML aware tool. Personally, once I got used to using XML templates, I couldn't go back, but they are slower to process ( an xml parser has to run behind the scenes ) and they require valid XHTML in your output which can be a good or a bad thing. ( Invalid user submitted html content for example would need to be forced clean using something like Beautiful Soup or ElementTree ).</p>
| 1 | 2009-05-18T02:04:43Z | [
"python",
"django",
"django-templates"
] |
Visual Editor for Django Templates? | 872,065 | <p>Is there a tool out there for visually building Django templates?</p>
<p>Thanks</p>
| 16 | 2009-05-16T09:34:04Z | 3,940,622 | <p>I'm really liking Eclipse with Pydev and the Aptana Studio 3 Eclipse plugin. More info here: <a href="http://pydev.blogspot.com/2010/08/django-templates-editor.html" rel="nofollow">http://pydev.blogspot.com/2010/08/django-templates-editor.html</a></p>
<p>(The first thing I did was change the theme. I quite like the Mac Classic theme's Django template highlighting.)</p>
| 1 | 2010-10-15T08:27:59Z | [
"python",
"django",
"django-templates"
] |
Visual Editor for Django Templates? | 872,065 | <p>Is there a tool out there for visually building Django templates?</p>
<p>Thanks</p>
| 16 | 2009-05-16T09:34:04Z | 4,040,196 | <p>There is also <a href="http://www.jetbrains.com/pycharm/">PyCharm</a>.</p>
| 6 | 2010-10-28T05:59:17Z | [
"python",
"django",
"django-templates"
] |
Visual Editor for Django Templates? | 872,065 | <p>Is there a tool out there for visually building Django templates?</p>
<p>Thanks</p>
| 16 | 2009-05-16T09:34:04Z | 7,990,708 | <p>Don't forget for the <a href="https://code.djangoproject.com/wiki/Emacs" rel="nofollow">Emacs</a> Users there is django template assistance. The Emacs link will take you to more helpful documentation in Emacs.</p>
| 0 | 2011-11-03T05:40:42Z | [
"python",
"django",
"django-templates"
] |
No reverse error in Google App Engine Django patch? | 872,100 | <p>I am using <a href="http://en.wikipedia.org/wiki/Google%5FApp%5FEngine" rel="nofollow">Google App Engine</a> patch Django.</p>
<p>When I try to go to the admin site,</p>
<blockquote>
<p><a href="http://127.0.0.1:8080/admin/" rel="nofollow">http://127.0.0.1:8080/admin/</a></p>
</blockquote>
<p>, I keep getting this error:</p>
<blockquote>
<p>TemplateSyntaxError at /admin/
Caught an exception while rendering: Reverse for
'settings.django.contrib.auth.views.logout' with arguments
'()' and keyword arguments '{}' not found.</p>
</blockquote>
<p>It's a fresh installation and I have not changed much. But I
am not able to solve this problem.</p>
<p>This is the urls.py file that comes with the patch inside
the registration app:</p>
<pre><code>urlpatterns = patterns('',
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get to
# that way it can return a sensible "invalid key" message instead
# confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
activate,
name='registration_activate'),
url(r'^login/$',
auth_views.login,
{'template_name': 'registration/login.html'},
name='auth_login'),
url(r'^logout/$',
auth_views.logout,
name='auth_logout'),
url(r'^password/change/$',
auth_views.password_change,
name='auth_password_change'),
url(r'^password/change/done/$',
auth_views.password_change_done,
name='auth_password_change_done'),
url(r'^password/reset/$',
auth_views.password_reset,
name='auth_password_reset'),
url(r'^password/reset/confirm/(?P<uidb36>.+)/(?P<token>.+)/$',
auth_views.password_reset_confirm,
name='auth_password_reset_confirm'),
url(r'^password/reset/complete/$',
auth_views.password_reset_complete,
name='auth_password_reset_complete'),
url(r'^password/reset/done/$',
auth_views.password_reset_done,
name='auth_password_reset_done'),
url(r'^register/$',
register,
name='registration_register'),
url(r'^register/complete/$',
direct_to_template,
{'template': 'registration/registration_complete.html'},
name='registration_complete'),
)
</code></pre>
| 2 | 2009-05-16T10:02:28Z | 889,946 | <p>I could not find a proper answer to my question. Anyways I solved the problem temporarily by reinstalling the Django framework and the app engine SDK.</p>
| 1 | 2009-05-20T20:01:37Z | [
"python",
"django",
"google-app-engine",
"django-urls"
] |
What's wrong with this Python code? | 872,119 | <p>I'm very new so just learning, so go easy please!</p>
<pre><code>start = int(input('How much did you start with?:' ))
if start < 0:
print("That's impossible! Try again.")
print(start = int(input('How much did you start with:' )))
if start >= 0:
print(inorout = raw_input('Cool! Now have you put money in or taken it out?: '))
if inorout == in:
print(in = int(raw_input('Well done! How much did you put in?:')))
print(int(start + in))
</code></pre>
<p>This always results in syntax error? I'm sure I'm doing something obvious wrong!</p>
<p>Thanks!</p>
| -1 | 2009-05-16T10:09:06Z | 872,125 | <ul>
<li>You can't assign to variables in expressions in Python, like in C: print (start=int(input('blah'))) isn't correct. Do the assignment first in a separate statement.</li>
<li>The first line musn't be indented, but that might just be a copy and paste error.</li>
<li>The word <code>in</code> is a reserved word so you can't use it for variable names</li>
</ul>
| 7 | 2009-05-16T10:14:00Z | [
"python"
] |
What's wrong with this Python code? | 872,119 | <p>I'm very new so just learning, so go easy please!</p>
<pre><code>start = int(input('How much did you start with?:' ))
if start < 0:
print("That's impossible! Try again.")
print(start = int(input('How much did you start with:' )))
if start >= 0:
print(inorout = raw_input('Cool! Now have you put money in or taken it out?: '))
if inorout == in:
print(in = int(raw_input('Well done! How much did you put in?:')))
print(int(start + in))
</code></pre>
<p>This always results in syntax error? I'm sure I'm doing something obvious wrong!</p>
<p>Thanks!</p>
| -1 | 2009-05-16T10:09:06Z | 872,130 | <p>Assigning in statements is your problem.
Move the assignments out of print statements</p>
| 3 | 2009-05-16T10:19:05Z | [
"python"
] |
What's wrong with this Python code? | 872,119 | <p>I'm very new so just learning, so go easy please!</p>
<pre><code>start = int(input('How much did you start with?:' ))
if start < 0:
print("That's impossible! Try again.")
print(start = int(input('How much did you start with:' )))
if start >= 0:
print(inorout = raw_input('Cool! Now have you put money in or taken it out?: '))
if inorout == in:
print(in = int(raw_input('Well done! How much did you put in?:')))
print(int(start + in))
</code></pre>
<p>This always results in syntax error? I'm sure I'm doing something obvious wrong!</p>
<p>Thanks!</p>
| -1 | 2009-05-16T10:09:06Z | 872,465 | <ul>
<li>Consider prompting for input using a function wrapping a loop.</li>
<li>Don't use <a href="http://docs.python.org/library/functions.html#input" rel="nofollow">input</a> for general user input, use <a href="http://docs.python.org/library/functions.html#raw_input" rel="nofollow">raw_input</a> instead</li>
<li>Wrap your script execution in a main function so it doesn't execute on import</li>
</ul>
<p><hr /></p>
<pre><code>def ask_positive_integer(prompt, warning="Enter a positive integer, please!"):
while True:
response = raw_input(prompt)
try:
response = int(response)
if response < 0:
print(warning)
else:
return response
except ValueError:
print(warning)
def ask_in_or_out(prompt, warning="In or out, please!"):
'''
returns True if 'in' False if 'out'
'''
while True:
response = raw_input(prompt)
if response.lower() in ('i', 'in'): return True
if response.lower() in ('o', 'ou', 'out'): return False
print warning
def main():
start = ask_positive_integer('How much did you start with?: ')
in_ = ask_in_or_out('Cool! Now have you put money in or taken it out?: ')
if in_:
in_amount = ask_positive_integer('Well done! How much did you put in?: ')
print(start + in_amount)
else:
out_amount = ask_positive_integer('Well done! How much did you take out?: ')
print(start - out_amount)
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2009-05-16T13:49:35Z | [
"python"
] |
Sorting a list of objects by attribute | 872,181 | <p>I am trying to sort a list of objects in python, however this code will not work:</p>
<pre><code>import datetime
class Day:
def __init__(self, date, text):
self.date = date
self.text = text
def __cmp__(self, other):
return cmp(self.date, other.date)
mylist = [Day(datetime.date(2009, 01, 02), "Jan 2"), Day(datetime.date(2009, 01, 01), "Jan 1")]
print mylist
print mylist.sort()
</code></pre>
<p>The output of this is:</p>
<pre><code>[<__main__.Day instance at 0x519e0>, <__main__.Day instance at 0x51a08>]
None
</code></pre>
<p>Could somebody show me a good way solve this? Why is the <code>sort()</code> function returning <code>None</code>?</p>
| 0 | 2009-05-16T10:53:44Z | 872,190 | <p>mylist.sort() returns nothing, it sorts the list in place. Change it to </p>
<pre><code>mylist.sort()
print mylist
</code></pre>
<p>to see the correct result. </p>
<p>See <a href="http://docs.python.org/library/stdtypes.html#mutable-sequence-types" rel="nofollow">http://docs.python.org/library/stdtypes.html#mutable-sequence-types</a> note 7.</p>
<blockquote>
<p>The sort() and reverse() methods
modify the list in place for economy
of space when sorting or reversing a
large list. To remind you that they
operate by side effect, they donât
return the sorted or reversed list.</p>
</blockquote>
| 5 | 2009-05-16T11:00:58Z | [
"python"
] |
Sorting a list of objects by attribute | 872,181 | <p>I am trying to sort a list of objects in python, however this code will not work:</p>
<pre><code>import datetime
class Day:
def __init__(self, date, text):
self.date = date
self.text = text
def __cmp__(self, other):
return cmp(self.date, other.date)
mylist = [Day(datetime.date(2009, 01, 02), "Jan 2"), Day(datetime.date(2009, 01, 01), "Jan 1")]
print mylist
print mylist.sort()
</code></pre>
<p>The output of this is:</p>
<pre><code>[<__main__.Day instance at 0x519e0>, <__main__.Day instance at 0x51a08>]
None
</code></pre>
<p>Could somebody show me a good way solve this? Why is the <code>sort()</code> function returning <code>None</code>?</p>
| 0 | 2009-05-16T10:53:44Z | 872,213 | <p>See <a href="http://docs.python.org/library/functions.html#sorted" rel="nofollow"><code>sorted</code></a> for a function that will return a sorted copy of any iterable.</p>
| 2 | 2009-05-16T11:13:45Z | [
"python"
] |
How to convert python date format to 10-digit date format for mysql? | 872,255 | <p>how to convert python date format to 10 digit date format for mysql</p>
<p>example:
date in python -> 11-05-09</p>
<p>to something like 1239992972 (10 digit)</p>
<p>Thanks</p>
| 0 | 2009-05-16T11:41:22Z | 872,263 | <p>You can use the time module's strptime - you pass in a string time (e.g. 11-05-09) and a format and it will return a struct_time, which you can get the numerical value from (by calling time.mktime on the returned struct_time). See the <a href="http://docs.python.org/library/time.html#time.strptime" rel="nofollow">docs for <code>time.strptime</code></a> for further details.</p>
| 4 | 2009-05-16T11:46:14Z | [
"python"
] |
How to convert python date format to 10-digit date format for mysql? | 872,255 | <p>how to convert python date format to 10 digit date format for mysql</p>
<p>example:
date in python -> 11-05-09</p>
<p>to something like 1239992972 (10 digit)</p>
<p>Thanks</p>
| 0 | 2009-05-16T11:41:22Z | 872,264 | <p>If it is a datetime obj, you can do:</p>
<pre><code>import time
time.mktime(datetime_obj.timetuple())
</code></pre>
<p>If not:</p>
<pre><code>time.mktime(time.strptime("11-05-09", "%d-%m-%y"))
</code></pre>
| 2 | 2009-05-16T11:46:41Z | [
"python"
] |
How to convert python date format to 10-digit date format for mysql? | 872,255 | <p>how to convert python date format to 10 digit date format for mysql</p>
<p>example:
date in python -> 11-05-09</p>
<p>to something like 1239992972 (10 digit)</p>
<p>Thanks</p>
| 0 | 2009-05-16T11:41:22Z | 872,271 | <p>Use time.strptime() to convert the date into a time tuple, and then time.mktime() (or calendar.timegm()) to convert that into a floating point time. You'll probably need to truncate it to an integer after.</p>
<pre><code>tm = time.strptime('11-05-09', '%d-%m-%y')
time = time.mktime(tm)
time_int = int(time)
</code></pre>
<p><a href="http://docs.python.org/library/time.html" rel="nofollow">http://docs.python.org/library/time.html</a></p>
| 0 | 2009-05-16T11:50:15Z | [
"python"
] |
How to convert python date format to 10-digit date format for mysql? | 872,255 | <p>how to convert python date format to 10 digit date format for mysql</p>
<p>example:
date in python -> 11-05-09</p>
<p>to something like 1239992972 (10 digit)</p>
<p>Thanks</p>
| 0 | 2009-05-16T11:41:22Z | 30,144,025 | <p>You can use <a href="https://github.com/ralphavalon/easy_date" rel="nofollow">easy_date</a> to make it easy:</p>
<pre><code>import date_converter
timestamp = date_converter.string_to_timestamp('11-05-09','%d-%m-%y')
</code></pre>
| 0 | 2015-05-09T19:15:39Z | [
"python"
] |
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python) | 872,290 | <p>I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list).</p>
<p>What would be the most efficient way to do this in Python?</p>
<p>The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I "abuse" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long).</p>
<p>Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization.</p>
<p>Thanks</p>
| 6 | 2009-05-16T12:01:37Z | 872,295 | <p>You're basically testing whether a member is in a set or not, right?</p>
<p>If so, and because you said you have lots of memory, why not just load all the words as keys in memcache, and then for every word, just check if it is present in memcache or not.</p>
<p>Or use that data structure that is used by bash to autocomplete command names - this is fast and highly efficient in memory (can't remember the name).</p>
| 1 | 2009-05-16T12:04:42Z | [
"python",
"string"
] |
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python) | 872,290 | <p>I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list).</p>
<p>What would be the most efficient way to do this in Python?</p>
<p>The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I "abuse" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long).</p>
<p>Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization.</p>
<p>Thanks</p>
| 6 | 2009-05-16T12:01:37Z | 872,297 | <p>The python <a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset" rel="nofollow">Set</a> is what you should try.</p>
<blockquote>
<p>A set object is an unordered collection of distinct hashable objects. Common uses include <strong>membership testing</strong>, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. </p>
</blockquote>
| 13 | 2009-05-16T12:05:17Z | [
"python",
"string"
] |
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python) | 872,290 | <p>I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list).</p>
<p>What would be the most efficient way to do this in Python?</p>
<p>The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I "abuse" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long).</p>
<p>Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization.</p>
<p>Thanks</p>
| 6 | 2009-05-16T12:01:37Z | 872,299 | <p>A <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow">Trie</a> structure would suit your purposes. There are undoubtedly Python implementations to be found out there...</p>
| 3 | 2009-05-16T12:05:58Z | [
"python",
"string"
] |
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python) | 872,290 | <p>I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list).</p>
<p>What would be the most efficient way to do this in Python?</p>
<p>The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I "abuse" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long).</p>
<p>Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization.</p>
<p>Thanks</p>
| 6 | 2009-05-16T12:01:37Z | 872,300 | <p>If memory consumption isn't an issue and the words won't change, the fastest way to do this is put everything in a hash and search that way. In Python, this is the <a href="http://www.python.org/doc/2.5.2/tut/node7.html#SECTION007400000000000000000" rel="nofollow"><strong><code>Set</code></strong></a>. You'll have constant-time lookup.</p>
| 1 | 2009-05-16T12:06:07Z | [
"python",
"string"
] |
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python) | 872,290 | <p>I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list).</p>
<p>What would be the most efficient way to do this in Python?</p>
<p>The trivial solution is to load the file into a list and check whether the word is in that list. The list can be sorted, which I believe will shrink the complexity to O(logn). However I'm not sure about how Python implements searching through lists, and whether there's a performance penalty if such a large list is in memory. Can I "abuse" the fact I can put a cap on the length of words? (e.g. say the longest one is 15 characters long).</p>
<p>Please note I run the application on a machine with lots of memory, so I care less for memory consumption than for speed and CPU utilization.</p>
<p>Thanks</p>
| 6 | 2009-05-16T12:01:37Z | 872,301 | <p>500k character is not a large list. if items in your list are unique and you need to do this search repeatedly use <a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset" rel="nofollow"><code>set</code></a> which would lower the complexity to <code>O(1)</code> in the best case.</p>
| 1 | 2009-05-16T12:06:27Z | [
"python",
"string"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.