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
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
10,219,553
<pre><code>&gt;&gt;&gt; "+7".lstrip("-+").isdigit() True &gt;&gt;&gt; "-7".lstrip("-+").isdigit() True &gt;&gt;&gt; "7".lstrip("-+").isdigit() True &gt;&gt;&gt; "13.4".lstrip("-+").isdigit() False </code></pre> <p>So your function would be:</p> <pre><code>def is_int(val): return val[1].isdigit() and val.lstrip("-+").isdigit() </code></pre>
2
2012-04-18T23:25:01Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
12,863,921
<p>This is probably the most straightforward and pythonic way to approach it in my opinion. I didn't see this solution and it's basically the same as the regex one, but without the regex. </p> <pre><code>def is_int(test): import string return not (set(test) - set(string.digits)) </code></pre>
2
2012-10-12T17:07:52Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
29,031,758
<p>I think</p> <pre><code>s.startswith('-') and s[1:].isdigit() </code></pre> <p>would be better to rewrite to:</p> <pre><code>s.replace('-', '').isdigit() </code></pre> <p>because s[1:] also creates a new string</p>
0
2015-03-13T12:03:14Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
29,032,755
<p>I have one possibility that doesn't use int at all, and should not raise an exception unless the string does not represent a number</p> <pre><code>float(number)==float(number)//1 </code></pre> <p>It should work for any kind of string that float accepts, positive, negative, engineering notation...</p>
1
2015-03-13T12:52:31Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
29,330,386
<p>Here is a function that parses without raising errors. It handles obvious cases returns <code>None</code> on failure (handles up to 2000 '-/+' signs by default on CPython!):</p> <pre><code>#!/usr/bin/env python def get_int(number): splits = number.split('.') if len(splits) &gt; 2: # too many splits return None if len(splits) == 2 and splits[1]: # handle decimal part recursively :-) if get_int(splits[1]) != 0: return None int_part = splits[0].lstrip("+") if int_part.startswith('-'): # handle minus sign recursively :-) return get_int(int_part[1:]) * -1 # successful 'and' returns last truth-y value (cast is always valid) return int_part.isdigit() and int(int_part) </code></pre> <p>Some tests:</p> <pre><code>tests = ["0", "0.0", "0.1", "1", "1.1", "1.0", "-1", "-1.1", "-1.0", "-0", "--0", "---3", '.3', '--3.', "+13", "+-1.00", "--+123", "-0.000"] for t in tests: print "get_int(%s) = %s" % (t, get_int(str(t))) </code></pre> <p>Results:</p> <pre><code>get_int(0) = 0 get_int(0.0) = 0 get_int(0.1) = None get_int(1) = 1 get_int(1.1) = None get_int(1.0) = 1 get_int(-1) = -1 get_int(-1.1) = None get_int(-1.0) = -1 get_int(-0) = 0 get_int(--0) = 0 get_int(---3) = -3 get_int(.3) = None get_int(--3.) = 3 get_int(+13) = 13 get_int(+-1.00) = -1 get_int(--+123) = 123 get_int(-0.000) = 0 </code></pre> <p>For your needs you can use:</p> <pre><code>def int_predicate(number): return get_int(number) is not None </code></pre>
1
2015-03-29T14:33:37Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
39,972,859
<p>What about using <a href="https://docs.python.org/3/library/stdtypes.html#float.is_integer" rel="nofollow"><code>float.is_integer</code></a> ? :</p> <pre><code>float("7").is_integer() #True float("+1").is_integer() #True float("+1.0").is_integer() #True float("+1.7").is_integer() #False float("-3").is_integer() #True float("-3.0").is_integer() #True float("-3.7").is_integer() #False </code></pre>
0
2016-10-11T08:05:11Z
[ "python", "string", "integer" ]
Changing height of an object in wxPython
1,265,821
<ol> <li><p>How to change only hight of an object in wxPython, leaving its width automatic? In my case it's a TextCtrl.</p></li> <li><p>How to make the height of the window available for change and lock the width?</p></li> </ol>
2
2009-08-12T12:22:33Z
1,265,988
<p>For the width or height to be automatically determined based on context you use for it the value of -1, for example <code>(-1, 100)</code> for a height of 100 and automatic width.</p> <p>The default size for controls is usually <code>(-1, -1)</code>.</p> <p>If a width or height is specified and the sizer item for the control doesn't have <code>wx.EXPAND</code> flag set (note that even if this flag is set some sizers won't expand in both directions by default) you might call it "locked" as it won't chage that dimension.</p> <p>Make sure to study the workings of sizers in depth as it is one of the most important things in GUI design.</p>
6
2009-08-12T12:49:26Z
[ "python", "wxpython", "size" ]
Python non-trivial C++ Extension
1,266,570
<p>I have fairly large C++ library with several sub-libraries that support it, and I need to turn the whole thing into a python extension. I'm using distutils because it needs to be cross-platform, but if there's a better tool I'm open to suggestions.</p> <p>Is there a way to make distutils first compile the sub-libraries, and link them in when it creates an extension from the main library?</p>
4
2009-08-12T14:36:05Z
1,266,621
<p>I do just this with a massive C++ library in our product. There are several tools out there that can help you automate the task of writing bindings: the most popular is <a href="http://www.swig.org/">SWIG</a>, which has been around a while, is used in lots of projects, and generally works very well. </p> <p>The biggest thing against SWIG (in my opinion) is that the C++ codebase of SWIG itself is really rather crufty to put it mildly. It was written before the STL and has it's own semi-dynamic type system which is just old and creaky now. This won't matter much unless you ever have to get stuck in and make some modifications to the core (I once tried to add doxygen -> docstring conversion) but if you ever do, good luck to you! People also say that SWIG generated code is not that efficient, which may be true but for me I've never found the SWIG calls themselves to be enough of a bottleneck to worry about it.</p> <p>There are other tools you can use if SWIG doesn't float your boat: <a href="http://www.boost.org/doc/libs/1%5F39%5F0/libs/python/doc/index.html">boost.python</a> is also popular and could be a good option if you already use boost libraries in your C++ code. The downside is that it is heavy on compile times since it is pretty much all c++ template based.</p> <p>Both these tools require you to do some work up-front in order to define what will be exposed and quite how it will be done. For SWIG you provide interface files which are like C++ headers but stripped down, and with some extra directives to tell SWIG how to translate complex types etc. Writing these interfaces can be tedious, so you may want to look at something like <a href="http://www.language-binding.net/pygccxml/pygccxml.html">pygccxml</a> to help you auto-generate them for you.</p> <p>The author of that package actually wrote another extension which you might like: <a href="http://www.language-binding.net/pyplusplus/pyplusplus.html">py++</a>. This package does two things: it can autogenerate binding definitions that can then be fed to boost.python to generate python bindings: basically it is the full solution for most people. You might want to start there if you no particulrly special or difficult requirements to meet.</p> <p>Some other questions that might prove useful as a reference:</p> <ul> <li><a href="http://stackoverflow.com/questions/456884/extending-python-to-swig-or-not-to-swig">Extending python - to swig or not to swig</a></li> <li><a href="http://stackoverflow.com/questions/135834/python-swig-vs-ctypes">SWIG vs CTypes</a></li> <li><a href="http://stackoverflow.com/questions/1076300/extending-python-with-c-c">Extending Python with C/C++</a></li> </ul> <p>You may also find <a href="http://lcgapp.cern.ch/project/cls/work-packages/scripting/evaluation-report.html">this comparison</a> of binding generation tools for Python handy. As Alex points out in the comments though, its rather old now but at least gives you some idea of the landscape...</p> <p>In terms of how to drive the build, you may want to look at a more advanced built tool that distutils: if you want to stick with Python I would highly recommend <a href="http://code.google.com/p/waf/">Waf</a> as a framework (others will tell you <a href="http://www.scons.org/">SCons</a> is the way to go, but believe me it's slow as hell: I've been there and back already!)...it takes a little learning, but when you get your head around it is extremely powerful. And since it's pure Python it will integrate perfectly with any other Python code you have as part of your build process (say for example you use Py++ in the end)...</p>
10
2009-08-12T14:42:17Z
[ "c++", "python", "swig", "distutils", "py++" ]
Does PHP have an equivalent to Python's list comprehension syntax?
1,266,911
<p>Python has syntactically sweet list comprehensions:</p> <pre><code>S = [x**2 for x in range(10)] print S; [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] </code></pre> <p>In PHP I would need to do some looping:</p> <pre><code>$output = array(); $Nums = range(0,9); foreach ($Nums as $num) { $out[] = $num*=$num; } print_r($out); </code></pre> <p>to get:</p> <p>Array ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 )</p> <p>Is there anyway to get a similar list comprehension syntax in PHP? Is there anyway to do it with any of the new features in PHP 5.3?</p> <p>Thanks!</p>
46
2009-08-12T15:26:07Z
1,266,942
<p>Maybe something like this?</p> <pre><code>$out=array_map(function($x) {return $x*$x;}, range(0, 9)) </code></pre> <p>This will work in PHP 5.3+, in an older version you'd have to define the callback for <a href="http://php.net/array%5Fmap">array_map</a> separately</p> <pre><code>function sq($x) {return $x*$x;} $out=array_map('sq', range(0, 9)); </code></pre>
56
2009-08-12T15:32:02Z
[ "php", "python", "arrays" ]
Does PHP have an equivalent to Python's list comprehension syntax?
1,266,911
<p>Python has syntactically sweet list comprehensions:</p> <pre><code>S = [x**2 for x in range(10)] print S; [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] </code></pre> <p>In PHP I would need to do some looping:</p> <pre><code>$output = array(); $Nums = range(0,9); foreach ($Nums as $num) { $out[] = $num*=$num; } print_r($out); </code></pre> <p>to get:</p> <p>Array ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 )</p> <p>Is there anyway to get a similar list comprehension syntax in PHP? Is there anyway to do it with any of the new features in PHP 5.3?</p> <p>Thanks!</p>
46
2009-08-12T15:26:07Z
1,266,945
<p>not out of the box, but take a look at: <a href="http://code.google.com/p/php-lc/" rel="nofollow">http://code.google.com/p/php-lc/</a> or <a href="http://code.google.com/p/phparrayplus/" rel="nofollow">http://code.google.com/p/phparrayplus/</a></p>
2
2009-08-12T15:32:44Z
[ "php", "python", "arrays" ]
Does PHP have an equivalent to Python's list comprehension syntax?
1,266,911
<p>Python has syntactically sweet list comprehensions:</p> <pre><code>S = [x**2 for x in range(10)] print S; [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] </code></pre> <p>In PHP I would need to do some looping:</p> <pre><code>$output = array(); $Nums = range(0,9); foreach ($Nums as $num) { $out[] = $num*=$num; } print_r($out); </code></pre> <p>to get:</p> <p>Array ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 )</p> <p>Is there anyway to get a similar list comprehension syntax in PHP? Is there anyway to do it with any of the new features in PHP 5.3?</p> <p>Thanks!</p>
46
2009-08-12T15:26:07Z
11,628,187
<p>PHP 5.5 may support list comprehensions - see the mailing list announcement:</p> <ul> <li><a href="http://markmail.org/thread/uvendztpe2rrwiif" rel="nofollow">[PHP-DEV] List comprehensions and generator expressions for PHP</a> (28 Jun 2012)</li> </ul> <p>And further discussion:</p> <ul> <li><a href="http://blog.ircmaxell.com/2012/07/what-generators-can-do-for-you.html" rel="nofollow">What Generators Can Do For You</a> (by ircmaxell; 23 Jul 2012) - has a Fibonacci example.</li> <li><a href="http://nikic.github.com/2012/07/10/What-PHP-5-5-might-look-like.html#generators" rel="nofollow">What PHP 5.5 might look like</a> (by NikiC; 10 Jul 2012)</li> <li><a href="https://wiki.php.net/rfc/generators" rel="nofollow">Request for Comments: Generators</a> (Wiki started 05 Jun 2012)</li> </ul>
4
2012-07-24T09:44:37Z
[ "php", "python", "arrays" ]
Does PHP have an equivalent to Python's list comprehension syntax?
1,266,911
<p>Python has syntactically sweet list comprehensions:</p> <pre><code>S = [x**2 for x in range(10)] print S; [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] </code></pre> <p>In PHP I would need to do some looping:</p> <pre><code>$output = array(); $Nums = range(0,9); foreach ($Nums as $num) { $out[] = $num*=$num; } print_r($out); </code></pre> <p>to get:</p> <p>Array ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 )</p> <p>Is there anyway to get a similar list comprehension syntax in PHP? Is there anyway to do it with any of the new features in PHP 5.3?</p> <p>Thanks!</p>
46
2009-08-12T15:26:07Z
30,633,691
<p>In .NET, the equivalent of Python's "syntactically sweet list comprehensions" is LINQ. And in PHP, there're several ports of it, including <a href="https://github.com/Athari/YaLinqo" rel="nofollow">YaLinqo</a> library*. Syntactically, it's closer to SQL rather than a sequence of traditional constructs with <code>for</code> and <code>if</code>, but functionally, it's similar:</p> <pre><code>$a = Enumerable::range(0, 10)-&gt;select('$v * $v'); </code></pre> <p>This produces an iterator which can either be output to console:</p> <pre><code>var_dump($a-&gt;toArray()); // by transforming the iterator to an array echo $a-&gt;toString(', '); // or by imploding into a string </code></pre> <p>or iterated over using <code>foreach</code>:</p> <pre><code>foreach ($a as $i) echo $i, PHP_EOL; </code></pre> <p>Here, <code>'$v * $v'</code> is a shortcut for <code>function ($v) { return $v * $v; }</code> which this library supports. Unfortunately, PHP doesn't support short syntax for closures, but such "string lambdas" can be used to make the code shorter.</p> <p>There're many more methods, starting with <code>where</code> (<code>if</code> equivalent) and ending with <code>groupJoin</code> which performs joining transformation with grouping.</p> <p><sub>* developed by me</sub></p>
0
2015-06-04T01:54:36Z
[ "php", "python", "arrays" ]
Python: remove lots of items from a list
1,267,260
<p>I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.</p> <p>I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in the list.</p> <p>So, I might have</p> <pre><code>myList = [(20000, 11), (16000, 4), (14000, 9)...] myDict = {11:20000, 9:14000, ...} </code></pre> <p>I want to remove each (v, k) tuple from the list.</p> <p>Currently I am doing:</p> <pre><code>for k, v in myDict.iteritems(): myList.remove((v, k)) </code></pre> <p>Removing 838 tuples from the list containing 20,000 tuples takes anywhere from 3 - 4 seconds. I will most likely be removing more like 10,000 tuples from a list of 1,000,000 so I need this to be faster.</p> <p>Is there a better way to do this?</p> <p>I can provide code used to test, plus pickled data from the actual application if needed.</p>
10
2009-08-12T16:28:46Z
1,267,294
<p>The problem looks to me to be the fact you are using a <code>list</code> as the container you are trying to remove from, and it is a totally unordered type. So to find each item in the list is a linear operation (<a href="http://en.wikipedia.org/wiki/Big%5FO%5Fnotation" rel="nofollow">O(n)</a>), it has to iterate over the whole list until it finds a match.</p> <p>If you could swap the <code>list</code> for some other container (<code>set</code>?) which uses a <code>hash()</code> of each item to order them, then each match could be performed much quicker.</p> <p>The following code shows how you could do this using a combination of ideas offered by myself and Nick on this thread:</p> <pre><code>list_set = set(original_list) dict_set = set(zip(original_dict.values(), original_dict.keys())) difference_set = list(list_set - dict_set) final_list = [] for item in original_list: if item in difference_set: final_list.append(item) </code></pre>
2
2009-08-12T16:35:38Z
[ "python" ]
Python: remove lots of items from a list
1,267,260
<p>I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.</p> <p>I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in the list.</p> <p>So, I might have</p> <pre><code>myList = [(20000, 11), (16000, 4), (14000, 9)...] myDict = {11:20000, 9:14000, ...} </code></pre> <p>I want to remove each (v, k) tuple from the list.</p> <p>Currently I am doing:</p> <pre><code>for k, v in myDict.iteritems(): myList.remove((v, k)) </code></pre> <p>Removing 838 tuples from the list containing 20,000 tuples takes anywhere from 3 - 4 seconds. I will most likely be removing more like 10,000 tuples from a list of 1,000,000 so I need this to be faster.</p> <p>Is there a better way to do this?</p> <p>I can provide code used to test, plus pickled data from the actual application if needed.</p>
10
2009-08-12T16:28:46Z
1,267,317
<p>Every time you call <code>myList.remove</code>, Python has to scan over the entire list to search for that item and remove it. In the worst case scenario, every item you look for would be at the end of the list each time.</p> <p>Have you tried doing the "inverse" operation of:</p> <pre><code>newMyList = [(v,k) for (v,k) in myList if not k in myDict] </code></pre> <p>But I'm really not sure how well that would scale, either, since you would be making a copy of the original list -- could potentially be a lot of memory usage there.</p> <p>Probably the best alternative here is to wait for Alex Martelli to post some mind-blowingly intuitive, simple, and efficient approach.</p>
5
2009-08-12T16:40:09Z
[ "python" ]
Python: remove lots of items from a list
1,267,260
<p>I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.</p> <p>I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in the list.</p> <p>So, I might have</p> <pre><code>myList = [(20000, 11), (16000, 4), (14000, 9)...] myDict = {11:20000, 9:14000, ...} </code></pre> <p>I want to remove each (v, k) tuple from the list.</p> <p>Currently I am doing:</p> <pre><code>for k, v in myDict.iteritems(): myList.remove((v, k)) </code></pre> <p>Removing 838 tuples from the list containing 20,000 tuples takes anywhere from 3 - 4 seconds. I will most likely be removing more like 10,000 tuples from a list of 1,000,000 so I need this to be faster.</p> <p>Is there a better way to do this?</p> <p>I can provide code used to test, plus pickled data from the actual application if needed.</p>
10
2009-08-12T16:28:46Z
1,267,318
<p>You'll have to measure, but I can imagine this to be more performant:</p> <pre><code>myList = filter(lambda x: myDict.get(x[1], None) != x[0], myList) </code></pre> <p>because the lookup happens in the dict, which is more suited for this kind of thing. Note, though, that this will create a new list before removing the old one; so there's a memory tradeoff. If that's an issue, rethinking your container type as jkp suggest might be in order.</p> <p><strong>Edit</strong>: Be careful, though, if <code>None</code> is actually in your list -- you'd have to use a different "placeholder."</p>
19
2009-08-12T16:40:11Z
[ "python" ]
Python: remove lots of items from a list
1,267,260
<p>I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.</p> <p>I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in the list.</p> <p>So, I might have</p> <pre><code>myList = [(20000, 11), (16000, 4), (14000, 9)...] myDict = {11:20000, 9:14000, ...} </code></pre> <p>I want to remove each (v, k) tuple from the list.</p> <p>Currently I am doing:</p> <pre><code>for k, v in myDict.iteritems(): myList.remove((v, k)) </code></pre> <p>Removing 838 tuples from the list containing 20,000 tuples takes anywhere from 3 - 4 seconds. I will most likely be removing more like 10,000 tuples from a list of 1,000,000 so I need this to be faster.</p> <p>Is there a better way to do this?</p> <p>I can provide code used to test, plus pickled data from the actual application if needed.</p>
10
2009-08-12T16:28:46Z
1,267,319
<pre><code>[(i, j) for i, j in myList if myDict.get(j) != i] </code></pre>
2
2009-08-12T16:40:14Z
[ "python" ]
Python: remove lots of items from a list
1,267,260
<p>I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.</p> <p>I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in the list.</p> <p>So, I might have</p> <pre><code>myList = [(20000, 11), (16000, 4), (14000, 9)...] myDict = {11:20000, 9:14000, ...} </code></pre> <p>I want to remove each (v, k) tuple from the list.</p> <p>Currently I am doing:</p> <pre><code>for k, v in myDict.iteritems(): myList.remove((v, k)) </code></pre> <p>Removing 838 tuples from the list containing 20,000 tuples takes anywhere from 3 - 4 seconds. I will most likely be removing more like 10,000 tuples from a list of 1,000,000 so I need this to be faster.</p> <p>Is there a better way to do this?</p> <p>I can provide code used to test, plus pickled data from the actual application if needed.</p>
10
2009-08-12T16:28:46Z
1,267,333
<p>Try something like this:</p> <pre><code>myListSet = set(myList) myDictSet = set(zip(myDict.values(), myDict.keys())) myList = list(myListSet - myDictSet) </code></pre> <p>This will convert <code>myList</code> to a set, will swap the keys/values in <code>myDict</code> and put them into a set, and will then find the difference, turn it back into a list, and assign it back to myList. :)</p>
2
2009-08-12T16:41:56Z
[ "python" ]
Python: remove lots of items from a list
1,267,260
<p>I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.</p> <p>I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in the list.</p> <p>So, I might have</p> <pre><code>myList = [(20000, 11), (16000, 4), (14000, 9)...] myDict = {11:20000, 9:14000, ...} </code></pre> <p>I want to remove each (v, k) tuple from the list.</p> <p>Currently I am doing:</p> <pre><code>for k, v in myDict.iteritems(): myList.remove((v, k)) </code></pre> <p>Removing 838 tuples from the list containing 20,000 tuples takes anywhere from 3 - 4 seconds. I will most likely be removing more like 10,000 tuples from a list of 1,000,000 so I need this to be faster.</p> <p>Is there a better way to do this?</p> <p>I can provide code used to test, plus pickled data from the actual application if needed.</p>
10
2009-08-12T16:28:46Z
1,268,545
<pre><code>[i for i in myList if i not in list(zip(myDict.values(), myDict.keys()))] </code></pre>
0
2009-08-12T20:30:34Z
[ "python" ]
Python: remove lots of items from a list
1,267,260
<p>I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.</p> <p>I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in the list.</p> <p>So, I might have</p> <pre><code>myList = [(20000, 11), (16000, 4), (14000, 9)...] myDict = {11:20000, 9:14000, ...} </code></pre> <p>I want to remove each (v, k) tuple from the list.</p> <p>Currently I am doing:</p> <pre><code>for k, v in myDict.iteritems(): myList.remove((v, k)) </code></pre> <p>Removing 838 tuples from the list containing 20,000 tuples takes anywhere from 3 - 4 seconds. I will most likely be removing more like 10,000 tuples from a list of 1,000,000 so I need this to be faster.</p> <p>Is there a better way to do this?</p> <p>I can provide code used to test, plus pickled data from the actual application if needed.</p>
10
2009-08-12T16:28:46Z
1,269,380
<p>A list containing a million 2-tuples is not large on most machines running Python. However if you absolutely must do the removal in situ, here is a clean way of doing it properly:</p> <pre><code>def filter_by_dict(my_list, my_dict): sentinel = object() for i in xrange(len(my_list) - 1, -1, -1): key = my_list[i][1] if my_dict.get(key, sentinel) is not sentinel: del my_list[i] </code></pre> <p><strong>Update</strong> Actually each del costs O(n) shuffling the list pointers down using C's memmove(), so if there are d dels, it's <code>O(n*d)</code> not <code>O(n**2)</code>. Note that (1) the OP suggests that d approx == <code>0.01 * n</code> and (2) the <code>O(n*d)</code> effort is copying one pointer to somewhere else in memory ... so this method could in fact be somewhat faster than a quick glance would indicate. Benchmarks, anyone?</p> <p>What are you going to do with the list <strong>after</strong> you have removed the items that are in the dict? Is it possible to piggy-back the dict-filtering onto the next step?</p>
0
2009-08-13T00:06:52Z
[ "python" ]
Python: remove lots of items from a list
1,267,260
<p>I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.</p> <p>I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in the list.</p> <p>So, I might have</p> <pre><code>myList = [(20000, 11), (16000, 4), (14000, 9)...] myDict = {11:20000, 9:14000, ...} </code></pre> <p>I want to remove each (v, k) tuple from the list.</p> <p>Currently I am doing:</p> <pre><code>for k, v in myDict.iteritems(): myList.remove((v, k)) </code></pre> <p>Removing 838 tuples from the list containing 20,000 tuples takes anywhere from 3 - 4 seconds. I will most likely be removing more like 10,000 tuples from a list of 1,000,000 so I need this to be faster.</p> <p>Is there a better way to do this?</p> <p>I can provide code used to test, plus pickled data from the actual application if needed.</p>
10
2009-08-12T16:28:46Z
1,274,668
<p>To remove about 10,000 tuples from a list of about 1,000,000, if the values are hashable, the fastest approach should be:</p> <pre><code>totoss = set((v,k) for (k,v) in myDict.iteritems()) myList[:] = [x for x in myList if x not in totoss] </code></pre> <p>The preparation of the set is a small one-time cost, wich saves doing tuple unpacking and repacking, or tuple indexing, a lot of times. Assignign to <code>myList[:]</code> instead of assigning to <code>myList</code> is also semantically important (in case there are any other references to <code>myList</code> around, it's not enough to rebind just the name -- you really want to rebind the <em>contents</em>!-).</p> <p>I don't have your test-data around to do the time measurement myself, alas!, but, let me know how it plays our on your test data!</p> <p>If the values are not hashable (e.g. they're sub-lists, for example), fastest is probably:</p> <pre><code>sentinel = object() myList[:] = [x for x in myList if myDict.get(x[0], sentinel) != x[1]] </code></pre> <p>or maybe (shouldn't make a big difference either way, but I suspect the previous one is better -- indexing is cheaper than unpacking and repacking):</p> <pre><code>sentinel = object() myList[:] = [(a,b) for (a,b) in myList if myDict.get(a, sentinel) != b] </code></pre> <p>In these two variants the sentinel idiom is used to ward against values of <code>None</code> (which is not a problem for the preferred set-based approach -- if values are hashable!) as it's going to be way cheaper than <code>if a not in myDict or myDict[a] != b</code> (which requires two indexings into myDict).</p>
9
2009-08-13T21:23:00Z
[ "python" ]
What's the best way to do literate programming in Python on Windows?
1,267,280
<p>I've been playing with various ways of doing literate programming in Python. I like <a href="http://www.cs.tufts.edu/~nr/noweb/"><code>noweb</code></a>, but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will be in the final program --- which I don't necessarily know when I write it. I don't want to use Leo, because I'm very attached to Emacs.</p> <p>Is there a good literate programming tool that:</p> <ol> <li>Runs on Windows</li> <li>Allows me to set the indentation of the chunks when they're used, not when they're written</li> <li>Still lets me work in Emacs</li> </ol> <p>Thanks!</p> <hr> <p>Correction: <code>noweb</code> <em>does</em> allow me to indent later --- I misread the paper I found on it. </p> <blockquote> <blockquote> <blockquote> <p>By default, <code>notangle</code> preserves whitespace and maintains indentation when expanding chunks. It can therefore be used with languages like Miranda and Haskell, in which indentation is significant</p> </blockquote> </blockquote> </blockquote> <p>That leaves me with only the "Runs on Windows" problem.</p>
31
2009-08-12T16:32:54Z
1,268,602
<p>I did this:</p> <p><a href="http://sourceforge.net/projects/pywebtool/">http://sourceforge.net/projects/pywebtool/</a></p> <p>You can get any number of web/weave products that will help you construct a document and code in one swoop.</p> <p>You can -- pretty easily -- write your own. It's not rocket science to yank the Python code blocks out of RST source and assemble it. Indeed, I suggest you write your own Docutils directives to assemble the Python code from an RST source document.</p> <p>You run the RST through docutils rst2html (or Sphinx) to produce your final HTML report.</p> <p>You run your own utility on the same RST source to extract the Python code blocks and produce the final modules.</p>
6
2009-08-12T20:39:55Z
[ "python", "windows", "literate-programming", "noweb" ]
What's the best way to do literate programming in Python on Windows?
1,267,280
<p>I've been playing with various ways of doing literate programming in Python. I like <a href="http://www.cs.tufts.edu/~nr/noweb/"><code>noweb</code></a>, but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will be in the final program --- which I don't necessarily know when I write it. I don't want to use Leo, because I'm very attached to Emacs.</p> <p>Is there a good literate programming tool that:</p> <ol> <li>Runs on Windows</li> <li>Allows me to set the indentation of the chunks when they're used, not when they're written</li> <li>Still lets me work in Emacs</li> </ol> <p>Thanks!</p> <hr> <p>Correction: <code>noweb</code> <em>does</em> allow me to indent later --- I misread the paper I found on it. </p> <blockquote> <blockquote> <blockquote> <p>By default, <code>notangle</code> preserves whitespace and maintains indentation when expanding chunks. It can therefore be used with languages like Miranda and Haskell, in which indentation is significant</p> </blockquote> </blockquote> </blockquote> <p>That leaves me with only the "Runs on Windows" problem.</p>
31
2009-08-12T16:32:54Z
2,709,739
<p>You might find <a href="http://www.cs.tufts.edu/~nr/noweb" rel="nofollow">noweb 3</a> easier to build on Windows. It was designed to be more portable than standard noweb.</p>
2
2010-04-25T20:02:16Z
[ "python", "windows", "literate-programming", "noweb" ]
What's the best way to do literate programming in Python on Windows?
1,267,280
<p>I've been playing with various ways of doing literate programming in Python. I like <a href="http://www.cs.tufts.edu/~nr/noweb/"><code>noweb</code></a>, but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will be in the final program --- which I don't necessarily know when I write it. I don't want to use Leo, because I'm very attached to Emacs.</p> <p>Is there a good literate programming tool that:</p> <ol> <li>Runs on Windows</li> <li>Allows me to set the indentation of the chunks when they're used, not when they're written</li> <li>Still lets me work in Emacs</li> </ol> <p>Thanks!</p> <hr> <p>Correction: <code>noweb</code> <em>does</em> allow me to indent later --- I misread the paper I found on it. </p> <blockquote> <blockquote> <blockquote> <p>By default, <code>notangle</code> preserves whitespace and maintains indentation when expanding chunks. It can therefore be used with languages like Miranda and Haskell, in which indentation is significant</p> </blockquote> </blockquote> </blockquote> <p>That leaves me with only the "Runs on Windows" problem.</p>
31
2009-08-12T16:32:54Z
2,887,123
<p>I have written Pweave <a href="http://mpastell.com/pweave">http://mpastell.com/pweave</a>, that is aimed for dynamic report generation and uses noweb syntax. It is a pure python script so it also runs on Windows. It doesn't fix your indent problem, but maybe you can modify it for that, the code is really quite simple. </p>
9
2010-05-22T06:01:40Z
[ "python", "windows", "literate-programming", "noweb" ]
What's the best way to do literate programming in Python on Windows?
1,267,280
<p>I've been playing with various ways of doing literate programming in Python. I like <a href="http://www.cs.tufts.edu/~nr/noweb/"><code>noweb</code></a>, but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will be in the final program --- which I don't necessarily know when I write it. I don't want to use Leo, because I'm very attached to Emacs.</p> <p>Is there a good literate programming tool that:</p> <ol> <li>Runs on Windows</li> <li>Allows me to set the indentation of the chunks when they're used, not when they're written</li> <li>Still lets me work in Emacs</li> </ol> <p>Thanks!</p> <hr> <p>Correction: <code>noweb</code> <em>does</em> allow me to indent later --- I misread the paper I found on it. </p> <blockquote> <blockquote> <blockquote> <p>By default, <code>notangle</code> preserves whitespace and maintains indentation when expanding chunks. It can therefore be used with languages like Miranda and Haskell, in which indentation is significant</p> </blockquote> </blockquote> </blockquote> <p>That leaves me with only the "Runs on Windows" problem.</p>
31
2009-08-12T16:32:54Z
11,155,300
<p>You could use org-mode and babel-tangle.</p> <p>That works quite well, since you can give :noweb-ref to source blocks.</p> <p>Here’s a minimal example: <a href="http://orgmode.org/worg/org-contrib/babel/intro.html#literate-programming">Activate org-babel-tangle</a>, then put this into the file <code>noweb-test.org</code>:</p> <pre><code>#+begin_src python :exports none :noweb-ref c abc = "abc" #+end_src #+begin_src python :noweb yes :tangle noweb-test.py def x(): &lt;&lt;c&gt;&gt; return abc print(x()) #+end_src </code></pre> <p>You can also use properties of headlines for giving the noweb-ref. It can then even automatically concatenate several source blocks into one noweb reference.</p> <p>Add <code>:results output</code> to the <code>#+begin_src</code> line of the second block to see the print results under that block when you hit <code>C-c C-c</code> in the block.</p>
7
2012-06-22T11:27:27Z
[ "python", "windows", "literate-programming", "noweb" ]
What's the best way to do literate programming in Python on Windows?
1,267,280
<p>I've been playing with various ways of doing literate programming in Python. I like <a href="http://www.cs.tufts.edu/~nr/noweb/"><code>noweb</code></a>, but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will be in the final program --- which I don't necessarily know when I write it. I don't want to use Leo, because I'm very attached to Emacs.</p> <p>Is there a good literate programming tool that:</p> <ol> <li>Runs on Windows</li> <li>Allows me to set the indentation of the chunks when they're used, not when they're written</li> <li>Still lets me work in Emacs</li> </ol> <p>Thanks!</p> <hr> <p>Correction: <code>noweb</code> <em>does</em> allow me to indent later --- I misread the paper I found on it. </p> <blockquote> <blockquote> <blockquote> <p>By default, <code>notangle</code> preserves whitespace and maintains indentation when expanding chunks. It can therefore be used with languages like Miranda and Haskell, in which indentation is significant</p> </blockquote> </blockquote> </blockquote> <p>That leaves me with only the "Runs on Windows" problem.</p>
31
2009-08-12T16:32:54Z
14,341,393
<p>See also my last LP tool: <a href="http://code.google.com/p/nano-lp" rel="nofollow">http://code.google.com/p/nano-lp</a>. It does not requires special input format, supports Markdown/MultiMarkdown, reStructuredText, OpenOffice/LibreOffice, Creole, TeX/LaTeX and has super light and clean syntax - no more cryptic literate programs.</p>
0
2013-01-15T15:46:49Z
[ "python", "windows", "literate-programming", "noweb" ]
What's the best way to do literate programming in Python on Windows?
1,267,280
<p>I've been playing with various ways of doing literate programming in Python. I like <a href="http://www.cs.tufts.edu/~nr/noweb/"><code>noweb</code></a>, but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will be in the final program --- which I don't necessarily know when I write it. I don't want to use Leo, because I'm very attached to Emacs.</p> <p>Is there a good literate programming tool that:</p> <ol> <li>Runs on Windows</li> <li>Allows me to set the indentation of the chunks when they're used, not when they're written</li> <li>Still lets me work in Emacs</li> </ol> <p>Thanks!</p> <hr> <p>Correction: <code>noweb</code> <em>does</em> allow me to indent later --- I misread the paper I found on it. </p> <blockquote> <blockquote> <blockquote> <p>By default, <code>notangle</code> preserves whitespace and maintains indentation when expanding chunks. It can therefore be used with languages like Miranda and Haskell, in which indentation is significant</p> </blockquote> </blockquote> </blockquote> <p>That leaves me with only the "Runs on Windows" problem.</p>
31
2009-08-12T16:32:54Z
22,131,669
<p>The de-facto standard in the community is IPython notebooks.</p> <p>Excellent example in which Peter Norvig demonstrates algorithms to solve the Travelling Salesman Problem: <a href="http://nbviewer.ipython.org/url/norvig.com/ipython/TSPv3.ipynb">http://nbviewer.ipython.org/url/norvig.com/ipython/TSPv3.ipynb</a></p> <p>More examples listed at <a href="https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks">https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks</a></p>
8
2014-03-02T18:38:13Z
[ "python", "windows", "literate-programming", "noweb" ]
How do I calculate the numeric value of a string with unicode components in python?
1,267,314
<p>Along the lines of my previous question, <a href="http://stackoverflow.com/questions/1263796/how-do-i-convert-unicode-characters-to-floats-in-python">http://stackoverflow.com/questions/1263796/how-do-i-convert-unicode-characters-to-floats-in-python</a> , I would like to find a more elegant solution to calculating the value of a string that contains unicode numeric values.</p> <p>For example, take the strings "1⅕" and "1 ⅕". I would like these to resolve to 1.2</p> <p>I know that I can iterate through the string by character, check for unicodedata.category(x) == "No" on each character, and convert the unicode characters by unicodedata.numeric(x). I would then have to split the string and sum the values. However, this seems rather hacky and unstable. Is there a more elegant solution for this in Python?</p>
4
2009-08-12T16:38:49Z
1,267,346
<pre><code>&gt;&gt;&gt; import unicodedata &gt;&gt;&gt; b = '10 ⅕' &gt;&gt;&gt; int(b[:-1]) + unicodedata.numeric(b[-1]) 10.2 define convert_dubious_strings(s): try: return int(s) except UnicodeEncodeError: return int(b[:-1]) + unicodedata.numeric(b[-1]) </code></pre> <p>and if it might have no integer part than another try-except sub-block needs to be added.</p>
1
2009-08-12T16:44:53Z
[ "python", "string", "unicode", "floating-point" ]
How do I calculate the numeric value of a string with unicode components in python?
1,267,314
<p>Along the lines of my previous question, <a href="http://stackoverflow.com/questions/1263796/how-do-i-convert-unicode-characters-to-floats-in-python">http://stackoverflow.com/questions/1263796/how-do-i-convert-unicode-characters-to-floats-in-python</a> , I would like to find a more elegant solution to calculating the value of a string that contains unicode numeric values.</p> <p>For example, take the strings "1⅕" and "1 ⅕". I would like these to resolve to 1.2</p> <p>I know that I can iterate through the string by character, check for unicodedata.category(x) == "No" on each character, and convert the unicode characters by unicodedata.numeric(x). I would then have to split the string and sum the values. However, this seems rather hacky and unstable. Is there a more elegant solution for this in Python?</p>
4
2009-08-12T16:38:49Z
1,267,425
<p>I think you'll need a regular expression, explicitly listing the characters that you want to support. Not all numerical characters are suitable for the kind of composition that you envision - for example, what should be the numerical value of</p> <pre><code>u"4\N{CIRCLED NUMBER FORTY TWO}2\N{SUPERSCRIPT SIX}" </code></pre> <p>???</p> <p>Do </p> <pre><code>for i in range(65536): if unicodedata.category(unichr(i)) == 'No': print hex(i), unicodedata.name(unichdr(i)) </code></pre> <p>and go through the list defining which ones you <em>really</em> want to support.</p>
-1
2009-08-12T16:59:56Z
[ "python", "string", "unicode", "floating-point" ]
How do I calculate the numeric value of a string with unicode components in python?
1,267,314
<p>Along the lines of my previous question, <a href="http://stackoverflow.com/questions/1263796/how-do-i-convert-unicode-characters-to-floats-in-python">http://stackoverflow.com/questions/1263796/how-do-i-convert-unicode-characters-to-floats-in-python</a> , I would like to find a more elegant solution to calculating the value of a string that contains unicode numeric values.</p> <p>For example, take the strings "1⅕" and "1 ⅕". I would like these to resolve to 1.2</p> <p>I know that I can iterate through the string by character, check for unicodedata.category(x) == "No" on each character, and convert the unicode characters by unicodedata.numeric(x). I would then have to split the string and sum the values. However, this seems rather hacky and unstable. Is there a more elegant solution for this in Python?</p>
4
2009-08-12T16:38:49Z
1,267,473
<p>This might be sufficient for you, depending on the strange edge cases you want to deal with:</p> <pre><code>val = 0 for c in my_unicode_string: if unicodedata.category(unichr(c)) == 'No': cval = unicodedata.numeric(c) elif c.isdigit(): cval = int(c) else: continue if cval == int(cval): val *= 10 val += cval print val </code></pre> <p>Whole digits are assumed to be another digit in the number, fractional characters are assumed to be fractions to add to the number. Doesn't do the right thing with spaces between digits, repeated fractions, etc.</p>
0
2009-08-12T17:11:06Z
[ "python", "string", "unicode", "floating-point" ]
How do I calculate the numeric value of a string with unicode components in python?
1,267,314
<p>Along the lines of my previous question, <a href="http://stackoverflow.com/questions/1263796/how-do-i-convert-unicode-characters-to-floats-in-python">http://stackoverflow.com/questions/1263796/how-do-i-convert-unicode-characters-to-floats-in-python</a> , I would like to find a more elegant solution to calculating the value of a string that contains unicode numeric values.</p> <p>For example, take the strings "1⅕" and "1 ⅕". I would like these to resolve to 1.2</p> <p>I know that I can iterate through the string by character, check for unicodedata.category(x) == "No" on each character, and convert the unicode characters by unicodedata.numeric(x). I would then have to split the string and sum the values. However, this seems rather hacky and unstable. Is there a more elegant solution for this in Python?</p>
4
2009-08-12T16:38:49Z
1,267,487
<p>I think this is what you want...</p> <pre><code>import unicodedata def eval_unicode(s): #sum all the unicode fractions u = sum(map(unicodedata.numeric, filter(lambda x: unicodedata.category(x)=="No",s))) #eval the regular digits (with optional dot) as a float, or default to 0 n = float("".join(filter(lambda x:x.isdigit() or x==".", s)) or 0) return n+u </code></pre> <p>or the "comprehensive" solution, for those who prefer that style:</p> <pre><code>import unicodedata def eval_unicode(s): #sum all the unicode fractions u = sum(unicodedata.numeric(i) for i in s if unicodedata.category(i)=="No") #eval the regular digits (with optional dot) as a float, or default to 0 n = float("".join(i for i in s if i.isdigit() or i==".") or 0) return n+u </code></pre> <p>But beware, there are many unicode values that seem to not have a numeric value assigned in python (for example ⅜⅝ don't work... or maybe is just a matter with my keyboard xD).</p> <p>Another note on the implementation: it's "too robust", it will work even will malformed numbers like "123½3 ½" and will eval it to 1234.0... but it won't work if there are more than one dots.</p>
2
2009-08-12T17:14:17Z
[ "python", "string", "unicode", "floating-point" ]
How do you resolve traditional coding standard vs python idomatic code?
1,267,444
<p>In my experience code clarity and readability are the primary concerns in traditional coding standards. PEP-8 would have been rejected by some of my previous customers.</p> <p>The idiomatic concepts such as, using dictionaries and lambda functions to emulate the behavior of a switch statement looks like something that would have clearly been forbidden by "Don't use tricky code" mandate in prior coding standards.</p> <p>Typical coding standards have "whenever it improves the readability of the code break up statements into multiple lines." Again lambda functions are right out.</p> <p>Beyond that, code reviews are assumed and I've had customers that not only reviewed the code, but REQUIRED software people to be part of the review. This was done to insure the code was readable without requiring an uber-geek specializing in a particular language to look at the code.</p> <p><strong>How are these types of concerns addressed with Python?</strong> End of original question.</p> <p>Edit: I reread PEP-8. I must retract the "PEP-8 would be rejected" statement. (This may just save my life from the Python lynch mob gathering out side.) The "This is not complete" and "Break the rules when it improves clarity" statements in that PEP do not require such harshness. Lamda statements are not addressed in that PEP. (That falls into the not complete category)</p> <p>@Javier: Do you have some recomended reading about the advantages of lamda?</p> <p>@RichieHindle: You may and it's a valueable suggestion, thank you.</p>
-3
2009-08-12T17:04:27Z
1,267,455
<p>You should write code that's idiomatic in the language you're using, and anyone reviewing the code should be familiar enough with the language to recognise and understand idiomatic code.</p> <p>Using a dictionary for dispatching is idiomatic Python IMHO. Go with what's Pythonic rather than trying to fit coding standards that were designed for other languages onto Python.</p> <p>(Of course all this applies to any language.)</p>
11
2009-08-12T17:08:00Z
[ "python", "coding-style", "code-review" ]
How do you resolve traditional coding standard vs python idomatic code?
1,267,444
<p>In my experience code clarity and readability are the primary concerns in traditional coding standards. PEP-8 would have been rejected by some of my previous customers.</p> <p>The idiomatic concepts such as, using dictionaries and lambda functions to emulate the behavior of a switch statement looks like something that would have clearly been forbidden by "Don't use tricky code" mandate in prior coding standards.</p> <p>Typical coding standards have "whenever it improves the readability of the code break up statements into multiple lines." Again lambda functions are right out.</p> <p>Beyond that, code reviews are assumed and I've had customers that not only reviewed the code, but REQUIRED software people to be part of the review. This was done to insure the code was readable without requiring an uber-geek specializing in a particular language to look at the code.</p> <p><strong>How are these types of concerns addressed with Python?</strong> End of original question.</p> <p>Edit: I reread PEP-8. I must retract the "PEP-8 would be rejected" statement. (This may just save my life from the Python lynch mob gathering out side.) The "This is not complete" and "Break the rules when it improves clarity" statements in that PEP do not require such harshness. Lamda statements are not addressed in that PEP. (That falls into the not complete category)</p> <p>@Javier: Do you have some recomended reading about the advantages of lamda?</p> <p>@RichieHindle: You may and it's a valueable suggestion, thank you.</p>
-3
2009-08-12T17:04:27Z
1,267,526
<p><strong>Software is hard.</strong> No-ubergeek rule is good but it doesn't mean that any random person with a title <em>programmer</em> could review or should be able to understand any code he's looking at with ease.</p> <p>Lambdas that span multiple lines are shouldn't exist in your code regardless who you're writing for. They're no different from proper functions in this sense, so why would you need them? There is nothing tricky about language idioms and they tend to be quite clear as well.</p>
3
2009-08-12T17:21:14Z
[ "python", "coding-style", "code-review" ]
How do you resolve traditional coding standard vs python idomatic code?
1,267,444
<p>In my experience code clarity and readability are the primary concerns in traditional coding standards. PEP-8 would have been rejected by some of my previous customers.</p> <p>The idiomatic concepts such as, using dictionaries and lambda functions to emulate the behavior of a switch statement looks like something that would have clearly been forbidden by "Don't use tricky code" mandate in prior coding standards.</p> <p>Typical coding standards have "whenever it improves the readability of the code break up statements into multiple lines." Again lambda functions are right out.</p> <p>Beyond that, code reviews are assumed and I've had customers that not only reviewed the code, but REQUIRED software people to be part of the review. This was done to insure the code was readable without requiring an uber-geek specializing in a particular language to look at the code.</p> <p><strong>How are these types of concerns addressed with Python?</strong> End of original question.</p> <p>Edit: I reread PEP-8. I must retract the "PEP-8 would be rejected" statement. (This may just save my life from the Python lynch mob gathering out side.) The "This is not complete" and "Break the rules when it improves clarity" statements in that PEP do not require such harshness. Lamda statements are not addressed in that PEP. (That falls into the not complete category)</p> <p>@Javier: Do you have some recomended reading about the advantages of lamda?</p> <p>@RichieHindle: You may and it's a valueable suggestion, thank you.</p>
-3
2009-08-12T17:04:27Z
1,268,407
<p>If you don't like using a dict of functions to implement switch type functionality, then just don't use it and use an if-else structure instead.</p> <pre><code>if var == "a": pass elif var == "b": pass elif var == "c": pass else: #Default case pass </code></pre> <p>There. That was easy, wasn't it.</p>
1
2009-08-12T20:03:28Z
[ "python", "coding-style", "code-review" ]
How do you resolve traditional coding standard vs python idomatic code?
1,267,444
<p>In my experience code clarity and readability are the primary concerns in traditional coding standards. PEP-8 would have been rejected by some of my previous customers.</p> <p>The idiomatic concepts such as, using dictionaries and lambda functions to emulate the behavior of a switch statement looks like something that would have clearly been forbidden by "Don't use tricky code" mandate in prior coding standards.</p> <p>Typical coding standards have "whenever it improves the readability of the code break up statements into multiple lines." Again lambda functions are right out.</p> <p>Beyond that, code reviews are assumed and I've had customers that not only reviewed the code, but REQUIRED software people to be part of the review. This was done to insure the code was readable without requiring an uber-geek specializing in a particular language to look at the code.</p> <p><strong>How are these types of concerns addressed with Python?</strong> End of original question.</p> <p>Edit: I reread PEP-8. I must retract the "PEP-8 would be rejected" statement. (This may just save my life from the Python lynch mob gathering out side.) The "This is not complete" and "Break the rules when it improves clarity" statements in that PEP do not require such harshness. Lamda statements are not addressed in that PEP. (That falls into the not complete category)</p> <p>@Javier: Do you have some recomended reading about the advantages of lamda?</p> <p>@RichieHindle: You may and it's a valueable suggestion, thank you.</p>
-3
2009-08-12T17:04:27Z
1,268,484
<blockquote> <p>But it isn't a good replacement for a light weight switch. In some cases it's a hammer instead of a screwdriver.</p> </blockquote> <p>Python cannot make jump table optimizations mostly due to its nature as a dynamic language. Therefore if Python had a switch statement, it would be no different from a hash table.</p> <p>You complained about the verboseness in your example and here I present to you a cleaner way.</p> <pre><code>fruits = dict( red="apple", blue="blueberry", pink="watermelon") name = fruits[color] </code></pre>
3
2009-08-12T20:17:28Z
[ "python", "coding-style", "code-review" ]
How do you resolve traditional coding standard vs python idomatic code?
1,267,444
<p>In my experience code clarity and readability are the primary concerns in traditional coding standards. PEP-8 would have been rejected by some of my previous customers.</p> <p>The idiomatic concepts such as, using dictionaries and lambda functions to emulate the behavior of a switch statement looks like something that would have clearly been forbidden by "Don't use tricky code" mandate in prior coding standards.</p> <p>Typical coding standards have "whenever it improves the readability of the code break up statements into multiple lines." Again lambda functions are right out.</p> <p>Beyond that, code reviews are assumed and I've had customers that not only reviewed the code, but REQUIRED software people to be part of the review. This was done to insure the code was readable without requiring an uber-geek specializing in a particular language to look at the code.</p> <p><strong>How are these types of concerns addressed with Python?</strong> End of original question.</p> <p>Edit: I reread PEP-8. I must retract the "PEP-8 would be rejected" statement. (This may just save my life from the Python lynch mob gathering out side.) The "This is not complete" and "Break the rules when it improves clarity" statements in that PEP do not require such harshness. Lamda statements are not addressed in that PEP. (That falls into the not complete category)</p> <p>@Javier: Do you have some recomended reading about the advantages of lamda?</p> <p>@RichieHindle: You may and it's a valueable suggestion, thank you.</p>
-3
2009-08-12T17:04:27Z
1,268,563
<p>In answer to your question:</p> <blockquote> <p>how do you handle the "default" condition in Python?</p> </blockquote> <p>You do this:</p> <pre><code>fruits = { "red": "apple", "blue": "blueberry", "pink": "watermelon", } print fruits.get(colour, "unknown") </code></pre> <p>Or you use the <code>defaultdict</code> class, which behaves like a normal dictionary but gives a default value when a key isn't found.</p>
1
2009-08-12T20:33:23Z
[ "python", "coding-style", "code-review" ]
Does __str__() call decode() method behind scenes?
1,267,754
<p>It seems to me that built-in functions <code>__repr__</code> and <code>__str__</code> have an important difference in their base definition.</p> <pre><code>&gt;&gt;&gt; t2 = u'\u0131\u015f\u0131k' &gt;&gt;&gt; print t2 ışık &gt;&gt;&gt; t2 Out[0]: u'\u0131\u015f\u0131k' </code></pre> <p><code>t2.decode</code> raises an error since <code>t2</code> is a unicode string.</p> <pre><code>&gt;&gt;&gt; enc = 'utf-8' &gt;&gt;&gt; t2.decode(enc) ------------------------------------------------------------ Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; File "C:\java\python\Python25\Lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin al not in range(128) </code></pre> <p><code>__str__</code> raises an error as if <code>decode()</code> function is being called:</p> <pre><code>&gt;&gt;&gt; t2.__str__() ------------------------------------------------------------ Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin al not in range(128) </code></pre> <p>but <code>__repr__</code> works without problem:</p> <pre><code>&gt;&gt;&gt; t2.__repr__() Out[0]: "u'\\u0131\\u015f\\u0131k'" </code></pre> <p>Why does <code>__str__</code> produce an error whereas <code>__repr__</code> work properly?</p> <p>This small difference seems to cause a bug in one django application that I am working on.</p>
0
2009-08-12T18:03:28Z
1,267,835
<p>Basically, <code>__str__</code> can only output ascii strings. Since t2 contains unicode codepoints above ascii, it cannot be represented with just a string. <code>__repr__</code>, on the other hand, tries to output the python code needed to recreate the object. You'll see that the output from repr(t2) (this syntax is preferred to <code>t2.__repr_()</code>) is exactly what you set t2 equal to up on the first line. The result from repr looks roughly like ['\', 'u', '0', ...], which are all ascii values, but the output from str is trying to be [chr(0x0131), chr(0x015f), chr(0x0131), 'k'], most of which are above the range of characters acceptable in a python string. Generally, when dealing with django applications, you should use <code>__unicode__</code> for everything, and never touch <code>__str__</code>.</p> <p>More info in <a href="http://www.djangoproject.com/documentation/models/str/" rel="nofollow">the django documentation on strings</a>.</p>
7
2009-08-12T18:20:16Z
[ "python", "django", "string", "unicode" ]
Does __str__() call decode() method behind scenes?
1,267,754
<p>It seems to me that built-in functions <code>__repr__</code> and <code>__str__</code> have an important difference in their base definition.</p> <pre><code>&gt;&gt;&gt; t2 = u'\u0131\u015f\u0131k' &gt;&gt;&gt; print t2 ışık &gt;&gt;&gt; t2 Out[0]: u'\u0131\u015f\u0131k' </code></pre> <p><code>t2.decode</code> raises an error since <code>t2</code> is a unicode string.</p> <pre><code>&gt;&gt;&gt; enc = 'utf-8' &gt;&gt;&gt; t2.decode(enc) ------------------------------------------------------------ Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; File "C:\java\python\Python25\Lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin al not in range(128) </code></pre> <p><code>__str__</code> raises an error as if <code>decode()</code> function is being called:</p> <pre><code>&gt;&gt;&gt; t2.__str__() ------------------------------------------------------------ Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin al not in range(128) </code></pre> <p>but <code>__repr__</code> works without problem:</p> <pre><code>&gt;&gt;&gt; t2.__repr__() Out[0]: "u'\\u0131\\u015f\\u0131k'" </code></pre> <p>Why does <code>__str__</code> produce an error whereas <code>__repr__</code> work properly?</p> <p>This small difference seems to cause a bug in one django application that I am working on.</p>
0
2009-08-12T18:03:28Z
1,267,923
<p>In general, calling <code>str.__unicode__()</code> or <code>unicode.__str__()</code> is a very bad idea, because bytes can't be safely converted to Unicode character points and vice versa. The exception is ASCII values, which are generally the same in all single-byte encodings. The problem is that you're using the wrong method for conversion.</p> <p>To convert <code>unicode</code> to <code>str</code>, you should use <code>encode()</code>:</p> <pre><code>&gt;&gt;&gt; t1 = u"\u0131\u015f\u0131k" &gt;&gt;&gt; t1.encode("utf-8") '\xc4\xb1\xc5\x9f\xc4\xb1k' </code></pre> <p>To convert <code>str</code> to <code>unicode</code>, use <code>decode()</code>:</p> <pre><code>&gt;&gt;&gt; t2 = '\xc4\xb1\xc5\x9f\xc4\xb1k' &gt;&gt;&gt; t2.decode("utf-8") u'\u0131\u015f\u0131k' </code></pre>
5
2009-08-12T18:34:12Z
[ "python", "django", "string", "unicode" ]
Does __str__() call decode() method behind scenes?
1,267,754
<p>It seems to me that built-in functions <code>__repr__</code> and <code>__str__</code> have an important difference in their base definition.</p> <pre><code>&gt;&gt;&gt; t2 = u'\u0131\u015f\u0131k' &gt;&gt;&gt; print t2 ışık &gt;&gt;&gt; t2 Out[0]: u'\u0131\u015f\u0131k' </code></pre> <p><code>t2.decode</code> raises an error since <code>t2</code> is a unicode string.</p> <pre><code>&gt;&gt;&gt; enc = 'utf-8' &gt;&gt;&gt; t2.decode(enc) ------------------------------------------------------------ Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; File "C:\java\python\Python25\Lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin al not in range(128) </code></pre> <p><code>__str__</code> raises an error as if <code>decode()</code> function is being called:</p> <pre><code>&gt;&gt;&gt; t2.__str__() ------------------------------------------------------------ Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin al not in range(128) </code></pre> <p>but <code>__repr__</code> works without problem:</p> <pre><code>&gt;&gt;&gt; t2.__repr__() Out[0]: "u'\\u0131\\u015f\\u0131k'" </code></pre> <p>Why does <code>__str__</code> produce an error whereas <code>__repr__</code> work properly?</p> <p>This small difference seems to cause a bug in one django application that I am working on.</p>
0
2009-08-12T18:03:28Z
1,268,096
<p>To add a bit of support to John's good answer:</p> <p>To understand the naming of the two methods <em>encode()</em> and <em>decode()</em>, you just have to see that Python considers unicode strings of the form <strong>u'...'</strong> to be in the <strong>reference format</strong>. You <em>encode</em> going from the reference format into another format (e.g. utf-8), and you <em>decode</em> from some other format to come to the reference format. The unicode format is always considered the "real thing" :-).</p>
2
2009-08-12T19:04:37Z
[ "python", "django", "string", "unicode" ]
Does __str__() call decode() method behind scenes?
1,267,754
<p>It seems to me that built-in functions <code>__repr__</code> and <code>__str__</code> have an important difference in their base definition.</p> <pre><code>&gt;&gt;&gt; t2 = u'\u0131\u015f\u0131k' &gt;&gt;&gt; print t2 ışık &gt;&gt;&gt; t2 Out[0]: u'\u0131\u015f\u0131k' </code></pre> <p><code>t2.decode</code> raises an error since <code>t2</code> is a unicode string.</p> <pre><code>&gt;&gt;&gt; enc = 'utf-8' &gt;&gt;&gt; t2.decode(enc) ------------------------------------------------------------ Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; File "C:\java\python\Python25\Lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin al not in range(128) </code></pre> <p><code>__str__</code> raises an error as if <code>decode()</code> function is being called:</p> <pre><code>&gt;&gt;&gt; t2.__str__() ------------------------------------------------------------ Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin al not in range(128) </code></pre> <p>but <code>__repr__</code> works without problem:</p> <pre><code>&gt;&gt;&gt; t2.__repr__() Out[0]: "u'\\u0131\\u015f\\u0131k'" </code></pre> <p>Why does <code>__str__</code> produce an error whereas <code>__repr__</code> work properly?</p> <p>This small difference seems to cause a bug in one django application that I am working on.</p>
0
2009-08-12T18:03:28Z
1,268,599
<p>Note that in Python 3, unicode is the default, and <code>__str__()</code> should always give you unicode.</p>
0
2009-08-12T20:39:34Z
[ "python", "django", "string", "unicode" ]
Django Formset without instance
1,267,810
<p>In <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets">this</a> Django Doc explain how to create a formset that allows you to edit books belonging to a particular author.</p> <p>What I want to do is: Create a formset that allows you to ADD new book belonging to a NEW author... Add the Book and their Authors in the same formset.</p> <p>Can you gime a light? thanks.</p>
6
2009-08-12T18:14:45Z
1,268,136
<p>This depends on whether you're doing it yourself, or using the built-in admin.</p> <p>If you're using the admin, you can use <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects" rel="nofollow">inlines</a>.</p> <p>If you're doing this in your own application, then it's up to you. Create a single form which has fields for a new <code>author</code> and <code>book</code>. When the user submits the form, it's your job to create the new records.</p>
0
2009-08-12T19:11:15Z
[ "python", "django", "forms", "formset", "inline-formset" ]
Django Formset without instance
1,267,810
<p>In <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets">this</a> Django Doc explain how to create a formset that allows you to edit books belonging to a particular author.</p> <p>What I want to do is: Create a formset that allows you to ADD new book belonging to a NEW author... Add the Book and their Authors in the same formset.</p> <p>Can you gime a light? thanks.</p>
6
2009-08-12T18:14:45Z
1,269,142
<p>When you're instantiating the form and formset for the initial display, you don't need to provide an instance - so you will just get blank forms.</p> <p>When you pass in the data on POST, you can do the form first, save it, and get an instance. Then you can pass that instance into the formset, so that it correctly saves the related objects.</p>
6
2009-08-12T22:47:28Z
[ "python", "django", "forms", "formset", "inline-formset" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
1,267,883
<pre><code>c = a / (b * 1.0) </code></pre>
70
2009-08-12T18:26:57Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
1,267,890
<p>You can cast to float by doing <code>c = a / float(b)</code>. If the numerator or denominator is a float, then the result will be also.</p> <hr> <p>A caveat: as commenters have pointed out, this won't work if <code>b</code> might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.</p>
523
2009-08-12T18:28:02Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
1,267,892
<pre><code>&gt;&gt;&gt; from __future__ import division &gt;&gt;&gt; a = 4 &gt;&gt;&gt; b = 6 &gt;&gt;&gt; c = a / b &gt;&gt;&gt; c 0.66666666666666663 </code></pre>
508
2009-08-12T18:28:26Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
1,267,901
<p>In Python 3.x, the single slash (<code>/</code>) always means true (non-truncating) division. (The <code>//</code> operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a</p> <pre><code>from __future__ import division </code></pre> <p>at the top of your module.</p>
49
2009-08-12T18:30:30Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
3,784,679
<p>Just making any of the parameters for division in floating-point format also produces the output in floating-point.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; 4.0/3 1.3333333333333333 </code></pre> <p>or,</p> <pre><code>&gt;&gt;&gt; 4 / 3.0 1.3333333333333333 </code></pre> <p>or, </p> <pre><code>&gt;&gt;&gt; 4 / float(3) 1.3333333333333333 </code></pre> <p>or, </p> <pre><code>&gt;&gt;&gt; float(4) / 3 1.3333333333333333 </code></pre>
25
2010-09-24T06:22:39Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
20,766,181
<p>This will also work</p> <pre><code>&gt;&gt;&gt; u=1./5 &gt;&gt;&gt; print u </code></pre> <blockquote> <p>0.2</p> </blockquote>
8
2013-12-24T19:58:41Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
20,979,168
<p>If you want to use "true" (floating point) division by default, there is a command line flag:</p> <pre><code>python -Q new foo.py </code></pre> <p>There are some drawbacks (from the PEP):</p> <blockquote> <p>It has been argued that a command line option to change the default is evil. It can certainly be dangerous in the wrong hands: for example, it would be impossible to combine a 3rd party library package that requires -Qnew with another one that requires -Qold. </p> </blockquote> <p>You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.</p> <p>For full details on division changes read: <a href="http://www.python.org/dev/peps/pep-0238/">PEP 238 -- Changing the Division Operator</a></p>
6
2014-01-07T18:33:47Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
27,078,572
<p>Add a dot (<code>.</code>) to indicate floating point numbers</p> <pre><code>&gt;&gt;&gt; 4/3. 1.3333333333333333 </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; from __future__ import division &gt;&gt;&gt; 4/3 1.3333333333333333 </code></pre>
16
2014-11-22T14:39:24Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
32,649,302
<pre><code>from operator import truediv c = truediv(a, b) </code></pre>
3
2015-09-18T10:04:34Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
32,657,822
<blockquote> <h1>How can I force division to be floating point in Python?</h1> <p>I have two integer values a and b, but I need their ratio in floating point. I know that a &lt; b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a.</p> <p>How can I force c to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre> </blockquote> <p>What is really being asked here is:</p> <p>"How do I force true division such that <code>a / b</code> will return a fraction?"</p> <h2>Upgrade to Python 3</h2> <p>In Python 3, to get true division, you simply do <code>a / b</code>. </p> <pre><code>&gt;&gt;&gt; 1/2 0.5 </code></pre> <p>Floor division, the classic division behavior for integers, is now <code>a // b</code>:</p> <pre><code>&gt;&gt;&gt; 1//2 0 &gt;&gt;&gt; 1//2.0 0.0 </code></pre> <p>However, you may be stuck using Python 2, or you may be writing code that must work in both 2 and 3.</p> <h2>If Using Python 2</h2> <p>In Python 2, it's not so simple. Some ways of dealing with classic Python 2 division are better and more robust than others.</p> <h3>Recommended</h3> <p>You can get Python 3 division behavior in any given module with the following import at the top:</p> <pre><code>from __future__ import division </code></pre> <p>which then applies Python 3 style division to the entire module. It also works in a python shell at any given point. In Python 2:</p> <pre><code>&gt;&gt;&gt; from __future__ import division &gt;&gt;&gt; 1/2 0.5 &gt;&gt;&gt; 1//2 0 &gt;&gt;&gt; 1//2.0 0.0 </code></pre> <p>This is really the best solution as it ensures the code in your module is more forward compatible with Python 3.</p> <h3>Other Options</h3> <p>If you don't want to apply this to the entire module, you're limited to a few workarounds. The most popular is to coerce one of the operands to a float. One robust solution is <code>a / (b * 1.0)</code>. In a fresh Python shell:</p> <pre><code>&gt;&gt;&gt; 1/(2 * 1.0) 0.5 </code></pre> <p>Also robust is <code>truediv</code> from the <code>operator</code> module <code>operator.truediv(a, b)</code>, but this is likely slower because it's a function call:</p> <pre><code>&gt;&gt;&gt; from operator import truediv &gt;&gt;&gt; truediv(1, 2) 0.5 </code></pre> <h3>Not Recommended</h3> <p>Commonly seen is <code>a / float(b)</code>. This will raise a TypeError if b is a complex number. Since division with complex numbers is defined, it makes sense to me to not have division fail when passed a complex number for the divisor.</p> <pre><code>&gt;&gt;&gt; 1 / float(2) 0.5 &gt;&gt;&gt; 1 / float(2j) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: can't convert complex to float </code></pre> <p>It doesn't make much sense to me to purposefully make your code more brittle.</p> <p>You can also run Python with the <code>-Qnew</code> flag, but this has the downside of executing all modules with the new Python 3 behavior, and some of your modules may expect classic division, so this is not recommended. But to demonstrate:</p> <pre><code>$ python -Qnew -c 'print 1/2' 0.5 $ python -Qnew -c 'print 1/2j' -0.5j </code></pre>
31
2015-09-18T17:29:08Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
<p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a&lt;b</code> and I want to calculate <code>a/b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python in the following?</p> <pre><code>c = a / b </code></pre>
455
2009-08-12T18:25:15Z
34,670,051
<pre><code>from operator import truediv c = truediv(a, b) </code></pre> <p>where a is dividend and b is the divisor. This function is handy when quotient after division of two integers is a float.</p>
2
2016-01-08T05:23:18Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
How to prevent Satchmo forms from displaying asterisk after required fields?
1,267,874
<p>I'm customizing my Satchmo store forms and have an icon that appears before any required fields. The problem is, Satchmo seems to want to render a text asterisk after the required fields. I'm using <code>field.label</code> to get this label, should I be using something else?</p> <p><strong>EDIT:</strong> All my form templates are hard coded. I have an inclusion tag that takes a field and wraps it in a standard field template I've developed. My template uses the <code>{{ field.label }}</code> to display the friendly name of the field. It seem the label itself has a single asterisk in it at the end.</p>
2
2009-08-12T18:25:45Z
1,282,557
<p>What happens if you do the following?</p> <ol> <li>Copy some or all of Satchmo's form templates to a new location and modify them to remove the asterisks</li> <li>Arrange it so that your copies of those templates are seen before Satchmo's copies (by configuring the template loader settings appropriately, say by placing the app with the copied templates above Satchmo in <code>settings.INSTALLED_APPS</code>)</li> </ol> <p><strong>Update:</strong> I'm not able to reproduce your results with a vanilla Satchmo 0.8.1 installation. Can you give some more information? Here's what I did: First, I modified <code>templates/contact/update_form.html</code>, which contains hard-coded asterisks. I could easily remove them by changing the template; they disappeared from the UI. Instead, I left them in but added immediately after, in parentheses, <code>{{ form.field.label }}</code> after each of the fields in a section of the form. This is the result:</p> <p><img src="http://imgur.com/XdJpm.png" alt="alt text" /></p> <p>The labels here do contain an asterisk - as I mentioned earlier, this is because <code>ContactInfoForm</code> hardcodes this behaviour in its <code>__init__</code> method. You would have to undo this behaviour, perhaps by using a derived class which removes trailing <code>*</code>s from field labels.</p> <p>However, I did not find any <code>*</code>s appearing in other required fields. For example, here's a screenshot of the checkout form when I tried submitting <em>without</em> entering required information:</p> <p><img src="http://imgur.com/oudfQ.png" alt="alt text" /></p> <p>As you can see the credit card number and CCV are required fields but do not appear with an asterisk at the prompt. Nor do the labels have asterisks. So, the problem you are experiencing appears to be something to do with your customisations, but without more information it is difficult to be more helpful.</p>
1
2009-08-15T18:55:44Z
[ "python", "django", "forms", "field", "satchmo" ]
Python standard module for emulating geometric points
1,267,968
<p>Is there a standard class in Python to emulate a geometric point that includes coordinates and a value, including arithmetic operations between the coordinates? </p>
0
2009-08-12T18:41:48Z
1,268,052
<p>If you just want standard matrix arithmetic operations for your coordinates, try <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a>'s array type.</p>
1
2009-08-12T18:56:38Z
[ "python", "geometry" ]
Standard Solution for Decoding Additive Numbers
1,268,050
<p>From the Oracle docs.</p> <blockquote> <p>A number representing one or more statistics class. The following class numbers are additive:</p> </blockquote> <pre><code> 1 - User 2 - Redo 4 - Enqueue 8 - Cache 16 - OS 32 - Real Application Clusters 64 - SQL 128 - Debug </code></pre> <p>It there a standard solution for taking say 22 and decoding that into 16, 4, and 2? My first guess would be to create an object which holds every possible combination and use that as a lookup? Is there a better solution using binary or something? Preferred solution would by in Python. (disclaimer: This is not homework.)</p>
0
2009-08-12T18:56:07Z
1,268,066
<p>Each of those values corresponds to a single bit. So use the binary.</p> <pre><code>1&lt;&lt;0 - 1 - User 1&lt;&lt;1 - 2 - Redo 1&lt;&lt;2 - 4 - Enqueue 1&lt;&lt;3 - 8 - Cache 1&lt;&lt;4 - 16 - OS 1&lt;&lt;5 - 32 - Real Application Clusters 1&lt;&lt;6 - 64 - SQL 1&lt;&lt;7 - 128 - Debug </code></pre> <p>Use &amp; to test for each bit.</p> <pre><code>def decode(value): readable = [] flags = ['User', 'Redo', 'Enqueue', 'Cache', 'OS', 'Real Application Clusters', 'SQL', 'Debug'] for i, flag in enumerate(flags): if value &amp; (1&lt;&lt;i): readable.append(flags[i]) return readable print decode(22) </code></pre>
4
2009-08-12T18:59:10Z
[ "python", "algorithm" ]
Standard Solution for Decoding Additive Numbers
1,268,050
<p>From the Oracle docs.</p> <blockquote> <p>A number representing one or more statistics class. The following class numbers are additive:</p> </blockquote> <pre><code> 1 - User 2 - Redo 4 - Enqueue 8 - Cache 16 - OS 32 - Real Application Clusters 64 - SQL 128 - Debug </code></pre> <p>It there a standard solution for taking say 22 and decoding that into 16, 4, and 2? My first guess would be to create an object which holds every possible combination and use that as a lookup? Is there a better solution using binary or something? Preferred solution would by in Python. (disclaimer: This is not homework.)</p>
0
2009-08-12T18:56:07Z
1,268,111
<p>You want to use binary operations to decode the original. The following code actually returns the correct strings:</p> <pre><code>&gt;&gt;&gt; FLAGS = ('User', 'Redo', 'Enqueue', 'Cache', 'OS', ... 'Real Application Clusters', 'SQL', 'Debug') &gt;&gt;&gt; def getFlags(value): ... flags = [] ... for i, flag in enumerate(FLAGS): ... if value &amp; (1 &lt;&lt; i): ... flags.append(flag) ... return flags ... &gt;&gt;&gt; print getFlags(22) ['Redo', 'Enqueue', 'OS'] </code></pre> <p>If you really just want the constants:</p> <pre><code>&gt;&gt;&gt; def binaryDecomposition(value): ... return [1 &lt;&lt; i for i in xrange(len(FLAGS)) if value &amp; (1 &lt;&lt; i)] ... &gt;&gt;&gt; print binaryDecomposition(22) [2, 4, 16] </code></pre>
4
2009-08-12T19:07:29Z
[ "python", "algorithm" ]
Displaying X and y axis in pylab
1,268,175
<p>Is there a way in pylab to display the X and Y axis? I know using grid() will display them, but it comes with numerous other lines all given the same emphasis.</p>
1
2009-08-12T19:19:34Z
1,268,859
<p><code>foo.grid(b=True)</code> should help, but it is very raw.</p> <p>If you supply any of the additional arguments it automatically assumes that b is True</p> <p>For example:</p> <pre><code>foo.grid(label='My awesome grid') </code></pre>
1
2009-08-12T21:34:30Z
[ "python", "matplotlib" ]
Displaying X and y axis in pylab
1,268,175
<p>Is there a way in pylab to display the X and Y axis? I know using grid() will display them, but it comes with numerous other lines all given the same emphasis.</p>
1
2009-08-12T19:19:34Z
1,269,164
<p>What plot function do you use?</p> <p>Axis are drawn automatically by all plotting functions I've seen so far, e.g.</p> <pre><code>from pylab import * hist(randn(10000), 100) show() </code></pre> <p>Additionally, axis can be generated manually with the <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.axes" rel="nofollow">axes() function</a>.</p>
3
2009-08-12T22:53:08Z
[ "python", "matplotlib" ]
Displaying X and y axis in pylab
1,268,175
<p>Is there a way in pylab to display the X and Y axis? I know using grid() will display them, but it comes with numerous other lines all given the same emphasis.</p>
1
2009-08-12T19:19:34Z
1,269,451
<p>If you are looking to name the axis you can using the label function:</p> <pre><code>import pylab pylab.xlabel("X") pylab.ylabel("Y") pylab.plot(range(10)) pylab.show() </code></pre> <p>Anyway, I'm pretty sure the x and y axis are automatically generated.</p> <p><a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.axes">matplotlib axes documentation</a></p> <p>If you just want an empty plot then:</p> <pre><code>pylab.plot([None], [None]) </code></pre> <p>this will give you the x and y axis with both going from 0 to 1. Now if you would like to change the range of either of those then you can:</p> <pre><code>pylab.xlim(xmin=0, xmax=100) pylab.ylim(ymin=0, ymax=100) </code></pre> <p>hope that helps.</p>
8
2009-08-13T00:32:25Z
[ "python", "matplotlib" ]
Displaying X and y axis in pylab
1,268,175
<p>Is there a way in pylab to display the X and Y axis? I know using grid() will display them, but it comes with numerous other lines all given the same emphasis.</p>
1
2009-08-12T19:19:34Z
1,273,543
<p>It sounds like your problem has been addressed in the new <a href="http://matplotlib.sourceforge.net/users/whats%5Fnew.html" rel="nofollow">Matplotlib 0.99</a> with the Axis spine placement feature. Take a <a href="http://matplotlib.sourceforge.net/examples/pylab%5Fexamples/spine%5Fplacement%5Fdemo.html#pylab-examples-spine-placement-demo" rel="nofollow">look at the examples</a>.</p>
2
2009-08-13T17:47:29Z
[ "python", "matplotlib" ]
Displaying X and y axis in pylab
1,268,175
<p>Is there a way in pylab to display the X and Y axis? I know using grid() will display them, but it comes with numerous other lines all given the same emphasis.</p>
1
2009-08-12T19:19:34Z
33,480,294
<p>The best way for me is to add vertical and horizontal lines at 0:</p> <pre><code>pylab.axvline(linewidth=0.5, color = 'k') pylab.axhline(linewidth=0.5, color = 'k') </code></pre>
0
2015-11-02T14:46:54Z
[ "python", "matplotlib" ]
Django ModelForm CheckBox Widget
1,268,209
<p>I'm currently have an issue, and likely overlooking something very trivial. I have a field in my model that should allow for multiple choices via a checkbox form (it doesn't have to be a checkbox in the admin screen, just in the form area that the end-user will see). Currently I have the field setup like so:</p> <pre><code># Type of Media MEDIA_CHOICES = ( ('1', 'Magazine'), ('2', 'Radio Station'), ('3', 'Journal'), ('4', 'TV Station'), ('5', 'Newspaper'), ('6', 'Website'), ) media_choice = models.CharField(max_length=25, choices=MEDIA_CHOICES) </code></pre> <p>I need to take that and make a checkbox selectable field in a form out of it though. When I create a ModelForm, it wants to do a drop down box. So I naturally overrode that field, and I get my checkbox that I want. However, when the form's submitted, it would appear that nothing useful is saved when I look at the admin screen. The database does however show that I have a number of things selected, which is a positive sign. However, how can I get that to reflect in the admin screen properly?</p> <p>Edit: FWIW I'll gladly accept documentation links as answers, because it would seem I'm just glossing over something obvious.</p>
1
2009-08-12T19:26:34Z
1,268,493
<p>In such a case, the easiest way is to put the choices into a separate model and then use a ManyToMany relationship. After that, you simply override the ModelForm's widget for that field to use <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxSelectMultiple">forms.CheckboxSelectMultiple</a> and Django will automatically do the right thing. If you insist to use a CharField, you'll probably have to do something like <a href="http://www.djangosnippets.org/snippets/1200/">this snippet</a>.</p> <p>@ 2. comment: how are you overriding the widget? This is how I do it and it works flawlessly:</p> <pre><code>class SomeModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SomeModelForm, self).__init__(*args, **kwargs) self.fields['some_field'].widget = forms.CheckboxSelectMultiple() </code></pre>
13
2009-08-12T20:19:08Z
[ "python", "django", "django-models", "django-forms" ]
Django ModelForm CheckBox Widget
1,268,209
<p>I'm currently have an issue, and likely overlooking something very trivial. I have a field in my model that should allow for multiple choices via a checkbox form (it doesn't have to be a checkbox in the admin screen, just in the form area that the end-user will see). Currently I have the field setup like so:</p> <pre><code># Type of Media MEDIA_CHOICES = ( ('1', 'Magazine'), ('2', 'Radio Station'), ('3', 'Journal'), ('4', 'TV Station'), ('5', 'Newspaper'), ('6', 'Website'), ) media_choice = models.CharField(max_length=25, choices=MEDIA_CHOICES) </code></pre> <p>I need to take that and make a checkbox selectable field in a form out of it though. When I create a ModelForm, it wants to do a drop down box. So I naturally overrode that field, and I get my checkbox that I want. However, when the form's submitted, it would appear that nothing useful is saved when I look at the admin screen. The database does however show that I have a number of things selected, which is a positive sign. However, how can I get that to reflect in the admin screen properly?</p> <p>Edit: FWIW I'll gladly accept documentation links as answers, because it would seem I'm just glossing over something obvious.</p>
1
2009-08-12T19:26:34Z
1,269,612
<p>I've just started to look into widgets assignment with ModelForms. In a lot of examples I've seen, piquadrat's included, the Form's __ init __ method is overridden.</p> <p>I find this a little confusing, and just overriding the desired field is more natural for me:</p> <pre><code>class SomeModelForm(forms.ModelForm): some_field = forms.CharField(choices=MEDIA_CHOICES, widget=forms.CheckboxSelectMultiple) class Meta: model=SomeModel </code></pre> <p>Note: I'm using Django 1.1. </p>
1
2009-08-13T01:41:00Z
[ "python", "django", "django-models", "django-forms" ]
Django ModelForm CheckBox Widget
1,268,209
<p>I'm currently have an issue, and likely overlooking something very trivial. I have a field in my model that should allow for multiple choices via a checkbox form (it doesn't have to be a checkbox in the admin screen, just in the form area that the end-user will see). Currently I have the field setup like so:</p> <pre><code># Type of Media MEDIA_CHOICES = ( ('1', 'Magazine'), ('2', 'Radio Station'), ('3', 'Journal'), ('4', 'TV Station'), ('5', 'Newspaper'), ('6', 'Website'), ) media_choice = models.CharField(max_length=25, choices=MEDIA_CHOICES) </code></pre> <p>I need to take that and make a checkbox selectable field in a form out of it though. When I create a ModelForm, it wants to do a drop down box. So I naturally overrode that field, and I get my checkbox that I want. However, when the form's submitted, it would appear that nothing useful is saved when I look at the admin screen. The database does however show that I have a number of things selected, which is a positive sign. However, how can I get that to reflect in the admin screen properly?</p> <p>Edit: FWIW I'll gladly accept documentation links as answers, because it would seem I'm just glossing over something obvious.</p>
1
2009-08-12T19:26:34Z
4,262,838
<p>Using piquadrat's answer worked for me, but needed to add a line to define the queryset for the M2M. See <a href="http://bitkickers.blogspot.com/2010/05/django-manytomanyfield-on-modelform-as.html" rel="nofollow">this link</a>.</p>
0
2010-11-24T01:53:17Z
[ "python", "django", "django-models", "django-forms" ]
Python: Possible to share in-memory data between 2 separate processes
1,268,252
<p>I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server?</p> <p>So, serverA starts up and creates an object. serverB starts up and can read from the object in serverA.</p> <p><strong>* EDIT *</strong></p> <p>The data to be shared is a list of 1 million tuples.</p>
27
2009-08-12T19:33:11Z
1,268,264
<pre><code>mmap.mmap(0, 65536, 'GlobalSharedMemory') </code></pre> <p>I think the tag ("GlobalSharedMemory") must be the same for all processes wishing to share the same memory.</p> <p><a href="http://docs.python.org/library/mmap.html">http://docs.python.org/library/mmap.html</a></p>
12
2009-08-12T19:36:36Z
[ "python" ]
Python: Possible to share in-memory data between 2 separate processes
1,268,252
<p>I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server?</p> <p>So, serverA starts up and creates an object. serverB starts up and can read from the object in serverA.</p> <p><strong>* EDIT *</strong></p> <p>The data to be shared is a list of 1 million tuples.</p>
27
2009-08-12T19:33:11Z
1,268,499
<p>You can use the Python Multiprocessing module.</p> <p><a href="http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow">http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes</a></p>
1
2009-08-12T20:20:08Z
[ "python" ]
Python: Possible to share in-memory data between 2 separate processes
1,268,252
<p>I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server?</p> <p>So, serverA starts up and creates an object. serverB starts up and can read from the object in serverA.</p> <p><strong>* EDIT *</strong></p> <p>The data to be shared is a list of 1 million tuples.</p>
27
2009-08-12T19:33:11Z
1,269,055
<p>Without some deep and dark rewriting of the Python core runtime (to allow forcing of an allocator that uses a given segment of shared memory and ensures compatible addresses between disparate processes) there is no way to "share objects in memory" in any general sense. That list will hold a million addresses of tuples, each tuple made up of addresses of all of its items, and each of these addresses will have be assigned by pymalloc in a way that inevitably varies among processes and spreads all over the heap.</p> <p>On just about every system except Windows, it's possible to spawn a subprocess that has essentially read-only access to objects in the parent process's space... as long as the parent process doesn't alter those objects, either. That's obtained with a call to <code>os.fork()</code>, that in practice "snapshots" all of the memory space of the current process and starts another simultaneous process on the copy/snapshot. On all modern operating systems, this is actually very fast thanks to a "copy on write" approach: the pages of virtual memory that are not altered by either process after the fork are not really copied (access to the same pages is instead shared); as soon as either process modifies any bit in a previously shared page, poof, that page is copied, and the page table modified, so the modifying process now has its own copy while the other process still sees the original one.</p> <p>This extremely limited form of sharing can still be a lifesaver in some cases (although it's extremely limited: remember for example that adding a reference to a shared object counts as "altering" that object, due to reference counts, and so will force a page copy!)... except on Windows, of course, where it's not available. With this single exception (which I don't think will cover your use case), sharing of object graphs that include references/pointers to other objects is basically unfeasible -- and just about any objects set of interest in modern languages (including Python) falls under this classification.</p> <p>In extreme (but sufficiently simple) cases one can obtain sharing by renouncing the native memory representation of such object graphs. For example, a list of a million tuples each with sixteen floats could actually be represented as a single block of 128 MB of shared memory -- all the 16M floats in double-precision IEEE representation laid end to end -- with a little shim on top to "make it look like" you're addressing things in the normal way (and, of course, the not-so-little-after-all shim would also have to take care of the extremely hairy inter-process synchronization problems that are certain to arise;-). It only gets hairier and more complicated from there.</p> <p>Modern approaches to concurrency are more and more disdaining shared-anything approaches in favor of shared-nothing ones, where tasks communicate by message passing (even in multi-core systems using threading and shared address spaces, the synchronization issues and the performance hits the HW incurs in terms of caching, pipeline stalls, etc, when large areas of memory are actively modified by multiple cores at once, are pushing people away).</p> <p>For example, the multiprocessing module in Python's standard library relies mostly on pickling and sending objects back and forth, not on sharing memory (surely not in a R/W way!-).</p> <p>I realize this is not welcome news to the OP, but if he does need to put multiple processors to work, he'd better think in terms of having anything they must share reside in places where they can be accessed and modified by message passing -- a database, a memcache cluster, a dedicated process that does nothing but keep those data in memory and send and receive them on request, and other such message-passing-centric architectures.</p>
63
2009-08-12T22:20:42Z
[ "python" ]
Python: Possible to share in-memory data between 2 separate processes
1,268,252
<p>I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server?</p> <p>So, serverA starts up and creates an object. serverB starts up and can read from the object in serverA.</p> <p><strong>* EDIT *</strong></p> <p>The data to be shared is a list of 1 million tuples.</p>
27
2009-08-12T19:33:11Z
1,270,886
<p>Why not just use a database for the shared data? You have a multitude of lightweight options where you don't need to worry about the concurrency issues: sqlite, any of the nosql/key-value breed of databases, etc. </p>
0
2009-08-13T09:03:16Z
[ "python" ]
Python: Possible to share in-memory data between 2 separate processes
1,268,252
<p>I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server?</p> <p>So, serverA starts up and creates an object. serverB starts up and can read from the object in serverA.</p> <p><strong>* EDIT *</strong></p> <p>The data to be shared is a list of 1 million tuples.</p>
27
2009-08-12T19:33:11Z
1,270,922
<p>Why not stick the shared data into memcache server? then both servers can access it quite easily.</p>
1
2009-08-13T09:13:36Z
[ "python" ]
Python: Possible to share in-memory data between 2 separate processes
1,268,252
<p>I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server?</p> <p>So, serverA starts up and creates an object. serverB starts up and can read from the object in serverA.</p> <p><strong>* EDIT *</strong></p> <p>The data to be shared is a list of 1 million tuples.</p>
27
2009-08-12T19:33:11Z
1,271,568
<p>You could write a C library to create and manipulate shared-memory arrays for your specific purpose, and then use ctypes to access them from Python.</p> <p>Or, put them on the filesystem in /dev/shm (which is tmpfs). You'd save a lot of development effort for very little performance overhead: reads/writes from a tmpfs filesystem are little more than a memcpy.</p>
2
2009-08-13T12:06:53Z
[ "python" ]
Python: Possible to share in-memory data between 2 separate processes
1,268,252
<p>I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server?</p> <p>So, serverA starts up and creates an object. serverB starts up and can read from the object in serverA.</p> <p><strong>* EDIT *</strong></p> <p>The data to be shared is a list of 1 million tuples.</p>
27
2009-08-12T19:33:11Z
28,376,308
<p>There are a couple<sup>1</sup> of third party libraries available for low-level shared memory manipulations in Python:</p> <ul> <li><a href="http://semanchuk.com/philip/sysv_ipc/" rel="nofollow">sysv_ipc</a> <ul> <li>> For posix non-compliant systems</li> </ul></li> <li><a href="http://semanchuk.com/philip/posix_ipc/" rel="nofollow">posix_ipc</a> <ul> <li>> Works in Windows with cygwin</li> </ul></li> </ul> <p>Both of which are available <a href="https://pypi.python.org/pypi?%3Aaction=search&amp;term=sysv_ipc%20%7C%7C%20posix_ipc&amp;submit=search" rel="nofollow">via pip</a></p> <p>[1] Another package, <a href="http://nikitathespider.com/python/shm/" rel="nofollow">shm</a>, is available but <em>deprecated</em>. See <a href="http://semanchuk.com/philip/PythonIpc/" rel="nofollow">this page</a> for a comparison of the libraries.</p> <h2><a href="http://www.stuffaboutcode.com/2013/08/shared-memory-c-python-ipc.html" rel="nofollow">Example Code</a> for C to Python Communication <a href="https://plus.google.com/+MartinOHanlon" rel="nofollow">c/o Martin O'Hanlon</a>:</h2> <h3>shmwriter.c</h3> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/ipc.h&gt; #include &lt;sys/shm.h&gt; int main(int argc, const char **argv) { int shmid; // give your shared memory an id, anything will do key_t key = 123456; char *shared_memory; // Setup shared memory, 11 is the size if ((shmid = shmget(key, 11, IPC_CREAT | 0666)) &lt; 0) { printf("Error getting shared memory id"); exit(1); } // Attached shared memory if ((shared_memory = shmat(shmid, NULL, 0)) == (char *) -1) { printf("Error attaching shared memory id"); exit(1); } // copy "hello world" to shared memory memcpy(shared_memory, "Hello World", sizeof("Hello World")); // sleep so there is enough time to run the reader! sleep(10); // Detach and remove shared memory shmdt(shmid); shmctl(shmid, IPC_RMID, NULL); } </code></pre> <h3>shmreader.py</h3> <pre><code>import sysv_ipc # Create shared memory object memory = sysv_ipc.SharedMemory(123456) # Read value from shared memory memory_value = memory.read() # Find the 'end' of the string and strip i = memory_value.find('\0') if i != -1: memory_value = memory_value[:i] print memory_value </code></pre>
2
2015-02-06T23:01:35Z
[ "python" ]
Importing Model / Lib Class and calling from controller
1,268,432
<p>I'm new to python and pylons although experienced in PHP. </p> <p>I'm trying to write a model class which will act as a my data access to my database (couchdb). My problem is simple </p> <p>My model looks like this and is called models/BlogModel.py</p> <pre><code>from couchdb import * class BlogModel: def getTitles(self): # code to get titles here def saveTitle(self): # code to save title here </code></pre> <p>My controller is called controllers/main.py</p> <pre><code>import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort, redirect_to from billion.lib.base import BaseController, render log = logging.getLogger(__name__) from billion.model import BlogModel class MainController(BaseController): def index(self): return render('/main.mako') </code></pre> <p>In my index action, how do I access the method getTitles() in BlogModel? </p> <p>I've tried </p> <pre><code>x = BlogModel() x.getTitles() </code></pre> <p>But i get TypeError: 'module' object is not callable</p> <p>Also BlogModel.getTitles() results in AttributeError: 'module' object has no attribute 'getTitles'</p> <p>Is this down to the way I'm including the class ? Can someone tell me the best way to do this ?</p> <p>thanks</p>
1
2009-08-12T20:07:23Z
1,268,461
<pre><code>x = BlogModel.BlogModel() </code></pre> <p>Or, more verbosely:</p> <p>After you did the import, you have an object in your namespace called 'BlogModel'. That object is the BlogModel module. (The module name comes from the filename.) Inside that module, there is a class object called 'BlogModel', which is what you were after. (The class name comes from the source code you wrote.)</p> <p>Instead of:</p> <pre><code>from billion.model import BlogModel </code></pre> <p>You could use:</p> <pre><code>from billion.model.BlogModel import BlogModel </code></pre> <p>then your</p> <pre><code>x = BlogModel() </code></pre> <p>would work.</p>
2
2009-08-12T20:13:46Z
[ "python", "model-view-controller", "pylons" ]
Regex Matching Error
1,268,761
<p>I am new to Python (I dont have any programming training either), so please keep that in mind as I ask my question.</p> <p>I am trying to search a retrieved webpage and find all links using a specified pattern. I have done this successfully in other scripts, but I am getting an error that says </p> <blockquote> <pre><code>raise error, v # invalid expression </code></pre> <p>sre_constants.error: multiple repeat</p> </blockquote> <p>I have to admit I do not know why, but again, I am new to Python and Regular Expressions. However, even when I don't use patterns and use a specific link (just to test the matching), I do not believe I return any matches (nothing is sent to the window when I print match.group(0). The link I tested is commented out below.</p> <p>Any ideas? It usually is easier for me to learn by example, but any advice you can give is greatly appreciated!</p> <p>Brock</p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup import re url = "http://forums.epicgames.com/archive/index.php?f-356-p-164.html" page = urllib2.urlopen(url).read() soup = BeautifulSoup(page) pattern = r'&lt;a href="http://forums.epicgames.com/archive/index.php?t-([0-9]+).html"&gt;(.?+)&lt;/a&gt; &lt;i&gt;((.?+) replies)' #pattern = r'href="http://forums.epicgames.com/archive/index.php?t-622233.html"&gt;Gears of War 2: Horde Gameplay&lt;/a&gt; &lt;i&gt;(20 replies)' for match in re.finditer(pattern, page, re.S): print match(0) </code></pre>
8
2009-08-12T21:15:29Z
1,268,780
<p>You need to escape the literal '?' and the literal '(' and ')' that you are trying to match.</p> <p>Also, instead of '?+', I think you're looking for the non-greedy matching provided by '+?'.</p> <p><a href="http://docs.python.org/library/re.html" rel="nofollow">More documentation here.</a></p> <p>For your case, try this:</p> <pre><code>pattern = r'&lt;a href="http://forums.epicgames.com/archive/index.php\?t-([0-9]+).html"&gt; (.+?)&lt;/a&gt; &lt;i&gt;\((.+?) replies\)' </code></pre>
1
2009-08-12T21:19:14Z
[ "python", "regex" ]
Regex Matching Error
1,268,761
<p>I am new to Python (I dont have any programming training either), so please keep that in mind as I ask my question.</p> <p>I am trying to search a retrieved webpage and find all links using a specified pattern. I have done this successfully in other scripts, but I am getting an error that says </p> <blockquote> <pre><code>raise error, v # invalid expression </code></pre> <p>sre_constants.error: multiple repeat</p> </blockquote> <p>I have to admit I do not know why, but again, I am new to Python and Regular Expressions. However, even when I don't use patterns and use a specific link (just to test the matching), I do not believe I return any matches (nothing is sent to the window when I print match.group(0). The link I tested is commented out below.</p> <p>Any ideas? It usually is easier for me to learn by example, but any advice you can give is greatly appreciated!</p> <p>Brock</p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup import re url = "http://forums.epicgames.com/archive/index.php?f-356-p-164.html" page = urllib2.urlopen(url).read() soup = BeautifulSoup(page) pattern = r'&lt;a href="http://forums.epicgames.com/archive/index.php?t-([0-9]+).html"&gt;(.?+)&lt;/a&gt; &lt;i&gt;((.?+) replies)' #pattern = r'href="http://forums.epicgames.com/archive/index.php?t-622233.html"&gt;Gears of War 2: Horde Gameplay&lt;/a&gt; &lt;i&gt;(20 replies)' for match in re.finditer(pattern, page, re.S): print match(0) </code></pre>
8
2009-08-12T21:15:29Z
1,268,783
<p>That means your regular expression has an error.</p> <pre><code>(.?+)&lt;/a&gt; &lt;i&gt;((.?+) </code></pre> <p>What does ?+ mean? Both ? and + are meta characters that does not make sense right next to each other. Maybe you forgot to escape the '?' or something.</p>
1
2009-08-12T21:19:26Z
[ "python", "regex" ]
Regex Matching Error
1,268,761
<p>I am new to Python (I dont have any programming training either), so please keep that in mind as I ask my question.</p> <p>I am trying to search a retrieved webpage and find all links using a specified pattern. I have done this successfully in other scripts, but I am getting an error that says </p> <blockquote> <pre><code>raise error, v # invalid expression </code></pre> <p>sre_constants.error: multiple repeat</p> </blockquote> <p>I have to admit I do not know why, but again, I am new to Python and Regular Expressions. However, even when I don't use patterns and use a specific link (just to test the matching), I do not believe I return any matches (nothing is sent to the window when I print match.group(0). The link I tested is commented out below.</p> <p>Any ideas? It usually is easier for me to learn by example, but any advice you can give is greatly appreciated!</p> <p>Brock</p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup import re url = "http://forums.epicgames.com/archive/index.php?f-356-p-164.html" page = urllib2.urlopen(url).read() soup = BeautifulSoup(page) pattern = r'&lt;a href="http://forums.epicgames.com/archive/index.php?t-([0-9]+).html"&gt;(.?+)&lt;/a&gt; &lt;i&gt;((.?+) replies)' #pattern = r'href="http://forums.epicgames.com/archive/index.php?t-622233.html"&gt;Gears of War 2: Horde Gameplay&lt;/a&gt; &lt;i&gt;(20 replies)' for match in re.finditer(pattern, page, re.S): print match(0) </code></pre>
8
2009-08-12T21:15:29Z
1,268,804
<p>To extend on what others wrote:</p> <p>.? means "one or zero of any character"</p> <p>.+ means "one ore more of any character"</p> <p>As you can hopefully see, combining the two makes no sense; they are different and contradictory "repeat" characters. So, your error about "multiple repeats" is because you combined those two "repeat" characters in your regular expression. To fix it, just decide which one you actually meant to use, and delete the other.</p>
0
2009-08-12T21:24:03Z
[ "python", "regex" ]
Regex Matching Error
1,268,761
<p>I am new to Python (I dont have any programming training either), so please keep that in mind as I ask my question.</p> <p>I am trying to search a retrieved webpage and find all links using a specified pattern. I have done this successfully in other scripts, but I am getting an error that says </p> <blockquote> <pre><code>raise error, v # invalid expression </code></pre> <p>sre_constants.error: multiple repeat</p> </blockquote> <p>I have to admit I do not know why, but again, I am new to Python and Regular Expressions. However, even when I don't use patterns and use a specific link (just to test the matching), I do not believe I return any matches (nothing is sent to the window when I print match.group(0). The link I tested is commented out below.</p> <p>Any ideas? It usually is easier for me to learn by example, but any advice you can give is greatly appreciated!</p> <p>Brock</p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup import re url = "http://forums.epicgames.com/archive/index.php?f-356-p-164.html" page = urllib2.urlopen(url).read() soup = BeautifulSoup(page) pattern = r'&lt;a href="http://forums.epicgames.com/archive/index.php?t-([0-9]+).html"&gt;(.?+)&lt;/a&gt; &lt;i&gt;((.?+) replies)' #pattern = r'href="http://forums.epicgames.com/archive/index.php?t-622233.html"&gt;Gears of War 2: Horde Gameplay&lt;/a&gt; &lt;i&gt;(20 replies)' for match in re.finditer(pattern, page, re.S): print match(0) </code></pre>
8
2009-08-12T21:15:29Z
1,268,929
<p>As you're discovering, parsing arbitrary HTML is not easy to do correctly. That's what packages like Beautiful Soup do. Note, you're calling it in your script but then not using the results. Refer to its documentation <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20HTML" rel="nofollow">here</a> for examples of how to make your task a lot easier!</p>
1
2009-08-12T21:46:48Z
[ "python", "regex" ]
Regex Matching Error
1,268,761
<p>I am new to Python (I dont have any programming training either), so please keep that in mind as I ask my question.</p> <p>I am trying to search a retrieved webpage and find all links using a specified pattern. I have done this successfully in other scripts, but I am getting an error that says </p> <blockquote> <pre><code>raise error, v # invalid expression </code></pre> <p>sre_constants.error: multiple repeat</p> </blockquote> <p>I have to admit I do not know why, but again, I am new to Python and Regular Expressions. However, even when I don't use patterns and use a specific link (just to test the matching), I do not believe I return any matches (nothing is sent to the window when I print match.group(0). The link I tested is commented out below.</p> <p>Any ideas? It usually is easier for me to learn by example, but any advice you can give is greatly appreciated!</p> <p>Brock</p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup import re url = "http://forums.epicgames.com/archive/index.php?f-356-p-164.html" page = urllib2.urlopen(url).read() soup = BeautifulSoup(page) pattern = r'&lt;a href="http://forums.epicgames.com/archive/index.php?t-([0-9]+).html"&gt;(.?+)&lt;/a&gt; &lt;i&gt;((.?+) replies)' #pattern = r'href="http://forums.epicgames.com/archive/index.php?t-622233.html"&gt;Gears of War 2: Horde Gameplay&lt;/a&gt; &lt;i&gt;(20 replies)' for match in re.finditer(pattern, page, re.S): print match(0) </code></pre>
8
2009-08-12T21:15:29Z
1,268,976
<pre><code>import urllib2 import re from BeautifulSoup import BeautifulSoup url = "http://forums.epicgames.com/archive/index.php?f-356-p-164.html" page = urllib2.urlopen(url).read() soup = BeautifulSoup(page) # Get all the links links = [str(match) for match in soup('a')] s = r'&lt;a href="http://forums.epicgames.com/archive/index.php\?t-\d+.html"&gt;(.+?)&lt;/a&gt;' r = re.compile(s) for link in links: m = r.match(link) if m: print m.groups(1)[0] </code></pre>
0
2009-08-12T22:01:25Z
[ "python", "regex" ]
Really long query
1,268,899
<p>How do u do long query? Is there way to optimize it? I would do complicated and long query:</p> <pre><code>all_accepted_parts = acceptedFragment.objects.filter(fragmentID = fragment.objects.filter(categories = fragmentCategory.objects.filter(id=1))) </code></pre> <p>but it doesn't work, i get: </p> <pre><code>Error binding parameter 0 - probably unsupported type. </code></pre> <p>I will be thankful for any hint how i could optimize it or solve of course too - more thankful :)</p>
0
2009-08-12T21:41:22Z
1,269,024
<p>If it's not working, you can't optimize it. First make it work.</p> <p>At first glance, it seems that you have really mixed concepts about fields, relationships and equality/membership. First go thought the docs, and build your query piece by piece on the python shell (likely from the inside out).</p> <p>Just a shot in the dark:</p> <pre><code>all_accepted_parts = acceptedFragment.objects.filter(fragment__in = fragment.objects.filter(categories = fragmentCategory.objects.get(id=1))) </code></pre> <p>or maybe:</p> <pre><code>all_accepted_parts = acceptedFragment.objects.filter(fragment__in = fragment.objects.filter(categories = 1)) </code></pre>
4
2009-08-12T22:10:55Z
[ "python", "django", "django-models" ]
Really long query
1,268,899
<p>How do u do long query? Is there way to optimize it? I would do complicated and long query:</p> <pre><code>all_accepted_parts = acceptedFragment.objects.filter(fragmentID = fragment.objects.filter(categories = fragmentCategory.objects.filter(id=1))) </code></pre> <p>but it doesn't work, i get: </p> <pre><code>Error binding parameter 0 - probably unsupported type. </code></pre> <p>I will be thankful for any hint how i could optimize it or solve of course too - more thankful :)</p>
0
2009-08-12T21:41:22Z
1,269,125
<p>As others have said, we really need the models, and some explanation of what you're actually trying to achieve.</p> <p>But it looks like you want to do a related table lookup. Rather than getting all the related objects in a separate nested query, you should use Django's related model syntax to do the join within your query.</p> <p>Something like:</p> <pre><code>acceptedFragment.objects.filter(fragment__categories__id = 1) </code></pre>
4
2009-08-12T22:42:33Z
[ "python", "django", "django-models" ]
Python http proxy library based on libevent or comparable technology?
1,268,984
<p>I'm looking to build an intelligent reverse http proxy capable of routing, header examination and enrichment (eg. examine and build cookies and http headers), and various other fanciness. For a general idea of what I'm looking to build see <a href="http://www.igvita.com/2009/04/20/ruby-proxies-for-scale-and-monitoring/" rel="nofollow">Ruby Proxies for Scale and Monitoring</a> - except in Python.</p> <p>I realize that Twisted is an exceedingly good answer for this, and that eventmachine was inspired by Twisted, but I'm looking for something other than Twisted. </p> <p>Ideally a library or package that includes http proxying capabilities I could modify with my own little plugins.</p> <p>I remember seeing something based on eventlib that had http server capabilities built in, but I can't seem to find it.</p> <p>I'm also taking a deep look at perlbal; that looks almost like the perfect solution, except it's in Perl.</p> <p>Any recommendations?</p>
3
2009-08-12T22:02:30Z
1,269,155
<p>Not sure if meets all your needs, but <a href="http://pypi.python.org/pypi/proxylet/" rel="nofollow">proxylet</a> is a reverse proxy based on Linden Lab's <a href="http://eventlet.net/" rel="nofollow">eventlet</a>.</p>
3
2009-08-12T22:51:46Z
[ "python", "http", "proxy", "libevent" ]
InlineFormSet with queryset of different model
1,269,052
<p>What we're trying to do is populate a list of inline forms with initial values using some queryset of a different model. We have products, metrics (some category or type or rating), and a rating, which stores the actual rating and ties metrics to products.</p> <pre><code>class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(max_length=6) class Metric(models.Model): name = models.CharField(max_length=80) description = models.TextField() class Rating(models.Model) rating = models.IntegerField(max_length=3) metric = models.ForeignKey(Metric) product = models.ForeignKey(Product) </code></pre> <p>The end result we're going for is a list of all possible ratings for a Product on the Product admin page. If we have 20 Metrics in our database, when we go to the Product page we want to see 20 forms for Ratings on the page, each one tied to a different Metric. We can't use a queryset based on Ratings to populate the page, because the Rating for a particular Product/Metric combination might not yet exist.</p> <p>We've been looking at all the forms and formset code in Django, and are hoping to come up with a solution as simple as this:</p> <p><a href="http://www.thenestedfloat.com/articles/limiting-inline-admin-objects-in-django" rel="nofollow">http://www.thenestedfloat.com/articles/limiting-inline-admin-objects-in-django</a></p> <p>He just overrides something in BaseInlineFormSet and gives it to the inline. Maybe we can just make something like </p> <pre><code>class RatingInlineFormset(BaseInlineFormset): </code></pre> <p>With some overrides. Any ideas?</p>
1
2009-08-12T22:19:30Z
1,843,537
<p>Are you looking for an admin or front-end solution? The admin way is the following, you could reverse engineer it to get a similar front-end solution:</p> <pre><code># admin.py class RatingInline(admin.StackedInline): model = Rating class ProductAdmin(admin.ModelAdmin): inlines = [ RatingInline ] class MetricAdmin(admin.ModelAdmin): pass class RatingAdmin(admin.ModelAdmin): pass admin.site.register(Product, ProductAdmin) admin.site.register(Metric, MetricAdmin) admin.site.register(Rating, RatingAdmin) </code></pre>
0
2009-12-03T22:42:49Z
[ "python", "django", "forms", "django-admin", "django-forms" ]
InlineFormSet with queryset of different model
1,269,052
<p>What we're trying to do is populate a list of inline forms with initial values using some queryset of a different model. We have products, metrics (some category or type or rating), and a rating, which stores the actual rating and ties metrics to products.</p> <pre><code>class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(max_length=6) class Metric(models.Model): name = models.CharField(max_length=80) description = models.TextField() class Rating(models.Model) rating = models.IntegerField(max_length=3) metric = models.ForeignKey(Metric) product = models.ForeignKey(Product) </code></pre> <p>The end result we're going for is a list of all possible ratings for a Product on the Product admin page. If we have 20 Metrics in our database, when we go to the Product page we want to see 20 forms for Ratings on the page, each one tied to a different Metric. We can't use a queryset based on Ratings to populate the page, because the Rating for a particular Product/Metric combination might not yet exist.</p> <p>We've been looking at all the forms and formset code in Django, and are hoping to come up with a solution as simple as this:</p> <p><a href="http://www.thenestedfloat.com/articles/limiting-inline-admin-objects-in-django" rel="nofollow">http://www.thenestedfloat.com/articles/limiting-inline-admin-objects-in-django</a></p> <p>He just overrides something in BaseInlineFormSet and gives it to the inline. Maybe we can just make something like </p> <pre><code>class RatingInlineFormset(BaseInlineFormset): </code></pre> <p>With some overrides. Any ideas?</p>
1
2009-08-12T22:19:30Z
8,985,270
<p>I have managed to implement similar functionality a bit like this:</p> <pre><code>from django.forms.models import BaseInlineFormSet from django.forms.models import inlineformset_factory class RawQueryAdapter(object): """ Implement some extra methods to make a RawQuery compatible with FormSet, which is expecting a QuerySet """ ordered = True def __init__(self, qs): self.qs = qs self.db = qs.db def filter(self, *args, **kwargs): return self def __len__(self): return len(list(self.qs)) def __getitem__(self, key): return self.qs[key] class BaseRatingFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): sql = """ SELECT r.id, %s as product_id, m.id as metric_id FROM myapp_metric m LEFT JOIN myapp_rating r ON m.id = r.metric_id AND r.product_id = %s """ id = kwargs['instance'].id or 'NULL' qs = RawQueryAdapter(Rating.objects.raw(sql % (id, id))) super(BaseRatingFormSet, self).__init__(queryset=qs, *args, **kwargs) def _construct_form(self, i, **kwargs): pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name) if self.data.get(pk_key) == '': # Skip parent (BaseModelFormSet) implementation as it won't work # with our injected raw data if i &lt; self.initial_form_count() and not kwargs.get('instance'): kwargs['instance'] = self.get_queryset()[i] return super(BaseModelFormSet, self)._construct_form(i, **kwargs) return super(BaseRatingFormSet, self)._construct_form(i, **kwargs) RatingFormSet = inlineformset_factory( Product, Rating, can_delete=False, max_num=0, formset=BaseRatingFormSet, ) </code></pre> <p>EDIT: The condition must be done in the LEFT JOIN, not the WHERE, otherwise you will have missing lines.</p>
0
2012-01-24T10:32:13Z
[ "python", "django", "forms", "django-admin", "django-forms" ]
Calling a base class's classmethod in Python
1,269,217
<p>Consider the following code:</p> <pre><code>class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cls, a): print 'In derived!' # Base.do(cls, a) -- can't pass `cls` Base.do(a) if __name__ == '__main__': d = Derived() d.do('hello') &gt; $ python play.py &gt; In derived! &gt; &lt;class '__main__.Base'&gt; msg </code></pre> <p>From <code>Derived.do</code>, how do I call <code>Base.do</code>? I would normally use <code>super</code> or even the base class name directly if this is a normal object method, but apparently I can't find a way to call the classmethod in the base class. In the above example, <code>Base.do(a)</code> prints <code>Base</code> class instead of <code>Derived</code> class.</p>
56
2009-08-12T23:07:22Z
1,269,224
<pre><code>super(Derived, cls).do(a) </code></pre> <p><em>EDIT</em>: Oh, wait a minute... it's not clear exactly what you're asking. This is how you would invoke the code in the base class's version of the method, from the derived class.</p>
64
2009-08-12T23:09:50Z
[ "python", "class", "overriding", "class-method" ]
Calling a base class's classmethod in Python
1,269,217
<p>Consider the following code:</p> <pre><code>class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cls, a): print 'In derived!' # Base.do(cls, a) -- can't pass `cls` Base.do(a) if __name__ == '__main__': d = Derived() d.do('hello') &gt; $ python play.py &gt; In derived! &gt; &lt;class '__main__.Base'&gt; msg </code></pre> <p>From <code>Derived.do</code>, how do I call <code>Base.do</code>? I would normally use <code>super</code> or even the base class name directly if this is a normal object method, but apparently I can't find a way to call the classmethod in the base class. In the above example, <code>Base.do(a)</code> prints <code>Base</code> class instead of <code>Derived</code> class.</p>
56
2009-08-12T23:07:22Z
1,269,233
<p>This works for me:</p> <pre><code>Base.do('hi') </code></pre>
0
2009-08-12T23:12:48Z
[ "python", "class", "overriding", "class-method" ]
Calling a base class's classmethod in Python
1,269,217
<p>Consider the following code:</p> <pre><code>class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cls, a): print 'In derived!' # Base.do(cls, a) -- can't pass `cls` Base.do(a) if __name__ == '__main__': d = Derived() d.do('hello') &gt; $ python play.py &gt; In derived! &gt; &lt;class '__main__.Base'&gt; msg </code></pre> <p>From <code>Derived.do</code>, how do I call <code>Base.do</code>? I would normally use <code>super</code> or even the base class name directly if this is a normal object method, but apparently I can't find a way to call the classmethod in the base class. In the above example, <code>Base.do(a)</code> prints <code>Base</code> class instead of <code>Derived</code> class.</p>
56
2009-08-12T23:07:22Z
5,682,347
<p>this has been a while, but I think I may have found an answer. When you decorate a method to become a classmethod the original unbound method is stored in a property named 'im_func':</p> <pre><code>class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cls, a): print 'In derived!' # Base.do(cls, a) -- can't pass `cls` Base.do.im_func(cls, a) if __name__ == '__main__': d = Derived() d.do('hello') </code></pre>
8
2011-04-15T21:01:49Z
[ "python", "class", "overriding", "class-method" ]
Differences between Smalltalk and python?
1,269,242
<p>I'm studying Smalltalk right now. It looks very similar to python (actually, the opposite, python is very similar to Smalltalk), so I was wondering, as a python enthusiast, if it's really worth for me to study it.</p> <p>Apart from message passing, what are other notable conceptual differences between Smalltalk and python which could allow me to see new programming horizons ?</p>
8
2009-08-12T23:17:31Z
1,269,258
<p>In Python, the "basic" constructs such as <code>if/else</code>, short-circuiting boolean operators, and loops are part of the language itself. In Smalltalk, they are all just messages. In that sense, while both Python and Smalltalk agree that "everything is an object", Smalltalk goes further in that it also asserts that "everything is a message".</p> <p>[EDIT] Some examples.</p> <p>Conditional statement in Smalltalk:</p> <pre><code>((x &gt; y) and: [x &gt; z]) ifTrue: [ ... ] ifFalse: [ ... ] </code></pre> <p>Note how <code>and:</code> is just a message on <code>Boolean</code> (itself produced as a result of passing message <code>&gt;</code> to <code>x</code>), and the second argument of <code>and:</code> is not a plain expression, but a block, enabling lazy (i.e. short-circuiting) evaluation. This produces another <code>Boolean</code> object, which also supports the message <code>ifTrue:ifFalse:</code>, taking two more blocks (i.e. lambdas) as arguments, and running one or the other depending on the value of the Boolean.</p>
16
2009-08-12T23:24:01Z
[ "python", "smalltalk" ]
Differences between Smalltalk and python?
1,269,242
<p>I'm studying Smalltalk right now. It looks very similar to python (actually, the opposite, python is very similar to Smalltalk), so I was wondering, as a python enthusiast, if it's really worth for me to study it.</p> <p>Apart from message passing, what are other notable conceptual differences between Smalltalk and python which could allow me to see new programming horizons ?</p>
8
2009-08-12T23:17:31Z
1,269,259
<p>Smalltalk historically has had an amazing IDE built in. I have missed this IDE on many languages.</p> <p>Smalltalk also has the lovely property that it is typically in a living system. You start up clean and start modifying things. This is basically an object persistent storage system. That being said, this is both good and bad. What you run is part of your system and part of what you ship. The system can be setup quite nicely before being distributed. The down side, is that the system has everything you run as part of what you ship. You need to be very careful packaging for redistribution.</p> <p>Now, that being said, it has been a while since I have worked with Smalltalk (about 20 years). Yes, I know, fun times for those who do the math. Smalltalk is a nice language, fun to program in, fun to learn, but I have found it a little hard to ship things in.</p> <p>Enjoy playing with it if you do. I have been playing with Python and loving it.</p> <p>Jacob</p>
7
2009-08-12T23:24:14Z
[ "python", "smalltalk" ]
Differences between Smalltalk and python?
1,269,242
<p>I'm studying Smalltalk right now. It looks very similar to python (actually, the opposite, python is very similar to Smalltalk), so I was wondering, as a python enthusiast, if it's really worth for me to study it.</p> <p>Apart from message passing, what are other notable conceptual differences between Smalltalk and python which could allow me to see new programming horizons ?</p>
8
2009-08-12T23:17:31Z
1,269,266
<p>The language aspect often isn't that important, and many languages are quite <em>samey</em>,</p> <p>From what I see, Python and Smalltalk share OOP ideals ... but are very different in their implementation and the power in the presented language interface.</p> <p>the real value comes in what the <em>subtle</em> differences in the syntax allows in terms of <strong>implementation</strong>. Take a look at Self and other meta-heavy languages.</p> <p>Look past the syntax and immediate semantics to what the subtle differences allow the implementation to do.</p> <p>For example:</p> <blockquote> <p>Everything in Smalltalk-80 is available for modification from within a running program</p> </blockquote> <p>What differences between Python and Smalltalk allow deeper maniplation if any? How does the language enable the implementation of the compiler/runtime?</p>
2
2009-08-12T23:25:26Z
[ "python", "smalltalk" ]
Differences between Smalltalk and python?
1,269,242
<p>I'm studying Smalltalk right now. It looks very similar to python (actually, the opposite, python is very similar to Smalltalk), so I was wondering, as a python enthusiast, if it's really worth for me to study it.</p> <p>Apart from message passing, what are other notable conceptual differences between Smalltalk and python which could allow me to see new programming horizons ?</p>
8
2009-08-12T23:17:31Z
1,271,000
<p>As someone new to smalltalk, the two things that really strike me are the image-based system, and that reflection is everywhere. These two simple facts appear to give rise to everything else cool in the system:</p> <ul> <li>The image means that you do everything by manipulating objects, including writing and compiling code</li> <li>Reflection allows you to inspect the state of any object. Since classes are objects and their sources are objects, you can inspect and manipulate code</li> <li>You have access to the current execution context, so you can have a look at the stack, and from there, compiled code and the source of that code and so on</li> <li>The stack is an object, so you can save it away and then resume later. Bingo, continuations!</li> </ul> <p>All of the above starts to come together in cool ways:</p> <ul> <li>The browser lets you explore the source of literally everything, including the VM in Squeak</li> <li>You can make changes that affect your live program, so there's no need to restart and navigate your way through to whatever you're working on</li> <li>Even better, when your program throws an exception you can debug the live code. You fix the bug, update the state if it's become inconsistent and then have your program continue.</li> <li>The browser will tell you if it thinks you've made a typo</li> <li>It's absurdly easy to browse up and down the class hierarchy, or find out what messages a object responds to, or which code sends a given message, or which objects can receive a given message</li> <li>You can inspect and manipulate the state of any object in the system</li> <li>You can make any two objects literally switch places with become:, which lets you do crazy stuff like stub out any object and then lazily pull it in from elsewhere if it's sent a message.</li> </ul> <p>The image system and reflection has made all of these perfectly natural and normal things for a smalltalker for about thirty years.</p>
9
2009-08-13T09:34:40Z
[ "python", "smalltalk" ]
Differences between Smalltalk and python?
1,269,242
<p>I'm studying Smalltalk right now. It looks very similar to python (actually, the opposite, python is very similar to Smalltalk), so I was wondering, as a python enthusiast, if it's really worth for me to study it.</p> <p>Apart from message passing, what are other notable conceptual differences between Smalltalk and python which could allow me to see new programming horizons ?</p>
8
2009-08-12T23:17:31Z
33,929,812
<p>The Smalltalk language itself is very important. It comprises a small set of powerful, orthogonal features that makes the language highly extensible. As Alan Lovejoy says: "Smalltalk is also fun because defining and using <em>domain specific languages</em> isn’t an afterthought, it’s the only way Smalltalk works at all." The language notation is critically important because: "Differences in the expressive power of the programming notation used do matter." For more, read the full article <a href="https://medium.com/smalltalk-talk/getting-the-message-667d77ff78d" rel="nofollow">here</a>.</p>
0
2015-11-26T02:49:51Z
[ "python", "smalltalk" ]
In GTK, is there an easy way to scale all widgets by an arbitrary amount?
1,269,268
<p>I want my widget to look exactly like it does now, except to be smaller. It includes buttons, labels, text, images, etc. Is there any way to just say "scale this to be half the size", and have GTK do all the image processing, widget resizing, etc., necessary? If not, what's the easiest way to accomplish this?</p>
0
2009-08-12T23:25:54Z
1,269,286
<p>There is no built in way to do this. To do this, you'll have to consider what is "taking up space" in your ui, and how to reduce it.</p> <p>If your UI is mostly text and images, you can use a smaller font size, then scale all images down by an appropriate percentage. The widget sizing will shrink automatically once the text and images that they are displaying shrinks (unless you've done Bad Things like hardcode heights/widths, use GtkFixed, etc).</p> <p>The tricky part will be determining the relationship between font point size and image scale.</p> <p>EDIT:</p> <p><a href="http://mail.python.org/pipermail/python-list/2004-September/279618.html" rel="nofollow">Here's a post about the pygtk syntax to change the font size</a>.</p>
1
2009-08-12T23:29:55Z
[ "python", "user-interface", "gtk", "pygtk" ]
In GTK, is there an easy way to scale all widgets by an arbitrary amount?
1,269,268
<p>I want my widget to look exactly like it does now, except to be smaller. It includes buttons, labels, text, images, etc. Is there any way to just say "scale this to be half the size", and have GTK do all the image processing, widget resizing, etc., necessary? If not, what's the easiest way to accomplish this?</p>
0
2009-08-12T23:25:54Z
1,283,493
<p>Change the theme from the user interface is not something that I recommend, but you can do it if you require it, using a custom gtkrc may help you to change the font and the way the buttons are drawed, mostly because of the xthickness and ythickness.</p> <pre><code> import gtk file = "/path/to/the/gtkrc" gtk.rc_parse(file) gtk.rc_add_default_file(file) gtk.rc_reparse_all() </code></pre> <p>And the custom gtkrc may look like this:</p> <pre><code>gtk_color_scheme = "fg_color:#ECE9E9;bg_color:#ECE9E9;base_color:#FFFFFF;text_color:#000000;selected_bg_color:#008DD7;selected_fg_color:#FFFFFF;tooltip_bg_color:#000000;tooltip_fg_color:#F5F5B5" style "theme-fixes" { fg[NORMAL] = @fg_color fg[PRELIGHT] = @fg_color fg[SELECTED] = @selected_fg_color fg[ACTIVE] = @fg_color fg[INSENSITIVE] = darker (@bg_color) bg[NORMAL] = @bg_color bg[PRELIGHT] = shade (1.02, @bg_color) bg[SELECTED] = @selected_bg_color bg[INSENSITIVE] = @bg_color bg[ACTIVE] = shade (0.9, @bg_color) base[NORMAL] = @base_color base[PRELIGHT] = shade (0.95, @bg_color) base[ACTIVE] = shade (0.9, @selected_bg_color) base[SELECTED] = @selected_bg_color base[INSENSITIVE] = @bg_color text[NORMAL] = @text_color text[PRELIGHT] = @text_color text[ACTIVE] = @selected_fg_color text[SELECTED] = @selected_fg_color text[INSENSITIVE] = darker (@bg_color) GtkTreeView::odd_row_color = shade (0.929458256, @base_color) GtkTreeView::even_row_color = @base_color GtkTreeView::horizontal-separator = 12 font_name = "Helvetica World 7" } class "*" style "theme-fixes" </code></pre>
2
2009-08-16T05:12:15Z
[ "python", "user-interface", "gtk", "pygtk" ]
In GTK, is there an easy way to scale all widgets by an arbitrary amount?
1,269,268
<p>I want my widget to look exactly like it does now, except to be smaller. It includes buttons, labels, text, images, etc. Is there any way to just say "scale this to be half the size", and have GTK do all the image processing, widget resizing, etc., necessary? If not, what's the easiest way to accomplish this?</p>
0
2009-08-12T23:25:54Z
1,283,503
<p>Having written a 100% scalable gtk app, what I did was limit myself to gdk_draw_line, and gdk_draw_rectangle, which were easy to then scale myself. Text was "done" via gdk_draw_line. (for certain low values of "done.") See: <a href="http://wordwarvi.sourceforge.net" rel="nofollow">http://wordwarvi.sourceforge.net</a></p> <p>Not that it helps you any, I'm guessing.</p>
0
2009-08-16T05:24:10Z
[ "python", "user-interface", "gtk", "pygtk" ]
In GTK, is there an easy way to scale all widgets by an arbitrary amount?
1,269,268
<p>I want my widget to look exactly like it does now, except to be smaller. It includes buttons, labels, text, images, etc. Is there any way to just say "scale this to be half the size", and have GTK do all the image processing, widget resizing, etc., necessary? If not, what's the easiest way to accomplish this?</p>
0
2009-08-12T23:25:54Z
1,309,447
<p>Resolution independence has been worked on by some gtk devs, and here is an update with a very big patch to introduce it into GTK. The patch is however a year old now and it is still unclear how/when/if it is going to be included: (screenshots at the end)</p> <p><a href="http://mail.gnome.org/archives/gtk-devel-list/2008-August/msg00044.html" rel="nofollow">http://mail.gnome.org/archives/gtk-devel-list/2008-August/msg00044.html</a></p>
2
2009-08-20T23:49:45Z
[ "python", "user-interface", "gtk", "pygtk" ]
Scale an image in GTK
1,269,320
<p>In GTK, how can I scale an image? Right now I load images with PIL and scale them beforehand, but is there a way to do it with GTK?</p>
11
2009-08-12T23:44:38Z
1,283,486
<p>Load the image from a file using gtk.gdk.Pixbuf for that:</p> <pre><code>import gtk pixbuf = gtk.gdk.pixbuf_new_from_file('/path/to/the/image.png') </code></pre> <p>then scale it:</p> <pre><code>pixbuf = pixbuf.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR) </code></pre> <p>Then, if you want use it in a gtk.Image, crate the widget and set the image from the pixbuf.</p> <pre><code>image = gkt.Image() image.set_from_pixbuf(pixbuf) </code></pre> <p>Or maybe in a direct way:</p> <pre><code>image = gtk.image_new_from_pixbuf(pixbuf) </code></pre>
10
2009-08-16T05:06:11Z
[ "python", "user-interface", "image", "gtk", "pygtk" ]
Scale an image in GTK
1,269,320
<p>In GTK, how can I scale an image? Right now I load images with PIL and scale them beforehand, but is there a way to do it with GTK?</p>
11
2009-08-12T23:44:38Z
1,309,462
<p>It might be more effective to simply scale them before loading. I especially think so since I use these functions to load in 96x96 thumbnails from sometimes very large JPEGs, still very fast.</p> <pre><code>gtk.gdk.pixbuf_new_from_file_at_scale(..) gtk.gdk.pixbuf_new_from_file_at_size(..) </code></pre>
6
2009-08-20T23:55:21Z
[ "python", "user-interface", "image", "gtk", "pygtk" ]
Scale an image in GTK
1,269,320
<p>In GTK, how can I scale an image? Right now I load images with PIL and scale them beforehand, but is there a way to do it with GTK?</p>
11
2009-08-12T23:44:38Z
19,303,924
<p>Scale image from URL. ( <a href="http://www.pygtk.org/docs/pygtk/class-gdkpixbufloader.html#method-gdkpixbufloader--set-size" rel="nofollow">scale reference</a> )</p> <pre><code>import pygtk pygtk.require('2.0') import gtk import urllib2 class MainWin: def destroy(self, widget, data=None): print "destroy signal occurred" gtk.main_quit() def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect("destroy", self.destroy) self.window.set_border_width(10) self.image=gtk.Image() self.response=urllib2.urlopen( 'http://192.168.1.11/video/1024x768.jpeg') self.loader=gtk.gdk.PixbufLoader() self.loader.set_size(200, 100) #### works but throwing: glib.GError: Unrecognized image file format self.loader.write(self.response.read()) self.loader.close() self.image.set_from_pixbuf(self.loader.get_pixbuf()) self.window.add(self.image) self.image.show() self.window.show() def main(self): gtk.main() if __name__ == "__main__": MainWin().main() </code></pre> <p>*<strong>EDIT: (work out fix) *</strong></p> <pre><code>try: self.loader=gtk.gdk.PixbufLoader() self.loader.set_size(200, 100) # ignore tihs: # glib.GError: Unrecognized image file format self.loader.write(self.response.read()) self.loader.close() self.image.set_from_pixbuf(self.loader.get_pixbuf()) except Exception, err: print err pass </code></pre>
1
2013-10-10T18:52:13Z
[ "python", "user-interface", "image", "gtk", "pygtk" ]
How can I change the font size in GTK?
1,269,326
<p>Is there an easy way to change the font size of text elements in GTK? Right now the best I can do is do <code>set_markup</code> on a label, with something silly like:</p> <pre><code>lbl.set_markup("&lt;span font_desc='Tahoma 5.4'&gt;%s&lt;/span&gt;" % text) </code></pre> <p>This 1) requires me to set the font , 2) seems like a lot of overhead (having to parse the markup), and 3) would make it annoying to change the font size of buttons and such. Is there a better way?</p>
1
2009-08-12T23:46:40Z
1,269,338
<p>In C, you can do:</p> <pre><code>gtk_widget_modify_font(lbl, pango_font_description_from_string("Tahoma 5.4")); </code></pre> <p>In PyGTK, I believe it's something like:</p> <pre><code>pangoFont = pango.FontDescription("Tahoma 5.4") lbl.modify_font(pangoFont) </code></pre>
3
2009-08-12T23:52:32Z
[ "python", "fonts", "gtk", "pygtk", "gtk2" ]
How can I change the font size in GTK?
1,269,326
<p>Is there an easy way to change the font size of text elements in GTK? Right now the best I can do is do <code>set_markup</code> on a label, with something silly like:</p> <pre><code>lbl.set_markup("&lt;span font_desc='Tahoma 5.4'&gt;%s&lt;/span&gt;" % text) </code></pre> <p>This 1) requires me to set the font , 2) seems like a lot of overhead (having to parse the markup), and 3) would make it annoying to change the font size of buttons and such. Is there a better way?</p>
1
2009-08-12T23:46:40Z
1,269,367
<p>If you want to change font overall in your app(s), I'd leave this job to gtkrc (then becomes a google question, and "gtkrc font" query brings us to <a href="http://ubuntuforums.org/showthread.php?t=846348">this ubuntu forums link</a> which has the following snippet of the the gtkrc file):</p> <pre><code>style "font" { font_name = "Corbel 8" } widget_class "*" style "font" gtk-font-name = "Corbel 8" </code></pre> <p>(replace the font with the one you/user need)</p> <p>Then the user will get consistent experience and will be able to change the settings easily without need for them to poke in the code and without you needing to handle the overhead of maintaining your personal configuration-related code. I understand you can make this setting more specific if you have a more precise definition for the widget_class.</p> <p>YMMV for different platforms, but AFAIK this file is always present at some location if GTK is being used, and allows to the user to be in charge of presentation details.</p>
6
2009-08-13T00:02:07Z
[ "python", "fonts", "gtk", "pygtk", "gtk2" ]
Python threading question - returning control to parent
1,269,466
<p>Basically, I have a python program which listens for DeviceAdded DBus events (e.g. when someone plugs in a USB drive), and when an event occurs, I want to create a thread which collects metadata on that newly connected device. However, I want to do this asynchronously - that is, allow one thread to keep collecting metadata on the device while returning control to the parent which can keep listening for these events. At the moment, my thread blocks until the collection is finished. Here is a sample of my code:</p> <pre><code>class DeviceAddedListener: def __init__(self): self.bus = dbus.SystemBus() self.hal_manager_obj = self.bus.get_object("org.freedesktop.Hal", "/org$ self.hal_manager = dbus.Interface(self.hal_manager_obj, "org.freedeskto$ self.hal_manager.connect_to_signal("DeviceAdded", self._filter) def _filter(self, udi): device_obj = self.bus.get_object ("org.freedesktop.Hal", udi) device = dbus.Interface(device_obj, "org.freedesktop.Hal.Device") if device.QueryCapability("volume"): return self.capture(device) def capture(self,volume): self.device_file = volume.GetProperty("block.device") self.label = volume.GetProperty("volume.label") self.fstype = volume.GetProperty("volume.fstype") self.mounted = volume.GetProperty("volume.is_mounted") self.mount_point = volume.GetProperty("volume.mount_point") try: self.size = volume.GetProperty("volume.size") except: self.size = 0 print "New storage device detected:" print " device_file: %s" % self.device_file print " label: %s" % self.label print " fstype: %s" % self.fstype if self.mounted: print " mount_point: %s" % self.mount_point response = raw_input("\nWould you like to acquire %s [y/N]? " % self.device_file) if (response == "y"): self.get_meta() thread.start_new_thread(DoSomething(self.device_file)) else: print "Returning to idle" if __name__ == '__main__': from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) loop = gobject.MainLoop() DeviceAddedListener() loop.run() </code></pre> <p>Any thoughts would be greatly appreciated :) I have excluded the import list to save space</p>
0
2009-08-13T00:37:30Z
1,269,514
<p>Try spawning a thread just for the capture stuff, by changing the following lines in your <code>_filter()</code> function to this:</p> <pre><code>if device.QueryCapability("volume"): threading.start_new_thread(self.capture, (device)) </code></pre> <p>This is assuming that the bulk of the work is happening in the <code>capture()</code> function. If not, then just spawn the thread a little earlier, possibly on the whole <code>_filter()</code> function. This should then spawn a new thread for every filtered device detected. Bear in mind that I haven't done any dbus stuff and can't really test this, but it's an idea.</p> <p>Also, you're trying to get user input from the capture function which, using the app as you've defined it, isn't really a nice thing to do in threads. What if a second device is connected while the first prompt is still on screen? Might not play nicely.</p> <p>The design of this thing might be exactly the way you want it for specific reasons, but I can't help feeling like it could be a lot slicker. It's not really designed with threads in mind from what I can tell.</p>
2
2009-08-13T00:53:12Z
[ "python", "multithreading", "dbus" ]