title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
wxPython: Good way to overlay a wx.Panel on an existing wx.Panel
1,032,138
<p>I have a wx.Frame, in which there is a main wx.Panel with several widgets inside of it. I want one button in there to cause a "help panel" to come up. This help panel would probably be a wx.Panel, and I want it to overlay the entire main wx.Panel (not including the menu bar of the wx.Frame). There should be some sort of close button on the help button that will make it disappear again.</p> <p>What is a good way to achieve this? I've looked into wx.Notebook but haven't found a way to make it not show the tabs.</p> <p>Note that I don't want to destroy and recreate the help panel every time the user closes and opens it: I just want it to be hidden.</p>
4
2009-06-23T12:04:54Z
1,032,282
<p>There are several ways</p> <p>a) you can create a custom child panel, and make it same size and position at 0,0 among top of all child widgets. no need of destroying it just Show/Hide it this also resizes with parent frame</p> <p>b) popup a wx.PopupWindow or derived class and place and size it at correct location</p> <p>so as suggest in a) here is an example, where all controls are put in panel using sizer, as separate help cntrl is created which can be shown/hidden from button, but you can create a custom cntrl which hides itself on clicking close</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.panel = wx.Panel(self) # create controls self.cntrlPanel = wx.Panel(self.panel) stc1 = wx.StaticText(self.cntrlPanel, label="wow it works") stc2 = wx.StaticText(self.cntrlPanel, label="yes it works") btn = wx.Button(self.cntrlPanel, label="help?") btn.Bind(wx.EVT_BUTTON, self._onShowHelp) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(stc1) sizer.Add(stc2) sizer.Add(btn) self.cntrlPanel.SetSizer(sizer) # create help panel self.helpPanel = wx.Panel(self.panel) self.stcHelp = wx.StaticText(self.helpPanel, label="help help help\n"*8) btn = wx.Button(self.helpPanel, label="close[x]") btn.Bind(wx.EVT_BUTTON, self._onShowCntrls) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.stcHelp) sizer.Add(btn) self.helpPanel.SetSizer(sizer) self.helpPanel.Hide() self.helpPanel.Raise() self.helpPanel.SetBackgroundColour((240,250,240)) self.Bind(wx.EVT_SIZE, self._onSize) self._onShowCntrls(None) def _onShowHelp(self, event): self.helpPanel.SetPosition((0,0)) self.helpPanel.Show() self.cntrlPanel.Hide() def _onShowCntrls(self, event): self.cntrlPanel.SetPosition((0,0)) self.helpPanel.Hide() self.cntrlPanel.Show() def _onSize(self, event): event.Skip() self.helpPanel.SetSize(self.GetClientSizeTuple()) self.cntrlPanel.SetSize(self.GetClientSizeTuple()) app = wx.PySimpleApp() frame = MyFrame() frame.Show() app.SetTopWindow(frame) app.MainLoop() </code></pre>
10
2009-06-23T12:36:25Z
[ "python", "user-interface", "wxpython" ]
Python: finding keys with unique values in a dictionary?
1,032,281
<p>I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.</p> <p>I will clarify with an example. Say my input is dictionary a, constructed as follows:</p> <pre><code>a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # &lt;-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # &lt;-- unique a['wallaby'] = 5 a['badger'] = 5 </code></pre> <p>The result I expect is <code>['dog', 'snake']</code>.</p> <p>There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.</p>
14
2009-06-23T12:35:47Z
1,032,335
<p>Note that this actually is a bruteforce:</p> <pre><code>l = a.values() b = [x for x in a if l.count(a[x]) == 1] </code></pre>
5
2009-06-23T12:43:40Z
[ "python", "dictionary" ]
Python: finding keys with unique values in a dictionary?
1,032,281
<p>I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.</p> <p>I will clarify with an example. Say my input is dictionary a, constructed as follows:</p> <pre><code>a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # &lt;-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # &lt;-- unique a['wallaby'] = 5 a['badger'] = 5 </code></pre> <p>The result I expect is <code>['dog', 'snake']</code>.</p> <p>There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.</p>
14
2009-06-23T12:35:47Z
1,032,429
<p>You could do something like this (just count the number of occurrences for each value):</p> <pre><code>def unique(a): from collections import defaultdict count = defaultdict(lambda: 0) for k, v in a.iteritems(): count[v] += 1 for v, c in count.iteritems(): if c &lt;= 1: yield v </code></pre>
-1
2009-06-23T12:59:49Z
[ "python", "dictionary" ]
Python: finding keys with unique values in a dictionary?
1,032,281
<p>I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.</p> <p>I will clarify with an example. Say my input is dictionary a, constructed as follows:</p> <pre><code>a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # &lt;-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # &lt;-- unique a['wallaby'] = 5 a['badger'] = 5 </code></pre> <p>The result I expect is <code>['dog', 'snake']</code>.</p> <p>There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.</p>
14
2009-06-23T12:35:47Z
1,032,444
<p>I think efficient way if dict is too large would be</p> <pre><code>countMap = {} for v in a.itervalues(): countMap[v] = countMap.get(v,0) + 1 uni = [ k for k, v in a.iteritems() if countMap[v] == 1] </code></pre>
12
2009-06-23T13:02:44Z
[ "python", "dictionary" ]
Python: finding keys with unique values in a dictionary?
1,032,281
<p>I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.</p> <p>I will clarify with an example. Say my input is dictionary a, constructed as follows:</p> <pre><code>a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # &lt;-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # &lt;-- unique a['wallaby'] = 5 a['badger'] = 5 </code></pre> <p>The result I expect is <code>['dog', 'snake']</code>.</p> <p>There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.</p>
14
2009-06-23T12:35:47Z
1,032,491
<pre><code>&gt;&gt;&gt; b = [] &gt;&gt;&gt; import collections &gt;&gt;&gt; bag = collections.defaultdict(lambda: 0) &gt;&gt;&gt; for v in a.itervalues(): ... bag[v] += 1 ... &gt;&gt;&gt; b = [k for (k, v) in a.iteritems() if bag[v] == 1] &gt;&gt;&gt; b.sort() # optional &gt;&gt;&gt; print b ['dog', 'snake'] &gt;&gt;&gt; </code></pre>
4
2009-06-23T13:10:45Z
[ "python", "dictionary" ]
Python: finding keys with unique values in a dictionary?
1,032,281
<p>I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.</p> <p>I will clarify with an example. Say my input is dictionary a, constructed as follows:</p> <pre><code>a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # &lt;-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # &lt;-- unique a['wallaby'] = 5 a['badger'] = 5 </code></pre> <p>The result I expect is <code>['dog', 'snake']</code>.</p> <p>There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.</p>
14
2009-06-23T12:35:47Z
1,032,572
<p>Use nested list comprehensions!</p> <pre><code>print [v[0] for v in dict([(v, [k for k in a.keys() if a[k] == v]) for v in set(a.values())]).values() if len(v) == 1] </code></pre>
-2
2009-06-23T13:26:10Z
[ "python", "dictionary" ]
Python: finding keys with unique values in a dictionary?
1,032,281
<p>I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.</p> <p>I will clarify with an example. Say my input is dictionary a, constructed as follows:</p> <pre><code>a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # &lt;-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # &lt;-- unique a['wallaby'] = 5 a['badger'] = 5 </code></pre> <p>The result I expect is <code>['dog', 'snake']</code>.</p> <p>There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.</p>
14
2009-06-23T12:35:47Z
1,032,575
<p>Here's another variation.</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; inverse= collections.defaultdict(list) &gt;&gt;&gt; for k,v in a.items(): ... inverse[v].append(k) ... &gt;&gt;&gt; [ v[0] for v in inverse.values() if len(v) == 1 ] ['dog', 'snake'] </code></pre> <p>I'm partial to this because the inverted dictionary is such a common design pattern.</p>
0
2009-06-23T13:27:12Z
[ "python", "dictionary" ]
Python: finding keys with unique values in a dictionary?
1,032,281
<p>I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.</p> <p>I will clarify with an example. Say my input is dictionary a, constructed as follows:</p> <pre><code>a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # &lt;-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # &lt;-- unique a['wallaby'] = 5 a['badger'] = 5 </code></pre> <p>The result I expect is <code>['dog', 'snake']</code>.</p> <p>There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.</p>
14
2009-06-23T12:35:47Z
1,032,583
<p>Here is a solution that only requires traversing the dict once:</p> <pre><code>def unique_values(d): seen = {} # dict (value, key) result = set() # keys with unique values for k,v in d.iteritems(): if v in seen: result.discard(seen[v]) else: seen[v] = k result.add(k) return list(result) </code></pre>
5
2009-06-23T13:29:07Z
[ "python", "dictionary" ]
Python: finding keys with unique values in a dictionary?
1,032,281
<p>I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.</p> <p>I will clarify with an example. Say my input is dictionary a, constructed as follows:</p> <pre><code>a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # &lt;-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # &lt;-- unique a['wallaby'] = 5 a['badger'] = 5 </code></pre> <p>The result I expect is <code>['dog', 'snake']</code>.</p> <p>There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.</p>
14
2009-06-23T12:35:47Z
1,032,615
<p>A little more verbose, but does need only one pass over a:</p> <pre><code>revDict = {} for k, v in a.iteritems(): if v in revDict: revDict[v] = None else: revDict[v] = k [ x for x in revDict.itervalues() if x != None ] </code></pre> <p>( I hope it works, since I can't test it here )</p>
2
2009-06-23T13:33:54Z
[ "python", "dictionary" ]
Python: finding keys with unique values in a dictionary?
1,032,281
<p>I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.</p> <p>I will clarify with an example. Say my input is dictionary a, constructed as follows:</p> <pre><code>a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # &lt;-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # &lt;-- unique a['wallaby'] = 5 a['badger'] = 5 </code></pre> <p>The result I expect is <code>['dog', 'snake']</code>.</p> <p>There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.</p>
14
2009-06-23T12:35:47Z
1,032,951
<p>What about subclassing? </p> <pre><code>class UniqueValuesDict(dict): def __init__(self, *args): dict.__init__(self, *args) self._inverse = {} def __setitem__(self, key, value): if value in self.values(): if value in self._inverse: del self._inverse[value] else: self._inverse[value] = key dict.__setitem__(self, key, value) def unique_values(self): return self._inverse.values() a = UniqueValuesDict() a['cat'] = 1 a['fish'] = 1 a[None] = 1 a['duck'] = 1 a['dog'] = 2 # &lt;-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # &lt;-- unique a['wallaby'] = 5 a['badger'] = 5 assert a.unique_values() == ['dog', 'snake'] </code></pre>
2
2009-06-23T14:35:02Z
[ "python", "dictionary" ]
Python Formatter Tool
1,032,393
<p>I was wondering if there exists a sort of Python beautifier like the gnu-indent command line tool for C code. Of course indentation is not the point in Python since it is programmer's responsibility but I wish to get my code written in a perfectly homogenous way, taking care particularly of having always identical blank space between operands or after and before separators and between blocks.</p>
24
2009-06-23T12:53:52Z
1,032,414
<p><a href="http://freshmeat.net/projects/pylint/" rel="nofollow">PyLint</a> has some formatting checks.</p>
1
2009-06-23T12:57:13Z
[ "python", "formatter" ]
Python Formatter Tool
1,032,393
<p>I was wondering if there exists a sort of Python beautifier like the gnu-indent command line tool for C code. Of course indentation is not the point in Python since it is programmer's responsibility but I wish to get my code written in a perfectly homogenous way, taking care particularly of having always identical blank space between operands or after and before separators and between blocks.</p>
24
2009-06-23T12:53:52Z
1,032,415
<p>Have you looked at <a href="http://www.koders.com/python/fid66946EDA1E4704E4DE82C3385E16309B10C0C683.aspx?s=md5" rel="nofollow">pindent</a>?</p>
1
2009-06-23T12:57:14Z
[ "python", "formatter" ]
Python Formatter Tool
1,032,393
<p>I was wondering if there exists a sort of Python beautifier like the gnu-indent command line tool for C code. Of course indentation is not the point in Python since it is programmer's responsibility but I wish to get my code written in a perfectly homogenous way, taking care particularly of having always identical blank space between operands or after and before separators and between blocks.</p>
24
2009-06-23T12:53:52Z
1,502,993
<p>I am the one who asks the question. In fact, the tool the closest to my needs seems to be <a href="http://www.lacusveris.com/PythonTidy/">PythonTidy</a> (it's a Python program of course : Python is best served by himself ;) ).</p>
14
2009-10-01T09:55:50Z
[ "python", "formatter" ]
Python Formatter Tool
1,032,393
<p>I was wondering if there exists a sort of Python beautifier like the gnu-indent command line tool for C code. Of course indentation is not the point in Python since it is programmer's responsibility but I wish to get my code written in a perfectly homogenous way, taking care particularly of having always identical blank space between operands or after and before separators and between blocks.</p>
24
2009-06-23T12:53:52Z
26,106,417
<p>autopep8 attempts to automate making your code conform to pep8 coding standards</p> <p><a href="https://pypi.python.org/pypi/autopep8" rel="nofollow">https://pypi.python.org/pypi/autopep8</a></p>
2
2014-09-29T18:26:24Z
[ "python", "formatter" ]
Check if only one variable in a list of variables is set
1,032,411
<p>I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this <a href="http://stackoverflow.com/questions/432842/how-do-you-get-the-logical-xor-of-two-variables-in-python">logical xor post</a> and is trying to find a way to adapt to multiple variables and only one true.</p> <p>Example</p> <pre><code>&gt;&gt;&gt;TrueXor(1,0,0) True &gt;&gt;&gt;TrueXor(0,0,1) True &gt;&gt;&gt;TrueXor(1,1,0) False &gt;&gt;&gt;TrueXor(0,0,0,0,0) False </code></pre>
9
2009-06-23T12:56:22Z
1,032,441
<pre><code>&gt;&gt;&gt; def f(*n): ... n = [bool(i) for i in n] ... return n.count(True) == 1 ... &gt;&gt;&gt; f(0, 0, 0) False &gt;&gt;&gt; f(1, 0, 0) True &gt;&gt;&gt; f(1, 0, 1) False &gt;&gt;&gt; f(1, 1, 1) False &gt;&gt;&gt; f(0, 1, 0) True &gt;&gt;&gt; </code></pre>
3
2009-06-23T13:02:33Z
[ "python", "xor" ]
Check if only one variable in a list of variables is set
1,032,411
<p>I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this <a href="http://stackoverflow.com/questions/432842/how-do-you-get-the-logical-xor-of-two-variables-in-python">logical xor post</a> and is trying to find a way to adapt to multiple variables and only one true.</p> <p>Example</p> <pre><code>&gt;&gt;&gt;TrueXor(1,0,0) True &gt;&gt;&gt;TrueXor(0,0,1) True &gt;&gt;&gt;TrueXor(1,1,0) False &gt;&gt;&gt;TrueXor(0,0,0,0,0) False </code></pre>
9
2009-06-23T12:56:22Z
1,032,442
<p>There isn't one built in but it's not to hard to roll you own:</p> <pre><code>def TrueXor(*args): return sum(args) == 1 </code></pre> <p>Since "[b]ooleans are a subtype of plain integers" (<a href="http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex">source</a>) you can sum the list of integers quite easily and you can also pass true booleans into this function as well.</p> <p>So these two calls are homogeneous:</p> <pre><code>TrueXor(1, 0, 0) TrueXor(True, False, False) </code></pre> <p>If you want explicit boolean conversion: <code>sum( bool(x) for x in args ) == 1</code>.</p>
15
2009-06-23T13:02:34Z
[ "python", "xor" ]
Check if only one variable in a list of variables is set
1,032,411
<p>I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this <a href="http://stackoverflow.com/questions/432842/how-do-you-get-the-logical-xor-of-two-variables-in-python">logical xor post</a> and is trying to find a way to adapt to multiple variables and only one true.</p> <p>Example</p> <pre><code>&gt;&gt;&gt;TrueXor(1,0,0) True &gt;&gt;&gt;TrueXor(0,0,1) True &gt;&gt;&gt;TrueXor(1,1,0) False &gt;&gt;&gt;TrueXor(0,0,0,0,0) False </code></pre>
9
2009-06-23T12:56:22Z
1,032,477
<p>The question you linked to already provides the solution for two variables. All you have to do is extend it to work on n variables:</p> <pre><code>import operator def only_one_set(*vars): bools = [bool(v) for v in vars] return reduce(operator.xor, bools, False) &gt;&gt;&gt; a, b, c, d, e = False, '', [], 10, -99 &gt;&gt;&gt; only_one_set(a, b, c, d) True &gt;&gt;&gt; only_one_set(a, b, c, d, e) False </code></pre>
1
2009-06-23T13:08:36Z
[ "python", "xor" ]
Check if only one variable in a list of variables is set
1,032,411
<p>I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this <a href="http://stackoverflow.com/questions/432842/how-do-you-get-the-logical-xor-of-two-variables-in-python">logical xor post</a> and is trying to find a way to adapt to multiple variables and only one true.</p> <p>Example</p> <pre><code>&gt;&gt;&gt;TrueXor(1,0,0) True &gt;&gt;&gt;TrueXor(0,0,1) True &gt;&gt;&gt;TrueXor(1,1,0) False &gt;&gt;&gt;TrueXor(0,0,0,0,0) False </code></pre>
9
2009-06-23T12:56:22Z
1,032,487
<p>Here's my straightforward approach. I've renamed it only_one since xor with more than one input is usually a parity checker, not an "only one" checker.</p> <pre><code>def only_one(*args): result = False for a in args: if a: if result: return False else: result = True return result </code></pre> <p>Testing:</p> <pre><code>&gt;&gt;&gt; only_one(1,0,0) True &gt;&gt;&gt; only_one(0,0,1) True &gt;&gt;&gt; only_one(1,1,0) False &gt;&gt;&gt; only_one(0,0,0,0,0) False &gt;&gt;&gt; only_one(1,1,0,1) False </code></pre>
1
2009-06-23T13:10:10Z
[ "python", "xor" ]
Check if only one variable in a list of variables is set
1,032,411
<p>I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this <a href="http://stackoverflow.com/questions/432842/how-do-you-get-the-logical-xor-of-two-variables-in-python">logical xor post</a> and is trying to find a way to adapt to multiple variables and only one true.</p> <p>Example</p> <pre><code>&gt;&gt;&gt;TrueXor(1,0,0) True &gt;&gt;&gt;TrueXor(0,0,1) True &gt;&gt;&gt;TrueXor(1,1,0) False &gt;&gt;&gt;TrueXor(0,0,0,0,0) False </code></pre>
9
2009-06-23T12:56:22Z
1,033,153
<p>I think the sum-based solution is fine for the given example, but keep in mind that boolean predicates in python always short-circuit their evaluation. So you might want to consider something more consistent with <a href="http://docs.python.org/library/functions.html#all">all and any</a>.</p> <pre><code>def any_one(iterable): it = iter(iterable) return any(it) and not any(it) </code></pre>
7
2009-06-23T15:07:06Z
[ "python", "xor" ]
using two for loops in python
1,032,722
<p>I have started to learn python recently and have a question about for loops that I was hoping someone could answer. I want to be able to print all the possible products of two numbers from one to ten. so: 2 by 2, 2 by 3, 2 by 4...2 by 10, 3 by 2, 3 by 3...3 by 10, 4 by 2, 4 by 3 etc...I would have thought the easiest way to do so would be to use two for loops but I am not sure. could anyone please tell me how this is done. thanks very much. asadm.</p>
3
2009-06-23T13:57:41Z
1,032,749
<pre><code>for i in range(1, 11): for j in range(1, 11): print i * j </code></pre>
4
2009-06-23T14:01:16Z
[ "python", "for-loop", "combinations" ]
using two for loops in python
1,032,722
<p>I have started to learn python recently and have a question about for loops that I was hoping someone could answer. I want to be able to print all the possible products of two numbers from one to ten. so: 2 by 2, 2 by 3, 2 by 4...2 by 10, 3 by 2, 3 by 3...3 by 10, 4 by 2, 4 by 3 etc...I would have thought the easiest way to do so would be to use two for loops but I am not sure. could anyone please tell me how this is done. thanks very much. asadm.</p>
3
2009-06-23T13:57:41Z
1,032,782
<p>Just for fun (and the itertools-addicted SO readers) using only one for-loop:</p> <pre><code>from itertools import product for i,j in product(xrange(1,11), xrange(1,11)): print i*j </code></pre> <p>EDIT: using xrange as suggested by Hank Gay</p>
4
2009-06-23T14:07:09Z
[ "python", "for-loop", "combinations" ]
using two for loops in python
1,032,722
<p>I have started to learn python recently and have a question about for loops that I was hoping someone could answer. I want to be able to print all the possible products of two numbers from one to ten. so: 2 by 2, 2 by 3, 2 by 4...2 by 10, 3 by 2, 3 by 3...3 by 10, 4 by 2, 4 by 3 etc...I would have thought the easiest way to do so would be to use two for loops but I am not sure. could anyone please tell me how this is done. thanks very much. asadm.</p>
3
2009-06-23T13:57:41Z
1,032,895
<p>Here is another way</p> <pre><code>a = [i*j for i in xrange(1,11) for j in xrange(i,11)] </code></pre> <p><strong>note</strong> we need to start second iterator from 'i' instead of 1, so this is doubly efficient</p> <p>edit: proof that it is same as simple solution</p> <pre><code>b = [] for i in range(1,11): for j in range(1,11): b.append(i*j) print set(a) == set(b) </code></pre>
8
2009-06-23T14:26:16Z
[ "python", "for-loop", "combinations" ]
Dump stacktraces of all active Threads
1,032,813
<p>I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. </p> <p>Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I have a feeling it's a loop which doesn't terminate properly, but i cannot reproduce it in the test-environemt for verification. I managed to register a signal handler which can be triggered from the outside, so i can trigger some code as soon as the situation occurs again. If I could dump the stacktrace for all active threads, that would give me a clue what goes wrong. The hole thing runs on python 2.4...</p> <p>Any ideas on how to trace down situations like these are appreciated :)</p> <p>Cheers, Chriss</p>
19
2009-06-23T14:13:38Z
1,032,896
<p>There is an applicable recipe on <a href="http://code.activestate.com/recipes/496960/" rel="nofollow">ASPN</a>. You can use <code>threading.enumerate()</code> to get all the tids, then just call _async_raise() with some suitable exception to force a stack trace.</p>
0
2009-06-23T14:26:48Z
[ "python", "multithreading", "plone", "zope" ]
Dump stacktraces of all active Threads
1,032,813
<p>I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. </p> <p>Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I have a feeling it's a loop which doesn't terminate properly, but i cannot reproduce it in the test-environemt for verification. I managed to register a signal handler which can be triggered from the outside, so i can trigger some code as soon as the situation occurs again. If I could dump the stacktrace for all active threads, that would give me a clue what goes wrong. The hole thing runs on python 2.4...</p> <p>Any ideas on how to trace down situations like these are appreciated :)</p> <p>Cheers, Chriss</p>
19
2009-06-23T14:13:38Z
1,032,930
<p>2.4. Too bad. From Python 2.5 on there is <code>sys._current_frames()</code>.</p> <p>But you could try <a href="http://www.majid.info/mylos/stories/2004/06/10/threadframe.html" rel="nofollow">threadframe</a>. And if the makefile gives you trouble you could try this <a href="http://www.wsanchez.net/blog/2004/06/stack_traces_in_python_threads.html#comment-55" rel="nofollow">setup.py for threadframe</a></p> <p><a href="http://www.majid.info/python/threadframe/threadframe-0.2/sample.txt" rel="nofollow">Sample output when using threadframe</a></p>
7
2009-06-23T14:31:33Z
[ "python", "multithreading", "plone", "zope" ]
Dump stacktraces of all active Threads
1,032,813
<p>I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. </p> <p>Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I have a feeling it's a loop which doesn't terminate properly, but i cannot reproduce it in the test-environemt for verification. I managed to register a signal handler which can be triggered from the outside, so i can trigger some code as soon as the situation occurs again. If I could dump the stacktrace for all active threads, that would give me a clue what goes wrong. The hole thing runs on python 2.4...</p> <p>Any ideas on how to trace down situations like these are appreciated :)</p> <p>Cheers, Chriss</p>
19
2009-06-23T14:13:38Z
1,038,671
<p>When using Zope, you want to install <a href="http://pypi.python.org/pypi/Products.signalstack" rel="nofollow"><code>Products.signalstack</code></a> or <a href="https://pypi.python.org/pypi/mr.freeze" rel="nofollow">mr.freeze</a>; these were designed for just this purpose!</p> <p>Send a USR1 signal to your Zope server and it'll immediately dump stack traces for all threads to the console. It'll do this even if all Zope threads are locked up.</p> <p>Under the hood these packages indirectly use <a href="https://majid.info/blog/threadframe-multithreaded-stack-frame-extraction-for-python/" rel="nofollow"><code>threadframes</code></a>; for Python versions 2.5 and up, when <em>not</em> using Zope, you can build the same functionality using the <a href="https://docs.python.org/2/library/sys.html#sys._current_frames" rel="nofollow"><code>sys._current_frames()</code></a> function to access per-thread stack frames.</p> <p>As of <a href="https://github.com/zopefoundation/Zope/commit/16796274463f21327e1b7bb3831b39eb671460af" rel="nofollow">Zope 2.12.5</a> this functionality is integrated into Zope itself, and there is no need to install additional packages anymore.</p>
6
2009-06-24T14:18:14Z
[ "python", "multithreading", "plone", "zope" ]
Dump stacktraces of all active Threads
1,032,813
<p>I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. </p> <p>Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I have a feeling it's a loop which doesn't terminate properly, but i cannot reproduce it in the test-environemt for verification. I managed to register a signal handler which can be triggered from the outside, so i can trigger some code as soon as the situation occurs again. If I could dump the stacktrace for all active threads, that would give me a clue what goes wrong. The hole thing runs on python 2.4...</p> <p>Any ideas on how to trace down situations like these are appreciated :)</p> <p>Cheers, Chriss</p>
19
2009-06-23T14:13:38Z
7,317,379
<p>As jitter points out in an earlier answer <code>sys._current_frames()</code> gives you what you need for v2.5+. For the lazy the following code snippet worked for me and may help you:</p> <pre><code>print &gt;&gt; sys.stderr, "\n*** STACKTRACE - START ***\n" code = [] for threadId, stack in sys._current_frames().items(): code.append("\n# ThreadID: %s" % threadId) for filename, lineno, name, line in traceback.extract_stack(stack): code.append('File: "%s", line %d, in %s' % (filename, lineno, name)) if line: code.append(" %s" % (line.strip())) for line in code: print &gt;&gt; sys.stderr, line print &gt;&gt; sys.stderr, "\n*** STACKTRACE - END ***\n" </code></pre>
27
2011-09-06T09:02:15Z
[ "python", "multithreading", "plone", "zope" ]
Dump stacktraces of all active Threads
1,032,813
<p>I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. </p> <p>Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I have a feeling it's a loop which doesn't terminate properly, but i cannot reproduce it in the test-environemt for verification. I managed to register a signal handler which can be triggered from the outside, so i can trigger some code as soon as the situation occurs again. If I could dump the stacktrace for all active threads, that would give me a clue what goes wrong. The hole thing runs on python 2.4...</p> <p>Any ideas on how to trace down situations like these are appreciated :)</p> <p>Cheers, Chriss</p>
19
2009-06-23T14:13:38Z
24,334,576
<p>For Python 3.3 and later, there is <a href="https://docs.python.org/3/library/faulthandler.html#dumping-the-traceback" rel="nofollow"><code>faulthandler.dump_traceback()</code></a>.</p> <p>The code below produces similar output, but includes the thread name and could be enhanced to print more information.</p> <pre><code>for th in threading.enumerate(): print(th) traceback.print_stack(sys._current_frames()[th.ident]) print() </code></pre>
8
2014-06-20T19:46:18Z
[ "python", "multithreading", "plone", "zope" ]
Dump stacktraces of all active Threads
1,032,813
<p>I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. </p> <p>Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I have a feeling it's a loop which doesn't terminate properly, but i cannot reproduce it in the test-environemt for verification. I managed to register a signal handler which can be triggered from the outside, so i can trigger some code as soon as the situation occurs again. If I could dump the stacktrace for all active threads, that would give me a clue what goes wrong. The hole thing runs on python 2.4...</p> <p>Any ideas on how to trace down situations like these are appreciated :)</p> <p>Cheers, Chriss</p>
19
2009-06-23T14:13:38Z
33,466,873
<p>Just for completeness sake, <a href="https://pypi.python.org/pypi/Products.LongRequestLogger" rel="nofollow">Products.LongRequestLogger</a> is super helpful to identify bottlenecks, and to do so it dumps stacktraces at specific intervals.</p>
1
2015-11-01T20:32:30Z
[ "python", "multithreading", "plone", "zope" ]
Template driven feed parsing
1,032,976
<p>Requirements: I have a python project which parses data feeds from multiple sources in varying formats (Atom, valid XML, invalid XML, csv, almost-garbage, etc...) and inserts the resulting data into a database. The catch is the information required to parse each of the feeds must also be stored in the database.</p> <p>Current solution: My previous solution was to store small python scripts which are eval'ed on the raw data, and return a data object for the parsed data. I'd really like to get away from this method as it obviously opens up a nasty security hole.</p> <p>Ideal solution: What I'm looking for is what I would describe as a template-driven feed parser for python, so that I can write a template file for each of the feed formats, and this template file would be used to make sense of the various data formats.</p> <p>I've had limited success finding something like this in the past, and was hoping someone may have a good suggestion.</p> <p>Thanks everyone!</p>
2
2009-06-23T14:39:33Z
1,033,530
<p>Instead of <code>eval</code>ing scripts, maybe you should consider making a package of them? Parsing CSV is one thing — the format is simple and regular, parsing XML requires completely another approach. Considering you don't want to write every single parser from scratch, why not just write a bunch of small modules, each having identical API and use them? I believe, using Python itself (not some templating DSL) is ideal for this sort of thing.</p> <p>For example, this is an approach I've seen in one <a href="https://code.launchpad.net/~ero-sennin/fetchtorrent/trunk" rel="nofollow">small torrent-fetching script</a> I'm using:</p> <p>Main program:</p> <pre><code>... def import_plugin(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod ... feed_parser = import_plugin('parsers.%s' % feed['format']) data = feed_parser(...) ... </code></pre> <p><code>parsers/csv.py</code>:</p> <pre><code>#!/usr/bin/python from __future__ import absolute_import import urllib2 import csv def parse_feed(...): ... </code></pre> <p>If you don't particularly like dynamically loaded modules, you may consider writing, for example, a single module with several parses classes (probably derived from some "abstract parser" base class).</p> <pre><code>class BaseParser(object): ... class CSVParser(BaseParser): ... register_feed_parser(CSVParser, ['text/plain', 'text/csv']) ... parsers = get_registered_feed_parsers(feed['mime_type']) data = None for parser in parsers: try: data = parser(feed['data']) if data is not None: break except ParsingError: pass ... </code></pre>
1
2009-06-23T16:01:19Z
[ "python" ]
Decorators that are properties of decorated objects?
1,033,107
<p>I want to create a decorator that allows me to refer back to the decorated object and grab another decorator from it, the same way you can use setter/deleter on properties:</p> <pre><code>@property def x(self): return self._x @x.setter def x(self, y): self._x = y </code></pre> <p>Specifically, I'd like it to act basically the same as property, but emulate a sequence instead of a single value. Here's my first shot at it, but it doesn't seem to work:</p> <pre><code>def listprop(indices): def dec(func): class c(object): def __init__(self, l): self.l = l def __getitem__(self, i): if not i in self.l: raise Exception("Invalid item: " + i) return func(i) @staticmethod def setter(func): def set(self, i, val): if not i in self.l: raise Exception("Invalid item: " + i) func(i, val) c.__setitem__ = set return c(indices) return dec # ... class P: @listprop(range(3)) def prop(self, i): return get_prop(i) @prop.setter def prop(self, i, val): set_prop(i, val) </code></pre> <p>I'm pretty sure that <code>c.__setitem__ = set</code> is wrong, but I can't figure out how to get a reference to the instance at that point. Ideas?</p> <p>Alex Martelli's solution works on 2.6, but something about it is failing on 2.4 and 2.5 (I'd prefer to have it work on these older versions as well, though it's not strictly necessary):</p> <p>2.4:</p> <pre><code>&gt;&gt;&gt; p = P() &gt;&gt;&gt; p.prop &gt;&gt;&gt; p.prop[0] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? TypeError: unsubscriptable object </code></pre> <p>2.5:</p> <pre><code>&gt;&gt;&gt; p = P() &gt;&gt;&gt; p.prop &gt;&gt;&gt; p.prop[0] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'NoneType' object is unsubscriptable </code></pre> <p>2.6:</p> <pre><code>&gt;&gt;&gt; p = P() &gt;&gt;&gt; p.prop &lt;__main__.c object at 0x017F5730&gt; &gt;&gt;&gt; p.prop[0] 0 </code></pre>
1
2009-06-23T14:59:12Z
1,033,313
<p>I fixed many little details and the following version seems to work as you require:</p> <pre><code>def listprop(indices): def dec(func): class c(object): def __init__(self, l, obj=None): self.l = l self.obj = obj def __get__(self, obj, cls=None): return c(self.l, obj) def __getitem__(self, i): if not i in self.l: raise Exception("Invalid item: " + i) return func(self.obj, i) def setter(self, sfunc): def doset(self, i, val): if not i in self.l: raise Exception("Invalid item: " + i) sfunc(self.obj, i, val) c.__setitem__ = doset return self result = c(indices) return result return dec # ... class P: @staticmethod def get_prop(i): return i*100 @staticmethod def set_prop(i, val): print 'set %s to %s' % (i, val) @listprop(range(3)) def prop(self, i): return self.get_prop(i) @prop.setter def prop(self, i, val): self.set_prop(i, val) </code></pre> <p>As you see, assigning to <code>c.__setitem__</code> was not the problem -- there were others, such as c lacking a <code>__get__</code> (so it wasn't a descriptor, see <a href="http://users.rcn.com/python/download/Descriptor.htm" rel="nofollow">this guiide</a>) and setter returning None (so p.prop ended up as None).</p>
3
2009-06-23T15:29:29Z
[ "python", "decorator" ]
Specifying TkInter Callbacks In Dictionary For Display Launcher Function
1,033,130
<p>I am having trouble building a Python function that launches TkInter objects, with commands bound to menu buttons, using button specifications held in a dictionary.</p> <p>SITUATION</p> <p>I am building a GUI in Python using TkInter. I have written a Display class (based on the GuiMaker class in Lutz, "Programming Python") that should provide a window for data entry for a variety of entities, so the commands and display of any instance will vary. I would like to configure these entity-specific commands and displays in a dictionary file. The file is evaluated when the script is run, and its dictionary passed to a launcher function when a Display instance is called for. But the instances' commands can't find the instance methods I'm trying to bind to them.</p> <p>SPECIFICATION IN FUNCTIONS WORKS</p> <p>This isn't a problem when the Display instance is launched with configurations specified in a dedicated function. For instance this works fine:</p> <pre><code>def launchEmployee(): display = '' menuBar = [('File', 0, [('Save', 0, (lambda: display.onSave()))])] title = 'Employee Data Entry' display_args = {'title': title, 'menuBar': menuBar} display = DisplayScreen(**display_args) </code></pre> <p>The DisplayScreen subclasses from the GuiMaker, which has methods for processing the menuBar object to create a menu. It has an onSave() method.</p> <p>Done this way, the Display instance finds and runs its own onSave() method when the 'Save' button is clicked.</p> <p>SPECIFICATION FROM DICTIONARY FILE DOESN'T WORK</p> <p>But this doesn't work when I try to launch the Display instance from a launcher function, pulling its specification from a dictionary held in a separate file.</p> <p>config_file:</p> <pre><code>{'menuBar':[('File', 0, [('Save', 0, (lambda: display.onSave()))])], 'title': 'Employee Data Entry'} </code></pre> <p>script file:</p> <pre><code>config = eval(open('config_file', 'r').read()) def launchDisplay(config): display = '' display = DisplayScreen(**config) </code></pre> <p>Run this way, clicking 'Save' generates an error, saying there is no global object 'display'.</p> <p>THEORY: DICTIONARY CASE LOOKS FOR OBJECTS IN SCOPE AT EVAL() CALL</p> <p>I speculate that in the function case, 'display' is a string object, whose lack of the method onSave() isn't a problem for the the assigment to menuBar because its examination for the method is deferred inside the lambda function. When the Display instance is assigned to the 'display' object, this overloads the prior assignment of the string object, but Python still knows about 'display' and goes to it when asked for its onSave() method.</p> <p>If so, the configuration case is failing because the 'display' object doesn't exist at all when the config dictionary is created by evaluation. This doen't cause an error at the eval() call because, again, the lambda function hides the object from inspection until called. But when called, Python goes looking for the 'display' object in scope at the moment of the eval() call, where it finds nothing, and then reports an error.</p> <p>BUT: PUTTING EVAL() CALL IN SCOPE DOESN'T HELP</p> <p>But I have tried moving the evaluation of the dictionary file into the function and after the creation of the 'display' string object, and this doesn't work either.</p> <p>SO:</p> <p>What is going on here?<br /> How can I specify methods to be bound to commands in a dictionary to be accessed when instantiating the display object? It really seems better to specify these screens in a configuration file than in a host of duplicative functions.</p>
0
2009-06-23T15:03:04Z
1,033,498
<p>When your <code>lambda</code> executes is when scope applies, but the issue is a bit subtler.</p> <p>In the first case that <code>lambda</code> is a nested function of <code>launchEmployee</code> so the Python compiler (when it compiles the enclosing function) knows to scan its body for references to local variables of the enclosing function and forms the closure appropriately</p> <p>In the second case, the <code>eval</code> hides the nested function from the Python compiler at the time it's compiling the enclosing function, so it doesn't even <em>know</em> it's an enclosing function, nor that it should form a closure, or how.</p> <p>I suggest you don't play around with names but rather insert the new <code>display</code> object into the <code>lambda</code> after instantiating it. That does require finding the <code>lambda</code> (or more than one lambda) but you may do it by systematically (e.g. recursively) walking all items in config's values, looking for ones which are instances of <code>type(lambda:0)</code> and adopting some convention such as, 'the widget being created is referred in those lambdas by the name "widget" and is the last argument (with a default value)'.</p> <p>So you change your config file to:</p> <pre><code>'menuBar':[('File', 0, [('Save', 0, (lambda widget=None: widget.onSave()))])], 'title': 'Employee Data Entry'} </code></pre> <p>and, after <code>display = DisplayScreen(**config)</code>, post-process <code>config</code> as follows:</p> <pre><code>def place_widget(widget, mess): if isinstance(mess, (list, tuple)): for item in mess: place_widget(widget, item) elif isinstance(mess, type(lambda:0)): if mess.func_code.co_varnames[-1:] == ('widget',): mess.func_defaults = mess.func_defaults[:-1] + (widget,) </code></pre> <p>Admittedly somewhat-tricky code, but I don't see a straightforward way to do it within your specified context of an <code>eval</code>'d string made into a <code>dict</code> containing some <code>lambda</code>s.</p> <p>I would normally recommend standard library module <code>inspect</code> for such introspection, but since this post-processing function must inevitably mess around with the <code>func_defaults</code> (<code>inspect</code> only examines, does not alter objects' internals like that), it seems more consistent to have all of its code churn at the same, pretty-down-deep level.</p> <p><strong>Edit</strong>: a simpler approach is possible if you don't insist on having widgets be only local variables, but can instead make them e.g. attributes of a global object.</p> <p>So at module level you have, say:</p> <pre><code>class Bunch(object): pass widgets = Bunch() </code></pre> <p>and in your function you assign the newly made widget to <code>widgets.foobar</code> instead of assigning to bare name <code>foobar</code>. Then your <code>eval</code>ed <code>lambda</code> can be something like:</p> <pre><code>lambda: widgets.foobar.onSave() </code></pre> <p>and everything will be fine, because, this way, no closure is needed (it's only needed -- and none is forthcoming due to the <code>eval</code> -- in your original approach to preserve the <em>local</em> variables you are using for the time the <code>lambda</code> will be needing them).</p>
0
2009-06-23T15:56:19Z
[ "python" ]
SQLAlchemy: Object Mappings lost after commit?
1,033,199
<p>I got a simple problem in SQLAlchemy. I have one model in a table, lets call it Model1 here. I want to add a row in this table, and get the autoincremented key, so I can create another model with it, and use this key. This is not a flawed database design (1:1 relation etc). I simply need this key in another table, because the other table is being transferred to a remote host, and I need the matching keys so the servers will understand each other. There will be no further local reference between these 2 tables, and it's also not possible to create relations because of that.</p> <p>Consider the following code:</p> <pre><code>object1 = model.Model1(param) DBSession.add(object1) # if I do this, the line below fails with an UnboundExecutionError. # and if I dont do this, object1.id won't be set yet #transaction.commit() object2 = model.AnotherModel(object1.id) #id holds the primary, autoincremented key </code></pre> <p>I wished I wouldn't even have to commit "manually". Basically what I would like to achieve is, "Model1" is constantly growing, with increasing Model.id primary key. AnotherModel is always only a little fraction of Model1, which hasn't been processed yet. Of course I could add a flag in "Model1", a boolean field in the table to mark already processed elements, but I was hoping this would not be necessary.</p> <p>How can I get my above code working?</p> <p>Greets,</p> <p>Tom</p>
2
2009-06-23T15:13:00Z
1,034,593
<p>I've only used this with ForeignKeys, so you in the second case rather would do model.AnotherModel(model1=object1), and then it just worked (tm). So I suspect this may be a problem with your models, so maybe you could post them too?</p>
1
2009-06-23T19:20:17Z
[ "python", "database", "sqlalchemy" ]
SQLAlchemy: Object Mappings lost after commit?
1,033,199
<p>I got a simple problem in SQLAlchemy. I have one model in a table, lets call it Model1 here. I want to add a row in this table, and get the autoincremented key, so I can create another model with it, and use this key. This is not a flawed database design (1:1 relation etc). I simply need this key in another table, because the other table is being transferred to a remote host, and I need the matching keys so the servers will understand each other. There will be no further local reference between these 2 tables, and it's also not possible to create relations because of that.</p> <p>Consider the following code:</p> <pre><code>object1 = model.Model1(param) DBSession.add(object1) # if I do this, the line below fails with an UnboundExecutionError. # and if I dont do this, object1.id won't be set yet #transaction.commit() object2 = model.AnotherModel(object1.id) #id holds the primary, autoincremented key </code></pre> <p>I wished I wouldn't even have to commit "manually". Basically what I would like to achieve is, "Model1" is constantly growing, with increasing Model.id primary key. AnotherModel is always only a little fraction of Model1, which hasn't been processed yet. Of course I could add a flag in "Model1", a boolean field in the table to mark already processed elements, but I was hoping this would not be necessary.</p> <p>How can I get my above code working?</p> <p>Greets,</p> <p>Tom</p>
2
2009-06-23T15:13:00Z
1,035,329
<p>A couple of things:</p> <ul> <li>Could you please explain what the variable <code>transaction</code> is bound to?</li> <li>Exactly what statement raises the UnboundExecutionError?</li> <li>Please provide the full exception message, including stack trace.</li> <li>The 'normal' thing to do in this case, would be to call <code>DBSession.flush()</code>. Have you tried that?</li> </ul> <p>Example:</p> <pre><code>object1 = Model1(param) DBSession.add(object1) DBSession.flush() assert object1.id != None # flushing the session populates the id object2 = AnotherModel(object1.id) </code></pre> <p>For a great explanation to the SA session and what <code>flush()</code> does, see <a href="http://www.sqlalchemy.org/docs/05/session.html#id1" rel="nofollow">Using the Session</a>.</p> <p>Basically, <code>flush()</code> causes Pending instances to become Persistent - meaning that new objects are INSERTed into the database tables. <code>flush()</code> also UPDATEs the tables with values for instances that the session tracks that has changes.</p> <p><code>commit()</code> always issues <code>flush()</code> first.</p> <p>Within a transaction, you can flush multiple times. Each flush() causes UPDATEs and/or INSERTs in the database. The entire transaction can be commited or rolled back.</p>
3
2009-06-23T21:24:34Z
[ "python", "database", "sqlalchemy" ]
SQLAlchemy: Object Mappings lost after commit?
1,033,199
<p>I got a simple problem in SQLAlchemy. I have one model in a table, lets call it Model1 here. I want to add a row in this table, and get the autoincremented key, so I can create another model with it, and use this key. This is not a flawed database design (1:1 relation etc). I simply need this key in another table, because the other table is being transferred to a remote host, and I need the matching keys so the servers will understand each other. There will be no further local reference between these 2 tables, and it's also not possible to create relations because of that.</p> <p>Consider the following code:</p> <pre><code>object1 = model.Model1(param) DBSession.add(object1) # if I do this, the line below fails with an UnboundExecutionError. # and if I dont do this, object1.id won't be set yet #transaction.commit() object2 = model.AnotherModel(object1.id) #id holds the primary, autoincremented key </code></pre> <p>I wished I wouldn't even have to commit "manually". Basically what I would like to achieve is, "Model1" is constantly growing, with increasing Model.id primary key. AnotherModel is always only a little fraction of Model1, which hasn't been processed yet. Of course I could add a flag in "Model1", a boolean field in the table to mark already processed elements, but I was hoping this would not be necessary.</p> <p>How can I get my above code working?</p> <p>Greets,</p> <p>Tom</p>
2
2009-06-23T15:13:00Z
1,041,764
<p>if you want to get new primary key identifiers to generate without anything being committed, just call session.flush(). That will emit everything pending to the database within the current transaction. </p>
1
2009-06-25T01:29:33Z
[ "python", "database", "sqlalchemy" ]
Pylons - use Python 2.5 or 2.6?
1,033,367
<p>Which version of Python is recommended for Pylons, and why?</p>
4
2009-06-23T15:37:44Z
1,033,394
<p>Pylons itself <a href="http://pylonshq.com/docs/en/0.9.7/gettingstarted/" rel="nofollow">says</a> it needs at least 2.3, and recommends 2.4+. Since 2.6 is <a href="http://python.org/download/" rel="nofollow">production ready</a>, I'd use that.</p>
5
2009-06-23T15:41:43Z
[ "python", "pylons" ]
Pylons - use Python 2.5 or 2.6?
1,033,367
<p>Which version of Python is recommended for Pylons, and why?</p>
4
2009-06-23T15:37:44Z
1,033,433
<p><a href="http://pylonshq.com/docs/en/0.9.7/gettingstarted/#requirements" rel="nofollow">You can use Python 2.3 to 2.6</a>, though 2.3 support will be dropped in the next version. <a href="http://wiki.pylonshq.com/display/pylonscommunity/Pylons%2BRoadmap%2Bto%2B1.0" rel="nofollow">You can't use Python 3 yet</a>.</p> <p>There's no real reason to favor Python 2.5 or 2.6 at this point. Use what works best for you.</p>
2
2009-06-23T15:46:59Z
[ "python", "pylons" ]
Pylons - use Python 2.5 or 2.6?
1,033,367
<p>Which version of Python is recommended for Pylons, and why?</p>
4
2009-06-23T15:37:44Z
1,033,467
<p>I'd say use 2.5 : </p> <p>there is one reason to favor 2.5 over 2.6 : if you need to be compatible with the python given on a linux installation or on Macs (I dont' know what py version mac provide, but you get the idea).</p> <p>Of course, if you need some feature of 2.6, please do it, but if it's not the case why require 2.6 ? Remember that your app will be hosted somewhere where restrictions apply for deployment.</p> <p>If you will distribute your app on opensource, even more so.</p>
1
2009-06-23T15:51:05Z
[ "python", "pylons" ]
How to remove bad path characters in Python?
1,033,424
<p>What is the most cross platform way of removing bad path characters (e.g. "\" or ":" on Windows) in Python?</p> <h3>Solution</h3> <p>Because there seems to be no ideal solution I decided to be relatively restrictive and did use the following code:</p> <pre><code>def remove(value, deletechars): for c in deletechars: value = value.replace(c,'') return value; print remove(filename, '\/:*?"&lt;&gt;|') </code></pre>
13
2009-06-23T15:45:39Z
1,033,446
<p>That character is in <code>os.sep</code>, it'll be "\" or ":", depending on which system you're on.</p>
0
2009-06-23T15:48:32Z
[ "python", "path" ]
How to remove bad path characters in Python?
1,033,424
<p>What is the most cross platform way of removing bad path characters (e.g. "\" or ":" on Windows) in Python?</p> <h3>Solution</h3> <p>Because there seems to be no ideal solution I decided to be relatively restrictive and did use the following code:</p> <pre><code>def remove(value, deletechars): for c in deletechars: value = value.replace(c,'') return value; print remove(filename, '\/:*?"&lt;&gt;|') </code></pre>
13
2009-06-23T15:45:39Z
1,033,591
<p>If you are using python try <a href="http://docs.python.org/library/os.path.html" rel="nofollow">os.path</a> to avoid cross platform issues with paths.</p>
1
2009-06-23T16:08:22Z
[ "python", "path" ]
How to remove bad path characters in Python?
1,033,424
<p>What is the most cross platform way of removing bad path characters (e.g. "\" or ":" on Windows) in Python?</p> <h3>Solution</h3> <p>Because there seems to be no ideal solution I decided to be relatively restrictive and did use the following code:</p> <pre><code>def remove(value, deletechars): for c in deletechars: value = value.replace(c,'') return value; print remove(filename, '\/:*?"&lt;&gt;|') </code></pre>
13
2009-06-23T15:45:39Z
1,033,669
<p>Unfortunately, the set of acceptable characters varies by OS <em>and</em> by filesystem.</p> <ul> <li><p><a href="http://msdn.microsoft.com/en-us/library/aa365247.aspx">Windows</a>:</p> <blockquote> <ul> <li>Use almost any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following: <ul> <li>The following reserved characters are not allowed:<br /> &lt; &gt; : " / \ | ? *</li> <li>Characters whose integer representations are in the range from zero through 31 are not allowed.</li> <li>Any other character that the target file system does not allow.</li> </ul></li> </ul> </blockquote> <p>The list of accepted characters can vary depending on the OS and locale of the machine that first formatted the filesystem.</p> <p>.NET has <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx">GetInvalidFileNameChars</a> and <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars.aspx">GetInvalidPathChars</a>, but I don't know how to call those from Python.</p></li> <li>Mac OS: NUL is always excluded, "/" is excluded from POSIX layer, ":" excluded from Apple APIs <ul> <li>HFS+: any sequence of non-excluded characters that is representable by UTF-16 in the Unicode 2.0 spec</li> <li>HFS: any sequence of non-excluded characters representable in MacRoman (default) or other encodings, depending on the machine that created the filesystem</li> <li>UFS: same as HFS+</li> </ul></li> <li>Linux: <ul> <li>native (UNIX-like) filesystems: any byte sequence excluding NUL and "/"</li> <li>FAT, NTFS, other non-native filesystems: varies</li> </ul></li> </ul> <p>Your best bet is probably to either be overly-conservative on all platforms, or to just try creating the file name and handle errors.</p>
9
2009-06-23T16:21:28Z
[ "python", "path" ]
How to remove bad path characters in Python?
1,033,424
<p>What is the most cross platform way of removing bad path characters (e.g. "\" or ":" on Windows) in Python?</p> <h3>Solution</h3> <p>Because there seems to be no ideal solution I decided to be relatively restrictive and did use the following code:</p> <pre><code>def remove(value, deletechars): for c in deletechars: value = value.replace(c,'') return value; print remove(filename, '\/:*?"&lt;&gt;|') </code></pre>
13
2009-06-23T15:45:39Z
13,593,932
<p>I think the safest approach here is to just replace any suspicious characters. So, I think you can just replace (or get rid of) anything that isn't alphanumeric, -, _, a space, or a period. And here's how you do that:</p> <pre><code>import re re.sub('[^\w\-_\. ]', '_', filename) </code></pre> <p>The above escapes every character that's not a letter, <code>'_'</code>, <code>'-'</code>, <code>'.'</code> or space with an <code>'_'</code>. So, if you're looking at an entire path, you'll want to throw os.sep in the list of approved characters as well.</p> <p>Here's some sample output:</p> <pre><code>In [27]: re.sub('[^\w\-_\. ]', '_', 'some\\*-file._n\\\\ame') Out[27]: 'some__-file._n__ame' </code></pre>
7
2012-11-27T22:01:10Z
[ "python", "path" ]
python class attribute inheritance
1,033,443
<p>I am trying to save myself a bit of typing by writing the following code, but it seems I can't do this:</p> <pre><code>class lgrAdminObject(admin.ModelAdmin): fields = ["title","owner"] list_display = ["title","origin","approved", "sendToFrames"] class Photos(lgrAdminObject): fields.extend(["albums"]) </code></pre> <p>why doesn't that work? Also since they're not functions, I can't do the super trick</p> <pre><code>fields = super(Photos, self).fields fields.extend(["albums"]) </code></pre>
2
2009-06-23T15:47:56Z
1,033,516
<p>Inheritance applies <em>after</em> the class's body executes. In the class body, you can use <code>lgrAdminObject.fields</code> -- you sure you want to alter the superclass's attribute rather than making a copy of it first, though? Seems peculiar... I'd start with a copy:</p> <pre><code>class Photos(lgrAdminObject): fields = list(lgrAdminObject.fields) </code></pre> <p>before continuing with alterations.</p>
7
2009-06-23T15:59:32Z
[ "python", "django", "class", "inheritance" ]
python class attribute inheritance
1,033,443
<p>I am trying to save myself a bit of typing by writing the following code, but it seems I can't do this:</p> <pre><code>class lgrAdminObject(admin.ModelAdmin): fields = ["title","owner"] list_display = ["title","origin","approved", "sendToFrames"] class Photos(lgrAdminObject): fields.extend(["albums"]) </code></pre> <p>why doesn't that work? Also since they're not functions, I can't do the super trick</p> <pre><code>fields = super(Photos, self).fields fields.extend(["albums"]) </code></pre>
2
2009-06-23T15:47:56Z
1,033,525
<p>Have you tried this?</p> <pre><code>fields = lgrAdminObject.fields + ["albums"] </code></pre> <p>You need to create a new class attribute, not extend the one from the parent class.</p>
4
2009-06-23T16:00:38Z
[ "python", "django", "class", "inheritance" ]
python class attribute inheritance
1,033,443
<p>I am trying to save myself a bit of typing by writing the following code, but it seems I can't do this:</p> <pre><code>class lgrAdminObject(admin.ModelAdmin): fields = ["title","owner"] list_display = ["title","origin","approved", "sendToFrames"] class Photos(lgrAdminObject): fields.extend(["albums"]) </code></pre> <p>why doesn't that work? Also since they're not functions, I can't do the super trick</p> <pre><code>fields = super(Photos, self).fields fields.extend(["albums"]) </code></pre>
2
2009-06-23T15:47:56Z
1,033,543
<p>If you insist on using class attributes, you can reference the base class directly.</p> <pre><code>class Photos(lgrAdminObject): lgrAdminObject.fields.extend(["albums"]) </code></pre> <p>A trivial check follows:</p> <pre><code>&gt;&gt;&gt; class B0: ... fields = ["title","owner"] ... &gt;&gt;&gt; class C1(B0): ... B0.fields.extend(["albums"]) ... &gt;&gt;&gt; C1.fields ['title', 'owner', 'albums'] &gt;&gt;&gt; B0.fields ['title', 'owner', 'albums'] &gt;&gt;&gt; </code></pre> <p>Looks like the base attribute is modified as well, probably not what you were looking for. Look into defining some executable method (<code>__init__()</code>, maybe?).</p> <p>Or (better?) follow @Alex Martelli's suggestion and copy the base attribute:</p> <pre><code>&gt;&gt;&gt; class B0: ... fields = ["title","owner"] ... &gt;&gt;&gt; class C1(B0): ... fields = B0.fields[:] ... fields.extend(["albums"]) ... &gt;&gt;&gt; C1.fields ['title', 'owner', 'albums'] &gt;&gt;&gt; B0.fields ['title', 'owner'] &gt;&gt;&gt; </code></pre>
2
2009-06-23T16:03:07Z
[ "python", "django", "class", "inheritance" ]
python class attribute inheritance
1,033,443
<p>I am trying to save myself a bit of typing by writing the following code, but it seems I can't do this:</p> <pre><code>class lgrAdminObject(admin.ModelAdmin): fields = ["title","owner"] list_display = ["title","origin","approved", "sendToFrames"] class Photos(lgrAdminObject): fields.extend(["albums"]) </code></pre> <p>why doesn't that work? Also since they're not functions, I can't do the super trick</p> <pre><code>fields = super(Photos, self).fields fields.extend(["albums"]) </code></pre>
2
2009-06-23T15:47:56Z
1,034,359
<p>Also, note that when you have a list as a class attribute, it belongs to the class, not the instances. So if you modify it, it will change for all instances. It's probably better to use a tuple instead, unless you intend to modify it with this effect (and then you should document that clearly, because that is a common cause of confusion).</p>
1
2009-06-23T18:39:02Z
[ "python", "django", "class", "inheritance" ]
Monkeypatching a method call in Python
1,033,519
<p>How do I put off attribute access in Python?</p> <p>Let's assume we have:</p> <pre><code> def foo(): ... class Bar: ... bar = Bar() </code></pre> <p>Is it possible to implement Bar so that any time <code>bar</code> is accessed, a value returned by the callback <code>foo()</code> would be provided?</p> <p><code>bar</code> name already exists in the context. That's why it's access semantics should be preserved (it cannot be a callable, turning bar into a property of a class, using <code>SomeClass.bar</code> instead of <code>bar</code> also won't work). I need to keep everything as-is, but change the program so that <code>bar</code> would refer to on-the-fly generated data by <code>foo()</code>.</p> <p><strong>UPD</strong>: Thanks all for your answers, from which it seems impossible to do this type of thing in Python. I'm gonna find a workaround.</p>
-1
2009-06-23T16:00:02Z
1,033,555
<p>I guess you want to link some attribute "data" to foo:</p> <pre><code>class Bar: data = property(lambda self: foo()) bar = Bar() bar.data # calls foo() </code></pre>
6
2009-06-23T16:04:41Z
[ "python", "reference", "properties", "callback" ]
Monkeypatching a method call in Python
1,033,519
<p>How do I put off attribute access in Python?</p> <p>Let's assume we have:</p> <pre><code> def foo(): ... class Bar: ... bar = Bar() </code></pre> <p>Is it possible to implement Bar so that any time <code>bar</code> is accessed, a value returned by the callback <code>foo()</code> would be provided?</p> <p><code>bar</code> name already exists in the context. That's why it's access semantics should be preserved (it cannot be a callable, turning bar into a property of a class, using <code>SomeClass.bar</code> instead of <code>bar</code> also won't work). I need to keep everything as-is, but change the program so that <code>bar</code> would refer to on-the-fly generated data by <code>foo()</code>.</p> <p><strong>UPD</strong>: Thanks all for your answers, from which it seems impossible to do this type of thing in Python. I'm gonna find a workaround.</p>
-1
2009-06-23T16:00:02Z
1,033,604
<p>You're basically asking for a way to hijack a variable (how would you reassign it?) in the module namespace, which is not possible in Python.</p> <p>You'll have to use attribute accessors of a class if you want the described behavior:</p> <pre><code>class MyClass(object): def __getattr__(self, attr): if attr == 'bar': print 'getting bar... call the foo()!' else: return object.__getattribute__(self, attr) def __setattr__(self, attr, val): if attr == 'bar': print 'bar was set to', val else: object.__setattr__(self, attr, val) </code></pre>
2
2009-06-23T16:10:53Z
[ "python", "reference", "properties", "callback" ]
Monkeypatching a method call in Python
1,033,519
<p>How do I put off attribute access in Python?</p> <p>Let's assume we have:</p> <pre><code> def foo(): ... class Bar: ... bar = Bar() </code></pre> <p>Is it possible to implement Bar so that any time <code>bar</code> is accessed, a value returned by the callback <code>foo()</code> would be provided?</p> <p><code>bar</code> name already exists in the context. That's why it's access semantics should be preserved (it cannot be a callable, turning bar into a property of a class, using <code>SomeClass.bar</code> instead of <code>bar</code> also won't work). I need to keep everything as-is, but change the program so that <code>bar</code> would refer to on-the-fly generated data by <code>foo()</code>.</p> <p><strong>UPD</strong>: Thanks all for your answers, from which it seems impossible to do this type of thing in Python. I'm gonna find a workaround.</p>
-1
2009-06-23T16:00:02Z
1,033,624
<p>"any time bar is accessed"... What kinds of accesses are your callers going to be making? (E.g. are they doing "1+bar", are they doing "bar[5:]", are they doing "bar.func()", etc). Will they call the Bar() constructor each time?</p> <p>Right now, your question is so fuzzy and general that I think it's impossible. But if you're a bit more specific then we might be able to help.</p>
0
2009-06-23T16:14:25Z
[ "python", "reference", "properties", "callback" ]
Monkeypatching a method call in Python
1,033,519
<p>How do I put off attribute access in Python?</p> <p>Let's assume we have:</p> <pre><code> def foo(): ... class Bar: ... bar = Bar() </code></pre> <p>Is it possible to implement Bar so that any time <code>bar</code> is accessed, a value returned by the callback <code>foo()</code> would be provided?</p> <p><code>bar</code> name already exists in the context. That's why it's access semantics should be preserved (it cannot be a callable, turning bar into a property of a class, using <code>SomeClass.bar</code> instead of <code>bar</code> also won't work). I need to keep everything as-is, but change the program so that <code>bar</code> would refer to on-the-fly generated data by <code>foo()</code>.</p> <p><strong>UPD</strong>: Thanks all for your answers, from which it seems impossible to do this type of thing in Python. I'm gonna find a workaround.</p>
-1
2009-06-23T16:00:02Z
1,033,810
<p>Is this what you're looking for?</p> <pre><code>&gt;&gt;&gt; def foo(): print('foo() was called'); ... &gt;&gt;&gt; class Bar: ... pass; ... &gt;&gt;&gt; bar = Bar(); &gt;&gt;&gt; bar.data = foo; &gt;&gt;&gt; bar.data() foo() was called &gt;&gt;&gt; </code></pre>
0
2009-06-23T16:49:06Z
[ "python", "reference", "properties", "callback" ]
Monkeypatching a method call in Python
1,033,519
<p>How do I put off attribute access in Python?</p> <p>Let's assume we have:</p> <pre><code> def foo(): ... class Bar: ... bar = Bar() </code></pre> <p>Is it possible to implement Bar so that any time <code>bar</code> is accessed, a value returned by the callback <code>foo()</code> would be provided?</p> <p><code>bar</code> name already exists in the context. That's why it's access semantics should be preserved (it cannot be a callable, turning bar into a property of a class, using <code>SomeClass.bar</code> instead of <code>bar</code> also won't work). I need to keep everything as-is, but change the program so that <code>bar</code> would refer to on-the-fly generated data by <code>foo()</code>.</p> <p><strong>UPD</strong>: Thanks all for your answers, from which it seems impossible to do this type of thing in Python. I'm gonna find a workaround.</p>
-1
2009-06-23T16:00:02Z
1,034,142
<p>Thanks for the clarification!</p> <p>This just can't work! A variable is a variable in most languages, not a function-call. You can do much in Python, but you just can't do that.</p> <p>The reason is, that you have always some intrinsic language rules. One rule in Python is, that variables are variables. When you read a variable (not modifying it or anything else) you can rely, that it will be the same in the next code-line.</p> <p>Monkeypatching it to be a function call would just change this rule.</p> <p>What you want, could only be done by a still more dynamic language. Something like a macro-processing system or a language that do not have variables but something like labels that can be attached to anything. But this would also make compiler-creation for it much more difficult -- hence fully dynamic. The compiler would have to take all coding in the program into account.</p>
0
2009-06-23T17:58:38Z
[ "python", "reference", "properties", "callback" ]
Monkeypatching a method call in Python
1,033,519
<p>How do I put off attribute access in Python?</p> <p>Let's assume we have:</p> <pre><code> def foo(): ... class Bar: ... bar = Bar() </code></pre> <p>Is it possible to implement Bar so that any time <code>bar</code> is accessed, a value returned by the callback <code>foo()</code> would be provided?</p> <p><code>bar</code> name already exists in the context. That's why it's access semantics should be preserved (it cannot be a callable, turning bar into a property of a class, using <code>SomeClass.bar</code> instead of <code>bar</code> also won't work). I need to keep everything as-is, but change the program so that <code>bar</code> would refer to on-the-fly generated data by <code>foo()</code>.</p> <p><strong>UPD</strong>: Thanks all for your answers, from which it seems impossible to do this type of thing in Python. I'm gonna find a workaround.</p>
-1
2009-06-23T16:00:02Z
1,034,209
<p>You can override Bar's __new__ method to execute arbitrary code and return a new instance. See: <a href="http://docs.python.org/reference/datamodel.html#object.__new__" rel="nofollow">http://docs.python.org/reference/datamodel.html#object.__new__</a></p> <p>Here's a contrived example:</p> <pre><code>&gt;&gt;&gt; class Bar(object): ... def __new__(cls): ... print "Calling Bar.__new__" ... return super(Bar, cls).__new__(cls) ... &gt;&gt;&gt; bar = Bar() Calling Bar.__new__ &gt;&gt;&gt; bar &lt;__main__.Bar object at 0x0222B3D0&gt; </code></pre> <p>EDIT: I misunderstood what you wanted, your clarification cleared that up. I don't think what you want is possible.</p>
0
2009-06-23T18:12:43Z
[ "python", "reference", "properties", "callback" ]
Monkeypatching a method call in Python
1,033,519
<p>How do I put off attribute access in Python?</p> <p>Let's assume we have:</p> <pre><code> def foo(): ... class Bar: ... bar = Bar() </code></pre> <p>Is it possible to implement Bar so that any time <code>bar</code> is accessed, a value returned by the callback <code>foo()</code> would be provided?</p> <p><code>bar</code> name already exists in the context. That's why it's access semantics should be preserved (it cannot be a callable, turning bar into a property of a class, using <code>SomeClass.bar</code> instead of <code>bar</code> also won't work). I need to keep everything as-is, but change the program so that <code>bar</code> would refer to on-the-fly generated data by <code>foo()</code>.</p> <p><strong>UPD</strong>: Thanks all for your answers, from which it seems impossible to do this type of thing in Python. I'm gonna find a workaround.</p>
-1
2009-06-23T16:00:02Z
1,034,275
<p>If you want the results of foo(), the easiest way is to do this:</p> <pre><code>foo() </code></pre> <p>Anything else is just unnecessary complication. I suspect that you have oversimplified your example until it doens't make sense.</p> <p>Edit: OK, so you are trying to change somebody elses code. No, it's not possible to transform a variable to a method in a generic way. You could replace it with an object that will return different variables of it's used in a way that consistently will cause some sort of python method to be called. </p> <p>barrio.py: bar = "Some sort of string"</p> <p>fool.py:</p> <pre><code>import random class Foo: def __str__(self): return str(random.random()) import barrio barrio.bar = Foo() </code></pre> <p>Now run python:</p> <pre><code>&gt;&gt;&gt; import fool &gt;&gt;&gt; import barrio &gt;&gt;&gt; print barrio.bar 0.783394625457 &gt;&gt;&gt; print barrio.bar 0.662363816543 &gt;&gt;&gt; print barrio.bar 0.342930701226 &gt;&gt;&gt; print barrio.bar 0.781452467433 </code></pre> <p>This works because print will call <strong>str</strong> on the object, since it's not a string. But in general, no, it's not possible.</p>
0
2009-06-23T18:22:30Z
[ "python", "reference", "properties", "callback" ]
Methods for modular customization of locale messages?
1,033,580
<p>There many levels for the customization of programs.</p> <p>First of course is making it <strong>speak your language</strong> by creating i18n messages where tools like gettext and xgettext do a great job.</p> <p>Another comes when you need to <strong>modify the meaning</strong> of some messages to suite the purpose of your project.</p> <p><strong>The question is</strong>: is it possible to keep customized messages in a separate file in addition to the boilerplate translation and have the standard tools understand that customized messages take precedence?</p> <p>This would help to keep those messages from being committed to the public repository and from being overwritten by the boilerplate text when upgrading.</p> <p><strong>edit:</strong> since not too many people care about localization I think it's appropriate to collect answers for any platform, however I'm at the moment interested to implement this python/django.</p>
0
2009-06-23T16:07:24Z
1,034,057
<p>In Java, these localized strings are handled by ResourceBundles. ResourceBundles have a concept of variants. For example, you could have a base English resource, called <code>messages_en.propertie</code>s. Then you could customize for a specific variant of English with <code>message_en_US.properties</code> or <code>message_en_UK.properties</code>.</p> <p>US and UK are ISO country codes, but you could also setup your own custom variants that just contain those strings that you want to customize. For example:</p> <pre><code>#messages_en.properties button.click=Click label.go=Go #messages_en_ZZ.properties button.click=Click Me </code></pre> <p>By setting the locale to <code>en_ZZ</code>, your application would first look in <code>messages_en_ZZ.properties</code> to see if the customized string existed, and then fall back to <code>messages_en.properties</code> for your boilerplate translations. [More info on ResourceBundle loading precedence][1]</p> <p>[1]: <a href="http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.html#getBundle" rel="nofollow">http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.html#getBundle</a>(java.lang.String, java.util.Locale, java.lang.ClassLoader)</p>
1
2009-06-23T17:43:51Z
[ "python", "language-agnostic", "localization", "internationalization", "customization" ]
Methods for modular customization of locale messages?
1,033,580
<p>There many levels for the customization of programs.</p> <p>First of course is making it <strong>speak your language</strong> by creating i18n messages where tools like gettext and xgettext do a great job.</p> <p>Another comes when you need to <strong>modify the meaning</strong> of some messages to suite the purpose of your project.</p> <p><strong>The question is</strong>: is it possible to keep customized messages in a separate file in addition to the boilerplate translation and have the standard tools understand that customized messages take precedence?</p> <p>This would help to keep those messages from being committed to the public repository and from being overwritten by the boilerplate text when upgrading.</p> <p><strong>edit:</strong> since not too many people care about localization I think it's appropriate to collect answers for any platform, however I'm at the moment interested to implement this python/django.</p>
0
2009-06-23T16:07:24Z
1,036,232
<p>I think Qt's powerful i18n facilities (see <a href="http://doc.trolltech.com/4.5/i18n.html" rel="nofollow">here</a>) might meet your needs -- of course, they're available in Python, too, thanks to the usual, blessed <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQt</a>!-)</p>
1
2009-06-24T03:13:57Z
[ "python", "language-agnostic", "localization", "internationalization", "customization" ]
Python package install using pip or easy_install from repos
1,033,897
<p>The simplest way to deal with python package installations, so far, to me, has been to check out the source from the source control system and then add a symbolic link in the python dist-packages folder.</p> <p>Clearly since source control provides the complete control to downgrade, upgrade to any branch, tag, it works very well.</p> <p>Is there a way using one of the Package installers (easy_install or pip or other), one can achieve the same.</p> <p>easy_install obtains the tar.gz and install them using the setup.py install which installs in the dist-packages folder in python2.6. Is there a way to configure it, or pip to use the source version control system (SVN/GIT/Hg/Bzr) instead.</p>
14
2009-06-23T17:07:30Z
1,034,006
<p>If you download or check out the source distribution of a package — the one that has its "setup.py" inside of it — then if the package is based on the "setuptools" (which also power easy_install), you can move into that directory and say:</p> <pre><code>$ python setup.py develop </code></pre> <p>and it will create the right symlinks in dist-packages so that the .py files in the source distribution are the ones that get imported, rather than copies installed separately (which is what "setup.py install" would do — create separate copies that don't change immediately when you edit the source code to try a change).</p> <p>As the other response indicates, you should try reading the "setuptools" documentation to learn more. "setup.py develop" is a really useful feature! Try using it in combination with a virtualenv, and you can "setup.py develop" painlessly and without messing up your system-wide Python with packages you are only developing on temporarily:</p> <pre><code>http://pypi.python.org/pypi/virtualenv </code></pre>
11
2009-06-23T17:32:22Z
[ "python", "svn", "version-control", "easy-install", "pip" ]
Python package install using pip or easy_install from repos
1,033,897
<p>The simplest way to deal with python package installations, so far, to me, has been to check out the source from the source control system and then add a symbolic link in the python dist-packages folder.</p> <p>Clearly since source control provides the complete control to downgrade, upgrade to any branch, tag, it works very well.</p> <p>Is there a way using one of the Package installers (easy_install or pip or other), one can achieve the same.</p> <p>easy_install obtains the tar.gz and install them using the setup.py install which installs in the dist-packages folder in python2.6. Is there a way to configure it, or pip to use the source version control system (SVN/GIT/Hg/Bzr) instead.</p>
14
2009-06-23T17:07:30Z
1,034,335
<p>easy_install has support for downloading specific versions. For example:</p> <pre><code>easy_install python-dateutil==1.4.0 </code></pre> <p>Will install v1.4, while the latest version 1.4.1 would be picked if no version was specified.</p> <p>There is also support for svn checkouts, but using that doesn't give you much benefits from your manual version. See the manual for more information above.</p> <p>Being able to switch to specific branches is rarely useful unless you are developing the packages in question, and then it's typically not a good idea to install them in site-packages anyway.</p>
4
2009-06-23T18:35:33Z
[ "python", "svn", "version-control", "easy-install", "pip" ]
Python package install using pip or easy_install from repos
1,033,897
<p>The simplest way to deal with python package installations, so far, to me, has been to check out the source from the source control system and then add a symbolic link in the python dist-packages folder.</p> <p>Clearly since source control provides the complete control to downgrade, upgrade to any branch, tag, it works very well.</p> <p>Is there a way using one of the Package installers (easy_install or pip or other), one can achieve the same.</p> <p>easy_install obtains the tar.gz and install them using the setup.py install which installs in the dist-packages folder in python2.6. Is there a way to configure it, or pip to use the source version control system (SVN/GIT/Hg/Bzr) instead.</p>
14
2009-06-23T17:07:30Z
1,446,729
<p>easy_install accepts a URL for the source tree too. Works at least when the sources are in Subversion.</p>
0
2009-09-18T20:39:07Z
[ "python", "svn", "version-control", "easy-install", "pip" ]
Python package install using pip or easy_install from repos
1,033,897
<p>The simplest way to deal with python package installations, so far, to me, has been to check out the source from the source control system and then add a symbolic link in the python dist-packages folder.</p> <p>Clearly since source control provides the complete control to downgrade, upgrade to any branch, tag, it works very well.</p> <p>Is there a way using one of the Package installers (easy_install or pip or other), one can achieve the same.</p> <p>easy_install obtains the tar.gz and install them using the setup.py install which installs in the dist-packages folder in python2.6. Is there a way to configure it, or pip to use the source version control system (SVN/GIT/Hg/Bzr) instead.</p>
14
2009-06-23T17:07:30Z
1,625,662
<p>Using <a href="http://pip.openplans.org/">pip</a> this is quite easy. For instance:</p> <pre><code>pip install -e hg+http://bitbucket.org/andrewgodwin/south/#egg=South </code></pre> <p>Pip will automatically clone the source repo and run "setup.py develop" for you to install it into your environment (which hopefully is a <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>). Git, Subversion, Bazaar and Mercurial are all supported. </p> <p>You can also then run "pip freeze" and it will output a list of your currently-installed packages with their exact versions (including, for develop-installs, the exact revision from the VCS). You can put this straight into a requirements file and later run</p> <pre><code>pip install -r requirements.txt </code></pre> <p>to install that same set of packages at the exact same versions.</p>
26
2009-10-26T16:08:10Z
[ "python", "svn", "version-control", "easy-install", "pip" ]
Per-session transactions in Django
1,033,934
<p>I'm making a Django web-app which allows a user to build up a set of changes over a series of GETs/POSTs before committing them to the database (or reverting) with a final POST. I have to keep the updates isolated from any concurrent database users until they are confirmed (this is a configuration front-end), ruling out committing after each POST.</p> <p>My preferred solution is to use a per-session transaction. This keeps all the problems of remembering what's changed (and how it affects subsequent queries), together with implementing commit/rollback, in the database where it belongs. Deadlock and long-held locks are not an issue, as due to external constraints there can only be one user configuring the system at any one time, and they are well-behaved.</p> <p>However, I cannot find documentation on setting up Django's ORM to use this sort of transaction model. I have thrown together a minimal monkey-patch (ew!) to solve the problem, but dislike such a fragile solution. Has anyone else done this before? Have I missed some documentation somewhere?</p> <p>(My version of Django is 1.0.2 Final, and I am using an Oracle database.)</p>
7
2009-06-23T17:16:29Z
1,033,973
<p>Multiple, concurrent, session-scale transactions will generally lead to deadlocks or worse (worse == livelock, long delays while locks are held by another session.)</p> <p>This design is not the best policy, which is why Django discourages it.</p> <p>The better solution is the following.</p> <ol> <li><p>Design a <strong>Memento</strong> class that records the user's change. This could be a saved copy of their form input. You may need to record additional information if the state changes are complex. Otherwise, a copy of the form input may be enough.</p></li> <li><p>Accumulate the sequence of <strong>Memento</strong> objects in their session. Note that each step in the transaction will involve fetches from the data and validation to see if the chain of mementos will still "work". Sometimes they won't work because someone else changed something in this chain of mementos. What now?</p></li> <li><p>When you present the 'ready to commit?' page, you've replayed the sequence of <strong>Mementos</strong> and are pretty sure they'll work. When the submit "Commit", you have to replay the <strong>Mementos</strong> one last time, hoping they're still going to work. If they do, great. If they don't, someone changed something, and you're back at step 2: what now?</p></li> </ol> <p>This seems complex.</p> <p>Yes, it does. However it does not hold any locks, allowing blistering speed and little opportunity for deadlock. The transaction is confined to the "Commit" view function which actually applies the sequence of <strong>Mementos</strong> to the database, saves the results, and does a final commit to end the transaction.</p> <p>The alternative -- holding locks while the user steps out for a quick cup of coffee on step n-1 out of n -- is unworkable.</p> <p>For more information on <strong>Memento</strong>, see <a href="http://en.wikipedia.org/wiki/Memento%5Fpattern" rel="nofollow">this</a>.</p>
9
2009-06-23T17:24:42Z
[ "python", "django", "transactions" ]
Per-session transactions in Django
1,033,934
<p>I'm making a Django web-app which allows a user to build up a set of changes over a series of GETs/POSTs before committing them to the database (or reverting) with a final POST. I have to keep the updates isolated from any concurrent database users until they are confirmed (this is a configuration front-end), ruling out committing after each POST.</p> <p>My preferred solution is to use a per-session transaction. This keeps all the problems of remembering what's changed (and how it affects subsequent queries), together with implementing commit/rollback, in the database where it belongs. Deadlock and long-held locks are not an issue, as due to external constraints there can only be one user configuring the system at any one time, and they are well-behaved.</p> <p>However, I cannot find documentation on setting up Django's ORM to use this sort of transaction model. I have thrown together a minimal monkey-patch (ew!) to solve the problem, but dislike such a fragile solution. Has anyone else done this before? Have I missed some documentation somewhere?</p> <p>(My version of Django is 1.0.2 Final, and I am using an Oracle database.)</p>
7
2009-06-23T17:16:29Z
1,057,379
<p>In case anyone else ever has the exact same problem as me (I hope not), here is my monkeypatch. It's fragile and ugly, and changes private methods, but thankfully it's small. Please don't use it unless you really have to. As mentioned by others, any application using it effectively prevents multiple users doing updates at the same time, on penalty of deadlock. (In my application, there may be many readers, but multiple concurrent updates are deliberately excluded.)</p> <p>I have a "user" object which persists across a user session, and contains a persistent connection object. When I validate a particular HTTP interaction is part of a session, I also store the user object on django.db.connection, which is thread-local.</p> <pre><code>def monkeyPatchDjangoDBConnection(): import django.db def validConnection(): if django.db.connection.connection is None: django.db.connection.connection = django.db.connection.user.connection return True def close(): django.db.connection.connection = None django.db.connection._valid_connection = validConnection django.db.connection.close = close monkeyPatchDBConnection() def setUserOnThisThread(user): import django.db django.db.connection.user = user </code></pre> <p>This last is called automatically at the start of any method annotated with @login_required, so 99% of my code is insulated from the specifics of this hack.</p>
1
2009-06-29T09:23:48Z
[ "python", "django", "transactions" ]
Per-session transactions in Django
1,033,934
<p>I'm making a Django web-app which allows a user to build up a set of changes over a series of GETs/POSTs before committing them to the database (or reverting) with a final POST. I have to keep the updates isolated from any concurrent database users until they are confirmed (this is a configuration front-end), ruling out committing after each POST.</p> <p>My preferred solution is to use a per-session transaction. This keeps all the problems of remembering what's changed (and how it affects subsequent queries), together with implementing commit/rollback, in the database where it belongs. Deadlock and long-held locks are not an issue, as due to external constraints there can only be one user configuring the system at any one time, and they are well-behaved.</p> <p>However, I cannot find documentation on setting up Django's ORM to use this sort of transaction model. I have thrown together a minimal monkey-patch (ew!) to solve the problem, but dislike such a fragile solution. Has anyone else done this before? Have I missed some documentation somewhere?</p> <p>(My version of Django is 1.0.2 Final, and I am using an Oracle database.)</p>
7
2009-06-23T17:16:29Z
1,121,915
<p>I came up with something similar to the Memento pattern, but different enough that I think it bears posting. When a user starts an editing session, I duplicate the target object to a temporary object in the database. All subsequent editing operations affect the duplicate. Instead of saving the object state in a <strong>memento</strong> at each change, I store <strong>operation</strong> objects. When I apply an operation to an object, it returns the <em>inverse</em> operation, which I store. </p> <p>Saving operations is much cheaper for me than mementos, since the operations can be described with a few small data items, while the object being edited is much bigger. Also I apply the operations as I go and save the undos, so that the temporary in the db always corresponds to the version in the user's browser. I never have to replay a collection of changes; the temporary is always only one operation away from the next version.</p> <p>To implement "undo," I pop the last undo object off the stack (as it were--by retrieving the latest operation for the temporary object from the db) apply it to the temporary and return the transformed temporary. I could also push the resultant operation onto a redo stack if I cared to implement redo.</p> <p>To implement "save changes," i.e. commit, I de-activate and time-stamp the original object and activate the temporary in it's place.</p> <p>To implement "cancel," i.e. rollback, I do nothing! I could delete the temporary, of course, because there's no way for the user to retrieve it once the editing session is over, but I like to keep the canceled edit sessions so I can run stats on them before clearing them out with a cron job.</p>
2
2009-07-13T20:42:10Z
[ "python", "django", "transactions" ]
What is the difference between converting to hex on the client end and using rawtohex?
1,034,068
<p>I have a table that's created like this:</p> <pre><code>CREATE TABLE bin_test (id INTEGER PRIMARY KEY, b BLOB) </code></pre> <p>Using Python and cx_Oracle, if I do this:</p> <pre><code>value = "\xff\x00\xff\x00" #The string represented in hex by ff00ff00 self.connection.execute("INSERT INTO bin_test (b) VALUES (rawtohex(?))", (value,)) self.connection.execute("SELECT b FROM bin_test") </code></pre> <p>I eventually end up with a hex value of <code>a000a000</code>, which isn't correct! However if I do this:</p> <pre><code>import binascii value = "\xff\x00\xff\x00" self.connection.execute("INSERT INTO bin_test (b) VALUES (?)", (binascii.hexlify(value,))) self.connection.execute("SELECT b FROM bin_test") </code></pre> <p>I get the correct result. I have a type conversion system here, but it's a bit difficult to describe it here. Thus, can someone point me in the right direction as to whether I'm doing something wrong at the SQL level or whether something weird is happening with my conversions?</p>
2
2009-06-23T17:46:24Z
1,034,098
<p><code>RAWTOHEX</code> in <code>Oracle</code> is bit order insensitive, while on your machine it's of course sensitive.</p> <p>Also note that an argument to <code>RAWTOHEX()</code> can be implicitly converted to <code>VARCHAR2</code> by your library (i. e. transmitted as <code>SQLT_STR</code>), which makes it also encoding and collation sensitive.</p>
1
2009-06-23T17:51:15Z
[ "python", "oracle", "oracle10g", "blob", "cx-oracle" ]
What is the difference between converting to hex on the client end and using rawtohex?
1,034,068
<p>I have a table that's created like this:</p> <pre><code>CREATE TABLE bin_test (id INTEGER PRIMARY KEY, b BLOB) </code></pre> <p>Using Python and cx_Oracle, if I do this:</p> <pre><code>value = "\xff\x00\xff\x00" #The string represented in hex by ff00ff00 self.connection.execute("INSERT INTO bin_test (b) VALUES (rawtohex(?))", (value,)) self.connection.execute("SELECT b FROM bin_test") </code></pre> <p>I eventually end up with a hex value of <code>a000a000</code>, which isn't correct! However if I do this:</p> <pre><code>import binascii value = "\xff\x00\xff\x00" self.connection.execute("INSERT INTO bin_test (b) VALUES (?)", (binascii.hexlify(value,))) self.connection.execute("SELECT b FROM bin_test") </code></pre> <p>I get the correct result. I have a type conversion system here, but it's a bit difficult to describe it here. Thus, can someone point me in the right direction as to whether I'm doing something wrong at the SQL level or whether something weird is happening with my conversions?</p>
2
2009-06-23T17:46:24Z
1,034,127
<p>rawtohex() is for converting Oracles RAW datatypes to hex strings. It's possible it gets confused by you passing it a string, even if the string contains binary data. In this case, since Oracle expects a string of hex characters, give it a string of hex characters.</p>
1
2009-06-23T17:55:29Z
[ "python", "oracle", "oracle10g", "blob", "cx-oracle" ]
What is the difference between converting to hex on the client end and using rawtohex?
1,034,068
<p>I have a table that's created like this:</p> <pre><code>CREATE TABLE bin_test (id INTEGER PRIMARY KEY, b BLOB) </code></pre> <p>Using Python and cx_Oracle, if I do this:</p> <pre><code>value = "\xff\x00\xff\x00" #The string represented in hex by ff00ff00 self.connection.execute("INSERT INTO bin_test (b) VALUES (rawtohex(?))", (value,)) self.connection.execute("SELECT b FROM bin_test") </code></pre> <p>I eventually end up with a hex value of <code>a000a000</code>, which isn't correct! However if I do this:</p> <pre><code>import binascii value = "\xff\x00\xff\x00" self.connection.execute("INSERT INTO bin_test (b) VALUES (?)", (binascii.hexlify(value,))) self.connection.execute("SELECT b FROM bin_test") </code></pre> <p>I get the correct result. I have a type conversion system here, but it's a bit difficult to describe it here. Thus, can someone point me in the right direction as to whether I'm doing something wrong at the SQL level or whether something weird is happening with my conversions?</p>
2
2009-06-23T17:46:24Z
1,710,558
<p>I usually set the proper type of variable bindings specially when trying to pass an Oracle kinda of RAW data type into a query.</p> <p>for example something like:</p> <pre><code>self.connection.setinputsizes(cx_Oracle.BINARY) self.connection.execute( "INSERT INTO bin_test (b) VALUES (rawtohex(?))", (value,) )</code></pre>
0
2009-11-10T19:29:34Z
[ "python", "oracle", "oracle10g", "blob", "cx-oracle" ]
Python List Question
1,034,145
<p>i have an issue i could use some help with, i have python list that looks like this:</p> <pre><code>fail = [ ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', 'svin.txt'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] sha1 value, directory, filename </code></pre> <p>What i want is to separate this content in two different lists based on the sha1 value and directory. For example.</p> <pre><code>['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] </code></pre> <p>i want to add to the list <code>duplicate = []</code>, because it's in the same directory with the same sha1 value (and only that directory). The rest of the entries i want to add to another list, say <code>diff = []</code>, because the sha1 value is the same but the directories differ.</p> <p>I'm kinda lost with the logic here so all that help i could get would be thankful!</p> <p>EDIT: Fixed a typo, last value (filename) was in some cases a 1-list element, which was 100% incorrect, thansk to SilentGhost to become aware of this issue.</p>
1
2009-06-23T18:00:27Z
1,034,254
<p>you could simply loop through all the values then use an inner loop to compare directories, then if the directory is the same compare values, then assign lists. this would give you a decent n^2 algorithm to sort it out.</p> <p>maybe like this untested code:</p> <pre><code>&gt;&gt;&gt;for i in range(len(fail)-1): ... dir = fail[i][1] ... sha1 = fail[i][0] ... for j in range(i+1,len(fail)): ... if dir == fail[j][1]: #is this how you compare strings? ... if sha1 == fail[j][0]: ... #remove from fail and add to duplicate and add other to diff </code></pre> <p>again the code is untested.</p>
1
2009-06-23T18:19:21Z
[ "python", "list" ]
Python List Question
1,034,145
<p>i have an issue i could use some help with, i have python list that looks like this:</p> <pre><code>fail = [ ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', 'svin.txt'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] sha1 value, directory, filename </code></pre> <p>What i want is to separate this content in two different lists based on the sha1 value and directory. For example.</p> <pre><code>['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] </code></pre> <p>i want to add to the list <code>duplicate = []</code>, because it's in the same directory with the same sha1 value (and only that directory). The rest of the entries i want to add to another list, say <code>diff = []</code>, because the sha1 value is the same but the directories differ.</p> <p>I'm kinda lost with the logic here so all that help i could get would be thankful!</p> <p>EDIT: Fixed a typo, last value (filename) was in some cases a 1-list element, which was 100% incorrect, thansk to SilentGhost to become aware of this issue.</p>
1
2009-06-23T18:00:27Z
1,034,453
<pre><code>duplicate = [] # Sort the list so we can compare adjacent values fail.sort() #if you didn't want to modify the list in place you can use: #sortedFail = sorted(fail) # and then use sortedFail in the rest of the code instead of fail for i, x in enumerate(fail): if i+1 == len(fail): #end of the list break if x[:2] == fail[i+1][:2]: if x not in duplicate: duplicate.add(x) if fail[i+1] not in duplicate: duplicate.add(fail[i+1]) # diff is just anything not in duplicate as far as I can tell from the explanation diff = [d for d in fail if d not in duplicate] </code></pre> <p>With your example input </p> <pre><code>duplicate: [ ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', ['apa.txt']], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ] diff: [ ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', ['apa2.txt']], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'], ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', ['svin.txt']], ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'], ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'] ] </code></pre> <p>So perhaps I missed something, but I think this is what you were asking for.</p>
3
2009-06-23T18:54:37Z
[ "python", "list" ]
Python List Question
1,034,145
<p>i have an issue i could use some help with, i have python list that looks like this:</p> <pre><code>fail = [ ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', 'svin.txt'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] sha1 value, directory, filename </code></pre> <p>What i want is to separate this content in two different lists based on the sha1 value and directory. For example.</p> <pre><code>['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] </code></pre> <p>i want to add to the list <code>duplicate = []</code>, because it's in the same directory with the same sha1 value (and only that directory). The rest of the entries i want to add to another list, say <code>diff = []</code>, because the sha1 value is the same but the directories differ.</p> <p>I'm kinda lost with the logic here so all that help i could get would be thankful!</p> <p>EDIT: Fixed a typo, last value (filename) was in some cases a 1-list element, which was 100% incorrect, thansk to SilentGhost to become aware of this issue.</p>
1
2009-06-23T18:00:27Z
1,034,542
<p>Here's another way to go at it using dictionaries to group by sha and directory. This also gets rid of the random lists in the file names.</p> <pre><code>new_fail = {} # {sha: {dir: [filenames]}} for item in fail: # split data into it's parts sha, directory, filename = item # make sure the correct elements exist in the data structure if sha not in new_fail: new_fail[sha] = {} if directory not in new_fail[sha]: new_fail[sha][directory] = [] # this is where the lists are removed from the file names if type(filename) == type([]): filename = filename[0] new_fail[sha][directory].append(filename) diff = [] dup = [] # loop through the data, analyzing it for sha, val in new_fail.iteritems(): for directory, filenames in val.iteritems(): # check to see if the sha/dir combo has more than one file name if len(filenames) &gt; 1: for filename in filenames: dup.append([sha, directory, filename]) else: diff.append([sha, dir, filenames[0]]) </code></pre> <p>To print it:</p> <pre><code>print 'diff:' for i in diff: print i print '\ndup:' for i in dup: print i </code></pre> <p>Sample data looks like this:</p> <pre> diff: ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', 'svin.txt'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'] dup: ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt']</pre>
0
2009-06-23T19:11:01Z
[ "python", "list" ]
Python List Question
1,034,145
<p>i have an issue i could use some help with, i have python list that looks like this:</p> <pre><code>fail = [ ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', 'svin.txt'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] sha1 value, directory, filename </code></pre> <p>What i want is to separate this content in two different lists based on the sha1 value and directory. For example.</p> <pre><code>['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] </code></pre> <p>i want to add to the list <code>duplicate = []</code>, because it's in the same directory with the same sha1 value (and only that directory). The rest of the entries i want to add to another list, say <code>diff = []</code>, because the sha1 value is the same but the directories differ.</p> <p>I'm kinda lost with the logic here so all that help i could get would be thankful!</p> <p>EDIT: Fixed a typo, last value (filename) was in some cases a 1-list element, which was 100% incorrect, thansk to SilentGhost to become aware of this issue.</p>
1
2009-06-23T18:00:27Z
1,034,556
<p>In the following code sample, I use a key based on the SHA1 and directory name to detect unique and duplicate entries and spare dictionaries for housekeeping. </p> <pre><code># Test dataset fail = [ ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'], ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', ['svin.txt']], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', ['apa2.txt']], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', ['apa.txt']], ] def sort_duplicates(filelist): """Returns a tuplie whose first element is a list of unique files, and second element is a list of duplicate files. """ diff = [] diff_d = {} duplicate = [] duplicate_d = {} for entry in filelist: # Make an immutable key based on the SHA-1 and directory strings key = (entry[0], entry[1]) # If this entry is a known duplicate, add it to the duplicate list if key in duplicate_d: duplicate.append(entry) # If this entry is a new duplicate, add it to the duplicate list elif key in diff_d: duplicate.append(entry) duplicate_d[key] = entry # And relocate the matching entry to the duplicate list matching_entry = diff_d[key] duplicate.append(matching_entry) duplicate_d[key] = matching_entry del diff_d[key] diff.remove(matching_entry) # Otherwise add this entry to the different list else: diff.append(entry) diff_d[key] = entry return (diff, duplicate) def test(): global fail diff, dups = sort_duplicates(fail) print "Diff:", diff print "Dups:", dups test() </code></pre>
1
2009-06-23T19:13:15Z
[ "python", "list" ]
Python List Question
1,034,145
<p>i have an issue i could use some help with, i have python list that looks like this:</p> <pre><code>fail = [ ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', 'svin.txt'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] sha1 value, directory, filename </code></pre> <p>What i want is to separate this content in two different lists based on the sha1 value and directory. For example.</p> <pre><code>['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] </code></pre> <p>i want to add to the list <code>duplicate = []</code>, because it's in the same directory with the same sha1 value (and only that directory). The rest of the entries i want to add to another list, say <code>diff = []</code>, because the sha1 value is the same but the directories differ.</p> <p>I'm kinda lost with the logic here so all that help i could get would be thankful!</p> <p>EDIT: Fixed a typo, last value (filename) was in some cases a 1-list element, which was 100% incorrect, thansk to SilentGhost to become aware of this issue.</p>
1
2009-06-23T18:00:27Z
1,034,700
<p>I believe the accepted answer will be slightly more efficient (Python's internal sort should be faster than my dictionary walk), but since I already came up with this, I may as well post it. :-)</p> <p>This technique uses a multilevel dictionary to avoid both sorting and explicit comparisons.</p> <pre><code>hashes = {} diff = [] dupe = [] # build the dictionary for sha, path, files in fail: try: hashes[sha][path].append(files) except KeyError: try: hashes[sha][path] = [files] except: hashes[sha] = dict((path, [files])) for sha, paths in hashes.iteritems(): if len(paths) &gt; 1: for path, files in paths.iteritems(): for file in files: diff.append([sha, path, file]) for path, files in paths.iteritems(): if len(files) &gt; 1: for file in files: dupe.append([sha, path, file]) </code></pre> <p>The result will be:</p> <pre><code>diff = [ ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'], ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'], ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', ['svin.txt']], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', ['apa2.txt']], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'] ] dupe = [ [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', ['apa.txt']] ] </code></pre>
0
2009-06-23T19:36:02Z
[ "python", "list" ]
wxPython: Making something expand
1,034,399
<p>How do I make any wxPython widget (like wx.Panel or wx.Button) automatically expand to fill its parent window?</p>
4
2009-06-23T18:46:44Z
1,034,455
<p>The short answer: use a sizer with a proportion of 1 and the wx.Expand tag.</p> <p>So here I am in the <strong>init</strong> of a panel</p> <pre><code>sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.EXPAND) self.SetSizer(sizer) </code></pre>
8
2009-06-23T18:55:11Z
[ "python", "user-interface", "wxpython" ]
wxPython: Making something expand
1,034,399
<p>How do I make any wxPython widget (like wx.Panel or wx.Button) automatically expand to fill its parent window?</p>
4
2009-06-23T18:46:44Z
1,036,283
<p>this shows how you can expand child panel with frame resize it also show how you can switch two panels, one containing cntrls and one containing help I think this solves all your problems</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.panel = wx.Panel(self) # create controls self.cntrlPanel = wx.Panel(self.panel) stc1 = wx.StaticText(self.cntrlPanel, label="wow it works") stc2 = wx.StaticText(self.cntrlPanel, label="yes it works") btn = wx.Button(self.cntrlPanel, label="help?") btn.Bind(wx.EVT_BUTTON, self._onShowHelp) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(stc1) sizer.Add(stc2) sizer.Add(btn) self.cntrlPanel.SetSizer(sizer) # create help panel self.helpPanel = wx.Panel(self.panel) self.stcHelp = wx.StaticText(self.helpPanel, label="help help help\n"*8) btn = wx.Button(self.helpPanel, label="close[x]") btn.Bind(wx.EVT_BUTTON, self._onShowCntrls) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.stcHelp) sizer.Add(btn) self.helpPanel.SetSizer(sizer) self.helpPanel.Hide() self.helpPanel.Raise() self.helpPanel.SetBackgroundColour((240,250,240)) self.Bind(wx.EVT_SIZE, self._onSize) self._onShowCntrls(None) def _onShowHelp(self, event): self.helpPanel.SetPosition((0,0)) self.helpPanel.Show() self.cntrlPanel.Hide() def _onShowCntrls(self, event): self.cntrlPanel.SetPosition((0,0)) self.helpPanel.Hide() self.cntrlPanel.Show() def _onSize(self, event): event.Skip() self.helpPanel.SetSize(self.GetClientSizeTuple()) self.cntrlPanel.SetSize(self.GetClientSizeTuple()) app = wx.PySimpleApp() frame = MyFrame() frame.Show() app.SetTopWindow(frame) app.MainLoop() </code></pre>
1
2009-06-24T03:40:24Z
[ "python", "user-interface", "wxpython" ]
wxPython: Making something expand
1,034,399
<p>How do I make any wxPython widget (like wx.Panel or wx.Button) automatically expand to fill its parent window?</p>
4
2009-06-23T18:46:44Z
5,628,847
<p>In the case of a Button, to make a button fill its parent window when the parent window (a frame in my case) changes size, put <code>button.SetSize(parent_window.GetSize())</code> in the parent window's OnSize event handling routine.</p>
0
2011-04-11T23:45:36Z
[ "python", "user-interface", "wxpython" ]
How do I use the bash time function from python?
1,034,566
<p>I would like to use python to make system calls to programs and time them. From the Linux command line if you type:</p> <pre><code>$ time prog args </code></pre> <p>You get something along the lines of:</p> <pre><code>real 0m0.110s user 0m0.060s sys 0m0.024s </code></pre> <p>if you do a 'man time', it states that you can type:</p> <pre><code>$ time -f "%E" prog args </code></pre> <p>in order to format to get only display the elapsed time. This does not work in the shell. I beleive it doesn't work because bash must have its own time function. If you type:</p> <pre><code>$/usr/bin/time -f "%E" prog args </code></pre> <p>you get the expected output as stated in the man pages.</p> <p>I want the bash time because it seems to be more accurate. My problem is, when you try to use the 'time prog args' command from python, it doesn't behave the same way as when you type it in.</p> <p>Code below to see what I'm doing (Please excuse the sloppiness):</p> <pre><code>#!/usr/bin/env python """Quick &amp; Dirty script to time program execution for multiple inputs. Saves the results as a .csv for importing into excel.""" import subprocess timing = 'time -f "%E" ' program = 'java smartfib ' filename = 'smarttimes.csv' #arglist = [0, 10, 20, 30, 31, 32, 33, 34, 35] #arglist = [0, 2, 3, 5] arglist = range(50) timelist = list() #run the program with the specified input values for arg in arglist: cmd = timing + program + str(arg) pipe = subprocess.Popen(cmd, shell = True, bufsize = 256, stderr = subprocess.PIPE, stdout = subprocess.PIPE) [answer,times] = pipe.communicate() #read from pipe #print times if(int(answer) &lt; 0): print "overflow occured at fib(%d)!\n" %arg break #save (n, [time it takes to complete] as a tuple in a list) timelist.append([arg,times]) csv = list() #list for formatted comma separated values for excel for item in range(len(timelist)): csv.append( str(timelist[item][0]) + "," + timelist[item][1][2:].strip('\n') ) results = file(filename,'w') results.write('n,time(in s)\n') for item in range(len(csv)): results.write(csv[item]+'\n') results.close() def getTimeInSeconds(self, timestring): pass </code></pre>
1
2009-06-23T19:16:47Z
1,034,661
<p>You are correct that bash has it's own version of time.</p> <pre><code>$ type time time is a shell keyword </code></pre> <p>Perhaps you could explicitly invoke bash with the -c option to get it's timing.</p> <p>Depending on which distribution you're using, the default shell may be dash, a simpler shell that doesn't have time as a keyword. Both Debian and Ubuntu use dash but I don't know what Red Hat, Fedora and others use.</p>
2
2009-06-23T19:30:59Z
[ "python", "linux", "bash", "unix", "time" ]
How do I use the bash time function from python?
1,034,566
<p>I would like to use python to make system calls to programs and time them. From the Linux command line if you type:</p> <pre><code>$ time prog args </code></pre> <p>You get something along the lines of:</p> <pre><code>real 0m0.110s user 0m0.060s sys 0m0.024s </code></pre> <p>if you do a 'man time', it states that you can type:</p> <pre><code>$ time -f "%E" prog args </code></pre> <p>in order to format to get only display the elapsed time. This does not work in the shell. I beleive it doesn't work because bash must have its own time function. If you type:</p> <pre><code>$/usr/bin/time -f "%E" prog args </code></pre> <p>you get the expected output as stated in the man pages.</p> <p>I want the bash time because it seems to be more accurate. My problem is, when you try to use the 'time prog args' command from python, it doesn't behave the same way as when you type it in.</p> <p>Code below to see what I'm doing (Please excuse the sloppiness):</p> <pre><code>#!/usr/bin/env python """Quick &amp; Dirty script to time program execution for multiple inputs. Saves the results as a .csv for importing into excel.""" import subprocess timing = 'time -f "%E" ' program = 'java smartfib ' filename = 'smarttimes.csv' #arglist = [0, 10, 20, 30, 31, 32, 33, 34, 35] #arglist = [0, 2, 3, 5] arglist = range(50) timelist = list() #run the program with the specified input values for arg in arglist: cmd = timing + program + str(arg) pipe = subprocess.Popen(cmd, shell = True, bufsize = 256, stderr = subprocess.PIPE, stdout = subprocess.PIPE) [answer,times] = pipe.communicate() #read from pipe #print times if(int(answer) &lt; 0): print "overflow occured at fib(%d)!\n" %arg break #save (n, [time it takes to complete] as a tuple in a list) timelist.append([arg,times]) csv = list() #list for formatted comma separated values for excel for item in range(len(timelist)): csv.append( str(timelist[item][0]) + "," + timelist[item][1][2:].strip('\n') ) results = file(filename,'w') results.write('n,time(in s)\n') for item in range(len(csv)): results.write(csv[item]+'\n') results.close() def getTimeInSeconds(self, timestring): pass </code></pre>
1
2009-06-23T19:16:47Z
1,034,740
<p>I don't think time will be more accurate than Pythons methods, unless you use os.times() in versions below 2.5.3, and look at the user time, because earlier versions of Python has a big there.</p> <p>And although the time command behaves differently then bash's time builtin, they both return the relevant information, so I'm unclear on what the problem is, really.</p>
0
2009-06-23T19:42:21Z
[ "python", "linux", "bash", "unix", "time" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
1,034,598
<pre><code>def xstr(s): return '' if s is None else str(s) </code></pre>
91
2009-06-23T19:21:12Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
1,034,614
<pre><code>def xstr(s): return s if s else '' s = "%s%s" % (xstr(a), xstr(b)) </code></pre>
0
2009-06-23T19:25:57Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
1,034,632
<pre><code>def xstr(s): return {None:''}.get(s, s) </code></pre>
4
2009-06-23T19:28:12Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
1,034,633
<p>If you actually want your function to behave like the <code>str()</code> built-in, but return an empty string when the argument is None, do this:</p> <pre><code>def xstr(s): if s is None: return '' return str(s) </code></pre>
39
2009-06-23T19:28:18Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
1,034,668
<p>Functional way (one-liner)</p> <pre><code>xstr = lambda s: '' if s is None else s </code></pre>
6
2009-06-23T19:31:58Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
1,034,716
<p>Use short circuit evaluation:</p> <pre><code>s = a or '' + b or '' </code></pre> <p>Since + is not a very good operation on strings, better use format strings:</p> <pre><code>s = "%s%s" % (a or '', b or '') </code></pre>
-1
2009-06-23T19:37:21Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
1,035,497
<p>If you know that the value will always either be a string or None:</p> <pre><code>xstr = lambda s: s or "" print xstr("a") + xstr("b") # -&gt; 'ab' print xstr("a") + xstr(None) # -&gt; 'a' print xstr(None) + xstr("b") # -&gt; 'b' print xstr(None) + xstr(None) # -&gt; '' </code></pre>
64
2009-06-23T22:01:12Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
1,036,222
<p><code>return s or ''</code> will work just fine for your stated problem!</p>
38
2009-06-24T03:08:53Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
1,036,275
<p>Variation on the above if you need to be compatible with Python 2.4</p> <pre><code>xstr = lambda s: s is not None and s or '' </code></pre>
4
2009-06-24T03:37:06Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
1,036,316
<pre><code>def xstr(s): return s or "" </code></pre>
11
2009-06-24T03:56:07Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
12,215,416
<p>Probably the shortest would be <code>str(s or '')</code></p> <p>Because None is False, and "x or y" returns y if x is false. See <a href="http://docs.python.org/library/stdtypes.html#boolean-operations-and-or-not">Boolean Operators</a> for a detailed explanation. It's short, but not very explicit.</p>
28
2012-08-31T12:28:40Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
23,254,019
<p>I use max function:</p> <pre><code>max(None, '') #Returns blank max("Hello",'') #Returns Hello </code></pre> <p>Works like a charm ;) Just put your string in the first parameter of the function.</p>
1
2014-04-23T19:56:45Z
[ "string", "python", "idioms" ]
Python: most idiomatic way to convert None to empty string?
1,034,573
<p>What is the most idiomatic way to do the following?</p> <pre><code>def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) </code></pre> <p><strong>update:</strong> I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.</p> <pre><code>def xstr(s): if s is None: return '' else: return str(s) </code></pre>
69
2009-06-23T19:17:29Z
30,455,911
<p>We can always avoid type casting in scenarios explained below.</p> <pre><code>customer = "John" name = str(customer) if name is None print "Name is blank" else: print "Customer name : " + name </code></pre> <p>In the example above in case variable customer's value is None the it further gets casting while getting assigned to 'name'. The comparison in 'if' clause will always fail. </p> <pre><code>customer = "John" # even though its None still it will work properly. name = customer if name is None print "Name is blank" else: print "Customer name : " + str(name) </code></pre> <p>Above example will work properly. Such scenarios are very common when values are being fetched from URL, JSON or XML or even values need further type casting for any manipulation.</p>
1
2015-05-26T10:27:53Z
[ "string", "python", "idioms" ]
Obtaining references to function objects on the execution stack from the frame object?
1,034,688
<p>Given the output of <code>inspect.stack()</code>, is it possible to get the function objects from anywhere from the stack frame and call these? If so, how?</p> <p>(I already know how to get the names of the functions.)</p> <p>Here is what I'm getting at: Let's say I'm a function and I'm trying to determine if my caller is a generator or a regular function? I need to call <code>inspect.isgeneratorfunction()</code> on the function object. And how do you figure out who called you? <code>inspect.stack()</code>, right? So if I can somehow put those together, I'll have the answer to my question. Perhaps there is an easier way to do this?</p>
1
2009-06-23T19:34:07Z
1,035,610
<p>Here is a code snippet that do it. There is no error checking. The idea is to find in the locals of the grand parent the function object that was called. The function object returned should be the parent. If you want to also search the builtins, then simply look into stacks[2][0].f_builtins. </p> <pre><code>def f(): stacks = inspect.stack() grand_parent_locals = stacks[2][0].f_locals caller_name = stacks[1][3] candidate = grand_parent_locals[caller_name] </code></pre> <p>In the case of a class, one can write the following (inspired by Marcin solution)</p> <pre><code>class test(object): def f(self): stack = inspect.stack() parent_func_name = stack[1][3] parent_func = getattr(self, parent_func_name).im_func </code></pre>
2
2009-06-23T22:30:56Z
[ "python", "inspect", "stackframe" ]
Obtaining references to function objects on the execution stack from the frame object?
1,034,688
<p>Given the output of <code>inspect.stack()</code>, is it possible to get the function objects from anywhere from the stack frame and call these? If so, how?</p> <p>(I already know how to get the names of the functions.)</p> <p>Here is what I'm getting at: Let's say I'm a function and I'm trying to determine if my caller is a generator or a regular function? I need to call <code>inspect.isgeneratorfunction()</code> on the function object. And how do you figure out who called you? <code>inspect.stack()</code>, right? So if I can somehow put those together, I'll have the answer to my question. Perhaps there is an easier way to do this?</p>
1
2009-06-23T19:34:07Z
1,038,818
<p>I took the following approach, very similar to Eolmar's answer.</p> <pre><code>stack = inspect.stack() parent_locals = stack[1][0].f_locals['self'] parent_func_name = stack[1][3] parent_func_attr = getattr(parent_locals,parent_func_name) parent_func = parent_func_attr.im_func is_parent_gen = inspect.isgeneratorfunction(func) </code></pre>
0
2009-06-24T14:43:04Z
[ "python", "inspect", "stackframe" ]
Finding Nth item of unsorted list without sorting the list
1,034,846
<p>Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...</p>
15
2009-06-23T20:04:41Z
1,034,863
<p>Use heapsort. It only partially orders the list until you draw the elements out.</p>
1
2009-06-23T20:07:22Z
[ "python", "arrays", "sorting" ]
Finding Nth item of unsorted list without sorting the list
1,034,846
<p>Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...</p>
15
2009-06-23T20:04:41Z
1,034,864
<p>You can iterate the entire sequence maintaining a list of the 5 largest values you find (this will be O(n)). That being said I think it would just be simpler to sort the list.</p>
3
2009-06-23T20:07:52Z
[ "python", "arrays", "sorting" ]
Finding Nth item of unsorted list without sorting the list
1,034,846
<p>Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...</p>
15
2009-06-23T20:04:41Z
1,034,869
<p>You essentially want to produce a "top-N" list and select the one at the end of that list.</p> <p>So you can scan the array once and insert into an empty list when the largeArray item is greater than the last item of your top-N list, then drop the last item.</p> <p>After you finish scanning, pick the last item in your top-N list. </p> <p>An example for ints and N = 5:</p> <pre><code>int[] top5 = new int[5](); top5[0] = top5[1] = top5[2] = top5[3] = top5[4] = 0x80000000; // or your min value for(int i = 0; i &lt; largeArray.length; i++) { if(largeArray[i] &gt; top5[4]) { // insert into top5: top5[4] = largeArray[i]; // resort: quickSort(top5); } } </code></pre>
1
2009-06-23T20:09:33Z
[ "python", "arrays", "sorting" ]
Finding Nth item of unsorted list without sorting the list
1,034,846
<p>Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...</p>
15
2009-06-23T20:04:41Z
1,034,886
<p>Sorting would require O(nlogn) runtime at minimum - There are very efficient <a href="http://en.wikipedia.org/wiki/Quick%5Fselect">selection algorithms</a> which can solve your problem in linear time.</p> <p><code>Partition-based selection</code> (sometimes <code>Quick select</code>), which is based on the idea of quicksort (recursive partitioning), is a good solution (see link for pseudocode + <a href="http://goanna.cs.rmit.edu.au/~stbird/Tutorials/QuickSelect.html">Another example</a>).</p>
13
2009-06-23T20:12:07Z
[ "python", "arrays", "sorting" ]
Finding Nth item of unsorted list without sorting the list
1,034,846
<p>Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...</p>
15
2009-06-23T20:04:41Z
1,034,923
<p>As people have said, you can walk the list once keeping track of K largest values. If K is large this algorithm will be close to O(n<sup>2</sup>).</p> <p>However, you can store your Kth largest values as a binary tree and the operation becomes O(n log k).</p> <p>According to Wikipedia, this is the best selection algorithm:</p> <pre><code> function findFirstK(list, left, right, k) if right &gt; left select pivotIndex between left and right pivotNewIndex := partition(list, left, right, pivotIndex) if pivotNewIndex &gt; k // new condition findFirstK(list, left, pivotNewIndex-1, k) if pivotNewIndex &lt; k findFirstK(list, pivotNewIndex+1, right, k) </code></pre> <p>Its complexity is O(n)</p>
1
2009-06-23T20:18:55Z
[ "python", "arrays", "sorting" ]
Finding Nth item of unsorted list without sorting the list
1,034,846
<p>Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...</p>
15
2009-06-23T20:04:41Z
1,034,949
<p>A simple modified quicksort works very well in practice. It has average running time proportional to N (though worst case bad luck running time is O(N^2)).</p> <p>Proceed like a quicksort. Pick a pivot value randomly, then stream through your values and see if they are above or below that pivot value and put them into two bins based on that comparison. In quicksort you'd then recursively sort each of those two bins. But for the N-th highest value computation, you only need to sort ONE of the bins.. the population of each bin tells you which bin holds your n-th highest value. So for example if you want the 125th highest value, and you sort into two bins which have 75 in the "high" bin and 150 in the "low" bin, you can ignore the high bin and just proceed to finding the 125-75=50th highest value in the low bin alone.</p>
3
2009-06-23T20:23:03Z
[ "python", "arrays", "sorting" ]
Finding Nth item of unsorted list without sorting the list
1,034,846
<p>Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...</p>
15
2009-06-23T20:04:41Z
1,036,240
<p>A heap is the best data structure for this operation and Python has an excellent built-in library to do just this, called heapq.</p> <pre><code>import heapq def nth_largest(n, iter): return heapq.nlargest(n, iter)[-1] </code></pre> <p>Example Usage:</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; iter = [random.randint(0,1000) for i in range(100)] &gt;&gt;&gt; n = 10 &gt;&gt;&gt; nth_largest(n, iter) 920 </code></pre> <p>Confirm result by sorting:</p> <pre><code>&gt;&gt;&gt; list(sorted(iter))[-10] 920 </code></pre>
18
2009-06-24T03:21:47Z
[ "python", "arrays", "sorting" ]
Finding Nth item of unsorted list without sorting the list
1,034,846
<p>Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...</p>
15
2009-06-23T20:04:41Z
2,129,986
<p>You could try the Median of Medians method - it's speed is O(N).</p>
2
2010-01-25T03:07:17Z
[ "python", "arrays", "sorting" ]
Finding Nth item of unsorted list without sorting the list
1,034,846
<p>Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...</p>
15
2009-06-23T20:04:41Z
35,329,224
<p>One thing you should do if this is in production code is test with samples of your data. For example, you might consider 1000 or 10000 elements 'large' arrays, and code up a quickselect method from a recipe. </p> <p>The compiled nature of sorted, and its somewhat hidden and constantly evolving optimizations, make it faster than a python written quickselect method on small to medium sized datasets (&lt; 1,000,000 elements). Also, you might find as you increase the size of the array beyond that amount, memory is more efficiently handled in native code, and the benefit continues.</p> <p>So, even if quickselect is O(n) vs sorted's O(nlogn), that doesn't take into account how many actual machine code instructions processing each n elements will take, any impacts on pipelining, uses of processor caches and other things the creators and maintainers of sorted will bake into the python code. </p>
0
2016-02-11T01:28:32Z
[ "python", "arrays", "sorting" ]
python multiprocessing manager
1,034,848
<p>My problem is:</p> <p>I have 3 procs that would like to share config loaded from the same class and a couple of queues. I would like to spawn another proc as a multiprocessing.manager to share those informations. </p> <p>How can I do that? Could someone purchase a sample code avoiding use of global vars and making use of multiprocessing manager class?</p> <p>Python docs wasn't so helpfull :-(</p>
3
2009-06-23T20:05:03Z
1,035,629
<p>I found <a href="http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes" rel="nofollow">this</a> particular section in the Python multiprocessing docs helpful. The following program:</p> <pre><code>from multiprocessing import Process, Queue, current_process import time def f(q): name = current_process().name config = q.get() print "%s got config: %s" % (name, config) print "%s beginning processing at %s" % (name, time.asctime()) time.sleep(5) print "%s completing processing at %s" % (name, time.asctime()) if __name__ == '__main__': q = Queue() processes = [] cfg = { 'my' : 'config', 'data' : 'here' } for i in range(3): p = Process(target=f, args=(q,)) processes.append(p) p.start() q.put(cfg) for p in processes: p.join() </code></pre> <p>demonstrates the main script (which is the "multiprocessing manager" in your question) creating 3 processes and sending them each a configuration (shown here as a dictionary).</p> <p>Each process reads the configuration, does its processing (here, just sleep for 5 secs) then terminates. The output from running this script is:</p> <pre><code>Process-1 got config: {'my': 'config', 'data': 'here'} Process-1 beginning processing at Tue Jun 23 23:34:23 2009 Process-2 got config: {'my': 'config', 'data': 'here'} Process-2 beginning processing at Tue Jun 23 23:34:23 2009 Process-3 got config: {'my': 'config', 'data': 'here'} Process-3 beginning processing at Tue Jun 23 23:34:23 2009 Process-1 completing processing at Tue Jun 23 23:34:28 2009 Process-2 completing processing at Tue Jun 23 23:34:28 2009 Process-3 completing processing at Tue Jun 23 23:34:28 2009 </code></pre>
3
2009-06-23T22:36:17Z
[ "python", "multiprocessing" ]
How can I create a Word document using Python?
1,035,183
<p>I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I <a href="http://www.xhtml2pdf.com/">programatically convert</a> to a PDF file. However, my client is now requesting that the same document be made available in Word (.doc) format.</p> <p>So far, I haven't had much luck finding any solutions to this problem. Is anyone aware of an open source library (or *gulp* a proprietary solution) that may help resolve this issue?</p> <p>NOTE: All possible solutions must run on Linux. I believe this eliminates pywin32.</p>
32
2009-06-23T20:59:08Z
1,035,202
<p>Can you write is as the WordML XML files and zip it up into the .docx format? All your client would need is the Word 2007 filter if they aren't on Office 2007 already.</p> <p>There are many examples out there.</p> <p>You can also load XML directly into Word, starting with 2003, or <a href="http://www.tkachenko.com/blog/archives/000024.html" rel="nofollow">so I've been told</a>.</p>
0
2009-06-23T21:02:02Z
[ "python", "xml", "xslt", "ms-word" ]