title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 1,450,398 | <p>There's a few ways to do it.</p>
<ul>
<li><p><a href="http://docs.python.org/library/sys.html#sys.stdin"><code>sys.stdin</code></a> is a file-like object on which you can call functions <code>read</code> or <code>readlines</code> if you want to read everything or you want to read everything and split it by newline automatically. (You need to <code>import sys</code> for this to work.)</p></li>
<li><p>If you want to <em>prompt</em> the user for input, you can use <code>raw_input</code> in Python 2.X, and just <code>input</code> in Python 3. </p></li>
<li><p>If you actually just want to read command-line options, you can access them via the <a href="http://docs.python.org/library/sys.html#sys.argv">sys.argv</a> list.</p></li>
</ul>
<p>You will probably find <a href="http://en.wikibooks.org/wiki/Python_Programming/Input_and_output">this Wikibook article on I/O in Python</a> to be a useful reference as well.</p>
| 433 | 2009-09-20T05:53:17Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 1,454,400 | <p>You could use the <a href="http://docs.python.org/library/fileinput.html"><code>fileinput</code></a> module:</p>
<pre><code>import fileinput
for line in fileinput.input():
pass
</code></pre>
<p><a href="http://docs.python.org/library/fileinput.html"><code>fileinput</code></a> will loop through all the lines in the input specified as file names given in command-line arguments, or the standard input if no arguments are provided.</p>
| 637 | 2009-09-21T13:01:14Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 3,289,051 | <pre><code>import sys
for line in sys.stdin:
print line
</code></pre>
| 210 | 2010-07-20T10:30:06Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 5,185,255 | <p>Python also has built-in functions <code>input()</code> and <code>raw_input()</code>. See the Python documentation under <a href="http://docs.python.org/library/functions.html">Built-in Functions</a> or the Stack-Overflow documentation under <a class='doc-link' href="http://stackoverflow.com/documentation/python/809/python-3-vs-python-2/3552/user-input#t=201607212057211080896">User Input</a>.</p>
<p>For example,</p>
<pre><code>name = raw_input("Enter your name: ") # Python 2.x
</code></pre>
<p>or</p>
<pre><code>name = input("Enter your name: ") # Python 3
</code></pre>
| 127 | 2011-03-03T19:05:48Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 7,608,205 | <p>The answer proposed by others:</p>
<pre><code>for line in sys.stdin:
print line
</code></pre>
<p>is very simple and pythonic, but it must be noted that the script will wait until EOF before starting to iterate on the lines of input.</p>
<p>This means that <code>tail -f error_log | myscript.py</code> will not process lines as expected.</p>
<p>The correct script for such a use case would be:</p>
<pre><code>while 1:
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
break
if not line:
break
print line
</code></pre>
<p><strong>UPDATE</strong><br>
From the comments it has been cleared that on python 2 only there might be buffering involved, so that you end up waiting for the buffer to fill or EOF before the print call is issued.</p>
| 75 | 2011-09-30T09:08:09Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 11,887,913 | <p>This will echo standard input to standard output:</p>
<pre><code>import sys
line = sys.stdin.readline()
while line:
print line,
line = sys.stdin.readline()
</code></pre>
| 26 | 2012-08-09T16:31:57Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 17,927,520 | <p>Building on all the anwers using <code>sys.stdin</code>, you can also do something like the following to read from an argument file if at least one argument exists, and fall back to stdin otherwise:</p>
<pre><code>import sys
f = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
for line in f:
# Do your stuff
</code></pre>
<p>and use it as either</p>
<pre><code>$ python do-my-stuff.py infile.txt
</code></pre>
<p>or</p>
<pre><code>$ cat infile.txt | python do-my-stuff.py
</code></pre>
<p>or even</p>
<pre><code>$ python do-my-stuff.py < infile.txt
</code></pre>
<p>That would make your Python script behave like many GNU/Unix programs such as <code>cat</code>, <code>grep</code> and <code>sed</code>.</p>
| 19 | 2013-07-29T15:04:35Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 18,470,058 | <p>Try this:</p>
<pre><code>import sys
print sys.stdin.read().upper()
</code></pre>
<p>and check it with:</p>
<pre><code>$ echo "Hello World" | python myFile.py
</code></pre>
| 5 | 2013-08-27T15:43:43Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 24,855,121 | <p>You can read from stdin and then store inputs into <strong>"data"</strong> as follows:</p>
<pre><code>data = ""
for line in sys.stdin:
data += line
</code></pre>
| 8 | 2014-07-20T21:33:46Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 26,633,637 | <p>I had some issues when getting this to work for reading over sockets piped to it. When the socket got closed it started returning empty string in an active loop. So this is my solution to it (which I only tested in linux, but hope it works in all other systems)</p>
<pre><code>import sys, os
sep=os.linesep
while sep == os.linesep:
data = sys.stdin.readline()
sep = data[-len(os.linesep):]
print '> "%s"' % data.strip()
</code></pre>
<p>So if you start listening on a socket it will work properly (e.g. in bash):</p>
<pre><code>while :; do nc -l 12345 | python test.py ; done
</code></pre>
<p>And you can call it with telnet or just point a browser to localhost:12345</p>
| 3 | 2014-10-29T14:57:06Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 34,990,251 | <p>The following chip of code will help you :</p>
<pre><code>input_str = sys.stdin.read()
print input_str.split()
</code></pre>
| 5 | 2016-01-25T10:26:38Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 37,714,330 | <p>Regarding this:</p>
<p><code>for line in sys.stdin:</code></p>
<p>I just tried it on python 2.7 (following someone else's suggestion) for a very large file, and I don't recommend it, precisely for the reasons mentioned above (nothing happens for a long time). </p>
<p>I ended up with a slightly more pythonic solution (and it works on bigger files):</p>
<pre><code>with open(sys.argv[1], 'r') as f:
for line in f:
</code></pre>
<p>Then I can run the script locally as:</p>
<pre><code>python myscript.py "0 1 2 3 4..." # can be a multi-line string or filename - any std.in input will work
</code></pre>
| 2 | 2016-06-08T23:02:16Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 38,670,261 | <blockquote>
<h1>How do you read from stdin in Python?</h1>
<p>I'm trying to do some of the code golf challenges, but they all require the input to be taken from stdin. How do I get that in Python?</p>
</blockquote>
<h2>TLDR: Golfed, compatible in 2, 3, Windows, Unix</h2>
<p>Say you have a file with some lines:</p>
<pre><code>(echo foo & echo bar & echo baz) > inputs
</code></pre>
<p>We can accept that file and write it back out: </p>
<pre><code>python -c "import sys; sys.stdout.write(sys.stdin.read())" < inputs
</code></pre>
<p>Slightly longer, but reads from stdin iteratively (usually preferable):</p>
<pre><code>python -c "import sys; sys.stdout.write(''.join(sys.stdin))" < inputs
</code></pre>
<h2>Longer answer (Unix & Python 3 focused)</h2>
<p>Here's a complete, easily replicable demo, using two methods, the builtin function, <code>input</code> (use <code>rawinput</code> in Python 2), and <code>sys.stdin</code>. The data is unmodified, so the processing is a non-operation.</p>
<p>To begin with, let's create a file for inputs:</p>
<pre><code>$ (echo foo & echo bar & echo baz) > inputs
$ cat inputs
foo
bar
baz
</code></pre>
<h2>Builtin function, <code>input</code> (<code>rawinput</code> in Python 2)</h2>
<p>Here's how you can use <code>input</code> in Python 3 (or <code>raw_input</code> in Python 2) to read from stdin:</p>
<pre><code>$ cat > stdindemo.py << "EOF"
try:
while True:
print(input())
except EOFError:
pass
EOF
</code></pre>
<p><code>input</code> reads up util the newline and essentially strips it from the line. <code>print</code> adds a newline. So while they both modify the input, their modifications cancel. (So they are essentially each other's complement.) </p>
<p>When <code>input</code> gets the end-of-file character, it raises EOFError.</p>
<p>To separate the inputs from the output:</p>
<pre><code>$ cat > inputs << "EOF"
foo
bar
baz
EOF
</code></pre>
<p>And piping from cat:</p>
<pre><code>$ cat inputs | python3 -m stdindemo
foo
bar
baz
</code></pre>
<h2><code>sys.stdin</code></h2>
<p>Here we make a demo script using <code>sys.stdin</code>. The efficient way to iterate over a file-like object is to use the file-like object as an iterator. The complementary method to write to stdout from this input is to simply use <code>sys.stdout.write</code>:</p>
<pre><code>$ cat > stdindemo2.py << "EOF"
import sys
for line in sys.stdin:
sys.stdout.write(line)
EOF
</code></pre>
<p>And redirecting the inputs into the file:</p>
<pre><code>$ python3 -m stdindemo2 < inputs
foo
bar
baz
</code></pre>
<p>Golfed into a command:</p>
<pre><code>$ python -c "import sys; sys.stdout.write(sys.stdin.read())" < inputs
foo
bar
baz
</code></pre>
<h2>File Descriptors for Golfing - Python 3 (works on Windows and Linux/Unix)</h2>
<p>Since the file descriptors for stdin and stdout are 0 and 1 respectively, we can also pass those to <code>open</code> in Python 3 (not 2, and note that we still need the 'w' for writing to stdout).</p>
<p>If this works on your system, it will shave off more characters. </p>
<pre><code>$ python -c "open(1,'w').write(open(0).read())" < inputs
baz
bar
foo
</code></pre>
| 0 | 2016-07-30T04:10:43Z | [
"python",
"stdin"
] |
How do you read from stdin in Python? | 1,450,393 | <p>I'm trying to do some of the <a href="http://en.wikipedia.org/wiki/Code_golf">code golf</a> challenges, but they all require the input to be taken from <code>stdin</code>. How do I get that in Python?</p>
| 854 | 2009-09-20T05:48:07Z | 38,939,362 | <p>Read from <code>sys.stdin</code>, but to <strong>read binary data on Windows</strong>, you need to be extra careful, because <code>sys.stdin</code> there is opened in text mode and it will corrupt <code>\r\n</code> replacing them with <code>\n</code>.</p>
<p>The solution is to set mode to binary if Windows + Python 2 is detected, and on Python 3 use <code>sys.stdin.buffer</code>.</p>
<pre><code>import sys
PY3K = sys.version_info >= (3, 0)
if PY3K:
source = sys.stdin.buffer
else:
# Python 2 on Windows opens sys.stdin in text mode, and
# binary data that read from it becomes corrupted on \r\n
if sys.platform == "win32":
# set sys.stdin to binary mode
import os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
source = sys.stdin
b = source.read()
</code></pre>
| 1 | 2016-08-14T05:12:41Z | [
"python",
"stdin"
] |
How to get the name of a running Python script? | 1,450,478 | <p>How do I get the name of a running Python script?</p>
<p>I tried <code>os.__file__</code> but that returns the name of the file where <code>os</code> resides.</p>
| 4 | 2009-09-20T06:59:54Z | 1,450,484 | <p><code>sys.argv[0]</code> should give you the name of the script.</p>
| 1 | 2009-09-20T07:04:20Z | [
"python"
] |
How to get the name of a running Python script? | 1,450,478 | <p>How do I get the name of a running Python script?</p>
<p>I tried <code>os.__file__</code> but that returns the name of the file where <code>os</code> resides.</p>
| 4 | 2009-09-20T06:59:54Z | 1,450,485 | <pre><code>>> import os
>> import sys
>> print sys.argv[0]
</code></pre>
<p>or if you just want the script and not the full path</p>
<pre><code>>>
>> print os.path.basename(sys.argv[0])
</code></pre>
| 10 | 2009-09-20T07:04:33Z | [
"python"
] |
How to get the name of a running Python script? | 1,450,478 | <p>How do I get the name of a running Python script?</p>
<p>I tried <code>os.__file__</code> but that returns the name of the file where <code>os</code> resides.</p>
| 4 | 2009-09-20T06:59:54Z | 1,450,693 | <p>Use</p>
<pre><code>thisFile = __file__
</code></pre>
<p>It's magic!</p>
| 17 | 2009-09-20T10:01:22Z | [
"python"
] |
How to get the name of a running Python script? | 1,450,478 | <p>How do I get the name of a running Python script?</p>
<p>I tried <code>os.__file__</code> but that returns the name of the file where <code>os</code> resides.</p>
| 4 | 2009-09-20T06:59:54Z | 1,451,141 | <pre><code>sys.path[0]
</code></pre>
<p>returns the path of the script that launched the Python interpreter. </p>
<p>If you read this script directly, it will return the path of the script. If the script was imported from another script, it will return the path of that script.</p>
| 0 | 2009-09-20T14:27:57Z | [
"python"
] |
How to get the name of a running Python script? | 1,450,478 | <p>How do I get the name of a running Python script?</p>
<p>I tried <code>os.__file__</code> but that returns the name of the file where <code>os</code> resides.</p>
| 4 | 2009-09-20T06:59:54Z | 1,451,204 | <p>It depends on what you mean by "a running python script".</p>
<p><code>__file__</code> will give you the name of the currently executing file. If that's a module, you'll get where it was imported from e.g. blahblah.pyc</p>
<p><code>sys.argv[0]</code> will give you the name of the script that is being run, even if called from a module that that script imported.</p>
<p>Please do look up the answers to the earlier question on this topic (see S.Lott's comment on your question).</p>
| 3 | 2009-09-20T14:53:59Z | [
"python"
] |
How to check form entry for special characters in python? | 1,450,522 | <p>Let's say I have a form field for "Name". I want to display an error message if it contains special characters such as $,#,etc. The only acceptable characters should be any alphanumeric, the hyphen "-", and the apostrophe "'". I am not sure how i should search the name for these non-acceptable characters, especially the apostrophe. So in the code it should look like the following:</p>
<p>name = request.POST['name']</p>
<p>if name contains any non-acceptable characters then display error message.</p>
| 2 | 2009-09-20T07:29:31Z | 1,450,538 | <pre><code>import re
p = r"^[\w'-]+$"
if re.search(p, name):
# it's okay
else:
# display error
</code></pre>
| 1 | 2009-09-20T07:44:24Z | [
"python",
"forms"
] |
How to check form entry for special characters in python? | 1,450,522 | <p>Let's say I have a form field for "Name". I want to display an error message if it contains special characters such as $,#,etc. The only acceptable characters should be any alphanumeric, the hyphen "-", and the apostrophe "'". I am not sure how i should search the name for these non-acceptable characters, especially the apostrophe. So in the code it should look like the following:</p>
<p>name = request.POST['name']</p>
<p>if name contains any non-acceptable characters then display error message.</p>
| 2 | 2009-09-20T07:29:31Z | 1,450,539 | <p>You can use regular expressions to validate your string, like this:</p>
<pre><code>import re
if re.search(r"^[\w\d'-]+$", name):
# success
</code></pre>
<p>Another way:</p>
<pre><code>if set("#$").intersection(name):
print "bad chars in the name"
</code></pre>
| 3 | 2009-09-20T07:45:05Z | [
"python",
"forms"
] |
wx.StaticBitmap or wx.DC: Which is better to use for constantly changing images? | 1,450,639 | <p>I would like to have a python gui that loads different images from files. I've seen many exmples of loading an image with some code like:</p>
<pre><code>img = wx.Image("1.jpg", wx.BITMAP_TYPE_ANY, -1)
sb = wx.StaticBitmap(rightPanel, -1, wx.BitmapFromImage(img))
sizer.Add(sb)
</code></pre>
<p>It seems to be suited for an image that will be there for the entire life of the program. I could not find an elegant way to delete/reload images with this. Would using a wx.DC be a better idea for my application?</p>
| 1 | 2009-09-20T09:09:31Z | 1,450,677 | <p>You don't have to delete the <code>StaticBitmap</code>, you can just set another bitmap to it using it's <code>SetBitmap</code> method.</p>
<p>If the new image has different dimensions you will probably have to do an explicit <code>Layout</code> call on it's parent so that the sizers would adjust.</p>
| 0 | 2009-09-20T09:48:31Z | [
"python",
"user-interface",
"image",
"wxpython"
] |
wx.StaticBitmap or wx.DC: Which is better to use for constantly changing images? | 1,450,639 | <p>I would like to have a python gui that loads different images from files. I've seen many exmples of loading an image with some code like:</p>
<pre><code>img = wx.Image("1.jpg", wx.BITMAP_TYPE_ANY, -1)
sb = wx.StaticBitmap(rightPanel, -1, wx.BitmapFromImage(img))
sizer.Add(sb)
</code></pre>
<p>It seems to be suited for an image that will be there for the entire life of the program. I could not find an elegant way to delete/reload images with this. Would using a wx.DC be a better idea for my application?</p>
| 1 | 2009-09-20T09:09:31Z | 1,450,759 | <p>I read here: <a href="http://docs.wxwidgets.org/trunk/classwx%5Fstatic%5Fbitmap.html" rel="nofollow">http://docs.wxwidgets.org/trunk/classwx%5Fstatic%5Fbitmap.html</a></p>
<p>"Native implementations on some platforms are only meant for display of the small icons in the dialog boxes. In particular, under Windows 9x the size of bitmap is limited to 64*64 pixels."</p>
<p>Which may be a problem. If you do use a DC, then you may have to "double buffer" it, or it may flicker on redraw, resize or update.</p>
<p>Otherwise it seems to me that you should use a "normal" Bitmap if you are oging to update it often.</p>
| 0 | 2009-09-20T10:46:34Z | [
"python",
"user-interface",
"image",
"wxpython"
] |
wx.StaticBitmap or wx.DC: Which is better to use for constantly changing images? | 1,450,639 | <p>I would like to have a python gui that loads different images from files. I've seen many exmples of loading an image with some code like:</p>
<pre><code>img = wx.Image("1.jpg", wx.BITMAP_TYPE_ANY, -1)
sb = wx.StaticBitmap(rightPanel, -1, wx.BitmapFromImage(img))
sizer.Add(sb)
</code></pre>
<p>It seems to be suited for an image that will be there for the entire life of the program. I could not find an elegant way to delete/reload images with this. Would using a wx.DC be a better idea for my application?</p>
| 1 | 2009-09-20T09:09:31Z | 1,450,832 | <p>If you have rapidly changing big images, or you would like some custom effect in future, it better to write your own control and doing painting using paintDC, and it is not that hard.</p>
<p>Doing your own drawing you can correctly scale, avoid flicker and may be do blend of one image into other if you like :)</p>
| 1 | 2009-09-20T11:32:35Z | [
"python",
"user-interface",
"image",
"wxpython"
] |
Setting a colour scale in ipython | 1,450,874 | <p>I am new to python and am having trouble finding the correct syntax to use.
I want to plot some supernovae data onto a hammer projection. The data has coordinates alpha and beta. For each data point there is also a value delta describing a property of the SN.
I would like to create a colour scale that ranges from min. value of delta to max. value of delta and goes from red to violet.
This would mean that when I came to plot the data I could simply write:</p>
<p>subplot(111,projection="hammer")</p>
<p>p=plot([alpha],[beta],'o',mfc='delta')</p>
<p>where delta would represent a colour somewhere in the spectrum between red and violet. I.e if delta =0, the marker would be red and if delta =delta max. the marker would be violet and if delta =(delta. max)/2 the marker would be yellow.</p>
<p>Could anyone help me out with the syntax to do this?</p>
<p>Many thanks</p>
<p>Angela</p>
| 2 | 2009-09-20T11:58:37Z | 1,450,966 | <p>If you are thinking of a fixed color table, just map your delta values into the index range for that table. For example, you can construct a color table with color names recognized by your plot package:</p>
<pre><code>>>> colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
</code></pre>
<p>The range of possible <code>delta</code> values, from your example, is <code>0</code> to <code>delta.max</code>. Mapping that to the length of the color tables, gives the <code>step</code>:</p>
<pre><code>>>> step = delta.max / len(colors)
</code></pre>
<p>And the computation required to get a color name matching a given <code>data</code> point is:</p>
<pre><code>>>> color = colors[math.trunc(data / step)]
</code></pre>
<p>This method works for any set of pre-selected colors, for example RGB values expressed as hex numbers.</p>
<p>A quick google search discovered <a href="http://www.johnny-lin.com/pylib.shtml" rel="nofollow">Johnny Lin's Python Library</a>. It contains <a href="http://www.johnny-lin.com/cdat%5Ftips/tips%5Fcolor/new%5Fcm.html" rel="nofollow">color maps</a>, including <a href="http://www.johnny-lin.com/cdat%5Ftips/files/rainbow2.py" rel="nofollow"><code>Rainbow (red to violet, 790-380 nm)</code></a>.
You also need his <a href="http://www.johnny-lin.com/py%5Fcode/wavelen2rgb.py" rel="nofollow"><code>wavelen2rgb.py</code></a> (Calculate RGB values given the wavelength of visible light). Note that this library generates the colors as RGB triplets - you have to figure how your plotting library expects such color values.</p>
| 2 | 2009-09-20T12:57:37Z | [
"python"
] |
Setting a colour scale in ipython | 1,450,874 | <p>I am new to python and am having trouble finding the correct syntax to use.
I want to plot some supernovae data onto a hammer projection. The data has coordinates alpha and beta. For each data point there is also a value delta describing a property of the SN.
I would like to create a colour scale that ranges from min. value of delta to max. value of delta and goes from red to violet.
This would mean that when I came to plot the data I could simply write:</p>
<p>subplot(111,projection="hammer")</p>
<p>p=plot([alpha],[beta],'o',mfc='delta')</p>
<p>where delta would represent a colour somewhere in the spectrum between red and violet. I.e if delta =0, the marker would be red and if delta =delta max. the marker would be violet and if delta =(delta. max)/2 the marker would be yellow.</p>
<p>Could anyone help me out with the syntax to do this?</p>
<p>Many thanks</p>
<p>Angela</p>
| 2 | 2009-09-20T11:58:37Z | 1,451,311 | <p>I'm not familiar with plotting, but a nice method for generating rainbow colors is using the HSV (hue, saturation, value) colorspace. Set saturation and value to the maximum values, and vary the hue.</p>
<pre><code>import colorsys
def color(value):
return colorsys.hsv_to_rgb(value / delta.max / (1.1), 1, 1)
</code></pre>
<p>This wil get you RGB triplets for the rainbow colors. The (1.1) is there to end at violet at delta.max instead of going all the way back to red.
So, instead of selecting from a list, you call the function.</p>
<p>You can also try experimenting with the saturation and value (the 1's in the function above) if the returned colors are too bright.</p>
| 1 | 2009-09-20T15:45:57Z | [
"python"
] |
Setting a colour scale in ipython | 1,450,874 | <p>I am new to python and am having trouble finding the correct syntax to use.
I want to plot some supernovae data onto a hammer projection. The data has coordinates alpha and beta. For each data point there is also a value delta describing a property of the SN.
I would like to create a colour scale that ranges from min. value of delta to max. value of delta and goes from red to violet.
This would mean that when I came to plot the data I could simply write:</p>
<p>subplot(111,projection="hammer")</p>
<p>p=plot([alpha],[beta],'o',mfc='delta')</p>
<p>where delta would represent a colour somewhere in the spectrum between red and violet. I.e if delta =0, the marker would be red and if delta =delta max. the marker would be violet and if delta =(delta. max)/2 the marker would be yellow.</p>
<p>Could anyone help me out with the syntax to do this?</p>
<p>Many thanks</p>
<p>Angela</p>
| 2 | 2009-09-20T11:58:37Z | 1,451,981 | <p>Using the wavelen2rgb function of Johnny Lin's Python Library (as gimel suggested), the following code plots the SNs as filled circles. The code uses Tkinter which is always available with Python. You can get wavelen2rgb.py <a href="http://www.johnny-lin.com/py%5Fcode/wavelen2rgb.py" rel="nofollow">here</a>.</p>
<pre><code>def sn():
"Plot a diagram of supernovae, assuming wavelengths between 380 and 645nm."
from Tkinter import *
from random import Random
root = Tk() # initialize gui
dc = Canvas(root) # Create a canvas
dc.grid() # Show canvas
r = Random() # intitialize random number generator
for i in xrange(100): # plot 100 random SNs
a = r.randint(10, 400)
b = r.randint(10, 200)
wav = r.uniform(380.0, 645.0)
rgb = wavelen2rgb(wav, MaxIntensity=255) # Calculate color as RGB
col = "#%02x%02x%02x" % tuple(rgb) # Calculate color in the fornat that Tkinter expects
dc.create_oval(a-5, b-5, a+5, b+5, outline=col, fill=col) # Plot a filled circle
root.mainloop()
sn()
</code></pre>
<p>Here's the outpout:</p>
<p><img src="http://img38.imageshack.us/img38/3449/83921879.jpg" alt="alt text" /></p>
| 1 | 2009-09-20T20:52:18Z | [
"python"
] |
Paste text to active window linux | 1,450,892 | <p>I want to write application which paste some text to active window on some keystroke. How can i do this with Python or C++ ?</p>
<p>Update:
Sorry people. I think i don't describe problem clearly. I want to write app, which will work like a daemon and on some global keystroke paste some text to current active application (text editor, browser, jabber client) I think i will need to use some low level xserver api. </p>
| 1 | 2009-09-20T12:09:16Z | 1,451,337 | <p>Interacting between multiple applications interfaces can be tricky, so it may help to provide more information on specifically what you are trying to do. </p>
<p>Nonetheless, you have a few options if you want to use the clipboard to accomplish this. On Windows, the Windows API provides <a href="http://msdn.microsoft.com/en-us/library/ms649039%28VS.85%29.aspx" rel="nofollow">GetClipboardData</a> and <a href="http://msdn.microsoft.com/en-us/library/ms649051%28VS.85%29.aspx" rel="nofollow">SetClipboardData</a>. To use these functions from Python you would want to take advantage of <a href="http://python.net/crew/skippy/win32/" rel="nofollow">win32com</a>.</p>
<p>On Linux, you have two main options (that I know of) for interacting with the clipboard. <a href="http://www.pygtk.org/" rel="nofollow">PyGTK</a> provides a <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkclipboard.html" rel="nofollow">gtk.Clipboard</a> object. There is also a command line tool for setting the X "selection," <a href="http://www.vergenet.net/~conrad/software/xsel/" rel="nofollow">XSel</a>. You could interact with XSel using Python by means of <a href="http://docs.python.org/library/os.html#os.popen" rel="nofollow">os.popen</a> or <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a>. See <a href="http://www.answermysearches.com/python-how-to-copy-and-paste-to-the-clipboard-in-linux/286/" rel="nofollow">this guide</a> for info on using gtk.Clipboard and xsel.</p>
<p>In terms of how you actually use the clipboard. One application might poll the clipboard every so often looking for changes.</p>
<p>If you want to get into real "enterprisey" architecture, you could use a message bus, like <a href="http://www.rabbitmq.com/" rel="nofollow">RabbitMQ</a>, to communicate between the two applications.</p>
| 1 | 2009-09-20T15:53:53Z | [
"c++",
"python",
"linux",
"x11"
] |
Paste text to active window linux | 1,450,892 | <p>I want to write application which paste some text to active window on some keystroke. How can i do this with Python or C++ ?</p>
<p>Update:
Sorry people. I think i don't describe problem clearly. I want to write app, which will work like a daemon and on some global keystroke paste some text to current active application (text editor, browser, jabber client) I think i will need to use some low level xserver api. </p>
| 1 | 2009-09-20T12:09:16Z | 1,451,804 | <p>If you use Tkinter (a GUI library that works in Linux, MACOS, Windows and everywhere), and make any widget (for example a text widget), the copy (ctrl-c) and paste (ctrl-v) commands automatically work. For example the following code shows a Text widget, where you can type multi-line text, and copy and paste to other applications, or from other application (for example openoffice).</p>
<pre><code>from Tkinter import *
root = Tk() # Initialize GUI
t = Text(root) # Create a text widget
t.grid() # show the widget
root.mainloop() # Start the GUI
</code></pre>
<p>I have tested the code with Windows and Linux/KDE3.5</p>
| 0 | 2009-09-20T19:30:39Z | [
"c++",
"python",
"linux",
"x11"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 1,450,900 | <p>Use <code>re.sub</code>, like so:</p>
<pre><code>>>> import re
>>> re.sub("\D", "", "aas30dsa20")
'3020'
</code></pre>
<p><code>\D</code> matches any non-digit character so, the code above, is essentially replacing every non-digit character for the empty string.</p>
<p>Or you can use <code>filter</code>, like so (in Python 2k):</p>
<pre><code>>>> filter(lambda x: x.isdigit(), "aas30dsa20")
'3020'
</code></pre>
<p>Since in Python 3k, <code>filter</code> returns an iterator instead of a <code>list</code>, you can use the following instead:</p>
<pre><code>>>> ''.join(filter(lambda x: x.isdigit(), "aas30dsa20"))
'3020'
</code></pre>
| 104 | 2009-09-20T12:18:48Z | [
"python",
"string"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 1,450,905 | <p>Use a generator expression:</p>
<pre><code>>>> s = "foo200bar"
>>> new_s = "".join(i for i in s if i in "0123456789")
</code></pre>
| 1 | 2009-09-20T12:21:49Z | [
"python",
"string"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 1,450,907 | <p>Ugly but works:</p>
<pre><code>>>> s
'aaa12333bb445bb54b5b52'
>>> a = ''.join(filter(lambda x : x.isdigit(), s))
>>> a
'1233344554552'
>>>
</code></pre>
| 2 | 2009-09-20T12:23:03Z | [
"python",
"string"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 1,450,911 | <p>along the lines of bayer's answer:</p>
<pre><code>''.join(i for i in s if i.isdigit())
</code></pre>
| 9 | 2009-09-20T12:23:17Z | [
"python",
"string"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 1,450,912 | <p>You can use filter:</p>
<pre><code>filter(lambda x: x.isdigit(), "dasdasd2313dsa")
</code></pre>
<p>On python3.0 you have to join this (kinda ugly :( )</p>
<pre><code>''.join(filter(lambda x: x.isdigit(), "dasdasd2313dsa"))
</code></pre>
| 11 | 2009-09-20T12:24:05Z | [
"python",
"string"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 1,450,913 | <pre><code>s=''.join(i for i in s if i.isdigit())
</code></pre>
<p>Another generator variant.</p>
| 44 | 2009-09-20T12:24:18Z | [
"python",
"string"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 1,451,407 | <p>In Python 2.*, by far the fastest approach is the <code>.translate</code> method:</p>
<pre><code>>>> x='aaa12333bb445bb54b5b52'
>>> import string
>>> all=string.maketrans('','')
>>> nodigs=all.translate(all, string.digits)
>>> x.translate(all, nodigs)
'1233344554552'
>>>
</code></pre>
<p><code>string.maketrans</code> makes a translation table (a string of length 256) which in this case is the same as <code>''.join(chr(x) for x in range(256))</code> (just faster to make;-). <code>.translate</code> applies the translation table (which here is irrelevant since <code>all</code> essentially means identity) AND deletes characters present in the second argument -- the key part.</p>
<p><code>.translate</code> works very differently on Unicode strings (and strings in Python 3 -- I <strong>do</strong> wish questions specified which major-release of Python is of interest!) -- not quite this simple, not quite this fast, though still quite usable.</p>
<p>Back to 2.*, the performance difference is impressive...:</p>
<pre><code>$ python -mtimeit -s'import string; all=string.maketrans("", ""); nodig=all.translate(all, string.digits); x="aaa12333bb445bb54b5b52"' 'x.translate(all, nodig)'
1000000 loops, best of 3: 1.04 usec per loop
$ python -mtimeit -s'import re; x="aaa12333bb445bb54b5b52"' 're.sub(r"\D", "", x)'
100000 loops, best of 3: 7.9 usec per loop
</code></pre>
<p>Speeding things up by 7-8 times is hardly peanuts, so the <code>translate</code> method is well worth knowing and using. The other popular non-RE approach...:</p>
<pre><code>$ python -mtimeit -s'x="aaa12333bb445bb54b5b52"' '"".join(i for i in x if i.isdigit())'
100000 loops, best of 3: 11.5 usec per loop
</code></pre>
<p>is 50% slower than RE, so the <code>.translate</code> approach beats it by over an order of magnitude.</p>
<p>In Python 3, or for Unicode, you need to pass <code>.translate</code> a mapping (with ordinals, not characters directly, as keys) that returns <code>None</code> for what you want to delete. Here's a convenient way to express this for deletion of "everything but" a few characters:</p>
<pre><code>import string
class Del:
def __init__(self, keep=string.digits):
self.comp = dict((ord(c),c) for c in keep)
def __getitem__(self, k):
return self.comp.get(k)
DD = Del()
x='aaa12333bb445bb54b5b52'
x.translate(DD)
</code></pre>
<p>also emits <code>'1233344554552'</code>. However, putting this in xx.py we have...:</p>
<pre><code>$ python3.1 -mtimeit -s'import re; x="aaa12333bb445bb54b5b52"' 're.sub(r"\D", "", x)'
100000 loops, best of 3: 8.43 usec per loop
$ python3.1 -mtimeit -s'import xx; x="aaa12333bb445bb54b5b52"' 'x.translate(xx.DD)'
10000 loops, best of 3: 24.3 usec per loop
</code></pre>
<p>...which shows the performance advantage disappears, for this kind of "deletion" tasks, and becomes a performance decrease.</p>
| 77 | 2009-09-20T16:37:19Z | [
"python",
"string"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 14,092,390 | <p>The op mentions in the comments that he wants to keep the decimal place. This can be done with the re.sub method (as per the second and IMHO best answer) by explicitly listing the characters to keep e.g.</p>
<pre><code>>>> re.sub("[^0123456789\.]","","poo123.4and5fish")
'123.45'
</code></pre>
| 3 | 2012-12-30T16:31:51Z | [
"python",
"string"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 15,202,183 | <pre><code>x.translate(None, string.digits)
</code></pre>
<p>will delete all digits from string. To delete letters and keep the digits, do this:</p>
<pre><code>x.translate(None, string.letters)
</code></pre>
| 6 | 2013-03-04T13:00:04Z | [
"python",
"string"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 26,517,161 | <p>A fast version for Python 3:</p>
<pre><code># xx3.py
from collections import defaultdict
import string
_NoneType = type(None)
def keeper(keep):
table = defaultdict(_NoneType)
table.update({ord(c): c for c in keep})
return table
digit_keeper = keeper(string.digits)
</code></pre>
<p>Here's a performance comparison vs. regex:</p>
<pre><code>$ python3.3 -mtimeit -s'import xx3; x="aaa12333bb445bb54b5b52"' 'x.translate(xx3.digit_keeper)'
1000000 loops, best of 3: 1.02 usec per loop
$ python3.3 -mtimeit -s'import re; r = re.compile(r"\D"); x="aaa12333bb445bb54b5b52"' 'r.sub("", x)'
100000 loops, best of 3: 3.43 usec per loop
</code></pre>
<p>So it's a little bit more than 3 times faster than regex, for me. It's also faster than <code>class Del</code> above, because <code>defaultdict</code> does all its lookups in C, rather than (slow) Python. Here's that version on my same system, for comparison.</p>
<pre><code>$ python3.3 -mtimeit -s'import xx; x="aaa12333bb445bb54b5b52"' 'x.translate(xx.DD)'
100000 loops, best of 3: 13.6 usec per loop
</code></pre>
| 2 | 2014-10-22T21:09:42Z | [
"python",
"string"
] |
Python: removing characters except digits from string | 1,450,897 | <p>How can i remove all characters except numbers from string?</p>
| 72 | 2009-09-20T12:14:17Z | 39,235,227 | <p>You can easily do it using Regex</p>
<pre><code>>>> import re
>>> re.sub("\D","","£70,000")
70000
</code></pre>
| 0 | 2016-08-30T19:03:44Z | [
"python",
"string"
] |
Python's json module, converts int dictionary keys to strings | 1,450,957 | <p>I have found that when the following is run, python's json module (included since 2.6) converts int dictionary keys to strings.</p>
<pre><code>>>> import json
>>> releases = {1: "foo-v0.1"}
>>> json.dumps(releases)
'{"1": "foo-v0.1"}'
</code></pre>
<p>Is there any easy way to preserve the key as an int, without needing to parse the string on dump and load.
I believe it would be possible using the hooks provided by the json module, but again this still requires parsing.
Is there possibly an argument I have overlooked?
cheers, chaz</p>
<p>Sub-question:
Thanks for the answers. Seeing as json works as I feared, is there an easy way to convey key type by maybe parsing the output of dumps?
Also I should note the code doing the dumping and the code downloading the json object from a server and loading it, are both written by me.</p>
| 56 | 2009-09-20T12:52:40Z | 1,450,981 | <p>No, there is no such thing as a Number key in JavaScript. All object properties are converted to String.</p>
<pre><code>var a= {1: 'a'};
for (k in a)
alert(typeof k); // 'string'
</code></pre>
<p>This can lead to some curious-seeming behaviours:</p>
<pre><code>a[999999999999999999999]= 'a'; // this even works on Array
alert(a[1000000000000000000000]); // 'a'
alert(a['999999999999999999999']); // fail
alert(a['1e+21']); // 'a'
</code></pre>
<p>JavaScript Objects aren't really proper mappings as you'd understand it in languages like Python, and using keys that aren't String results in weirdness. This is why JSON always explicitly writes keys as strings, even where it doesn't look necessary.</p>
| 41 | 2009-09-20T13:08:01Z | [
"python",
"json"
] |
Python's json module, converts int dictionary keys to strings | 1,450,957 | <p>I have found that when the following is run, python's json module (included since 2.6) converts int dictionary keys to strings.</p>
<pre><code>>>> import json
>>> releases = {1: "foo-v0.1"}
>>> json.dumps(releases)
'{"1": "foo-v0.1"}'
</code></pre>
<p>Is there any easy way to preserve the key as an int, without needing to parse the string on dump and load.
I believe it would be possible using the hooks provided by the json module, but again this still requires parsing.
Is there possibly an argument I have overlooked?
cheers, chaz</p>
<p>Sub-question:
Thanks for the answers. Seeing as json works as I feared, is there an easy way to convey key type by maybe parsing the output of dumps?
Also I should note the code doing the dumping and the code downloading the json object from a server and loading it, are both written by me.</p>
| 56 | 2009-09-20T12:52:40Z | 1,451,857 | <p>This is one of those subtle differences among various mapping collections that can bite you.</p>
<p>In Python (and apparently in Lua) the keys to a mapping (dictionary or table, respectively) are object references. In Python they must be immutable types, or they must be objects which implement a <code>__hash__</code> method. (The Lua docs suggest that it automatically uses the object's ID as a hash/key even for mutable objects and relies on string interning to ensure that equivalent strings map to the same objects).</p>
<p>In Perl, Javascript, awk and many other languages the keys for hashes, associative arrays or whatever they're called for the given language, are strings (or "scalars" in Perl). In perl <code>$foo{1}, $foo{1.0}, and $foo{"1"}</code> are all references to the same mapping in <code>%foo</code> --- the key is <em>evaluated</em> as a scalar!</p>
<p>JSON started as a Javascript serialization technology. (JSON stands for [J]ava[S]cript [o]bject [n]otation.) Naturally it implements semantics for its mapping notation which are consistent with its mapping semantics.</p>
<p>If both ends of your serialization are going to be Python then you'd be better off using pickles. If you really need to convert these back from JSON into native Python objects I guess you have a couple of choices. First you could try (<code>try: ... except: ...</code>) to convert any key to a number in the event of a dictionary look-up failure. Alternatively, if you add code to the other end (the serializer or generator of this JSON data) then you could have it perform a JSON serialization on each of the key values --- providing those as a list of keys. (Then your Python code would first iterate over the list of keys, instantiating/deserializing them into native Python objects ... and then use those for access the values out of the mapping).</p>
| 43 | 2009-09-20T19:56:46Z | [
"python",
"json"
] |
Python's json module, converts int dictionary keys to strings | 1,450,957 | <p>I have found that when the following is run, python's json module (included since 2.6) converts int dictionary keys to strings.</p>
<pre><code>>>> import json
>>> releases = {1: "foo-v0.1"}
>>> json.dumps(releases)
'{"1": "foo-v0.1"}'
</code></pre>
<p>Is there any easy way to preserve the key as an int, without needing to parse the string on dump and load.
I believe it would be possible using the hooks provided by the json module, but again this still requires parsing.
Is there possibly an argument I have overlooked?
cheers, chaz</p>
<p>Sub-question:
Thanks for the answers. Seeing as json works as I feared, is there an easy way to convey key type by maybe parsing the output of dumps?
Also I should note the code doing the dumping and the code downloading the json object from a server and loading it, are both written by me.</p>
| 56 | 2009-09-20T12:52:40Z | 1,513,957 | <p>I've gotten bitten by the same problem. As others have pointed out, in JSON, the mapping keys must be strings. You can do one of two things. You can use a less strict JSON library, like <a href="http://deron.meranda.us/python/demjson/" rel="nofollow">demjson</a>, which allows integer strings. If no other programs (or no other in other languages) are going to read it, then you should be okay. Or you can use a different serialization language. I wouldn't suggest pickle. It's hard to read, and is <a href="http://www.toniblogs.com/08/2012/security/shellcoding-with-python-pickles/" rel="nofollow">not designed to be secure</a>. Instead, I'd suggest YAML, which is (nearly) a superset of JSON, and does allow integer keys. (At least <a href="http://pyyaml.org/" rel="nofollow">PyYAML</a> does.)</p>
| 6 | 2009-10-03T14:54:08Z | [
"python",
"json"
] |
Python's json module, converts int dictionary keys to strings | 1,450,957 | <p>I have found that when the following is run, python's json module (included since 2.6) converts int dictionary keys to strings.</p>
<pre><code>>>> import json
>>> releases = {1: "foo-v0.1"}
>>> json.dumps(releases)
'{"1": "foo-v0.1"}'
</code></pre>
<p>Is there any easy way to preserve the key as an int, without needing to parse the string on dump and load.
I believe it would be possible using the hooks provided by the json module, but again this still requires parsing.
Is there possibly an argument I have overlooked?
cheers, chaz</p>
<p>Sub-question:
Thanks for the answers. Seeing as json works as I feared, is there an easy way to convey key type by maybe parsing the output of dumps?
Also I should note the code doing the dumping and the code downloading the json object from a server and loading it, are both written by me.</p>
| 56 | 2009-09-20T12:52:40Z | 3,742,888 | <p>Alternatively you can also try converting dictionary to a list of [(k1,v1),(k2,v2)] format while encoding it using json, and converting it back to dictionary after decoding it back.
<pre><code>
>>>> import json
>>>> json.dumps(releases.items())
'[[1, "foo-v0.1"]]'
>>>> releases = {1: "foo-v0.1"}
>>>> releases == dict(json.loads(json.dumps(releases.items())))
True
</pre></code>
I believe this will need some more work like having some sort of flag to identify what all parameters to be converted to dictionary after decoding it back from json.</p>
| 14 | 2010-09-18T18:17:49Z | [
"python",
"json"
] |
Python's json module, converts int dictionary keys to strings | 1,450,957 | <p>I have found that when the following is run, python's json module (included since 2.6) converts int dictionary keys to strings.</p>
<pre><code>>>> import json
>>> releases = {1: "foo-v0.1"}
>>> json.dumps(releases)
'{"1": "foo-v0.1"}'
</code></pre>
<p>Is there any easy way to preserve the key as an int, without needing to parse the string on dump and load.
I believe it would be possible using the hooks provided by the json module, but again this still requires parsing.
Is there possibly an argument I have overlooked?
cheers, chaz</p>
<p>Sub-question:
Thanks for the answers. Seeing as json works as I feared, is there an easy way to convey key type by maybe parsing the output of dumps?
Also I should note the code doing the dumping and the code downloading the json object from a server and loading it, are both written by me.</p>
| 56 | 2009-09-20T12:52:40Z | 34,346,202 | <p>Answering your subquestion:</p>
<p>It can be accomplished by using <code>json.loads(jsonDict, object_hook=jsonKeys2str)</code></p>
<pre><code>def jsonKeys2str(x):
if isinstance(x, dict):
return {int(k):v for k,v in x.items()}
return x
</code></pre>
<p>This function will also work for nested dicts and uses a dict comprehension.</p>
<p>If you want to to cast the values too, use:</p>
<pre><code>def jsonKV2str(x):
if isinstance(x, dict):
return {int(k):(int(v) if isinstance(v, unicode) else v) for k,v in x.items()}
return x
</code></pre>
<p>Which tests the instance of the values and casts them only if they are strings objects (unicode to be exact). </p>
<p>Both functions assumes keys (and values) to be integers.</p>
<p>Thanks to:</p>
<p><a href="http://stackoverflow.com/questions/9442724/python-if-else-in-dict-comprehension">Python: if/else in dict comprehension?</a></p>
<p><a href="http://stackoverflow.com/questions/21193682/convert-a-string-key-to-int-in-a-dictionary">Convert a string key to int in a Dictionary</a></p>
| 3 | 2015-12-17T23:28:25Z | [
"python",
"json"
] |
Python's json module, converts int dictionary keys to strings | 1,450,957 | <p>I have found that when the following is run, python's json module (included since 2.6) converts int dictionary keys to strings.</p>
<pre><code>>>> import json
>>> releases = {1: "foo-v0.1"}
>>> json.dumps(releases)
'{"1": "foo-v0.1"}'
</code></pre>
<p>Is there any easy way to preserve the key as an int, without needing to parse the string on dump and load.
I believe it would be possible using the hooks provided by the json module, but again this still requires parsing.
Is there possibly an argument I have overlooked?
cheers, chaz</p>
<p>Sub-question:
Thanks for the answers. Seeing as json works as I feared, is there an easy way to convey key type by maybe parsing the output of dumps?
Also I should note the code doing the dumping and the code downloading the json object from a server and loading it, are both written by me.</p>
| 56 | 2009-09-20T12:52:40Z | 38,626,091 | <p>You can write your <code>json.dumps</code> by yourself, here is a example from <a href="https://github.com/damnever/djson" rel="nofollow">djson</a>: <a href="https://github.com/damnever/djson/blob/master/djson/encoder.py" rel="nofollow">encoder.py</a>. You can use it like this:</p>
<pre><code>assert dumps({1: "abc"}) == '{1: "abc"}'
</code></pre>
| 0 | 2016-07-28T02:17:43Z | [
"python",
"json"
] |
Security concerns with a Python PAM module? | 1,451,224 | <p>I'm interested in writing a PAM module that would make use of a popular authentication mechanism for Unix logins. Most of my past programming experience has been in Python, and the system I'm interacting with already has a Python API. I googled around and found <a href="http://pam-python.sourceforge.net/" rel="nofollow">pam_python</a>, which allows PAM modules to invoke the python intrepreter, therefore allowing PAM modules to be written essentially <em>in</em> Python.</p>
<p>However, I've read that there are security risks when allowing a user to invoke Python code that runs with a higher access level than the user itself, such as SUID Python scripts. Are these concerns applicable to a Python PAM module as well?</p>
| 12 | 2009-09-20T15:02:52Z | 1,451,379 | <p>The security concerns that you mention aren't, per se, about "allowing the user to invoke Python code" which runs with high access levels, but allowing the user to exercise any form of <em>control</em> over the running of such code -- most obviously by injecting or altering the code itself, but, more subtly, also by controlling that process's environment (and therefore the path from which that code imports modules, for example). (Similar concerns would apply with C-written code if the user was able to control the path from which the latter loads <code>.so</code>'s for example -- though the OS may help more directly with such a concern).</p>
<p>It appears to me that <code>pam_python</code> is well armored against such risks, and so it should be safely usable for your purposes. However, do note that <a href="http://pam-python.sourceforge.net/doc/html/" rel="nofollow">the docs</a> point out...:</p>
<blockquote>
<p>Writing PAM modules from Python incurs
a large performance penalty and
requires Python to be installed, so it
is not the best option for writing
modules that will be used widely.</p>
</blockquote>
<p>So, if you're right that the mechanism you're supplying will be popular, you will probably want to code your module in C to avoid these issues. However, prototyping it in Python as a proof of concept with limited distribution, before firming it up in C, is a viable strategy.</p>
| 16 | 2009-09-20T16:20:40Z | [
"python",
"security",
"pam",
"suid"
] |
How to stream binary data in python | 1,451,349 | <p>I want to stream a binary data using python. I do not have any idea how to achieve it. I did created python socket program using <code>SOCK_DGRAM</code>. Problem with <code>SOCK_STREAM</code> is that it does not work over internet as our isp dont allow tcp server socket. </p>
<p>I want to transmit screen shots periodically to remote computer.
I have an idea of maintaining a Que of binary data and have two threads write and read synchronously.
I do not want to use VNC .</p>
<p>How do I do it?</p>
<p>I did written server socket and client socket using SOCK_STREAM it was working on localhost and did not work over internet even if respective ip's are placed. We also did tried running tomcat web server on one pc and tried accessing via other pc on internet and was not working. </p>
| 1 | 2009-09-20T16:01:16Z | 1,451,356 | <p>There are two problems here.</p>
<p>First problem, you will need to be able to address the remote party. This is related to what you referred to as "does not work over Internet as most ISP don't allow TCP server socket". It is usually difficult because the other party could be placed behind a NAT or a firewall.</p>
<p>As for the second problem, the problem of actual transmitting of data after you can make a TCP connection, python socket would work if you can address the remote party.</p>
| 2 | 2009-09-20T16:06:13Z | [
"python",
"sockets"
] |
How to stream binary data in python | 1,451,349 | <p>I want to stream a binary data using python. I do not have any idea how to achieve it. I did created python socket program using <code>SOCK_DGRAM</code>. Problem with <code>SOCK_STREAM</code> is that it does not work over internet as our isp dont allow tcp server socket. </p>
<p>I want to transmit screen shots periodically to remote computer.
I have an idea of maintaining a Que of binary data and have two threads write and read synchronously.
I do not want to use VNC .</p>
<p>How do I do it?</p>
<p>I did written server socket and client socket using SOCK_STREAM it was working on localhost and did not work over internet even if respective ip's are placed. We also did tried running tomcat web server on one pc and tried accessing via other pc on internet and was not working. </p>
| 1 | 2009-09-20T16:01:16Z | 1,451,365 | <p>SOCK_STREAM is the correct way to stream data.</p>
<p>What you're saying about ISPs makes very little sense; they don't control whether or not your machine listens on a certain port on an interface. Perhaps you're talking about firewall/addressing issues?</p>
<p>If you insist on using UDP (and you shouldn't because you'll have to worry about packets arriving out of place or not arriving at all) then you'll need to first use <code>socket.bind</code> and then <code>socket.recvfrom</code> in a loop to read data and keep track of open connections. It'll be hard work to do correctly.</p>
| 3 | 2009-09-20T16:09:33Z | [
"python",
"sockets"
] |
Python: How to find presence of every list item in string | 1,451,390 | <p>What is the most pythonic way to find presence of every directory name <code>['spam', 'eggs']</code> in path e.g. <code>"/home/user/spam/eggs"</code></p>
<p>Usage example (doesn't work but explains my case):</p>
<pre><code>dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
if path.find(dirs):
print "All dirs are present in the path"
</code></pre>
<p>Thanks</p>
| 3 | 2009-09-20T16:28:05Z | 1,451,404 | <pre><code>names = ['spam', 'eggs']
dir = "/home/user/spam/eggs"
# Split into parts
parts = [ for part in dir.split('/') if part != '' ]
# Rejoin found paths
dirs = [ '/'.join(parts[0:n]) for (n, name) in enumerate(parts) if name in names ]
</code></pre>
<p>Edit : If you just want to verify whether all dirs exist:</p>
<pre><code>parts = "/home/user/spam/eggs".split('/')
print all(dir in parts for dir in ['spam', 'eggs'])
</code></pre>
| 2 | 2009-09-20T16:36:26Z | [
"python",
"list",
"path"
] |
Python: How to find presence of every list item in string | 1,451,390 | <p>What is the most pythonic way to find presence of every directory name <code>['spam', 'eggs']</code> in path e.g. <code>"/home/user/spam/eggs"</code></p>
<p>Usage example (doesn't work but explains my case):</p>
<pre><code>dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
if path.find(dirs):
print "All dirs are present in the path"
</code></pre>
<p>Thanks</p>
| 3 | 2009-09-20T16:28:05Z | 1,451,426 | <p>A one liner using generators (using textual lookup and not treating names as anything to do with the filesystem - your request is not totally clear to me)</p>
<pre><code>[x for x in dirs if x in path.split( os.sep )]
</code></pre>
| 0 | 2009-09-20T16:46:09Z | [
"python",
"list",
"path"
] |
Python: How to find presence of every list item in string | 1,451,390 | <p>What is the most pythonic way to find presence of every directory name <code>['spam', 'eggs']</code> in path e.g. <code>"/home/user/spam/eggs"</code></p>
<p>Usage example (doesn't work but explains my case):</p>
<pre><code>dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
if path.find(dirs):
print "All dirs are present in the path"
</code></pre>
<p>Thanks</p>
| 3 | 2009-09-20T16:28:05Z | 1,451,453 | <p>Looks line you want something like...:</p>
<pre><code>if all(d in path.split('/') for d in dirs):
...
</code></pre>
<p>This one-liner style is inefficient since it keeps splitting path for each d (and split makes a list, while a set is better for membership checking). Making it into a 2-liner:</p>
<pre><code>pathpieces = set(path.split('/'))
if all(d in pathpieces for d in dirs):
...
</code></pre>
<p>vastly improves performance.</p>
| 5 | 2009-09-20T16:59:44Z | [
"python",
"list",
"path"
] |
Python: How to find presence of every list item in string | 1,451,390 | <p>What is the most pythonic way to find presence of every directory name <code>['spam', 'eggs']</code> in path e.g. <code>"/home/user/spam/eggs"</code></p>
<p>Usage example (doesn't work but explains my case):</p>
<pre><code>dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
if path.find(dirs):
print "All dirs are present in the path"
</code></pre>
<p>Thanks</p>
| 3 | 2009-09-20T16:28:05Z | 1,451,458 | <p>Maybe this is what you want?</p>
<pre><code>dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
present = [dir for dir in dirs if dir in path]
</code></pre>
| 1 | 2009-09-20T17:01:14Z | [
"python",
"list",
"path"
] |
Python: How to find presence of every list item in string | 1,451,390 | <p>What is the most pythonic way to find presence of every directory name <code>['spam', 'eggs']</code> in path e.g. <code>"/home/user/spam/eggs"</code></p>
<p>Usage example (doesn't work but explains my case):</p>
<pre><code>dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
if path.find(dirs):
print "All dirs are present in the path"
</code></pre>
<p>Thanks</p>
| 3 | 2009-09-20T16:28:05Z | 1,451,910 | <h3><a href="http://docs.python.org/library/stdtypes.html#set.issubset"><code>set.issubset</code></a>:</h3>
<pre><code>>>> set(['spam', 'eggs']).issubset('/home/user/spam/eggs'.split('/'))
True
</code></pre>
| 9 | 2009-09-20T20:14:12Z | [
"python",
"list",
"path"
] |
Python MySQL - SELECTs work but not DELETEs? | 1,451,782 | <p>I'm new to Python and Python's MySQL adapter. I'm not sure if I'm missing something obvious here:</p>
<pre><code>db = MySQLdb.connect(# db details omitted)
cursor = self.db.cursor()
# WORKS
cursor.execute("SELECT site_id FROM users WHERE username=%s", (username))
record = cursor.fetchone()
# DOES NOT SEEM TO WORK
cursor.execute("DELETE FROM users WHERE username=%s", (username))
</code></pre>
<p>Any ideas?</p>
| 7 | 2009-09-20T19:22:23Z | 1,451,914 | <p>I'd guess that you are using a storage engine that supports transactions (e.g. InnoDB) but you don't call <code>db.commit()</code> after the DELETE. The effect of the DELETE is discarded if you don't commit.</p>
<p>See <a href="http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away">http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away</a>:</p>
<blockquote>
<p>Starting with 1.2.0, MySQLdb disables
autocommit by default, as required by
the DB-API standard (PEP-249). If you
are using InnoDB tables or some other
type of transactional table type,
you'll need to do connection.commit()
before closing the connection, or else
none of your changes will be written
to the database.</p>
</blockquote>
<p>See also this similar SO question: <a href="http://stackoverflow.com/questions/1028671/python-mysqldb-update-query-fails">http://stackoverflow.com/questions/1028671/python-mysqldb-update-query-fails</a></p>
| 11 | 2009-09-20T20:14:52Z | [
"python",
"mysql",
"select",
"sql-delete"
] |
Python MySQL - SELECTs work but not DELETEs? | 1,451,782 | <p>I'm new to Python and Python's MySQL adapter. I'm not sure if I'm missing something obvious here:</p>
<pre><code>db = MySQLdb.connect(# db details omitted)
cursor = self.db.cursor()
# WORKS
cursor.execute("SELECT site_id FROM users WHERE username=%s", (username))
record = cursor.fetchone()
# DOES NOT SEEM TO WORK
cursor.execute("DELETE FROM users WHERE username=%s", (username))
</code></pre>
<p>Any ideas?</p>
| 7 | 2009-09-20T19:22:23Z | 1,457,166 | <p>To your code above,
just add a call to <code>self.db.commit()</code>.</p>
<p>The feature is far from an annoyance:</p>
<p>It saves you from data corruption issues
when there are errors in your queries.</p>
| 0 | 2009-09-21T22:11:48Z | [
"python",
"mysql",
"select",
"sql-delete"
] |
Python MySQL - SELECTs work but not DELETEs? | 1,451,782 | <p>I'm new to Python and Python's MySQL adapter. I'm not sure if I'm missing something obvious here:</p>
<pre><code>db = MySQLdb.connect(# db details omitted)
cursor = self.db.cursor()
# WORKS
cursor.execute("SELECT site_id FROM users WHERE username=%s", (username))
record = cursor.fetchone()
# DOES NOT SEEM TO WORK
cursor.execute("DELETE FROM users WHERE username=%s", (username))
</code></pre>
<p>Any ideas?</p>
| 7 | 2009-09-20T19:22:23Z | 1,457,696 | <p>Perhaps you are violating a foreign key constraint.</p>
| 1 | 2009-09-22T01:22:50Z | [
"python",
"mysql",
"select",
"sql-delete"
] |
Python MySQL - SELECTs work but not DELETEs? | 1,451,782 | <p>I'm new to Python and Python's MySQL adapter. I'm not sure if I'm missing something obvious here:</p>
<pre><code>db = MySQLdb.connect(# db details omitted)
cursor = self.db.cursor()
# WORKS
cursor.execute("SELECT site_id FROM users WHERE username=%s", (username))
record = cursor.fetchone()
# DOES NOT SEEM TO WORK
cursor.execute("DELETE FROM users WHERE username=%s", (username))
</code></pre>
<p>Any ideas?</p>
| 7 | 2009-09-20T19:22:23Z | 13,190,265 | <p>The problem might be that you are not committing the changes. it can be done by
<code>conn.commit()</code></p>
<p>read more on this <a href="http://sahanlm.blogspot.com/2012/10/mysqldb-does-not-commit-then-read-this.html" rel="nofollow">here</a></p>
| 0 | 2012-11-02T06:14:42Z | [
"python",
"mysql",
"select",
"sql-delete"
] |
Simple file transfer over wifi between computer and mobile phone using python | 1,451,849 | <p>I'd like to be able to transfer files between my mobile phone and computer. The phone is a smartphone that can run python 2.5.4 and the computer is running windows xp (with python 2.5.4 and 3.1.1). </p>
<p>I'd like to have a simple python program on the phone that can send files to the computer and get files from the computer. The phone end should only run when invoked, the computer end can be a server, although preferably something that does not use a lot of resources. The phone end should be able to figure out what's in the relevant directory on the computer.</p>
<p>At the moment I'm getting files from computer to phone by running windows web server on the computer (ugh) and a script with socket.set_ default _ access_point (so the program can pick my router's ssid or other transport) and urlretrieve (to get the files) on the phone. I'm sending files the other way by email using smtplib. </p>
<p>Suggestions would be appreciated, whether a general idea, existing programs or anything in between.</p>
| 4 | 2009-09-20T19:53:18Z | 1,451,872 | <p>There are <a href="http://mail.python.org/pipermail/python-list/2008-February/649168.html" rel="nofollow">a couple of examples</a> out there, but you have to keep in mind that, IIRC, PyBluez will work only on Linux.</p>
<blockquote>
<p>I've previously done OBEX-related things, mostly fetching things from
mobile phones, using the obexftp program [2] which is part of the
OpenOBEX project [3]. Naturally, you can call the obexftp program from
Python and interpret the responses and exit codes using functions in
the os, popen2 and subprocess modules. I believe that obexftp also
supports "push" mode, but you could probably find something else
related to OpenOBEX if it does not.</p>
<p>Since Bluetooth communications are supported using sockets in GNU/
Linux distributions and in Python (provided that the Bluetooth support
is detected and configured), you could communicate with phones using
plain network programming, but this would probably require you to
implement the OBEX protocols yourself - not a straightforward task for
a number of reasons, including one I mention below. Thus, it's
probably easier to go with obexftp at least initially.</p>
</blockquote>
<p>You also have <a href="http://lightblue.sourceforge.net" rel="nofollow">lightblue</a>, that is a cross-os bluetooth library.</p>
<p>There is also a complete script, <a href="http://people.csail.mit.edu/kapu/symbian/python.html" rel="nofollow">PUTools: Python Utility Tools for PyS60 Python</a> (examples has Windows screenshots), that has a:</p>
<blockquote>
<p>Python interpreter that takes input and shows output on PC, connects over Bluetooth to phone, and executes on the phone. You also get simple shell functionality for the phone (cd, ls, rm, etc.). The tool also allows you to synchronize files both from PC to phone (very useful in application development) and from phone to PC (your images, logfiles from the program you are working on, etc.).</p>
</blockquote>
| 0 | 2009-09-20T20:01:05Z | [
"python",
"mobile-phones",
"file-transfer"
] |
Simple file transfer over wifi between computer and mobile phone using python | 1,451,849 | <p>I'd like to be able to transfer files between my mobile phone and computer. The phone is a smartphone that can run python 2.5.4 and the computer is running windows xp (with python 2.5.4 and 3.1.1). </p>
<p>I'd like to have a simple python program on the phone that can send files to the computer and get files from the computer. The phone end should only run when invoked, the computer end can be a server, although preferably something that does not use a lot of resources. The phone end should be able to figure out what's in the relevant directory on the computer.</p>
<p>At the moment I'm getting files from computer to phone by running windows web server on the computer (ugh) and a script with socket.set_ default _ access_point (so the program can pick my router's ssid or other transport) and urlretrieve (to get the files) on the phone. I'm sending files the other way by email using smtplib. </p>
<p>Suggestions would be appreciated, whether a general idea, existing programs or anything in between.</p>
| 4 | 2009-09-20T19:53:18Z | 1,452,284 | <p>I would use <a href="http://www.lag.net/paramiko/" rel="nofollow">paramiko</a>. It's secure fast and really simple. How bout this?</p>
<p>So we start by importing the module, and specifying the log file:</p>
<pre><code>import paramiko
paramiko.util.log_to_file('/tmp/paramiko.log')
</code></pre>
<p>We open an SSH transport:</p>
<pre><code>host = "example.com"
port = 22
transport = paramiko.Transport((host, port))
</code></pre>
<p>Next we want to authenticate. We can do this with a password:</p>
<pre><code>password = "example101"
username = "warrior"
transport.connect(username = username, password = password)
</code></pre>
<p>Another way is to use an SSH key:</p>
<pre><code>import os
privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
username = 'warrior'
transport.connect(username = username, pkey = mykey)
</code></pre>
<p>Now we can start the SFTP client:</p>
<pre><code>sftp = paramiko.SFTPClient.from_transport(transport)
</code></pre>
<p>Now lets pull a file across from the remote to the local system:</p>
<pre><code>filepath = '/home/zeth/lenna.jpg'
localpath = '/home/zeth/lenna.jpg'
sftp.get(filepath, localpath)
</code></pre>
<p>Now lets go the other way:</p>
<pre><code>filepath = '/home/zeth/lenna.jpg'
localpath = '/home/zeth/lenna.jpg'
sftp.put(filepath, localpath)
</code></pre>
<p>Lastly, we need to close the SFTP connection and the transport:</p>
<pre><code>sftp.close()
transport.close()
</code></pre>
<p>How's that?? I have to give <a href="http://commandline.org.uk/python/sftp-python/" rel="nofollow">credit</a> to this for the example.</p>
| 3 | 2009-09-20T23:12:10Z | [
"python",
"mobile-phones",
"file-transfer"
] |
Simple file transfer over wifi between computer and mobile phone using python | 1,451,849 | <p>I'd like to be able to transfer files between my mobile phone and computer. The phone is a smartphone that can run python 2.5.4 and the computer is running windows xp (with python 2.5.4 and 3.1.1). </p>
<p>I'd like to have a simple python program on the phone that can send files to the computer and get files from the computer. The phone end should only run when invoked, the computer end can be a server, although preferably something that does not use a lot of resources. The phone end should be able to figure out what's in the relevant directory on the computer.</p>
<p>At the moment I'm getting files from computer to phone by running windows web server on the computer (ugh) and a script with socket.set_ default _ access_point (so the program can pick my router's ssid or other transport) and urlretrieve (to get the files) on the phone. I'm sending files the other way by email using smtplib. </p>
<p>Suggestions would be appreciated, whether a general idea, existing programs or anything in between.</p>
| 4 | 2009-09-20T19:53:18Z | 1,457,187 | <p>I ended up using python's ftplib on the phone and FileZilla, an ftp sever, on the computer. Advantages are high degree of simplicity, although there may be security issues.</p>
<p>In case anyone cares, here's the guts of the client side code to send and receive files. Actual implementation has a bit more infrastructure.</p>
<pre><code>from ftplib import FTP
import os
ftp = FTP()
ftp.connect(server, port)
ftp.login(user, pwd)
files = ftp.nlst() # get a list of files on the server
# decide which file we want
fn = 'test.py' # filename on server and for local storage
d = 'c:/temp/' # local directory to store file
path = os.path.join(d,fn)
r = ftp.retrbinary('RETR %s' % fn, open(path, 'wb').write)
print(r) # should be: 226 Transfer OK
f = open(path, 'rb') # send file at path
r = ftp.storbinary('STOR %s' % fn, f) # call it fn on server
print(r) # should be: 226 Transfer OK
f.close()
ftp.quit()
</code></pre>
| 0 | 2009-09-21T22:18:09Z | [
"python",
"mobile-phones",
"file-transfer"
] |
Simple scraping of youtube xml to get a Python list of videos | 1,452,144 | <p>I have an xml feed, say:</p>
<p><a href="http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/" rel="nofollow">http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/</a></p>
<p>I want to get the list of hrefs for the videos:</p>
<pre><code> ['http://www.youtube.com/watch?v=aJvVkBcbFFY', 'ht....', ... ]
</code></pre>
| 1 | 2009-09-20T22:02:27Z | 1,452,164 | <pre><code>import urllib
from xml.dom import minidom
xmldoc = minidom.parse(urllib.urlopen('http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/'))
links = xmldoc.getElementsByTagName('link')
hrefs = []
for links in link:
if link.getAttribute('rel') == 'alternate':
hrefs.append( link.getAttribute('href') )
hrefs
</code></pre>
| 1 | 2009-09-20T22:19:08Z | [
"python",
"xml",
"youtube"
] |
Simple scraping of youtube xml to get a Python list of videos | 1,452,144 | <p>I have an xml feed, say:</p>
<p><a href="http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/" rel="nofollow">http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/</a></p>
<p>I want to get the list of hrefs for the videos:</p>
<pre><code> ['http://www.youtube.com/watch?v=aJvVkBcbFFY', 'ht....', ... ]
</code></pre>
| 1 | 2009-09-20T22:02:27Z | 1,452,167 | <p>Have a look at <a href="http://www.feedparser.org/" rel="nofollow">Universal Feed Parser</a>, which is an open source RSS and Atom feed parser for Python.</p>
| 3 | 2009-09-20T22:19:28Z | [
"python",
"xml",
"youtube"
] |
Simple scraping of youtube xml to get a Python list of videos | 1,452,144 | <p>I have an xml feed, say:</p>
<p><a href="http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/" rel="nofollow">http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/</a></p>
<p>I want to get the list of hrefs for the videos:</p>
<pre><code> ['http://www.youtube.com/watch?v=aJvVkBcbFFY', 'ht....', ... ]
</code></pre>
| 1 | 2009-09-20T22:02:27Z | 1,452,170 | <p>In such a simple case, this should be enough:</p>
<pre><code>import re, urllib2
request = urllib2.urlopen("http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/")
text = request.read()
videos = re.findall("http:\/\/www\.youtube\.com\/watch\?v=[\w-]+", text)
</code></pre>
<p>If you want to do more complicated stuff, parsing the XML will be better suited than regular expressions</p>
| 3 | 2009-09-20T22:20:52Z | [
"python",
"xml",
"youtube"
] |
Simple scraping of youtube xml to get a Python list of videos | 1,452,144 | <p>I have an xml feed, say:</p>
<p><a href="http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/" rel="nofollow">http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/</a></p>
<p>I want to get the list of hrefs for the videos:</p>
<pre><code> ['http://www.youtube.com/watch?v=aJvVkBcbFFY', 'ht....', ... ]
</code></pre>
| 1 | 2009-09-20T22:02:27Z | 1,452,219 | <pre><code>from xml.etree import cElementTree as ET
import urllib
def get_bass_fishing_URLs():
results = []
data = urllib.urlopen(
'http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/')
tree = ET.parse(data)
ns = '{http://www.w3.org/2005/Atom}'
for entry in tree.findall(ns + 'entry'):
for link in entry.findall(ns + 'link'):
if link.get('rel') == 'alternate':
results.append(link.get('href'))
</code></pre>
<p>as it appears that what you get are the so-called "alternate" links. The many small, possible variations if you want something slightly different, I hope, should be clear from the above code (plus the standard Python library <a href="http://docs.python.org/library/xml.etree.elementtree.html">docs</a> for ElementTree).</p>
| 7 | 2009-09-20T22:44:03Z | [
"python",
"xml",
"youtube"
] |
Detecting symlinks (mklink) on Vista/7 in Python without Pywin32 | 1,452,148 | <p>Currently the buildout recipe collective.recipe.omelette uses junction.exe on all versions of Windows to create symlinks. However junction.exe does not come with Windows by default and most importantly does not support creating symlinks to files (only directories) which causes a problem with quite a few Python packages.</p>
<p>On NT6+ (Vista and 7) there is now the mklink utility that not only comes by default but is also capable of creating symlinks to files as well as directories. I would like to update collective.recipe.omelette to use this if available and have done so except for one otherwise simple feature; detecting whether a file or folder is actually a symlink. Since this is a small buildout recipe, requiring Pywin32 in my opinion is a bit too much (unless setuptools could somehow only download it on Windows?).</p>
<p>Currently on Windows what omelette does is call junction.exe on the folder and then grep the response for "Substitute Name:" but I can't find anything as simple for mklink.</p>
<p>The only method I can think of is to call "dir" in the directory and then to go through the response line by line looking for "<SYMLINK>" and the folder/filename on the same line. Surely there is something better?</p>
| 3 | 2009-09-20T22:06:20Z | 1,452,321 | <p>Could you use <code>ctypes</code> to access the various needed functions and structures? <a href="http://bugs.python.org/file14878/windows%20symlink%20draft%209.patch" rel="nofollow">this patch</a>, currently under discussion, is intended to add symlink functionality to module <code>os</code> under Vista and Windows 7 -- but it won't be in before Python 2.7 and 3.2, so the wait (and the requirement for the very latest versions when they do eventually come) will likely be too long; a <code>ctypes</code>-based solution might tide you over and the code in the patch shows what it takes in C to do it (and ctypes-based programmed in Python is only a bit harder than the same programming in C).</p>
<p>Unless somebody's already released some other stand-alone utility like <code>junction.exe</code> for this purpose, I don't see other workable approaches (until that patch finally makes it into a future Python's stdlib) beyond using ctypes, Pywin32, or <code>dir</code>, and you've already ruled out the last two of these three options...!-)</p>
| 2 | 2009-09-20T23:35:01Z | [
"python",
"windows",
"windows-vista",
"pywin32"
] |
Detecting symlinks (mklink) on Vista/7 in Python without Pywin32 | 1,452,148 | <p>Currently the buildout recipe collective.recipe.omelette uses junction.exe on all versions of Windows to create symlinks. However junction.exe does not come with Windows by default and most importantly does not support creating symlinks to files (only directories) which causes a problem with quite a few Python packages.</p>
<p>On NT6+ (Vista and 7) there is now the mklink utility that not only comes by default but is also capable of creating symlinks to files as well as directories. I would like to update collective.recipe.omelette to use this if available and have done so except for one otherwise simple feature; detecting whether a file or folder is actually a symlink. Since this is a small buildout recipe, requiring Pywin32 in my opinion is a bit too much (unless setuptools could somehow only download it on Windows?).</p>
<p>Currently on Windows what omelette does is call junction.exe on the folder and then grep the response for "Substitute Name:" but I can't find anything as simple for mklink.</p>
<p>The only method I can think of is to call "dir" in the directory and then to go through the response line by line looking for "<SYMLINK>" and the folder/filename on the same line. Surely there is something better?</p>
| 3 | 2009-09-20T22:06:20Z | 1,452,480 | <p>On windows junctions and symbolic links have the attribute <code>FILE_ATTRIBUTE_REPARSE_POINT</code> (0x400) for reparse points. If you get the file's attributes, then detect this on?</p>
<p>You could use ctypes (as stated in the other answer) to access <a href="http://msdn.microsoft.com/en-us/library/aa364944%28VS.85%29.aspx" rel="nofollow">Kernel32.dll and GetFileAttributes</a>, and detect this value.</p>
| 2 | 2009-09-21T01:10:33Z | [
"python",
"windows",
"windows-vista",
"pywin32"
] |
Detecting symlinks (mklink) on Vista/7 in Python without Pywin32 | 1,452,148 | <p>Currently the buildout recipe collective.recipe.omelette uses junction.exe on all versions of Windows to create symlinks. However junction.exe does not come with Windows by default and most importantly does not support creating symlinks to files (only directories) which causes a problem with quite a few Python packages.</p>
<p>On NT6+ (Vista and 7) there is now the mklink utility that not only comes by default but is also capable of creating symlinks to files as well as directories. I would like to update collective.recipe.omelette to use this if available and have done so except for one otherwise simple feature; detecting whether a file or folder is actually a symlink. Since this is a small buildout recipe, requiring Pywin32 in my opinion is a bit too much (unless setuptools could somehow only download it on Windows?).</p>
<p>Currently on Windows what omelette does is call junction.exe on the folder and then grep the response for "Substitute Name:" but I can't find anything as simple for mklink.</p>
<p>The only method I can think of is to call "dir" in the directory and then to go through the response line by line looking for "<SYMLINK>" and the folder/filename on the same line. Surely there is something better?</p>
| 3 | 2009-09-20T22:06:20Z | 1,616,216 | <p>See <a href="https://github.com/jaraco/jaraco.windows/blob/master/jaraco/windows/filesystem/__init__.py" rel="nofollow">jaraco.windows.filesystem</a> (part of the <a href="http://pypi.python.org/pypi/jaraco.windows" rel="nofollow">jaraco.windows package</a>) for extensive examples on symlink operations in Windows without pywin32.</p>
| 4 | 2009-10-23T22:13:35Z | [
"python",
"windows",
"windows-vista",
"pywin32"
] |
Detecting symlinks (mklink) on Vista/7 in Python without Pywin32 | 1,452,148 | <p>Currently the buildout recipe collective.recipe.omelette uses junction.exe on all versions of Windows to create symlinks. However junction.exe does not come with Windows by default and most importantly does not support creating symlinks to files (only directories) which causes a problem with quite a few Python packages.</p>
<p>On NT6+ (Vista and 7) there is now the mklink utility that not only comes by default but is also capable of creating symlinks to files as well as directories. I would like to update collective.recipe.omelette to use this if available and have done so except for one otherwise simple feature; detecting whether a file or folder is actually a symlink. Since this is a small buildout recipe, requiring Pywin32 in my opinion is a bit too much (unless setuptools could somehow only download it on Windows?).</p>
<p>Currently on Windows what omelette does is call junction.exe on the folder and then grep the response for "Substitute Name:" but I can't find anything as simple for mklink.</p>
<p>The only method I can think of is to call "dir" in the directory and then to go through the response line by line looking for "<SYMLINK>" and the folder/filename on the same line. Surely there is something better?</p>
| 3 | 2009-09-20T22:06:20Z | 4,610,520 | <p>You could leverage the Tcl you have available with Tkinter, as that has a 'file link' command that knows about junctions, unlike Pythons os module.</p>
| 0 | 2011-01-06T00:03:08Z | [
"python",
"windows",
"windows-vista",
"pywin32"
] |
TurtleGraphics Python - Constraining random-moving turtle in a circle? | 1,452,311 | <p>How would I be able to make a randomly moving turtle be constrained inside a circle with a radius of 50, the circles center being at (0, 0)? So if the turtle is currently at location (x, y), it's distance from the center is math.sqrt(x ** 2 + y ** 2). Whenever the turtle's distance from the center is more than 50, have it turn around and continue. I have gotten the code to work with the screen size, but where do I put math.sqrt(x ** 2 + y ** 2) to get it to be constrained in a circle? Here's the code I have so far:</p>
<pre><code>import turtle, random, math
def bounded_random_walk(num_steps, step_size, max_turn):
turtle.reset()
width = turtle.window_width()
height = turtle.window_height()
for step in range(num_steps):
turtle.forward(step_size)
turn = random.randint(-max_turn, max_turn)
turtle.left(turn)
x, y = turtle.position()
if -width/2 <= x <= width/2 and -height/2 <= y <= height/2:
pass
else: # turn around!
turtle.left(180)
turtle.forward(step_size)
</code></pre>
<p>This code works for a turtle in the screen, but not in a circle.</p>
| 0 | 2009-09-20T23:28:50Z | 1,452,345 | <p>Where you're coding:</p>
<pre><code> if -width/2 <= x <= width/2 and -height/2 <= y <= height/2:
</code></pre>
<p>you really mean "if point(x, y) is inside the permitted area". So, when "the permitted area" is "a circle with radius 50 centered at origin", comparing the squares of distances and radius (it's clearer than taking square roots...!-) you'd have:</p>
<pre><code> if (x*x + y*y) <= 50*50:
</code></pre>
<p>leaving all the rest of your code unchanged.</p>
<p><strong>Edit</strong>: since the OP commented that this doesn't work for him I changed the if/else to:</p>
<pre><code> x, y = turtle.position()
# if -width/3 <= x <= width/3 and -height/3 <= y <= height/3:
if (x*x + y*y) <= 50*50:
pass
else: # turn around!
print 'Bounce', step, x, y
turtle.left(180)
turtle.forward(step_size)
</code></pre>
<p>and ran it as <code>bounded_random_walk(200, 10, 30)</code> from a Terminal.App on Mac OS X so the <code>print</code> would show. The result is I get about 50 to 60 prints of "Bounce" and the turtle clearly IS being bounded inside the desired circle, as logic and geometry also say it must.</p>
<p>So I hope the OP will edit their own answer along these lines (ideally on a system and in an arrangement where he can see the results of <code>print</code> or some other way of giving output and ideally show them to us) so that I can help him debug his code.</p>
| 1 | 2009-09-20T23:45:25Z | [
"python",
"turtle-graphics"
] |
Evaluation of boolean expressions in Python | 1,452,489 | <p>What truth value do objects evaluate to in Python?</p>
<p><strong>Related Questions</strong></p>
<ul>
<li><a href="http://stackoverflow.com/questions/1087135/boolean-value-of-objects-in-python">Boolean Value of Objects in Python</a>: Discussion about overriding the way it is evaluated</li>
</ul>
| 5 | 2009-09-21T01:15:21Z | 1,452,492 | <p><strong>Update</strong>: Removed all duplicate infomation with Meder's post </p>
<p>For custom objects in Python < 3.0 <code>__nonzero__</code> to change how it is evaluated. In Python 3.0 this is <code>__bool__</code> (<a href="http://stackoverflow.com/questions/1087135/boolean-value-of-objects-in-python/1087166#1087166">Reference</a> by e-satis)</p>
<p>It is important to understand what is meant by evaluate. One meaning is when an object is explicitly casting to a bool or implicitly cast by its location (in a if or while loop).</p>
<p>Another is == evalutation. 1==True, 0==False, nothing else is equal via ==.</p>
<pre><code>>>> None==False
False
>>> 1==True
True
>>> 0==False
True
>>> 2==False
False
>>> 2==True
False
</code></pre>
<p>Finally, for is, only True or False are themselves.</p>
| 7 | 2009-09-21T01:17:14Z | [
"python",
"object",
"boolean"
] |
Evaluation of boolean expressions in Python | 1,452,489 | <p>What truth value do objects evaluate to in Python?</p>
<p><strong>Related Questions</strong></p>
<ul>
<li><a href="http://stackoverflow.com/questions/1087135/boolean-value-of-objects-in-python">Boolean Value of Objects in Python</a>: Discussion about overriding the way it is evaluated</li>
</ul>
| 5 | 2009-09-21T01:15:21Z | 1,452,500 | <blockquote>
<p>Any object can be tested for truth
value, for use in an if or while
condition or as operand of the Boolean
operations below. The following values
are considered false:</p>
<ul>
<li><p>None</p></li>
<li><p>False</p></li>
<li><p>zero of any numeric type, for example, <code>0</code>, <code>0L</code>, <code>0.0</code>, <code>0j</code>.</p></li>
<li><p>any empty sequence, for example, <code>''</code>, <code>()</code>, <code>[]</code>.</p></li>
<li><p>any empty mapping, for example, <code>{}</code>.</p></li>
<li><p>instances of user-defined classes, if the class defines a <code>__nonzero__()</code> or <code>__len__()</code> method, when that method returns the integer zero or bool value <code>False</code>.</p></li>
</ul>
<p>All other values are considered true
-- so objects of many types are always true.
Operations and built-in functions that have a Boolean result always return 0 or <code>False</code> for false and 1 or <code>True</code> for true, unless otherwise stated. (Important exception: the Boolean operations "or" and "and" always return one of their operands.) </p>
</blockquote>
<p><a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing">https://docs.python.org/2/library/stdtypes.html#truth-value-testing</a></p>
<p>And as mentioned, you can override with custom objects by modifying nonzero.</p>
| 15 | 2009-09-21T01:21:22Z | [
"python",
"object",
"boolean"
] |
How to rapidly build a Web Application? | 1,452,652 | <p>To build a Web Application, what kind of open source web application frameworks / technologies are currently present that would be: </p>
<ul>
<li>Faster to learn. </li>
<li>Ease of use. </li>
<li>Have widgets for rapid development(From a GUI perspective). </li>
<li>Database integration.</li>
</ul>
<p>I would want this web app to communicate to a Java client.
I am not bound to Java on the server side and free to try out any good rapid application framework.<br />
To summarize, I haven't done much work for the server side hence am not conversant with the tools and technologies for the same.<br />
What would you suggest?<br />
Any and every input would be welcome!... </p>
| 3 | 2009-09-21T02:44:48Z | 1,452,667 | <p>There are tons, which ones are "good" depend on what you need.</p>
<p>There's Ruby on Rails, which is pretty handy.</p>
<p>For python there's django.</p>
<p>For PHP (I spend a lot of time dealing with PHP), you can look at:</p>
<ul>
<li>symfony</li>
<li>cakePHP</li>
<li>Solar</li>
<li>Zend Framework</li>
</ul>
<p>Which are all good in certain situations, and annoying in others.</p>
| 1 | 2009-09-21T02:48:15Z | [
"java",
"php",
"python",
"ruby-on-rails"
] |
How to rapidly build a Web Application? | 1,452,652 | <p>To build a Web Application, what kind of open source web application frameworks / technologies are currently present that would be: </p>
<ul>
<li>Faster to learn. </li>
<li>Ease of use. </li>
<li>Have widgets for rapid development(From a GUI perspective). </li>
<li>Database integration.</li>
</ul>
<p>I would want this web app to communicate to a Java client.
I am not bound to Java on the server side and free to try out any good rapid application framework.<br />
To summarize, I haven't done much work for the server side hence am not conversant with the tools and technologies for the same.<br />
What would you suggest?<br />
Any and every input would be welcome!... </p>
| 3 | 2009-09-21T02:44:48Z | 1,452,670 | <p>There is no single "right" answer to this question. As a Java programmer of some 10+ years when asked this question my usual answer is... PHP. There are several reasons for this:</p>
<ul>
<li>Low resource usage (Apache, nginx);</li>
<li>Cheaper hosting;</li>
<li>Really low barrier to entry;</li>
<li>It's really Web-oriented rather than being general purpose that can be used for Web (like Java);</li>
<li>The fact that PHP scripts aren't persistent (like Java servlets are) between requests makes them much more forgiving and less likely to cause memory leaks and other problems;</li>
<li>No deployment step (like Python, Perl, etc). I'd say this is about the best thing about dynamic scripted languages. Just save the file and click reload on your browser;</li>
<li>PHP might be inconsistent in syntax and several other things but it's also mature and used by some really large sites on the Web (eg Facebook, Yahoo, Flickr, Wikipedia);</li>
<li>PHP is by far the most popular Web development language.</li>
<li>Widgets can be done by any manner of Javascript frameworks like <a href="http://developer.yahoo.com/yui/">YUI</a>, <a href="http://www.extjs.com/">ExtJS</a>, <a href="http://www.smartclient.com/">SmartClient</a>, <a href="http://jqueryui.com/">jQuery UI</a>, etc;</li>
<li>PHP fits well with MySQL.</li>
</ul>
<p>That being said, a lot of these apply to other languages too (eg Python/Django).</p>
<p>I don't think you necessarily need a framework for PHP but if you do I'd look at one or more of:</p>
<ul>
<li><a href="http://www.google.com.au/search?rlz=1C1GGLS%5FenAU314AU317&sourceid=chrome&ie=UTF-8&q=kohana">Kohana</a>: it's like a more modern version of the more popular <a href="http://codeigniter.com/">CodeIgniter</a>;</li>
<li><a href="http://framework.zend.com/">Zend Framework</a>: it's modular so you can use as much or as little of it as you like;</li>
<li><a href="http://www.smarty.net/">Smarty</a>: it's a powerful templating system.</li>
</ul>
| 7 | 2009-09-21T02:48:41Z | [
"java",
"php",
"python",
"ruby-on-rails"
] |
How to rapidly build a Web Application? | 1,452,652 | <p>To build a Web Application, what kind of open source web application frameworks / technologies are currently present that would be: </p>
<ul>
<li>Faster to learn. </li>
<li>Ease of use. </li>
<li>Have widgets for rapid development(From a GUI perspective). </li>
<li>Database integration.</li>
</ul>
<p>I would want this web app to communicate to a Java client.
I am not bound to Java on the server side and free to try out any good rapid application framework.<br />
To summarize, I haven't done much work for the server side hence am not conversant with the tools and technologies for the same.<br />
What would you suggest?<br />
Any and every input would be welcome!... </p>
| 3 | 2009-09-21T02:44:48Z | 1,452,676 | <p>You've already tagged your question with "java", "php", "python", and "ruby-on-rails", so researching and learning more about those tools would probably help to answer your question.</p>
<p>However, I believe that <em>rapidly building</em> an application is almost never actually the correct goal. Normally, what you want to do is build an application that can be <em>rapidly maintained</em> -- that is, maintained with the lowest possible overall development cost over time.</p>
| 4 | 2009-09-21T02:49:17Z | [
"java",
"php",
"python",
"ruby-on-rails"
] |
How to rapidly build a Web Application? | 1,452,652 | <p>To build a Web Application, what kind of open source web application frameworks / technologies are currently present that would be: </p>
<ul>
<li>Faster to learn. </li>
<li>Ease of use. </li>
<li>Have widgets for rapid development(From a GUI perspective). </li>
<li>Database integration.</li>
</ul>
<p>I would want this web app to communicate to a Java client.
I am not bound to Java on the server side and free to try out any good rapid application framework.<br />
To summarize, I haven't done much work for the server side hence am not conversant with the tools and technologies for the same.<br />
What would you suggest?<br />
Any and every input would be welcome!... </p>
| 3 | 2009-09-21T02:44:48Z | 1,452,739 | <p><a href="http://www.djangoproject.com/" rel="nofollow">Django</a> has a few notable 'rapid' items including <a href="http://images.google.com/images?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=0Ku&q=django%20admin&um=1&ie=UTF-8&sa=N&tab=wi" rel="nofollow">automatically generated administrative interface</a>, bundled ORM (lowers dev time by not having to write SQL and some other code), and a large community with <a href="http://djangoplugables.com/" rel="nofollow">several re-usable apps</a>.</p>
<p>Where Django (or Ruby on Rails or any other MVC framework for that matter) isn't going to be rapid is the learning curve when you first come to developing on them. Django (and RoR) have quite a bit of seperation-of-concerns and if you're not used to that sort of environment, it takes a while to learn the framework. If you're using an ORM that's something to get used to as well, and then of course for any framework you go with there's the API to learn as well.</p>
<p>PHP on the other hand is a little more intuitive in terms of where you put the code and how pages make up your web app. It'll basically let you slap code wherever you want so in the beginning it will probably be faster. In the end it will be quicker but your final product will be sloppier and probably require re-factoring later on.</p>
<p>This comes down to a question of what's the use of the framework. If it's for a hobby site, just go with what's easy (php), otherwise you might want to consider a well-supported MVC framework.</p>
<p>As others have pointed out, jquery is probably the pick for pre-made GUI widgets.</p>
<p><strong>Edit</strong> -- And apparently now Django (as of 1.1) has <a href="http://www.slideshare.net/ericholscher/token-testing-slides" rel="nofollow">a very awesome set of unit testing tools</a> it comes bundled with. Things like an extended TestCase specifically for Django, a test client (you can do test page request w/o an actual client or server), a tool to give you a % of test coverage you have of the project, and a bunch of other neat stuff.</p>
| 8 | 2009-09-21T03:13:51Z | [
"java",
"php",
"python",
"ruby-on-rails"
] |
How to rapidly build a Web Application? | 1,452,652 | <p>To build a Web Application, what kind of open source web application frameworks / technologies are currently present that would be: </p>
<ul>
<li>Faster to learn. </li>
<li>Ease of use. </li>
<li>Have widgets for rapid development(From a GUI perspective). </li>
<li>Database integration.</li>
</ul>
<p>I would want this web app to communicate to a Java client.
I am not bound to Java on the server side and free to try out any good rapid application framework.<br />
To summarize, I haven't done much work for the server side hence am not conversant with the tools and technologies for the same.<br />
What would you suggest?<br />
Any and every input would be welcome!... </p>
| 3 | 2009-09-21T02:44:48Z | 1,452,751 | <p>Speaking only in terms of speed of development, Ruby on Rails is the fastest one out there.</p>
| 1 | 2009-09-21T03:19:34Z | [
"java",
"php",
"python",
"ruby-on-rails"
] |
How to rapidly build a Web Application? | 1,452,652 | <p>To build a Web Application, what kind of open source web application frameworks / technologies are currently present that would be: </p>
<ul>
<li>Faster to learn. </li>
<li>Ease of use. </li>
<li>Have widgets for rapid development(From a GUI perspective). </li>
<li>Database integration.</li>
</ul>
<p>I would want this web app to communicate to a Java client.
I am not bound to Java on the server side and free to try out any good rapid application framework.<br />
To summarize, I haven't done much work for the server side hence am not conversant with the tools and technologies for the same.<br />
What would you suggest?<br />
Any and every input would be welcome!... </p>
| 3 | 2009-09-21T02:44:48Z | 1,452,994 | <p>I would vote for <a href="http://grails.org/" rel="nofollow">Grails</a>.</p>
| 1 | 2009-09-21T05:20:41Z | [
"java",
"php",
"python",
"ruby-on-rails"
] |
How to rapidly build a Web Application? | 1,452,652 | <p>To build a Web Application, what kind of open source web application frameworks / technologies are currently present that would be: </p>
<ul>
<li>Faster to learn. </li>
<li>Ease of use. </li>
<li>Have widgets for rapid development(From a GUI perspective). </li>
<li>Database integration.</li>
</ul>
<p>I would want this web app to communicate to a Java client.
I am not bound to Java on the server side and free to try out any good rapid application framework.<br />
To summarize, I haven't done much work for the server side hence am not conversant with the tools and technologies for the same.<br />
What would you suggest?<br />
Any and every input would be welcome!... </p>
| 3 | 2009-09-21T02:44:48Z | 1,453,699 | <p>I would say part of the learning curve will go into understanding concepts. I have been learning about web-apps for some months now, and with my improved understanding of concepts right now, most frameworks show very much similarities. Here are my results so far:</p>
<ul>
<li>PHP: Great to learn about concepts for doing forms, http-post-requests, http-get-requests. easy interaction with database layer, and it is possible to obtain a working basic application in couple of hours. Almost no hassle with build-systems and web-server configuration.</li>
<li>Ruby-on-Rails: Great to learn about REST and more complicated CRUD applications. Great to learn about the complexity behind MVC and especially simple and powerful interaction with the database layer by using ActiveRecord. Introduction of meta-programming (code-that-writes-code, code-scaffolding) is great. Nice opportunities for free cloud-deployment, e.g. heroku.com and there is a very active community</li>
<li>Java: Powerful interaction with web-server possible (Tomcat, JBoss, ...) MVC is rather complicated here, and in general many configuration-steps necessary (build systems, ORM layer, ...) Grails is a great simplifaction and introduces meta-programming for Java. Jboss Seam introduces REST for Java (but have not looked into this yet)</li>
</ul>
| 2 | 2009-09-21T09:53:14Z | [
"java",
"php",
"python",
"ruby-on-rails"
] |
How to rapidly build a Web Application? | 1,452,652 | <p>To build a Web Application, what kind of open source web application frameworks / technologies are currently present that would be: </p>
<ul>
<li>Faster to learn. </li>
<li>Ease of use. </li>
<li>Have widgets for rapid development(From a GUI perspective). </li>
<li>Database integration.</li>
</ul>
<p>I would want this web app to communicate to a Java client.
I am not bound to Java on the server side and free to try out any good rapid application framework.<br />
To summarize, I haven't done much work for the server side hence am not conversant with the tools and technologies for the same.<br />
What would you suggest?<br />
Any and every input would be welcome!... </p>
| 3 | 2009-09-21T02:44:48Z | 15,717,155 | <p>You can build an runnable Java Web application within 5 to 10 minutes by using the following online Java web application generator:</p>
<p><a href="http://www.webappexpress.net" rel="nofollow">http://www.webappexpress.net</a></p>
| 0 | 2013-03-30T09:48:55Z | [
"java",
"php",
"python",
"ruby-on-rails"
] |
Creating Simultaneous Loops in Python | 1,452,694 | <p>I want to create a loop who has this sense:</p>
<pre>
for i in xrange(0,10):
for k in xrange(0,10):
z=k+i
print z
where the output should be
0
2
4
6
8
10
12
14
16
18
</pre>
| 3 | 2009-09-21T02:59:57Z | 1,452,705 | <p>What you want is two arrays and one loop, iterate over each array once, adding the results.</p>
| 0 | 2009-09-21T03:03:34Z | [
"python",
"loops"
] |
Creating Simultaneous Loops in Python | 1,452,694 | <p>I want to create a loop who has this sense:</p>
<pre>
for i in xrange(0,10):
for k in xrange(0,10):
z=k+i
print z
where the output should be
0
2
4
6
8
10
12
14
16
18
</pre>
| 3 | 2009-09-21T02:59:57Z | 1,452,706 | <p>You can do this in python - just have to make the tabs right and use the xrange argument for step.</p>
<p><code>for i in xrange(0, 20, 2);
print i
</code></p>
| 2 | 2009-09-21T03:04:02Z | [
"python",
"loops"
] |
Creating Simultaneous Loops in Python | 1,452,694 | <p>I want to create a loop who has this sense:</p>
<pre>
for i in xrange(0,10):
for k in xrange(0,10):
z=k+i
print z
where the output should be
0
2
4
6
8
10
12
14
16
18
</pre>
| 3 | 2009-09-21T02:59:57Z | 1,452,709 | <p>The <a href="http://docs.python.org/library/itertools.html"><code>itertools</code></a> module contains an <a href="http://docs.python.org/library/itertools.html#itertools.izip"><code>izip</code></a> function that combines iterators in the desired way:</p>
<pre><code>from itertools import izip
for (i, k) in izip(xrange(0,10), xrange(0,10)):
print i+k
</code></pre>
| 10 | 2009-09-21T03:04:48Z | [
"python",
"loops"
] |
Creating Simultaneous Loops in Python | 1,452,694 | <p>I want to create a loop who has this sense:</p>
<pre>
for i in xrange(0,10):
for k in xrange(0,10):
z=k+i
print z
where the output should be
0
2
4
6
8
10
12
14
16
18
</pre>
| 3 | 2009-09-21T02:59:57Z | 1,452,711 | <p>You can use <a href="http://docs.python.org/library/functions.html#zip"><code>zip</code></a> to turn multiple lists (or iterables) into pairwise* tuples:</p>
<pre><code>>>> for a,b in zip(xrange(10), xrange(10)):
... print a+b
...
0
2
4
6
8
10
12
14
16
18
</code></pre>
<p>But <code>zip</code> will not scale as well as <code>izip</code> (that sth mentioned) on larger sets. <code>zip</code>'s advantage is that it is a built-in and you don't have to <code>import itertools</code> -- and whether <em>that</em> is actually an advantage is subjective.</p>
<p>*Not just pairwise, but <em>n</em>-wise. The tuples' length will be the same as the number of iterables you pass in to <code>zip</code>.</p>
| 11 | 2009-09-21T03:05:18Z | [
"python",
"loops"
] |
Creating Simultaneous Loops in Python | 1,452,694 | <p>I want to create a loop who has this sense:</p>
<pre>
for i in xrange(0,10):
for k in xrange(0,10):
z=k+i
print z
where the output should be
0
2
4
6
8
10
12
14
16
18
</pre>
| 3 | 2009-09-21T02:59:57Z | 1,452,731 | <p>What about this?</p>
<pre><code>i = range(0,10)
k = range(0,10)
for x in range(0,10):
z=k[x]+i[x]
print z
</code></pre>
<p>0
2
4
6
8
10
12
14
16
18</p>
| 1 | 2009-09-21T03:10:50Z | [
"python",
"loops"
] |
RTSP library in Python or C/C++? | 1,452,710 | <p>I am trying to find any RTSP streaming library for Python or C/C++. </p>
<p>If not is there any other solutions for real time streaming?
How much easy or difficult it is to implement RTSP in Python or C/C++ and where to get started?</p>
| 2 | 2009-09-21T03:05:07Z | 1,452,756 | <p>With Python and Twisted, you could use <a href="http://www.flumotion.net/doc/flumotion/reference/trunk/flumotion.twisted.rtsp-module.html" rel="nofollow">this module</a>.</p>
| 2 | 2009-09-21T03:20:39Z | [
"c++",
"python",
"c",
"rtsp"
] |
RTSP library in Python or C/C++? | 1,452,710 | <p>I am trying to find any RTSP streaming library for Python or C/C++. </p>
<p>If not is there any other solutions for real time streaming?
How much easy or difficult it is to implement RTSP in Python or C/C++ and where to get started?</p>
| 2 | 2009-09-21T03:05:07Z | 1,453,259 | <p>try <a href="http://www.live555.com" rel="nofollow">live555</a>. They have a lots of libraries and modules for implementing rtp and rtsp (as well as sip) into your c and c++ programs</p>
| 4 | 2009-09-21T07:33:35Z | [
"c++",
"python",
"c",
"rtsp"
] |
Is there an C++ equivalent to Python's "import bigname as b"? | 1,452,883 | <p>I've always liked Python's</p>
<pre><code>import big_honkin_name as bhn
</code></pre>
<p>so you can then just use <code>bhn.thing</code> rather than the considerably more verbose <code>big_honkin_name.thing</code> in your source.</p>
<p>I've seen two type of namespace use in C++ code, either:</p>
<pre><code>using namespace big_honkin_name; // includes fn().
int a = fn (27);
</code></pre>
<p>(which I'm assured is a <em>bad</em> thing) or:</p>
<pre><code>int a = big_honkin_name::fn (27);
</code></pre>
<p>Is there a way to get Python functionality in C++ code, something like:</p>
<pre><code>alias namespace big_honkin_name as bhn;
int a = bhn::fn (27);
</code></pre>
| 4 | 2009-09-21T04:18:50Z | 1,452,891 | <p><a href="http://stackoverflow.com/questions/75538/hidden-features-of-c/78484#78484">StackOverflow to the rescue!</a> Yes you can. In short:</p>
<pre><code>namespace bhn = big_honkin_name;
</code></pre>
| 12 | 2009-09-21T04:24:32Z | [
"c++",
"python",
"namespaces",
"alias"
] |
Is there an C++ equivalent to Python's "import bigname as b"? | 1,452,883 | <p>I've always liked Python's</p>
<pre><code>import big_honkin_name as bhn
</code></pre>
<p>so you can then just use <code>bhn.thing</code> rather than the considerably more verbose <code>big_honkin_name.thing</code> in your source.</p>
<p>I've seen two type of namespace use in C++ code, either:</p>
<pre><code>using namespace big_honkin_name; // includes fn().
int a = fn (27);
</code></pre>
<p>(which I'm assured is a <em>bad</em> thing) or:</p>
<pre><code>int a = big_honkin_name::fn (27);
</code></pre>
<p>Is there a way to get Python functionality in C++ code, something like:</p>
<pre><code>alias namespace big_honkin_name as bhn;
int a = bhn::fn (27);
</code></pre>
| 4 | 2009-09-21T04:18:50Z | 1,452,894 | <p>It is easy..</p>
<pre><code>namespace bhn = big_honkin_name;
</code></pre>
| 6 | 2009-09-21T04:25:49Z | [
"c++",
"python",
"namespaces",
"alias"
] |
Is there an C++ equivalent to Python's "import bigname as b"? | 1,452,883 | <p>I've always liked Python's</p>
<pre><code>import big_honkin_name as bhn
</code></pre>
<p>so you can then just use <code>bhn.thing</code> rather than the considerably more verbose <code>big_honkin_name.thing</code> in your source.</p>
<p>I've seen two type of namespace use in C++ code, either:</p>
<pre><code>using namespace big_honkin_name; // includes fn().
int a = fn (27);
</code></pre>
<p>(which I'm assured is a <em>bad</em> thing) or:</p>
<pre><code>int a = big_honkin_name::fn (27);
</code></pre>
<p>Is there a way to get Python functionality in C++ code, something like:</p>
<pre><code>alias namespace big_honkin_name as bhn;
int a = bhn::fn (27);
</code></pre>
| 4 | 2009-09-21T04:18:50Z | 1,452,896 | <p>You can use</p>
<pre><code>using big_honkin_name::fn;
</code></pre>
<p>to import all functions named <code>fn</code> from the namespace <code>big_honkin_name</code>, so that you can then write</p>
<pre><code>int a = fn(27);
</code></pre>
<p>But that doesn't let you shrink down the name itself. To do (something similar to but not exactly) that, you could do as follows:</p>
<pre><code>int big_honkin_object_name;
</code></pre>
<p>You can later use:</p>
<pre><code>int& x(big_honkin_object_name);
</code></pre>
<p>And thereafter treat <code>x</code> the same as you would <code>big_honkin_object_name</code>. The compiler will in most cases eliminate the implied indirection.</p>
| 2 | 2009-09-21T04:26:27Z | [
"c++",
"python",
"namespaces",
"alias"
] |
Is there an C++ equivalent to Python's "import bigname as b"? | 1,452,883 | <p>I've always liked Python's</p>
<pre><code>import big_honkin_name as bhn
</code></pre>
<p>so you can then just use <code>bhn.thing</code> rather than the considerably more verbose <code>big_honkin_name.thing</code> in your source.</p>
<p>I've seen two type of namespace use in C++ code, either:</p>
<pre><code>using namespace big_honkin_name; // includes fn().
int a = fn (27);
</code></pre>
<p>(which I'm assured is a <em>bad</em> thing) or:</p>
<pre><code>int a = big_honkin_name::fn (27);
</code></pre>
<p>Is there a way to get Python functionality in C++ code, something like:</p>
<pre><code>alias namespace big_honkin_name as bhn;
int a = bhn::fn (27);
</code></pre>
| 4 | 2009-09-21T04:18:50Z | 1,452,905 | <pre><code>namespace bhn = big_honkin_name;
</code></pre>
<p>There's another way to use namespaces too:</p>
<pre><code>using big_honkin_name::fn;
int a = fn(27);
</code></pre>
| 11 | 2009-09-21T04:28:42Z | [
"c++",
"python",
"namespaces",
"alias"
] |
Is there an C++ equivalent to Python's "import bigname as b"? | 1,452,883 | <p>I've always liked Python's</p>
<pre><code>import big_honkin_name as bhn
</code></pre>
<p>so you can then just use <code>bhn.thing</code> rather than the considerably more verbose <code>big_honkin_name.thing</code> in your source.</p>
<p>I've seen two type of namespace use in C++ code, either:</p>
<pre><code>using namespace big_honkin_name; // includes fn().
int a = fn (27);
</code></pre>
<p>(which I'm assured is a <em>bad</em> thing) or:</p>
<pre><code>int a = big_honkin_name::fn (27);
</code></pre>
<p>Is there a way to get Python functionality in C++ code, something like:</p>
<pre><code>alias namespace big_honkin_name as bhn;
int a = bhn::fn (27);
</code></pre>
| 4 | 2009-09-21T04:18:50Z | 1,454,622 | <pre><code>using namespace big_honkin_name;
</code></pre>
<p>Is not a bad thing. Not at all. Used judiciously, bringing namespaces into scope <em>improves</em> clarity of code by removing unnecessary clutter.</p>
<p>(Unless it's in a header file in which case it's <em>very</em> poor practice.)</p>
<p>But yes, as others have pointed out you can create a namespace alias:</p>
<pre><code>namespace big = big_honkin_name;
</code></pre>
| 1 | 2009-09-21T13:53:32Z | [
"c++",
"python",
"namespaces",
"alias"
] |
Why doesn't a python dict.update() return the object? | 1,452,995 | <p>I 'm trying to do :</p>
<pre><code>award_dict = {
"url" : "http://facebook.com",
"imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png",
"count" : 1,
}
def award(name, count, points, desc_string, my_size, parent) :
if my_size > count :
a = {
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}
a.update(award_dict)
return self.add_award(a, siteAlias, alias).award
</code></pre>
<p>But if felt really cumbersome in the function, and I would have rather done :</p>
<pre><code> return self.add_award({
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}.update(award_dict), siteAlias, alias).award
</code></pre>
<p>Why doesn't update return the object so you can chain? </p>
<p>JQuery does this to do chaining. Why isn't it acceptable in python?</p>
| 56 | 2009-09-21T05:20:43Z | 1,452,998 | <p>Its not that it isn't acceptable, but rather that <code>dicts</code> weren't implemented that way.</p>
<p>If you look at Django's ORM, it makes extensive use of chaining. Its not discouraged, you could even inherit from <code>dict</code> and only override <code>update</code> to do update and <code>return self</code>, if you really want it.</p>
<pre><code>class myDict(dict):
def update(self, *args):
dict.update(self, *args)
return self
</code></pre>
| 2 | 2009-09-21T05:24:41Z | [
"python",
"language-features",
"language-design",
"monads"
] |
Why doesn't a python dict.update() return the object? | 1,452,995 | <p>I 'm trying to do :</p>
<pre><code>award_dict = {
"url" : "http://facebook.com",
"imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png",
"count" : 1,
}
def award(name, count, points, desc_string, my_size, parent) :
if my_size > count :
a = {
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}
a.update(award_dict)
return self.add_award(a, siteAlias, alias).award
</code></pre>
<p>But if felt really cumbersome in the function, and I would have rather done :</p>
<pre><code> return self.add_award({
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}.update(award_dict), siteAlias, alias).award
</code></pre>
<p>Why doesn't update return the object so you can chain? </p>
<p>JQuery does this to do chaining. Why isn't it acceptable in python?</p>
| 56 | 2009-09-21T05:20:43Z | 1,453,011 | <p>Python's API, by convention, distinguishes between procedures and functions. Functions compute new values out of their parameters (including any target object); procedures modify objects and don't return anything (i.e. they return None). So procedures have side effects, functions don't. update is a procedure, hence it doesn't return a value.</p>
<p>The motivation for doing it that way is that otherwise, you may get undesirable side effects. Consider</p>
<pre><code>bar = foo.reverse()
</code></pre>
<p>If reverse (which reverses the list in-place) would also return the list, users may think that reverse returns a new list which gets assigned to bar, and never notice that foo also gets modified. By making reverse return None, they immediately recognize that bar is not the result of the reversal, and will look more close what the effect of reverse is.</p>
| 24 | 2009-09-21T05:29:52Z | [
"python",
"language-features",
"language-design",
"monads"
] |
Why doesn't a python dict.update() return the object? | 1,452,995 | <p>I 'm trying to do :</p>
<pre><code>award_dict = {
"url" : "http://facebook.com",
"imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png",
"count" : 1,
}
def award(name, count, points, desc_string, my_size, parent) :
if my_size > count :
a = {
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}
a.update(award_dict)
return self.add_award(a, siteAlias, alias).award
</code></pre>
<p>But if felt really cumbersome in the function, and I would have rather done :</p>
<pre><code> return self.add_award({
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}.update(award_dict), siteAlias, alias).award
</code></pre>
<p>Why doesn't update return the object so you can chain? </p>
<p>JQuery does this to do chaining. Why isn't it acceptable in python?</p>
| 56 | 2009-09-21T05:20:43Z | 1,453,013 | <p>Python's mostly implementing a pragmatically tinged flavor of <a href="http://en.wikipedia.org/wiki/Command-query%5Fseparation">command-query separation</a>: mutators return <code>None</code> (with pragmatically induced exceptions such as <code>pop</code>;-) so they can't possibly be confused with accessors (and in the same vein, assignment is not an expression, the statement-expression separation is there, and so forth).</p>
<p>That doesn't mean there aren't a lot of ways to merge things up when you really want, e.g., <code>dict(a, **award_dict)</code> makes a new dict much like the one you appear to wish <code>.update</code> returned -- so why not use THAT if you really feel it's important?</p>
<p><strong>Edit</strong>: btw, no need, in your specific case, to create <code>a</code> along the way, either:</p>
<pre><code>dict(name=name, description=desc % count, points=points, parent_award=parent,
**award_dict)
</code></pre>
<p>creates a single dict with exactly the same semantics as your <code>a.update(award_dict)</code> (including, in case of conflicts, the fact that entries in <code>award_dict</code> override those you're giving explicitly; to get the other semantics, i.e., to have explicit entries "winning" such conflicts, pass <code>award_dict</code> as the sole <em>positional</em> arg, <em>before</em> the keyword ones, and bereft of the <code>**</code> form -- <code>dict(award_dict, name=name</code> etc etc).</p>
| 105 | 2009-09-21T05:31:28Z | [
"python",
"language-features",
"language-design",
"monads"
] |
Why doesn't a python dict.update() return the object? | 1,452,995 | <p>I 'm trying to do :</p>
<pre><code>award_dict = {
"url" : "http://facebook.com",
"imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png",
"count" : 1,
}
def award(name, count, points, desc_string, my_size, parent) :
if my_size > count :
a = {
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}
a.update(award_dict)
return self.add_award(a, siteAlias, alias).award
</code></pre>
<p>But if felt really cumbersome in the function, and I would have rather done :</p>
<pre><code> return self.add_award({
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}.update(award_dict), siteAlias, alias).award
</code></pre>
<p>Why doesn't update return the object so you can chain? </p>
<p>JQuery does this to do chaining. Why isn't it acceptable in python?</p>
| 56 | 2009-09-21T05:20:43Z | 10,731,332 | <pre><code>>>> dict_merge = lambda a,b: a.update(b) or a
>>> dict_merge({'a':1, 'b':3},{'c':5})
{'a': 1, 'c': 5, 'b': 3}
</code></pre>
<p>Note that as well as returning the merged dict, it modifies the first parameter in-place. So dict_merge(a,b) will modify a.</p>
<p>Or, of course, you can do it all inline:</p>
<pre><code>>>> (lambda a,b: a.update(b) or a)({'a':1, 'b':3},{'c':5})
{'a': 1, 'c': 5, 'b': 3}
</code></pre>
| 5 | 2012-05-24T04:50:13Z | [
"python",
"language-features",
"language-design",
"monads"
] |
Why doesn't a python dict.update() return the object? | 1,452,995 | <p>I 'm trying to do :</p>
<pre><code>award_dict = {
"url" : "http://facebook.com",
"imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png",
"count" : 1,
}
def award(name, count, points, desc_string, my_size, parent) :
if my_size > count :
a = {
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}
a.update(award_dict)
return self.add_award(a, siteAlias, alias).award
</code></pre>
<p>But if felt really cumbersome in the function, and I would have rather done :</p>
<pre><code> return self.add_award({
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}.update(award_dict), siteAlias, alias).award
</code></pre>
<p>Why doesn't update return the object so you can chain? </p>
<p>JQuery does this to do chaining. Why isn't it acceptable in python?</p>
| 56 | 2009-09-21T05:20:43Z | 16,070,292 | <pre><code>import itertools
dict_merge = lambda *args: dict(itertools.chain(*[d.iteritems() for d in args]))
</code></pre>
| 1 | 2013-04-17T21:07:50Z | [
"python",
"language-features",
"language-design",
"monads"
] |
Why doesn't a python dict.update() return the object? | 1,452,995 | <p>I 'm trying to do :</p>
<pre><code>award_dict = {
"url" : "http://facebook.com",
"imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png",
"count" : 1,
}
def award(name, count, points, desc_string, my_size, parent) :
if my_size > count :
a = {
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}
a.update(award_dict)
return self.add_award(a, siteAlias, alias).award
</code></pre>
<p>But if felt really cumbersome in the function, and I would have rather done :</p>
<pre><code> return self.add_award({
"name" : name,
"description" : desc_string % count,
"points" : points,
"parent_award" : parent,
}.update(award_dict), siteAlias, alias).award
</code></pre>
<p>Why doesn't update return the object so you can chain? </p>
<p>JQuery does this to do chaining. Why isn't it acceptable in python?</p>
| 56 | 2009-09-21T05:20:43Z | 34,782,171 | <p><em>not enough reputation for comment left on top answer</em></p>
<p>@beardc this doesn't seem to be CPython thing. PyPy gives me "TypeError: keywords must be strings"</p>
<p>The solution with <code>**kwargs</code> only works because the dictionary to be merged only has <strong>keys of type string</strong>.</p>
<p>i.e.</p>
<pre><code>>>> dict({1:2}, **{3:4})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings
</code></pre>
<p>vs</p>
<pre><code>>>> dict({1:2}, **{'3':4})
{1: 2, '3': 4}
</code></pre>
| 2 | 2016-01-14T05:14:42Z | [
"python",
"language-features",
"language-design",
"monads"
] |
Should I create mapper objects or use the declarative syntax in SQLAlchemy? | 1,453,219 | <p>There are two (three, but I'm not counting <a href="http://elixir.ematia.de/trac/wiki">Elixir</a>, as its not "official") ways to define a persisting object with <a href="http://www.sqlalchemy.org">SQLAlchemy</a>:</p>
<h3><a href="http://www.sqlalchemy.org/docs/05/mappers.html">Explicit syntax for mapper objects</a></h3>
<pre><code>from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import mapper
metadata = MetaData()
users_table = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
)
class User(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "<User('%s')>" % (self.name)
mapper(User, users_table) # &lt;Mapper at 0x...; User&gt;
</code></pre>
<h3><a href="http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html">Declarative syntax</a></h3>
<pre><code>from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
def __init__(self, name):
self.name = name
def __repr__(self):
return "<User('%s')>" % (self.name)
</code></pre>
<p>I can see that while using the mapper objects, I separate completely the ORM definition from the business logic, while using the declarative syntax, whenever I modify the business logic class, I can edit right there the database class (which ideally should be edited little).</p>
<p>What I'm not completely sure, is which approach is more maintainable for a business application?</p>
<p>I haven't been able to find a comparative between the two mapping methods, to be able to decide which one is a better fit for my project.</p>
<p>I'm leaning towards using the "normal" way (i.e. not the declarative extension) as it allows me to "hide", and keep out of the business view all the ORM logic, but I'd like to hear compelling arguments for both approaches.</p>
| 32 | 2009-09-21T07:19:43Z | 1,453,881 | <p>"What I'm not completely sure, is which approach is more maintainable for a business application?"</p>
<p>Can't be answered in general.</p>
<p>However, consider this.</p>
<p>The Django ORM is strictly declarative -- and people like that.</p>
<p>SQLAlchemy does several things, not all of which are relevant to all problems.</p>
<ol>
<li><p>SQLAlchemy creates DB-specific SQL from general purpose Python. If you want to mess with the SQL, or map Python classes to existing tables, then you have to use explicit mappings, because your focus is on the SQL, not the business objects and the ORM.</p></li>
<li><p>SQLAlchemy can use declarative style (like Django) to create everything for you. If you want this, then you are giving up explicitly writing table definitions and explicitly messing with the SQL.</p></li>
<li><p>Elixir is an alternative to save you having to look at SQL.</p></li>
</ol>
<p>The fundamental question is "Do you want to see and touch the SQL?"</p>
<p>If you think that touching the SQL makes things more "maintainable", then you have to use explicit mappings.</p>
<p>If you think that concealing the SQL makes things more "maintainable", then you have to use declarative style.</p>
<ul>
<li><p>If you think Elixir might diverge from SQLAlchemy, or fail to live up to it's promise in some way, then don't use it.</p></li>
<li><p>If you think Elixir will help you, then use it.</p></li>
</ul>
| 19 | 2009-09-21T10:39:11Z | [
"python",
"sqlalchemy"
] |
Should I create mapper objects or use the declarative syntax in SQLAlchemy? | 1,453,219 | <p>There are two (three, but I'm not counting <a href="http://elixir.ematia.de/trac/wiki">Elixir</a>, as its not "official") ways to define a persisting object with <a href="http://www.sqlalchemy.org">SQLAlchemy</a>:</p>
<h3><a href="http://www.sqlalchemy.org/docs/05/mappers.html">Explicit syntax for mapper objects</a></h3>
<pre><code>from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import mapper
metadata = MetaData()
users_table = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
)
class User(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "<User('%s')>" % (self.name)
mapper(User, users_table) # &lt;Mapper at 0x...; User&gt;
</code></pre>
<h3><a href="http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html">Declarative syntax</a></h3>
<pre><code>from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
def __init__(self, name):
self.name = name
def __repr__(self):
return "<User('%s')>" % (self.name)
</code></pre>
<p>I can see that while using the mapper objects, I separate completely the ORM definition from the business logic, while using the declarative syntax, whenever I modify the business logic class, I can edit right there the database class (which ideally should be edited little).</p>
<p>What I'm not completely sure, is which approach is more maintainable for a business application?</p>
<p>I haven't been able to find a comparative between the two mapping methods, to be able to decide which one is a better fit for my project.</p>
<p>I'm leaning towards using the "normal" way (i.e. not the declarative extension) as it allows me to "hide", and keep out of the business view all the ORM logic, but I'd like to hear compelling arguments for both approaches.</p>
| 32 | 2009-09-21T07:19:43Z | 1,453,888 | <p>In our team we settled on declarative syntax.</p>
<p>Rationale:</p>
<ul>
<li><code>metadata</code> is trivial to get to, if needed: <code>User.metadata</code>.</li>
<li>Your <code>User</code> class, by virtue of subclassing <code>Base</code>, has a nice ctor that takes kwargs for all fields. Useful for testing and otherwise. E.g.: <code>user=User(name='doe', password='42')</code>. So no need to write a ctor!</li>
<li>If you add an attribute/column, you only need to do it once. "Don't Repeat Yourself" is a nice principle.</li>
</ul>
<p>Regarding "keeping out ORM from business view": in reality your <code>User</code> class, defined in a "normal" way, gets seriously monkey-patched by SA when <code>mapper</code> function has its way with it. IMHO, declarative way is more honest because it screams: "this class is used in ORM scenarios, and may not be treated just as you would treat your simple non-ORM objects".</p>
| 13 | 2009-09-21T10:40:24Z | [
"python",
"sqlalchemy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.