title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Splitting up a list into parts of balanced lengths
1,380,162
<p>I need an algorithm which given a list <code>L</code> and a number <code>N</code>, returns a list of <code>N</code> smaller lists where the sublists are "balanced". Examples:</p> <pre><code>algo(range(1, 8), 3) -&gt; [[1,2,3], [4,5], [6,7]] algo(range(1, 6), 4) -&gt; [[1,2], [3], [4], [5]] algo(range(1, 12), 5) -&gt; [[1,2,3], [4,5], [6,7], [8,9], [10, 11]] </code></pre> <p>As you can see, the algorithm should "prefer" the first list in the output.</p> <p>I've been trying for hours, but I can't figure out a nice and terse algorithm for it. This will be implemented in Python, by the way, but it's really the algorithm that I'm after here. This is <em>not</em> homework, this is for a website which will display contents in a list in three columns (Django).</p> <p><hr /></p> <p>I got the best answer from #python on freenode and it is as follows:</p> <pre><code>def split_up(l, n): q, r = divmod(len(l), n) def division_point(i): return i * q + min(i, r) return [l[division_point(i):division_point(i+1)] for i in range(n)] </code></pre> <p>Don't ask me why it works though. :) I'll give the correct answer to the one with most votes though.</p>
6
2009-09-04T16:04:41Z
1,381,193
<p>Here's a tribute to functional lovers:</p> <pre><code>def algo(l, n): if n == 1: return [l] q, r = divmod(len(l),n) if r: q += 1 return [l[:q]] + algo(l[q:], n - 1) </code></pre> <p>This one is a little bit smaller:</p> <pre><code>def algo(l, n): k = l[:] q, r = divmod(len(l),n) return [[k.pop(0) for _ in [0] * m] for m in [q + 1] * r + [q] * (n - r)] </code></pre>
0
2009-09-04T19:44:04Z
[ "python", "algorithm" ]
Splitting up a list into parts of balanced lengths
1,380,162
<p>I need an algorithm which given a list <code>L</code> and a number <code>N</code>, returns a list of <code>N</code> smaller lists where the sublists are "balanced". Examples:</p> <pre><code>algo(range(1, 8), 3) -&gt; [[1,2,3], [4,5], [6,7]] algo(range(1, 6), 4) -&gt; [[1,2], [3], [4], [5]] algo(range(1, 12), 5) -&gt; [[1,2,3], [4,5], [6,7], [8,9], [10, 11]] </code></pre> <p>As you can see, the algorithm should "prefer" the first list in the output.</p> <p>I've been trying for hours, but I can't figure out a nice and terse algorithm for it. This will be implemented in Python, by the way, but it's really the algorithm that I'm after here. This is <em>not</em> homework, this is for a website which will display contents in a list in three columns (Django).</p> <p><hr /></p> <p>I got the best answer from #python on freenode and it is as follows:</p> <pre><code>def split_up(l, n): q, r = divmod(len(l), n) def division_point(i): return i * q + min(i, r) return [l[division_point(i):division_point(i+1)] for i in range(n)] </code></pre> <p>Don't ask me why it works though. :) I'll give the correct answer to the one with most votes though.</p>
6
2009-09-04T16:04:41Z
1,674,267
<p>Bit late to the party, but...</p> <pre><code>def algo(l, n): return [l[-(-len(l)*i//n):-(-len(l)*(i+1)//n)] for i in range(n)] </code></pre> <p>Use / instead of // in older versions of Python.</p>
0
2009-11-04T14:51:52Z
[ "python", "algorithm" ]
Set Snow Leopard to use python 2.5 rather than 2.6
1,380,281
<p>I just upgraded to Snow Leopard and I'm trying to get it to use the old python 2.5 install. I had with all my modules in it. Does anyone know how to set the default python install to 2.5?</p>
6
2009-09-04T16:27:01Z
1,380,314
<p>You want <a href="http://python%5Fselect.darwinports.com/" rel="nofollow"><code>python_select</code></a>.</p> <blockquote> <p>Description: Switch the default python interpreter</p> </blockquote>
0
2009-09-04T16:36:01Z
[ "python", "osx", "osx-snow-leopard" ]
Set Snow Leopard to use python 2.5 rather than 2.6
1,380,281
<p>I just upgraded to Snow Leopard and I'm trying to get it to use the old python 2.5 install. I had with all my modules in it. Does anyone know how to set the default python install to 2.5?</p>
6
2009-09-04T16:27:01Z
1,380,328
<p>I worked this out - if you have this problem open a terminal and type:</p> <pre><code>defaults write com.apple.versioner.python Version 2.5 </code></pre>
8
2009-09-04T16:38:04Z
[ "python", "osx", "osx-snow-leopard" ]
Can I add parameters to a python property to reduce code duplication?
1,380,566
<p>I have a the following class:</p> <pre><code> class Vector(object): def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z def _getx(self): return self._x def _setx(self, value): self._x = float(value) x = property(_getx, _setx) def _gety(self): return self._y def _sety(self, value): self._y = float(value) y = property(_gety, _sety) def _getz(self): return self._z def _setz(self, value): self._z = float(value) z = property(_getz, _setz) </code></pre> <p>The three getters and setters are all identical except for the object property they are modifying (x, y, z). Is there a way that I can write one get and one set and then pass the variable to modify so that I don't repeat myself?</p>
4
2009-09-04T17:30:12Z
1,380,594
<p>Not tested, but this should work:</p> <pre><code>def force_float(name): def get(self): return getattr(self, name) def set(self, x): setattr(self, name, float(x)) return property(get, set) class Vector(object): x = force_float("_x") y = force_float("_y") # etc </code></pre>
0
2009-09-04T17:36:23Z
[ "python" ]
Can I add parameters to a python property to reduce code duplication?
1,380,566
<p>I have a the following class:</p> <pre><code> class Vector(object): def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z def _getx(self): return self._x def _setx(self, value): self._x = float(value) x = property(_getx, _setx) def _gety(self): return self._y def _sety(self, value): self._y = float(value) y = property(_gety, _sety) def _getz(self): return self._z def _setz(self, value): self._z = float(value) z = property(_getz, _setz) </code></pre> <p>The three getters and setters are all identical except for the object property they are modifying (x, y, z). Is there a way that I can write one get and one set and then pass the variable to modify so that I don't repeat myself?</p>
4
2009-09-04T17:30:12Z
1,380,598
<p>Sure, make a custom descriptor as per the concepts clearly explained in <a href="http://users.rcn.com/python/download/Descriptor.htm">this doc</a>:</p> <pre><code>class JonProperty(object): def __init__(self, name): self.name = name def __get__(self, obj, objtype): return getattr(obj, self.name) def __set__(self, obj, val): setattr(obj, self.name, float(val)) </code></pre> <p>and then just use it:</p> <pre><code>class Vector(object): def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z x = JonProperty('_x') y = JonProperty('_y') z = JonProperty('_z') </code></pre>
17
2009-09-04T17:37:19Z
[ "python" ]
Can I add parameters to a python property to reduce code duplication?
1,380,566
<p>I have a the following class:</p> <pre><code> class Vector(object): def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z def _getx(self): return self._x def _setx(self, value): self._x = float(value) x = property(_getx, _setx) def _gety(self): return self._y def _sety(self, value): self._y = float(value) y = property(_gety, _sety) def _getz(self): return self._z def _setz(self, value): self._z = float(value) z = property(_getz, _setz) </code></pre> <p>The three getters and setters are all identical except for the object property they are modifying (x, y, z). Is there a way that I can write one get and one set and then pass the variable to modify so that I don't repeat myself?</p>
4
2009-09-04T17:30:12Z
1,381,393
<p>Why not just write this?</p> <pre><code>class Vector(object): def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z </code></pre> <p>If your getters and setters are a carryover in practice from something like Java, then DO NOT WRITE THEM. Just expose the attributes x, y, and z. You can change them to properties later if necessary, and, unlike Java (which would require some kind of recompile), all of the client code will still work just fine.</p> <p>On the theme of getters and setters in Python, the general consensus as I understand it is "don't write 'em til you need 'em." Only write setters and getters if they actually add value to your program (like protecting an internal data structure, perhaps). Otherwise, leave them out, and spend your time doing actual productive coding.</p>
2
2009-09-04T20:30:11Z
[ "python" ]
Slickest REPL console in any language
1,380,592
<p>Many languages of REPL consoles with additional features like autocomplete and intellisense. For instance, iPython, Mathematica, and PyCrust all make some effort to go beyond a basic read eval loop. REPLs are particularly useful in languages where interactive exploration is very important, such as Matlab or R.</p> <p>I'm looking for inspiration. What application provides the slickest REPL? Or what features do you always wish existed in your REPL of choice?</p>
3
2009-09-04T17:35:46Z
1,380,716
<p>I really like Safari's Web Inspector Javascript console. Specifically:</p> <ul> <li>Collapsible interactive object hierarchies</li> <li><code>sprintf</code>-style logging</li> <li>Pretty-printing of closures, allowing you to peer into the internals of anonymous functions</li> <li>Auto-complete / hinting of object properties on the command-line</li> </ul>
4
2009-09-04T18:03:29Z
[ "python", "matlab", "console" ]
Slickest REPL console in any language
1,380,592
<p>Many languages of REPL consoles with additional features like autocomplete and intellisense. For instance, iPython, Mathematica, and PyCrust all make some effort to go beyond a basic read eval loop. REPLs are particularly useful in languages where interactive exploration is very important, such as Matlab or R.</p> <p>I'm looking for inspiration. What application provides the slickest REPL? Or what features do you always wish existed in your REPL of choice?</p>
3
2009-09-04T17:35:46Z
1,380,780
<p>The command window in MATLAB 7.8.0 (R2009a) has a few nice features:</p> <ul> <li><strong>Tabbed-completion:</strong> You can type part of a variable or function name, then hit tab to get a selectable list of all possible variable or function completions. This also works when typing part of a string, which will bring up a selectable list of file names in the current directory that complete the string.</li> <li><strong>Argument-list format display:</strong> If you type a function name and an open parenthesis, you will automatically get a list of possible formats for the argument list along with a link to the help documentation for that function.</li> </ul> <p>Here's a screenshot of the two options:</p> <p><img src="http://i37.photobucket.com/albums/e77/kpeaton/REPL.jpg" alt="alt text" /></p>
3
2009-09-04T18:17:36Z
[ "python", "matlab", "console" ]
Slickest REPL console in any language
1,380,592
<p>Many languages of REPL consoles with additional features like autocomplete and intellisense. For instance, iPython, Mathematica, and PyCrust all make some effort to go beyond a basic read eval loop. REPLs are particularly useful in languages where interactive exploration is very important, such as Matlab or R.</p> <p>I'm looking for inspiration. What application provides the slickest REPL? Or what features do you always wish existed in your REPL of choice?</p>
3
2009-09-04T17:35:46Z
1,380,870
<p>Common Lisp and emacs with SLIME. All you could really want, think of, dream of, and then some.</p>
5
2009-09-04T18:39:20Z
[ "python", "matlab", "console" ]
Slickest REPL console in any language
1,380,592
<p>Many languages of REPL consoles with additional features like autocomplete and intellisense. For instance, iPython, Mathematica, and PyCrust all make some effort to go beyond a basic read eval loop. REPLs are particularly useful in languages where interactive exploration is very important, such as Matlab or R.</p> <p>I'm looking for inspiration. What application provides the slickest REPL? Or what features do you always wish existed in your REPL of choice?</p>
3
2009-09-04T17:35:46Z
1,380,924
<p>I think <a href="http://www.softpedia.com/screenshots/Windows-PowerShell%5F2.png" rel="nofollow">PowerShell</a> wins without any doubt.</p>
0
2009-09-04T18:48:19Z
[ "python", "matlab", "console" ]
How to get list opened windows in PyGTK or GTK in Ubuntu?
1,380,784
<p>How to get list opened windows in PyGTK or GTK or other programming language? in Ubuntu?</p> <p><strong>edit:</strong></p> <p>i want get list paths opened directories on desktop!</p>
4
2009-09-04T18:18:40Z
1,380,867
<p>From <a href="http://library.gnome.org/devel/pygtk/stable/class-gdkwindow.html#function-gdk--window-get-toplevels" rel="nofollow">the PyGTK reference</a>:</p> <blockquote> <p><code>gtk.gdk.window_get_toplevels()</code></p> <p>The <code>gtk.gdk.window_get_toplevels()</code> function returns a list of all toplevel windows known to PyGTK on the default screen. A toplevel window is a child of the root window (see the <code>gtk.gdk.get_default_root_window()</code> function).</p> </blockquote>
2
2009-09-04T18:37:30Z
[ "python", "ubuntu", "gtk", "pygtk", "window-management" ]
How to get list opened windows in PyGTK or GTK in Ubuntu?
1,380,784
<p>How to get list opened windows in PyGTK or GTK or other programming language? in Ubuntu?</p> <p><strong>edit:</strong></p> <p>i want get list paths opened directories on desktop!</p>
4
2009-09-04T18:18:40Z
1,380,909
<p>I really don't know how to check if a window is a GTK one. But if you want to check how many windows are currently open try "wmctrl -l". Install it first of course.</p>
1
2009-09-04T18:46:50Z
[ "python", "ubuntu", "gtk", "pygtk", "window-management" ]
How to get list opened windows in PyGTK or GTK in Ubuntu?
1,380,784
<p>How to get list opened windows in PyGTK or GTK or other programming language? in Ubuntu?</p> <p><strong>edit:</strong></p> <p>i want get list paths opened directories on desktop!</p>
4
2009-09-04T18:18:40Z
1,380,988
<p>You probably want to use libwnck:</p> <p><a href="http://library.gnome.org/devel/libwnck/stable/">http://library.gnome.org/devel/libwnck/stable/</a></p> <p>I believe there are python bindings in python-gnome or some similar package.</p> <p>Once you have the GTK+ mainloop running, you can do the following:</p> <pre> import wnck window_list = wnck.screen_get_default().get_windows() </pre> <p>Some interesting methods on a window from that list are get_name() and activate().</p> <p>This will print the names of windows to the console when you click the button. But for some reason I had to click the button twice. This is my first time using libwnck so I'm probably missing something. :-)</p> <pre> import pygtk pygtk.require('2.0') import gtk, wnck class WindowLister: def on_btn_click(self, widget, data=None): window_list = wnck.screen_get_default().get_windows() if len(window_list) == 0: print "No Windows Found" for win in window_list: print win.get_name() def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.button = gtk.Button("List Windows") self.button.connect("clicked", self.on_btn_click, None) self.window.add(self.button) self.window.show_all() def main(self): gtk.main() if __name__ == "__main__": lister = WindowLister() lister.main() </pre>
8
2009-09-04T19:01:40Z
[ "python", "ubuntu", "gtk", "pygtk", "window-management" ]
How to get list opened windows in PyGTK or GTK in Ubuntu?
1,380,784
<p>How to get list opened windows in PyGTK or GTK or other programming language? in Ubuntu?</p> <p><strong>edit:</strong></p> <p>i want get list paths opened directories on desktop!</p>
4
2009-09-04T18:18:40Z
1,381,472
<p>Parsing command line output is usually not the best way, you are dependent on that programs output not changing, which could vary from version or platfrom. Here is how to do it using Xlib:</p> <pre><code>import Xlib.display screen = Xlib.display.Display().screen() root_win = screen.root window_names = [] for window in root_win.query_tree()._data['children']: window_name = window.get_wm_name() window_names.append(window_name) print window_names </code></pre> <p>Note that this list will contain windows that you wouldn't normally classify as 'windows', but that doesn't matter for what you are trying to do.</p>
2
2009-09-04T20:47:15Z
[ "python", "ubuntu", "gtk", "pygtk", "window-management" ]
How to get list opened windows in PyGTK or GTK in Ubuntu?
1,380,784
<p>How to get list opened windows in PyGTK or GTK or other programming language? in Ubuntu?</p> <p><strong>edit:</strong></p> <p>i want get list paths opened directories on desktop!</p>
4
2009-09-04T18:18:40Z
4,975,656
<p>For whatever reason, I can't post a comment, but I'd like to add this as an addendum to Sandy's answer. </p> <p>Here's a chunk of code that lists the current windows on the console:</p> <pre><code>import pygtk pygtk.require('2.0') import gtk, wnck if __name__ == "__main__": default = wnck.screen_get_default() while gtk.events_pending(): gtk.main_iteration(False) window_list = default.get_windows() if len(window_list) == 0: print "No Windows Found" for win in window_list: if win.is_active(): print '***' + win.get_name() else: print win.get_name() </code></pre> <p>Thanks Sandy!</p>
4
2011-02-12T01:15:48Z
[ "python", "ubuntu", "gtk", "pygtk", "window-management" ]
How to get list opened windows in PyGTK or GTK in Ubuntu?
1,380,784
<p>How to get list opened windows in PyGTK or GTK or other programming language? in Ubuntu?</p> <p><strong>edit:</strong></p> <p>i want get list paths opened directories on desktop!</p>
4
2009-09-04T18:18:40Z
16,703,307
<p>Welcome to 2013! Here's the code using <code>Wnck</code> and its modern GObject Introspection libraries instead of the now deprecated PyGTK method. You may also check <a href="http://stackoverflow.com/a/16703115/624066">my other answer about wnck</a>:</p> <pre><code>from gi.repository import Gtk, Wnck Gtk.init([]) # necessary only if not using a Gtk.main() loop screen = Wnck.Screen.get_default() screen.force_update() # recommended per Wnck documentation # loop all windows for window in screen.get_windows(): print window.get_name() # ... do whatever you want with this window # clean up Wnck (saves resources, check documentation) window = None screen = None Wnck.shutdown() </code></pre> <p>As for documentation, check out the <a href="https://developer.gnome.org/libwnck/stable/">Libwnck Reference Manual</a>. It is not specific for python, but the whole point of using GObject Introspection is to have the same API across all languages, thanks to the <code>gir</code> bindings.</p> <p>Also, Ubuntu ships with both <code>wnck</code> and its corresponding <code>gir</code> binding out of the box, but if you need to install them:</p> <pre><code>sudo apt-get install libwnck-3-* gir1.2-wnck-3.0 </code></pre> <p>This will also install <code>libwnck-3-dev</code>, which is not necessary but will install useful documentation you can read using <a href="http://en.wikipedia.org/wiki/Devhelp">DevHelp</a></p>
7
2013-05-22T23:37:06Z
[ "python", "ubuntu", "gtk", "pygtk", "window-management" ]
Is packaging scripts as executables a solution for comercial applications?
1,380,852
<p>What happens when you package a script as an executable? Is this a good way to distribute commercial applications? I remember I read something a long time ago that when you package scripts as executables, at runtime the exe decompresses the scripts to a temporary directory where they get ran.</p> <p>If it's like that, than I don't think this can be viewed as a good solution, because a skilled user could find out where that directory is located and find the source code. I'm interested in Python &amp; Ruby.</p>
0
2009-09-04T18:34:54Z
1,380,877
<p>With Python (e.g. <a href="http://www.pyinstaller.org/" rel="nofollow">pyinstaller</a> -- be sure to get the SVN version, the "released" one is WAY out of date -- or <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>) you can package bytecode. Sure, it can be "reverse compiled", just like Java bytecode or .NET assemblies (or for that matter, machine code), but I think it's a decent level of "obscurity" despite the existence of disassemblers. I guess you could also use something like <a href="http://www.lysator.liu.se/~astrand/projects/pyobfuscate/" rel="nofollow">pyobfuscate</a> on the sources before you compile them, to make the names as unreadable as you can, but I have no personal experience doing that.</p>
3
2009-09-04T18:40:14Z
[ "python", "ruby", "executable" ]
Is packaging scripts as executables a solution for comercial applications?
1,380,852
<p>What happens when you package a script as an executable? Is this a good way to distribute commercial applications? I remember I read something a long time ago that when you package scripts as executables, at runtime the exe decompresses the scripts to a temporary directory where they get ran.</p> <p>If it's like that, than I don't think this can be viewed as a good solution, because a skilled user could find out where that directory is located and find the source code. I'm interested in Python &amp; Ruby.</p>
0
2009-09-04T18:34:54Z
1,381,231
<p>py2exe is great, I've used it before and it works just fine for encapsulating a program so it can run on other computers, even those lacking python. Like Alex said, it can be disassembled, but then so can C++ binaries. It's just a question of how much work the person is has to put into it. If someone has physical access to a the computer where data is stored, they have access to the data (And there's no difference between code and data). Compress it, encrypt it, compile it, those will only slow the determined.</p> <p>Realistically, if you want to make the source code to your program as inaccessible as possible, you probably shouldn't look at Python or Ruby. C++ and some of the others are far more difficult to decompile, thereby providing more obscurity. You can practice the fine art of obfuscation, but even that won't stop someone trying to steal it (It's not like you have to understand the code to put it up on the Pirate Bay).</p>
2
2009-09-04T19:51:39Z
[ "python", "ruby", "executable" ]
Is packaging scripts as executables a solution for comercial applications?
1,380,852
<p>What happens when you package a script as an executable? Is this a good way to distribute commercial applications? I remember I read something a long time ago that when you package scripts as executables, at runtime the exe decompresses the scripts to a temporary directory where they get ran.</p> <p>If it's like that, than I don't think this can be viewed as a good solution, because a skilled user could find out where that directory is located and find the source code. I'm interested in Python &amp; Ruby.</p>
0
2009-09-04T18:34:54Z
1,381,289
<p>Creating an application and creating a commercial software business are two distinct things. </p> <p>At my job we have a commercial application developed in Ruby on Rails that is installed at client sites; no obfuscation or encryption applied. </p> <p>There is just so much more going on at a business level: support, customization, training that it's almost ludicrous to think that they'd do something with the source code. Most sites are lucky if they can spare the cycles to manage the application, much less start wallowing in someone else's codebase. </p> <p>Now that being said, we aren't publicly distributing the code or anything, just that we've made the choice to invest in making the application better and doing better by our customers than to burn the time trying to restrict access to our application.</p>
3
2009-09-04T20:02:13Z
[ "python", "ruby", "executable" ]
Is packaging scripts as executables a solution for comercial applications?
1,380,852
<p>What happens when you package a script as an executable? Is this a good way to distribute commercial applications? I remember I read something a long time ago that when you package scripts as executables, at runtime the exe decompresses the scripts to a temporary directory where they get ran.</p> <p>If it's like that, than I don't think this can be viewed as a good solution, because a skilled user could find out where that directory is located and find the source code. I'm interested in Python &amp; Ruby.</p>
0
2009-09-04T18:34:54Z
1,381,595
<p>This has been discussed before here for the Python case and some answers are valid for Ruby too. I highly recommend you to read a previous question in this site titled: <a href="http://stackoverflow.com/questions/261638/how-do-i-protect-python-code">How do I protect python code?</a>. Pay attention to the first three answers.</p>
1
2009-09-04T21:21:13Z
[ "python", "ruby", "executable" ]
Add Variables to Tuple
1,380,860
<p>I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. </p> <p><strong>What I am Doing</strong>: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me with the syntax?</p> <p>Also if there is an efficient way of doing this, please share...</p> <p><strong>EDIT</strong> Let me edit this question a bit...I only need the tuple to enter info into the DB. Once the information is added to the DB, should I delete the tuple? I mean I don't need the tuple anymore.</p>
128
2009-09-04T18:36:18Z
1,380,872
<p>It's as easy as the following:</p> <pre><code>info_1 = "one piece of info" info_2 = "another piece" vars = (info_1, info_2) # 'vars' is now a tuple with the values ("info_1", "info_2") </code></pre> <p>However, tuples in Python are <em>immutable</em>, so you cannot append variables to a tuple once it is created.</p>
5
2009-09-04T18:39:30Z
[ "python", "tuples" ]
Add Variables to Tuple
1,380,860
<p>I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. </p> <p><strong>What I am Doing</strong>: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me with the syntax?</p> <p>Also if there is an efficient way of doing this, please share...</p> <p><strong>EDIT</strong> Let me edit this question a bit...I only need the tuple to enter info into the DB. Once the information is added to the DB, should I delete the tuple? I mean I don't need the tuple anymore.</p>
128
2009-09-04T18:36:18Z
1,380,873
<p>I'm pretty sure the syntax for this in python is:</p> <pre><code>user_input1 = raw_input("Enter Name: ") user_input2 = raw_input("Enter Value: ") info = (user_input1, user_input2) </code></pre> <p>once set, tuples cannot be changed.</p>
0
2009-09-04T18:39:31Z
[ "python", "tuples" ]
Add Variables to Tuple
1,380,860
<p>I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. </p> <p><strong>What I am Doing</strong>: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me with the syntax?</p> <p>Also if there is an efficient way of doing this, please share...</p> <p><strong>EDIT</strong> Let me edit this question a bit...I only need the tuple to enter info into the DB. Once the information is added to the DB, should I delete the tuple? I mean I don't need the tuple anymore.</p>
128
2009-09-04T18:36:18Z
1,380,875
<p>Tuples are immutable; you can't change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:</p> <pre><code>a = (1, 2, 3) b = a + (4, 5, 6) c = b[1:] </code></pre> <p>And, of course, build them from existing values:</p> <pre><code> name = "Joe" age = 40 location = "New York" joe = (name, age, location) </code></pre>
160
2009-09-04T18:39:39Z
[ "python", "tuples" ]
Add Variables to Tuple
1,380,860
<p>I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. </p> <p><strong>What I am Doing</strong>: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me with the syntax?</p> <p>Also if there is an efficient way of doing this, please share...</p> <p><strong>EDIT</strong> Let me edit this question a bit...I only need the tuple to enter info into the DB. Once the information is added to the DB, should I delete the tuple? I mean I don't need the tuple anymore.</p>
128
2009-09-04T18:36:18Z
1,380,915
<p>As other answers have noted, you cannot change an existing tuple, but you can always create a new tuple (which may take some or all items from existing tuples and/or other sources).</p> <p>For example, if all the items of interest are in scalar variables and you know the names of those variables:</p> <pre><code>def maketuple(variables, names): return tuple(variables[n] for n in names) </code></pre> <p>to be used, e.g, as in this example:</p> <pre><code>def example(): x = 23 y = 45 z = 67 return maketuple(vars(), 'x y z'.split()) </code></pre> <p>of course this one case would be more simply expressed as <code>(x, y, z)</code> (or even foregoing the names altogether, <code>(23, 45, 67)</code>), but the <code>maketuple</code> approach might be useful in some more complicated cases (e.g. where the names to use are also determined dynamically and appended to a list during the computation).</p>
1
2009-09-04T18:47:11Z
[ "python", "tuples" ]
Add Variables to Tuple
1,380,860
<p>I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. </p> <p><strong>What I am Doing</strong>: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me with the syntax?</p> <p>Also if there is an efficient way of doing this, please share...</p> <p><strong>EDIT</strong> Let me edit this question a bit...I only need the tuple to enter info into the DB. Once the information is added to the DB, should I delete the tuple? I mean I don't need the tuple anymore.</p>
128
2009-09-04T18:36:18Z
1,381,304
<p><strong>" once the info is added to the DB, should I delete the tuple? i mean i dont need the tuple anymore."</strong></p> <p>No.</p> <p>Generally, there's no reason to delete anything. There are some special cases for deleting, but they're very, very rare.</p> <p>Simply define a narrow scope (i.e., a function definition or a method function in a class) and the objects will be garbage collected at the end of the scope.</p> <p>Don't worry about deleting anything.</p> <p>[Note. I worked with a guy who -- in addition to trying to delete objects -- was always writing "reset" methods to clear them out. Like he was going to save them and reuse them. Also a silly conceit. Just ignore the objects you're no longer using. If you define your functions in small-enough blocks of code, you have nothing more to think about.]</p>
2
2009-09-04T20:06:31Z
[ "python", "tuples" ]
Add Variables to Tuple
1,380,860
<p>I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. </p> <p><strong>What I am Doing</strong>: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me with the syntax?</p> <p>Also if there is an efficient way of doing this, please share...</p> <p><strong>EDIT</strong> Let me edit this question a bit...I only need the tuple to enter info into the DB. Once the information is added to the DB, should I delete the tuple? I mean I don't need the tuple anymore.</p>
128
2009-09-04T18:36:18Z
8,538,676
<p>You can start with a blank tuple with something like t = (). You can add with +, but you have to add another tuple. If you want to add a single element, make it a singleton: t = t + (element,). You can add a tuple of multiple elements with or without that trailing comma.</p> <pre><code>&gt;&gt;&gt; t = () &gt;&gt;&gt; t = t + (1,) &gt;&gt;&gt; t (1,) &gt;&gt;&gt; t = t + (2,) &gt;&gt;&gt; t (1, 2) &gt;&gt;&gt; t = t + (3, 4, 5) &gt;&gt;&gt; t (1, 2, 3, 4, 5) &gt;&gt;&gt; t = t + (6, 7, 8,) &gt;&gt;&gt; t (1, 2, 3, 4, 5, 6, 7, 8) </code></pre>
111
2011-12-16T18:43:21Z
[ "python", "tuples" ]
Add Variables to Tuple
1,380,860
<p>I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. </p> <p><strong>What I am Doing</strong>: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me with the syntax?</p> <p>Also if there is an efficient way of doing this, please share...</p> <p><strong>EDIT</strong> Let me edit this question a bit...I only need the tuple to enter info into the DB. Once the information is added to the DB, should I delete the tuple? I mean I don't need the tuple anymore.</p>
128
2009-09-04T18:36:18Z
23,530,113
<p>Another tactic not yet mentioned is using appending to a list, and then converting the list to a tuple at the end:</p> <pre><code>mylist = [] for x in range(5): mylist.append(x) mytuple = tuple(mylist) print mytuple </code></pre> <p>returns</p> <pre><code>(0, 1, 2, 3, 4) </code></pre> <p>I sometimes use this when I have to pass a tuple as a function argument, which is often necessary for the numpy functions.</p>
16
2014-05-07T23:20:59Z
[ "python", "tuples" ]
What lightweight python library for simple scientific visualization in 3D
1,380,861
<p>I am writing a program in python to experiment an academic idea. Look at a resultant image the program generates:</p> <p><img src="http://imgur.com/zgdiP.png" alt="leaf" /></p> <p>The thick skeleton lines in the middle of the leaf is what need to be visualized. Every segment of the skeleton lines has a value associated with it, in the above image (drawn by <code>pycairo</code>), different shades of gray are used for visualization, the lighter color means higher value, black lines indicate the lines have value 0 associated with them. The problem is visualization using colors in this case is very unintuitive for human eyes, it would be much better to visualize the values in 3D like the following (taken from a paper):</p> <p><img src="http://imgur.com/MExU1.png" alt="2d in 3d" /></p> <p>the left image is a 3D visualization of the right one, the values associated with the lines are visualized as height of consecutive walls in 3D.</p> <p>What is the best library to do this? I don't want to invest much time into doing this, so a lightweight library is preferred.</p>
4
2009-09-04T18:36:35Z
1,380,886
<p>Have you looked at <a href="http://code.enthought.com/projects/mayavi/" rel="nofollow">mayavi</a>? Don't know if it meets your definition of "lightweight", but it does seem popular and reasonably easy to use for its power.</p>
3
2009-09-04T18:41:53Z
[ "python", "3d", "geometry", "visualization" ]
What lightweight python library for simple scientific visualization in 3D
1,380,861
<p>I am writing a program in python to experiment an academic idea. Look at a resultant image the program generates:</p> <p><img src="http://imgur.com/zgdiP.png" alt="leaf" /></p> <p>The thick skeleton lines in the middle of the leaf is what need to be visualized. Every segment of the skeleton lines has a value associated with it, in the above image (drawn by <code>pycairo</code>), different shades of gray are used for visualization, the lighter color means higher value, black lines indicate the lines have value 0 associated with them. The problem is visualization using colors in this case is very unintuitive for human eyes, it would be much better to visualize the values in 3D like the following (taken from a paper):</p> <p><img src="http://imgur.com/MExU1.png" alt="2d in 3d" /></p> <p>the left image is a 3D visualization of the right one, the values associated with the lines are visualized as height of consecutive walls in 3D.</p> <p>What is the best library to do this? I don't want to invest much time into doing this, so a lightweight library is preferred.</p>
4
2009-09-04T18:36:35Z
1,381,066
<p>If you want lightweight, then you can use <a href="http://pyopengl.sourceforge.net/" rel="nofollow">PyOpenGL</a> to just wrap OpenGL calls in python directly. This is probably the lightest-weight option.</p> <p>If you want lots of features, I'd recommend using <a href="http://vtk.org/" rel="nofollow">VTK</a>. It's a very powerful visualization toolkit with Python wrappers (included). There are other packages built on top of this (such as Mayavi and Paraview), but the VTK wrappers alone are often easier to use. This would probably be my first choice, since they have some good samples you can use - all you'd need to do is make a VtkPolyData instance, and throw it in a renderer.</p> <p>That being said, for ease of development, you might want something that simplifies this for you, such as wrappers for a light-weight rendering engine like <a href="http://irrlicht.sourceforge.net/links.html" rel="nofollow">Irrlicht</a> via <a href="https://opensvn.csie.org/traccgi/pyrr" rel="nofollow">Pyrr</a>. This makes it much easier to generate the picture.</p>
4
2009-09-04T19:18:31Z
[ "python", "3d", "geometry", "visualization" ]
Python list vs. MySQL Select performance
1,380,917
<p>I have a large list with 15k entries in a MySQL table from which I need to select a few items, many times. For example, I might want all entries with a number field between 1 and 10.</p> <p>In SQL this would be easy:</p> <pre><code>SELECT text FROM table WHERE number&gt;=1 AND number&lt;10; </code></pre> <p>If I extract the entire table to a Python list:</p> <pre><code>PyList = [[text1, number1], [text2, number2], ...] </code></pre> <p>I could then extract those same text values I want by running through the entire list</p> <pre><code>for item in PyList if item[1] &gt;=1 and item[1]&lt;10: result.append(item[0]) </code></pre> <p>Now, the performance question between the two is that I have to do this for a sliding window. I want to get those between 1 and 10, then 2 and 11, 3 and 12, ... 14990 and 15000 What approach is faster for a list this big?</p> <p>An improvement in Python I'm thinking about is to pre-order the Python list by number. When the window moves I could remove the lowest value from <code>result</code> and append all elements verifying the next condition to get the new <code>result</code>. I would also keep track of index in the PyList so I would know where to start from in the next iteration. This would spare me from running through the entire list again.</p> <p>I don't know how to speed up the MySQL for successive Selects that are very similar and I don't know how it works internally to understand performance differences between the two approaches. </p> <p>How would you implement this? </p>
0
2009-09-04T18:47:16Z
1,380,942
<p>Read all the data into Python (from the numbers you mention it should handily fit in memory), say into a variable <code>pylist</code> as you say, then prep an auxiliary data structure as follows:</p> <pre><code>import collections d = collections.defaultdict(list) for text, number in pylist: d[number].append(text) </code></pre> <p>Now, to get all texts for numbers between <code>low</code> included and <code>high</code> excluded,</p> <pre><code>def slidingwindow(d, low, high): result = [] for x in xrange(low, high): result.extend(d.get(x, ())) return result </code></pre>
0
2009-09-04T18:51:39Z
[ "python", "mysql" ]
Python list vs. MySQL Select performance
1,380,917
<p>I have a large list with 15k entries in a MySQL table from which I need to select a few items, many times. For example, I might want all entries with a number field between 1 and 10.</p> <p>In SQL this would be easy:</p> <pre><code>SELECT text FROM table WHERE number&gt;=1 AND number&lt;10; </code></pre> <p>If I extract the entire table to a Python list:</p> <pre><code>PyList = [[text1, number1], [text2, number2], ...] </code></pre> <p>I could then extract those same text values I want by running through the entire list</p> <pre><code>for item in PyList if item[1] &gt;=1 and item[1]&lt;10: result.append(item[0]) </code></pre> <p>Now, the performance question between the two is that I have to do this for a sliding window. I want to get those between 1 and 10, then 2 and 11, 3 and 12, ... 14990 and 15000 What approach is faster for a list this big?</p> <p>An improvement in Python I'm thinking about is to pre-order the Python list by number. When the window moves I could remove the lowest value from <code>result</code> and append all elements verifying the next condition to get the new <code>result</code>. I would also keep track of index in the PyList so I would know where to start from in the next iteration. This would spare me from running through the entire list again.</p> <p>I don't know how to speed up the MySQL for successive Selects that are very similar and I don't know how it works internally to understand performance differences between the two approaches. </p> <p>How would you implement this? </p>
0
2009-09-04T18:47:16Z
1,381,149
<p>It is difficult to answer without actual performance, but my gut feeling is that it would be better to go for the SQL with bind variables (I am not MySQL expert, but in this case query syntax <a href="http://www.kitebird.com/articles/pydbapi.html" rel="nofollow">should be</a> something like %varname). </p> <p>The reason is that you would return data only when needed (thus user interface would be responsive much in advance) and you would rely on a system highly optimized for that kind of operation. On the other hand, retrieving a larger chunk of data i usually faster than retrieving smaller ones, so the "full python" approach could have its edge.</p> <p>However, unless you have serious performance issues, I would still stick in using SQL, because it would lead to much simpler code, to read and understand.</p>
0
2009-09-04T19:34:22Z
[ "python", "mysql" ]
Python list vs. MySQL Select performance
1,380,917
<p>I have a large list with 15k entries in a MySQL table from which I need to select a few items, many times. For example, I might want all entries with a number field between 1 and 10.</p> <p>In SQL this would be easy:</p> <pre><code>SELECT text FROM table WHERE number&gt;=1 AND number&lt;10; </code></pre> <p>If I extract the entire table to a Python list:</p> <pre><code>PyList = [[text1, number1], [text2, number2], ...] </code></pre> <p>I could then extract those same text values I want by running through the entire list</p> <pre><code>for item in PyList if item[1] &gt;=1 and item[1]&lt;10: result.append(item[0]) </code></pre> <p>Now, the performance question between the two is that I have to do this for a sliding window. I want to get those between 1 and 10, then 2 and 11, 3 and 12, ... 14990 and 15000 What approach is faster for a list this big?</p> <p>An improvement in Python I'm thinking about is to pre-order the Python list by number. When the window moves I could remove the lowest value from <code>result</code> and append all elements verifying the next condition to get the new <code>result</code>. I would also keep track of index in the PyList so I would know where to start from in the next iteration. This would spare me from running through the entire list again.</p> <p>I don't know how to speed up the MySQL for successive Selects that are very similar and I don't know how it works internally to understand performance differences between the two approaches. </p> <p>How would you implement this? </p>
0
2009-09-04T18:47:16Z
1,381,413
<p>Simply define an index over <code>number</code> in your database, then the database can generate the result sets instantly. Plus it can do some calculations on these sets too, if that is your next step. </p> <p>Databases are actually great at such queries, I'd let it do its job before trying something else.</p>
1
2009-09-04T20:34:17Z
[ "python", "mysql" ]
Python list vs. MySQL Select performance
1,380,917
<p>I have a large list with 15k entries in a MySQL table from which I need to select a few items, many times. For example, I might want all entries with a number field between 1 and 10.</p> <p>In SQL this would be easy:</p> <pre><code>SELECT text FROM table WHERE number&gt;=1 AND number&lt;10; </code></pre> <p>If I extract the entire table to a Python list:</p> <pre><code>PyList = [[text1, number1], [text2, number2], ...] </code></pre> <p>I could then extract those same text values I want by running through the entire list</p> <pre><code>for item in PyList if item[1] &gt;=1 and item[1]&lt;10: result.append(item[0]) </code></pre> <p>Now, the performance question between the two is that I have to do this for a sliding window. I want to get those between 1 and 10, then 2 and 11, 3 and 12, ... 14990 and 15000 What approach is faster for a list this big?</p> <p>An improvement in Python I'm thinking about is to pre-order the Python list by number. When the window moves I could remove the lowest value from <code>result</code> and append all elements verifying the next condition to get the new <code>result</code>. I would also keep track of index in the PyList so I would know where to start from in the next iteration. This would spare me from running through the entire list again.</p> <p>I don't know how to speed up the MySQL for successive Selects that are very similar and I don't know how it works internally to understand performance differences between the two approaches. </p> <p>How would you implement this? </p>
0
2009-09-04T18:47:16Z
1,381,435
<p>It's certainly going to be much faster to pull the data into memory than run ~15,000 queries.</p> <p>My advice is to make sure the SQL query sorts the data by <code>number</code>. If the data is sorted, you can use the very fast lookup methods in the <code>bisect</code> standard library module to find indexes.</p>
1
2009-09-04T20:39:33Z
[ "python", "mysql" ]
Logging multithreaded processes in python
1,380,985
<p>I was thinking of using the logging module to log all events to one file. The number of threads should be constant from start to finish, but if one thread fails, I'd like to just log that and continue on. What's a simple way of accomplishing this? Thanks!</p>
3
2009-09-04T19:01:13Z
1,381,468
<p>Not entirely sure what you mean by "one thread fails", but if by "fail" you mean that an exception propagates all the way up to the top function of the thread, then you can wrap every thread's top function (e.g. in a decorator) to catch any exception, log whatever you wish, and re-raise. The <code>logging</code> module should ensure thread-safety of logging actions without further precautions being needed on your part on that score.</p>
7
2009-09-04T20:46:22Z
[ "python", "multithreading", "logging" ]
How do I wrap this C function, with multiple arguments, with ctypes?
1,381,016
<p>I have the function prototype here:</p> <pre><code>extern "C" void __stdcall__declspec(dllexport) ReturnPulse(double*,double*,double*,double*,double*); </code></pre> <p>I need to write some python to access this function that is in a DLL. I have loaded the DLL, but each of the double* is actually pointing to a variable number of doubles (an array), and I'm having trouble getting it to function properly.</p> <p>Thanks all!</p>
0
2009-09-04T19:08:26Z
1,381,031
<p>I haven't looked at ctypes too much, but try using a numpy array of the right type. If that doesn't just automatically work, they also have a ctypes attribute that should contain a pointer to the data.</p>
1
2009-09-04T19:12:23Z
[ "python", "arrays", "pointers", "return", "ctypes" ]
How do I wrap this C function, with multiple arguments, with ctypes?
1,381,016
<p>I have the function prototype here:</p> <pre><code>extern "C" void __stdcall__declspec(dllexport) ReturnPulse(double*,double*,double*,double*,double*); </code></pre> <p>I need to write some python to access this function that is in a DLL. I have loaded the DLL, but each of the double* is actually pointing to a variable number of doubles (an array), and I'm having trouble getting it to function properly.</p> <p>Thanks all!</p>
0
2009-09-04T19:08:26Z
1,381,494
<p>To make an array with, say, <code>n</code> doubles:</p> <pre><code>arr7 = ctypes.c_double * `n` x = arr7() </code></pre> <p>and pass <code>x</code> to your function where it wants a <code>double*</code>. Or if you need to initialize <code>x</code> as you make it:</p> <pre><code>x = arr7(i*0.1 for i in xrange(7)) </code></pre> <p>and the like. You can loop over <code>x</code>, index it, and so on.</p>
1
2009-09-04T20:51:20Z
[ "python", "arrays", "pointers", "return", "ctypes" ]
Wrong Mac OS X framework gets loaded
1,381,177
<p>I've compiled a Python module using my own Qt4 library located in <code>~/opt/qt-4.6.0/</code>, but when I try to import that module, the dynamic libraries that get loaded are from my MacPorts Qt4 installation. </p> <pre><code>$ /opt/local/bin/python2.6 &gt;&gt;&gt; import vtk objc[58041]: Class QMacSoundDelegate is implemented in both /Users/luis/opt/qt-4.6.0/lib/QtGui.framework/Versions/4/QtGui and /opt/local/libexec/qt4-mac/lib/QtGui.framework/Versions/4/QtGui. Using implementation from /opt/local/libexec/qt4-mac/lib/QtGui.framework/Versions/4/QtGui. objc[58045]: Class QCocoaColorPanelDelegate is implemented in both /Users/luis/opt/qt-4.6.0/lib/QtGui.framework/Versions/4/QtGui and /opt/local/libexec/qt4-mac/lib/QtGui.framework/Versions/4/QtGui. Using implementation from /opt/local/libexec/qt4-mac/lib/QtGui.framework/Versions/4/QtGui. [... more output like above ...] &gt;&gt;&gt; </code></pre> <p>Is there a way of telling Python (also installed from MacPorts) to load the frameworks located in my <code>~/opt/qt-4.6.0/lib/</code> directory? I'm not sure what environment variables to change.</p>
2
2009-09-04T19:40:30Z
1,381,353
<p>Try setting the <code>DYLD_LIBRARY_PATH</code> to put your libraries in <code>~/opt/qt/...</code> before the MacPorts' libraries before invoking python (take a look at <code>~/.profile</code> for an example of how to do this if you don't know; MacPorts does the exact same thing to put its libraries on the <code>DYLD_LIBRARY_PATH</code>). <code>dyld</code>, the OS X dynamic linker uses <code>DYLD_LIBRARY_PATH</code> to find libraries at load time (among other methods); See <code>man dyld</code> for more info.</p>
2
2009-09-04T20:18:04Z
[ "python", "osx", "qt4", "macports", "vtk" ]
Wrong Mac OS X framework gets loaded
1,381,177
<p>I've compiled a Python module using my own Qt4 library located in <code>~/opt/qt-4.6.0/</code>, but when I try to import that module, the dynamic libraries that get loaded are from my MacPorts Qt4 installation. </p> <pre><code>$ /opt/local/bin/python2.6 &gt;&gt;&gt; import vtk objc[58041]: Class QMacSoundDelegate is implemented in both /Users/luis/opt/qt-4.6.0/lib/QtGui.framework/Versions/4/QtGui and /opt/local/libexec/qt4-mac/lib/QtGui.framework/Versions/4/QtGui. Using implementation from /opt/local/libexec/qt4-mac/lib/QtGui.framework/Versions/4/QtGui. objc[58045]: Class QCocoaColorPanelDelegate is implemented in both /Users/luis/opt/qt-4.6.0/lib/QtGui.framework/Versions/4/QtGui and /opt/local/libexec/qt4-mac/lib/QtGui.framework/Versions/4/QtGui. Using implementation from /opt/local/libexec/qt4-mac/lib/QtGui.framework/Versions/4/QtGui. [... more output like above ...] &gt;&gt;&gt; </code></pre> <p>Is there a way of telling Python (also installed from MacPorts) to load the frameworks located in my <code>~/opt/qt-4.6.0/lib/</code> directory? I'm not sure what environment variables to change.</p>
2
2009-09-04T19:40:30Z
1,381,647
<p>Ok, after Barry Wark pointed me to <code>dyld(1)</code>, the man page described a number of variables that I could set.</p> <p>The first hint came from setting the environment variable <code>DYLD_PRINT_LIBRARIES</code>, so I could see what libraries were being loaded.</p> <pre><code>$ DYLD_PRINT_LIBRARIES=1 python -c 'import vtk' [... snip ...] dyld: loaded: /opt/local/libexec/qt4-mac/lib/QtGui.framework/Versions/4/QtGui dyld: loaded: /opt/local/lib/libpng12.0.dylib dyld: loaded: /opt/local/libexec/qt4-mac/lib/QtSql.framework/Versions/4/QtSql dyld: loaded: /opt/local/libexec/qt4-mac/lib/QtCore.framework/Versions/4/QtCore [... snip ...] dyld: loaded: /Users/luis/opt/qt-4.6.0/lib/QtGui.framework/Versions/4/QtGui dyld: loaded: /Users/luis/opt/qt-4.6.0/lib/QtSql.framework/Versions/4/QtSql dyld: loaded: /Users/luis/opt/qt-4.6.0/lib/QtCore.framework/Versions/4/QtCore [... snip ...] $ </code></pre> <p>Ah, so the frameworks for qt4-mac were indeed being loaded first, just as we suspected. Rereading the man page, the next thing we can try is changing the <code>DYLD_FRAMEWORK_PATH</code> so that it knows where to look. I now added this line to the end of my <code>~/.bash_profile</code></p> <pre><code>export DYLD_FRAMEWORK_PATH="${HOME}/opt/qt-4.6.0/lib:${DYLD_FRAMEWORK_PATH}" </code></pre> <p>and after logging back in, we try importing the vtk python module again:</p> <pre><code>$ python -c 'import vtk' $ </code></pre> <p>There's no output this time. Issue fixed!</p>
2
2009-09-04T21:33:33Z
[ "python", "osx", "qt4", "macports", "vtk" ]
Manipulating time in python
1,381,315
<p>In the code shown below, I need to manipulate the time var in python to display a date/time stamp in python to represent that delay.</p> <p>For example, when the user enters the delay time in hours, I need to set the jcarddeliver var to update itself with the value of the current date/time + delay.</p> <p>Also it should update the date var as well. For example, if the date is 24 Feb and time is 15:00 hrs and the delay time is 10 hrs, the jcarddeliver date should change to 25 Feb.</p> <pre><code>jcarddate = time.strftime("%a %m/%d/%y", time.localtime()) jcardtime = time.strftime("%H:%M:%S", time.localtime()) delay = raw_input("enter the delay: ") jcarddeliver = ?? </code></pre> <p>I just hope I am making sense.</p>
1
2009-09-04T20:09:42Z
1,381,347
<p>" i need to set the jcarddeliver var to update itself with the value of the current date/time + delay"</p> <p>How about reformulating this to</p> <p><code>jcarddeliver</code> should be the current date-time plus the delay.</p> <p>The "update itself" isn't perfectly sensible.</p> <p>Try the following:</p> <ol> <li><p>Try the most obvious way of computing "current date-time plus the delay"</p></li> <li><p>print the result.</p></li> <li><p>Try using <code>localtime()</code> on this result. What do you get?</p></li> </ol>
0
2009-09-04T20:16:27Z
[ "python", "datetime" ]
Manipulating time in python
1,381,315
<p>In the code shown below, I need to manipulate the time var in python to display a date/time stamp in python to represent that delay.</p> <p>For example, when the user enters the delay time in hours, I need to set the jcarddeliver var to update itself with the value of the current date/time + delay.</p> <p>Also it should update the date var as well. For example, if the date is 24 Feb and time is 15:00 hrs and the delay time is 10 hrs, the jcarddeliver date should change to 25 Feb.</p> <pre><code>jcarddate = time.strftime("%a %m/%d/%y", time.localtime()) jcardtime = time.strftime("%H:%M:%S", time.localtime()) delay = raw_input("enter the delay: ") jcarddeliver = ?? </code></pre> <p>I just hope I am making sense.</p>
1
2009-09-04T20:09:42Z
1,381,372
<p>The result of <code>time.time()</code> is a floating point value of the number of seconds since the Epoch. You can add seconds to this value and use <code>time.localtime()</code>, <code>time.ctime()</code> and other functions to get the result in various forms:</p> <pre><code>&gt;&gt;&gt; now = time.time() &gt;&gt;&gt; time.ctime(now) 'Fri Sep 04 16:19:59 2009' # &lt;-- this is local time &gt;&gt;&gt; then = now + (10.0 * 60.0 * 60.0) # &lt;-- 10 hours in seconds &gt;&gt;&gt; time.ctime(then) 'Sat Sep 05 02:19:59 2009' </code></pre>
1
2009-09-04T20:23:30Z
[ "python", "datetime" ]
Manipulating time in python
1,381,315
<p>In the code shown below, I need to manipulate the time var in python to display a date/time stamp in python to represent that delay.</p> <p>For example, when the user enters the delay time in hours, I need to set the jcarddeliver var to update itself with the value of the current date/time + delay.</p> <p>Also it should update the date var as well. For example, if the date is 24 Feb and time is 15:00 hrs and the delay time is 10 hrs, the jcarddeliver date should change to 25 Feb.</p> <pre><code>jcarddate = time.strftime("%a %m/%d/%y", time.localtime()) jcardtime = time.strftime("%H:%M:%S", time.localtime()) delay = raw_input("enter the delay: ") jcarddeliver = ?? </code></pre> <p>I just hope I am making sense.</p>
1
2009-09-04T20:09:42Z
1,381,769
<p>You could try the datetime module, e.g.</p> <pre><code>import datetime now = datetime.datetime.now() delay = float (raw_input ("enter delay (s): ")) dt = datetime.timedelta (seconds=delay) then = now + dt print now print then </code></pre>
3
2009-09-04T22:17:54Z
[ "python", "datetime" ]
Manipulating time in python
1,381,315
<p>In the code shown below, I need to manipulate the time var in python to display a date/time stamp in python to represent that delay.</p> <p>For example, when the user enters the delay time in hours, I need to set the jcarddeliver var to update itself with the value of the current date/time + delay.</p> <p>Also it should update the date var as well. For example, if the date is 24 Feb and time is 15:00 hrs and the delay time is 10 hrs, the jcarddeliver date should change to 25 Feb.</p> <pre><code>jcarddate = time.strftime("%a %m/%d/%y", time.localtime()) jcardtime = time.strftime("%H:%M:%S", time.localtime()) delay = raw_input("enter the delay: ") jcarddeliver = ?? </code></pre> <p>I just hope I am making sense.</p>
1
2009-09-04T20:09:42Z
23,622,496
<p>Try this:</p> <pre><code>now = time.time() then = now + 365*24*3600 print time.strftime('%Y-%m-%d', time.localtime(then)) </code></pre>
0
2014-05-13T03:50:25Z
[ "python", "datetime" ]
How to aggregate all attributes of a hierarchy of classes?
1,381,333
<p>There is a hierchy of classes. Each class <em>may</em> define a class variable (to be specific, it's a dictionary), all of which have the same variable name. I'd like the very root class to be able to somehow access all of these variables (i.e. all the dictionaries joined together), given an instance of a child class. I can't seem to find the way to do so. No matter what I try, I always get stuck on the fact that I cannot retrieve the direct parent class given the child class. How can this be accomplished?</p>
0
2009-09-04T20:13:34Z
1,381,443
<p>As long as you're using new-style classes (i.e., <code>object</code> or some other built-in type is the "deepest ancestor"), <code>__mro__</code> is what you're looking for. For example, given:</p> <pre><code>&gt;&gt;&gt; class Root(object): ... d = {'za': 23} ... &gt;&gt;&gt; class Trunk(Root): ... d = {'ki': 45} ... &gt;&gt;&gt; class Branch(Root): ... d = {'fu': 67} ... &gt;&gt;&gt; class Leaf(Trunk, Branch): ... d = {'po': 89} </code></pre> <p>now,</p> <pre><code>&gt;&gt;&gt; def getem(x): ... d = {} ... for x in x.__class__.__mro__: ... d.update(x.__dict__.get('d', ())) ... return d ... &gt;&gt;&gt; x = Leaf() &gt;&gt;&gt; getem(x) {'za': 23, 'ki': 45, 'po': 89, 'fu': 67} </code></pre>
1
2009-09-04T20:41:30Z
[ "python", "class", "hierarchy" ]
Easiest way to write a Python program with access to Django database functionality
1,381,346
<p>I have a website which fetches information from RSS feeds periodically (well, currently manually, and this is my problem). This is currently implemented as a normal Django view, which isn't very nice in my opinion. I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct URL to update the information.</p> <p>What is the easiest way to make a Python program have access to my particular Django application and the Django ORM?</p>
3
2009-09-04T20:16:20Z
1,381,395
<pre><code>from django.core.management import setup_environ from django.core.mail import EmailMultiAlternatives, send_mail from django.contrib.auth.models import User import settings from my.app.models import * setup_environ(settings) </code></pre> <p>This was how I did it for a cron that emailed parties daily updates. The .py lived in the root of my django app, so the import settings would reflect that accordingly.</p>
13
2009-09-04T20:30:39Z
[ "python", "django", "django-models", "django-orm" ]
Easiest way to write a Python program with access to Django database functionality
1,381,346
<p>I have a website which fetches information from RSS feeds periodically (well, currently manually, and this is my problem). This is currently implemented as a normal Django view, which isn't very nice in my opinion. I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct URL to update the information.</p> <p>What is the easiest way to make a Python program have access to my particular Django application and the Django ORM?</p>
3
2009-09-04T20:16:20Z
1,381,402
<p>You want something like this in your crontab:</p> <pre><code>PYTHONPATH=/path/to/your/project DJANGO_SETTINGS_MODULE=settings myscript.py </code></pre> <p>And then your python script should start with this:</p> <pre><code>#!/usr/bin/env python from django.conf import settings </code></pre> <p>From there, you should be able to import your models / views / forms / whatever else, and have an environment pretty much just like a <code>./manage.py shell</code></p> <p>Note: Depending on how you do your imports inside your project, this may not work exactly as shown. If you are always doing something like "from myproject.myapp.models import *", then you will want to set cron line to look more like this:</p> <pre><code>PYTHONPATH=/path/to/1_level_before_your_project DJANGO_SETTINGS_MODULE=myproject.settings myscript.py </code></pre>
0
2009-09-04T20:31:45Z
[ "python", "django", "django-models", "django-orm" ]
Easiest way to write a Python program with access to Django database functionality
1,381,346
<p>I have a website which fetches information from RSS feeds periodically (well, currently manually, and this is my problem). This is currently implemented as a normal Django view, which isn't very nice in my opinion. I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct URL to update the information.</p> <p>What is the easiest way to make a Python program have access to my particular Django application and the Django ORM?</p>
3
2009-09-04T20:16:20Z
1,381,517
<blockquote> <p>I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct URL to update the information.</p> </blockquote> <p>A simplistic alternative: write a cronjob to <em>automatically</em> "visit the correct URL to update the information" -- could be as simple as a <code>curl</code> or <code>wget</code>, after all. This doesn't answer the question in the title, but given the way you explain your real underlying problem it just might be the simplest and most immediate approach to solve it.</p>
0
2009-09-04T20:58:46Z
[ "python", "django", "django-models", "django-orm" ]
Easiest way to write a Python program with access to Django database functionality
1,381,346
<p>I have a website which fetches information from RSS feeds periodically (well, currently manually, and this is my problem). This is currently implemented as a normal Django view, which isn't very nice in my opinion. I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct URL to update the information.</p> <p>What is the easiest way to make a Python program have access to my particular Django application and the Django ORM?</p>
3
2009-09-04T20:16:20Z
1,381,619
<p>An alternative to all the approaches given here is to write your cron job as a custom <code>./manage.py</code> command. This is very easy to do, and gives you the ability to do <code>./manage.py yourcommand</code> either on the command line or in your crontab.</p> <p><a href="http://docs.djangoproject.com/en/dev/howto/custom-management-commands/">The documentation</a> on this is very sparse, but it does tell you to look at the code for the existing commands, which you can use as a template for your own.</p>
9
2009-09-04T21:27:12Z
[ "python", "django", "django-models", "django-orm" ]
Easiest way to write a Python program with access to Django database functionality
1,381,346
<p>I have a website which fetches information from RSS feeds periodically (well, currently manually, and this is my problem). This is currently implemented as a normal Django view, which isn't very nice in my opinion. I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct URL to update the information.</p> <p>What is the easiest way to make a Python program have access to my particular Django application and the Django ORM?</p>
3
2009-09-04T20:16:20Z
21,129,096
<p><strong>Edit</strong>: For Django 1.7</p> <pre><code>import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings") django.setup() #have fun </code></pre> <p><a href="https://stackoverflow.com/a/23241093/1552045">Credit</a></p> <hr> <p>Selected answer is <strong>deprecated</strong> since Django 1.4</p> <pre><code>import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings") #from your_app_name import models ##have fun </code></pre> <p>Source: <a href="http://stackoverflow.com/a/18760222">http://stackoverflow.com/a/18760222</a></p>
2
2014-01-15T04:24:31Z
[ "python", "django", "django-models", "django-orm" ]
C# way to mimic Python Dictionary Syntax
1,381,359
<p>Is there a good way in C# to mimic the following python syntax:</p> <pre><code>mydict = {} mydict["bc"] = {} mydict["bc"]["de"] = "123"; # &lt;-- This line mydict["te"] = "5"; # &lt;-- While also allowing this line </code></pre> <p>In other words, I'd like something with [] style access that can return either another dictionary or a string type, depending on how it has been set.</p> <p>I've been trying to work this out with a custom class but can't seem to succeed. Any ideas?</p> <p>Thanks!</p> <p>Edit: I'm being evil, I know. Jared Par's solution is great . . . for a 2-level dictionary of this form. However, I am also curious about further levels . . . for instance,</p> <pre><code>mydict["bc"]["df"]["ic"] = "32"; </code></pre> <p>And so on. Any ideas about that?</p> <p>Edit 3:</p> <p>Here is the final class I ended up using:</p> <pre><code>class PythonDict { /* Public properties and conversions */ public PythonDict this[String index] { get { return this.dict_[index]; } set { this.dict_[index] = value; } } public static implicit operator PythonDict(String value) { return new PythonDict(value); } public static implicit operator String(PythonDict value) { return value.str_; } /* Public methods */ public PythonDict() { this.dict_ = new Dictionary&lt;String, PythonDict&gt;(); } public PythonDict(String value) { this.str_ = value; } public bool isString() { return (this.str_ != null); } /* Private fields */ Dictionary&lt;String, PythonDict&gt; dict_ = null; String str_ = null; } </code></pre> <p>This class works for infinite levels, and can be read from without explicit conversion (dangerous, maybe, but hey).</p> <p>Usage like so:</p> <pre><code> PythonDict s = new PythonDict(); s["Hello"] = new PythonDict(); s["Hello"]["32"] = "hey there"; s["Hello"]["34"] = new PythonDict(); s["Hello"]["34"]["Section"] = "Your face"; String result = s["Hello"]["34"]["Section"]; s["Hi there"] = "hey"; </code></pre> <p>Thank you very much Jared Par!</p>
11
2009-09-04T20:21:21Z
1,381,380
<p>You can achieve this by having the class, lets call it PythonDictionary, which is returned from <code>mydict["bc"]</code> have the following members.</p> <ul> <li>A indexer property to allow for the ["de"] access</li> <li>A implicit conversion from string to PythonDictionary</li> </ul> <p>That should allow both cases to compile just fine. </p> <p>For example</p> <pre><code>public class PythonDictionary { public string this[string index] { get { ... } set { ... } } public static implicit operator PythonDictionary(string value) { ... } } public void Example() { Dictionary&lt;string, PythonDictionary&gt; map = new Dictionary&lt;string, PythonDictionary&gt;(); map["42"]["de"] = "foo"; map["42"] = "bar"; } </code></pre>
11
2009-09-04T20:26:12Z
[ "c#", "python", "syntax", "dictionary", "types" ]
Model inheritance approach with Django's ORM
1,381,423
<p>I want to store events in a web application I am fooling around with and I feel quite unsure about the pros and cons of each respective approach - using inheritance extensively or in a more modest manner.</p> <p>Example:</p> <pre><code>class Event(models.Model): moment = models.DateTimeField() class UserEvent(Event): user = models.ForeignKey(User) class Meta: abstract = True class UserRegistrationEvent(UserEvent): pass # Nothing to add really, the name of the class indicates it's type class UserCancellationEvent(UserEvent): reason = models.CharField() </code></pre> <p>It feels like I'm creating database tables like crazy. It would require alot of joins to select things out and might complicate querying. But it's design feels nice, I think.</p> <p>Would it be more reasonable to use a "flatter" model that just has more fields?</p> <pre><code>class Event(models.Model): moment = models.DateTimeField() user = models.ForeignKey(User, blank=True, null=True) type = models.CharField() # 'Registration', 'Cancellation' ... reason = models.CharField(blank=True, null=True) </code></pre> <p>Thanks for your comments on this, anyone.</p> <p>Philip</p>
3
2009-09-04T20:36:55Z
1,381,528
<p><a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">Flat is better than nested</a>. I don't see that the "deep inheritance" is really buying you anything in this case: I'd go for the flatter model as a simpler, plainer design, with likely better performance characteristics and ease of access.</p>
5
2009-09-04T21:02:05Z
[ "python", "django", "django-models", "model-inheritance" ]
Model inheritance approach with Django's ORM
1,381,423
<p>I want to store events in a web application I am fooling around with and I feel quite unsure about the pros and cons of each respective approach - using inheritance extensively or in a more modest manner.</p> <p>Example:</p> <pre><code>class Event(models.Model): moment = models.DateTimeField() class UserEvent(Event): user = models.ForeignKey(User) class Meta: abstract = True class UserRegistrationEvent(UserEvent): pass # Nothing to add really, the name of the class indicates it's type class UserCancellationEvent(UserEvent): reason = models.CharField() </code></pre> <p>It feels like I'm creating database tables like crazy. It would require alot of joins to select things out and might complicate querying. But it's design feels nice, I think.</p> <p>Would it be more reasonable to use a "flatter" model that just has more fields?</p> <pre><code>class Event(models.Model): moment = models.DateTimeField() user = models.ForeignKey(User, blank=True, null=True) type = models.CharField() # 'Registration', 'Cancellation' ... reason = models.CharField(blank=True, null=True) </code></pre> <p>Thanks for your comments on this, anyone.</p> <p>Philip</p>
3
2009-09-04T20:36:55Z
1,381,748
<p>You might want to try <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#id6" rel="nofollow">Abstract base models</a>. This implements inheritance without joins, by only creating tables for the derived classes, containing fields from both the parent and the derived model. This would allow you to keep your nested design, without the performance penalty of all those joins.</p>
0
2009-09-04T22:07:25Z
[ "python", "django", "django-models", "model-inheritance" ]
Purely functional data structures with copy-on-write?
1,381,592
<p>I want to have the advantage of functional data structures (multiple versions of data that can share structure) but be able to modify it in an imperative style. </p> <p>What I'm thinking about (and a possible use): a RPG game in which whole game history is stored (for example, to allow for travelling back in time). Using copy-on-write, I could simply clone the structure holding game state and modify it by introducing a new turn - but have access to the earlier turns (not necessarily all of them, maybe just selected snapshots of game state), without the penalty of having to copy everything every time.</p> <p><hr /></p> <p>Let's say <code>foo</code> is a map.</p> <pre><code>bar = foo.clone() </code></pre> <p>Nothing of <code>foo</code>'s structure (for example, tree) gets copied yet. However, from now on <code>bar</code> is treated as a copy and no changes are allowed to propagate back to `foo'.</p> <pre><code>baz = bar[someKey] baz.modifyInSomeWay() </code></pre> <p>Now</p> <ul> <li>a new object gets created, that is a modified copy of <code>baz</code>.</li> <li><code>bar</code> is replaced with a new map, holding new <code>baz</code> (possibly retaining some of <code>foo</code>'s structure).</li> <li><code>foo</code> is unaffected.</li> </ul> <p>But if we then do...</p> <pre><code>baz.modifyAgain() </code></pre> <p>...<code>baz</code> can be just modified, because we have a recent version of it. <code>bar</code> doesn't need to be changed.</p> <p>All this requires holding some version information about <code>foo</code> and <code>bar</code>, increasing it on <code>foo.clone()</code>, and passing it to <code>baz</code> somehow (by making it a proxy object?). </p> <p>Also, any part of structure that has been cloned becomes a 'part of history' and can't be changed anymore, which could be enforced at run-time.</p> <p><hr /></p> <p>This resembles JavaScript's prototypes a bit, but I it's more as it allows for changes to propagate upwards. I think it would be something like a version control system.</p> <ul> <li>Has this been done, and to what extent?</li> <li>Is this a good idea? If not, is there a way to save it?</li> <li>How could it be implemented? I was thinking about building it on top of some high-level GC-ed language, like Python.</li> </ul>
7
2009-09-04T21:19:28Z
1,381,664
<p><a href="http://en.wikipedia.org/wiki/Purely%5Ffunctional#Examples%5Fof%5Fpurely%5Ffunctional%5Fdata%5Fstructures">Functional ("persistent") data structures</a> are typically recursively built up out of immutable nodes (e.g. singly linked list where common suffixes are shared, search tree or heap where only the parts of the tree structure that are on the path from the root to the updated item need copying). </p> <p>Anything where the entire set has to be copied for every modification is bad. In those cases, you'd tend to overlay small "diffs" that are checked (taking extra time) with recursion to previous versions. Every so often, when the diffs become too large, you could do a deep copy/rebuild (so the amortized cost is not as bad).</p> <p>Persistent data structures can have significant overhead, but if you have very efficient allocation of small objects (JVM GC qualifies), they can be very practical - in the best case, equally as fast as the mutable equivalent, giving persistence only at the cost of the memory used - which can be much less than a full copy on every update.</p> <p>Depending on your language, you'll probably find the syntax you want difficult to achieve without operator overloading for assignment. Lvalues (mutable references) in C++ definitely require non-persistent semantics.</p>
8
2009-09-04T21:36:12Z
[ "python", "functional-programming", "immutability", "copy-on-write" ]
Purely functional data structures with copy-on-write?
1,381,592
<p>I want to have the advantage of functional data structures (multiple versions of data that can share structure) but be able to modify it in an imperative style. </p> <p>What I'm thinking about (and a possible use): a RPG game in which whole game history is stored (for example, to allow for travelling back in time). Using copy-on-write, I could simply clone the structure holding game state and modify it by introducing a new turn - but have access to the earlier turns (not necessarily all of them, maybe just selected snapshots of game state), without the penalty of having to copy everything every time.</p> <p><hr /></p> <p>Let's say <code>foo</code> is a map.</p> <pre><code>bar = foo.clone() </code></pre> <p>Nothing of <code>foo</code>'s structure (for example, tree) gets copied yet. However, from now on <code>bar</code> is treated as a copy and no changes are allowed to propagate back to `foo'.</p> <pre><code>baz = bar[someKey] baz.modifyInSomeWay() </code></pre> <p>Now</p> <ul> <li>a new object gets created, that is a modified copy of <code>baz</code>.</li> <li><code>bar</code> is replaced with a new map, holding new <code>baz</code> (possibly retaining some of <code>foo</code>'s structure).</li> <li><code>foo</code> is unaffected.</li> </ul> <p>But if we then do...</p> <pre><code>baz.modifyAgain() </code></pre> <p>...<code>baz</code> can be just modified, because we have a recent version of it. <code>bar</code> doesn't need to be changed.</p> <p>All this requires holding some version information about <code>foo</code> and <code>bar</code>, increasing it on <code>foo.clone()</code>, and passing it to <code>baz</code> somehow (by making it a proxy object?). </p> <p>Also, any part of structure that has been cloned becomes a 'part of history' and can't be changed anymore, which could be enforced at run-time.</p> <p><hr /></p> <p>This resembles JavaScript's prototypes a bit, but I it's more as it allows for changes to propagate upwards. I think it would be something like a version control system.</p> <ul> <li>Has this been done, and to what extent?</li> <li>Is this a good idea? If not, is there a way to save it?</li> <li>How could it be implemented? I was thinking about building it on top of some high-level GC-ed language, like Python.</li> </ul>
7
2009-09-04T21:19:28Z
1,382,934
<p>This sounds awfully convoluted and error prone compared to just having a fully immutable data structure and then using a wrapper which holds a reference to it and exposes an imperative interface which works by updating the wrapped version.</p> <p>e.g. in Scala</p> <pre><code>class ImmutableData{ def doStuff(blah : Blah) : ImmutableData = implementation } class MutableData(var wrapped : ImmutableData){ def doStuff(blah : Blah) : Unit = { wrapped = wrapped.doStuff(blah); } } </code></pre> <p>Sure it means you have to make two versions of the interface, but the semantics are a lot saner. </p>
0
2009-09-05T10:06:15Z
[ "python", "functional-programming", "immutability", "copy-on-write" ]
Purely functional data structures with copy-on-write?
1,381,592
<p>I want to have the advantage of functional data structures (multiple versions of data that can share structure) but be able to modify it in an imperative style. </p> <p>What I'm thinking about (and a possible use): a RPG game in which whole game history is stored (for example, to allow for travelling back in time). Using copy-on-write, I could simply clone the structure holding game state and modify it by introducing a new turn - but have access to the earlier turns (not necessarily all of them, maybe just selected snapshots of game state), without the penalty of having to copy everything every time.</p> <p><hr /></p> <p>Let's say <code>foo</code> is a map.</p> <pre><code>bar = foo.clone() </code></pre> <p>Nothing of <code>foo</code>'s structure (for example, tree) gets copied yet. However, from now on <code>bar</code> is treated as a copy and no changes are allowed to propagate back to `foo'.</p> <pre><code>baz = bar[someKey] baz.modifyInSomeWay() </code></pre> <p>Now</p> <ul> <li>a new object gets created, that is a modified copy of <code>baz</code>.</li> <li><code>bar</code> is replaced with a new map, holding new <code>baz</code> (possibly retaining some of <code>foo</code>'s structure).</li> <li><code>foo</code> is unaffected.</li> </ul> <p>But if we then do...</p> <pre><code>baz.modifyAgain() </code></pre> <p>...<code>baz</code> can be just modified, because we have a recent version of it. <code>bar</code> doesn't need to be changed.</p> <p>All this requires holding some version information about <code>foo</code> and <code>bar</code>, increasing it on <code>foo.clone()</code>, and passing it to <code>baz</code> somehow (by making it a proxy object?). </p> <p>Also, any part of structure that has been cloned becomes a 'part of history' and can't be changed anymore, which could be enforced at run-time.</p> <p><hr /></p> <p>This resembles JavaScript's prototypes a bit, but I it's more as it allows for changes to propagate upwards. I think it would be something like a version control system.</p> <ul> <li>Has this been done, and to what extent?</li> <li>Is this a good idea? If not, is there a way to save it?</li> <li>How could it be implemented? I was thinking about building it on top of some high-level GC-ed language, like Python.</li> </ul>
7
2009-09-04T21:19:28Z
37,143,788
<p><strong>1. Has this been done, and to what extent?</strong></p> <p>Yes, see for example qt5 <a href="http://doc.qt.io/qt-5/implicit-sharing.html" rel="nofollow">implicit sharing</a>.</p> <p><strong>2. Is this a good idea? If not, is there a way to save it?</strong></p> <p>Yes, it is a good idea. One of the proposed alternatives is to use a fully immutable data structure (wrapped in a imperative interface), but the problem is that even if a object is the only one to point to a data, a modification operation will create a copy of the data (there is no in place update), this is inefficient. Using the copy on write approach, a copy is made only in the first modification, subsequent modifications alters the copied data in place (if another reference to the same data wasn't created, off course).</p> <p><strong>3. How could it be implemented? I was thinking about building it on top of some high-level GC-ed language, like Python.</strong></p> <p>One way is to use reference counting, like in qt (see a description <a href="http://stackoverflow.com/a/4637973/5189607">here</a>). To implement it will requires either assignment operator overloading or a explicit method call (like <code>bar = foo.clone()</code>, but it may be fragile, what happens if someone forget to call <code>clone</code> and just do <code>bar = foo</code>?), so the counting can be kept.</p> <p>Other possibility in tho create a proxy object, like you said. See for example a <a href="https://github.com/diffoperator/pycow" rel="nofollow">pycow</a> (a python implementation).</p>
0
2016-05-10T16:08:28Z
[ "python", "functional-programming", "immutability", "copy-on-write" ]
MAC OS X Custom Application Keeping Bouncing in the Dock
1,381,739
<p>First of all, thank you for taking the time to read this. I am new to developing applications for the Mac and I am having some problems. My application works fine, and that is not the focus of my question. Rather, I have a python program which essentially does this:</p> <pre><code>for i in values: os.system(java program_and_options[i]) </code></pre> <p>However, every time my program executes the java program, a java window is created in my dock (with an annoying animation) and most importantly steals the focus of my mouse and keyboard. Then it goes away a second later, to be replaced by another Java instance. This means that my batch program cannot be used while I am interacting with my Mac, because I get a hiccup every second or more often and cannot get anything done. My problem is that the act of displaying something in the dock takes my focus, and I would like it not to. Is there a setting on OS X to never display something in the dock (such as Java or python)? </p> <p>Is there a Mac setting or term that I should use to properly describe this problem I am having? I completely lack the vocabulary to describe this problem and I hope I make sense. I appreciate any help. </p> <p>I am running Mac OS X, Version 10.5.7 with a 1.66 GHz Intel Core Due, 2 GB memory, Macintosh HD. I am running Python 2.5.1, java version "1.5.0_16" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284) Java HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing).</p> <p>Thanks again,</p> <p>-Brian J. Stinar-</p>
0
2009-09-04T20:53:48Z
1,381,740
<p>As far as I am aware there is no way to disable the annoying double Java bounce without making your Java application a first class citizen on Mac OS X (much like NetBeans, or Eclipse). As for making certain programs not show in the dock, there are .plist modifications that can be made so that the program does not show up in the dock. See <a href="http://www.macosxhints.com/article.php?story=20010701191518268" rel="nofollow">http://www.macosxhints.com/article.php?story=20010701191518268</a></p>
0
2009-09-04T21:46:16Z
[ "java", "python", "osx" ]
MAC OS X Custom Application Keeping Bouncing in the Dock
1,381,739
<p>First of all, thank you for taking the time to read this. I am new to developing applications for the Mac and I am having some problems. My application works fine, and that is not the focus of my question. Rather, I have a python program which essentially does this:</p> <pre><code>for i in values: os.system(java program_and_options[i]) </code></pre> <p>However, every time my program executes the java program, a java window is created in my dock (with an annoying animation) and most importantly steals the focus of my mouse and keyboard. Then it goes away a second later, to be replaced by another Java instance. This means that my batch program cannot be used while I am interacting with my Mac, because I get a hiccup every second or more often and cannot get anything done. My problem is that the act of displaying something in the dock takes my focus, and I would like it not to. Is there a setting on OS X to never display something in the dock (such as Java or python)? </p> <p>Is there a Mac setting or term that I should use to properly describe this problem I am having? I completely lack the vocabulary to describe this problem and I hope I make sense. I appreciate any help. </p> <p>I am running Mac OS X, Version 10.5.7 with a 1.66 GHz Intel Core Due, 2 GB memory, Macintosh HD. I am running Python 2.5.1, java version "1.5.0_16" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284) Java HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing).</p> <p>Thanks again,</p> <p>-Brian J. Stinar-</p>
0
2009-09-04T20:53:48Z
1,382,272
<p>Does running Java with headless mode = true fix it?</p> <p><a href="http://zzamboni.org/brt/2007/12/07/disable-dock-icon-for-java-programs-in-mac-osx-howto/" rel="nofollow">http://zzamboni.org/brt/2007/12/07/disable-dock-icon-for-java-programs-in-mac-osx-howto/</a></p>
1
2009-09-05T02:20:54Z
[ "java", "python", "osx" ]
MAC OS X Custom Application Keeping Bouncing in the Dock
1,381,739
<p>First of all, thank you for taking the time to read this. I am new to developing applications for the Mac and I am having some problems. My application works fine, and that is not the focus of my question. Rather, I have a python program which essentially does this:</p> <pre><code>for i in values: os.system(java program_and_options[i]) </code></pre> <p>However, every time my program executes the java program, a java window is created in my dock (with an annoying animation) and most importantly steals the focus of my mouse and keyboard. Then it goes away a second later, to be replaced by another Java instance. This means that my batch program cannot be used while I am interacting with my Mac, because I get a hiccup every second or more often and cannot get anything done. My problem is that the act of displaying something in the dock takes my focus, and I would like it not to. Is there a setting on OS X to never display something in the dock (such as Java or python)? </p> <p>Is there a Mac setting or term that I should use to properly describe this problem I am having? I completely lack the vocabulary to describe this problem and I hope I make sense. I appreciate any help. </p> <p>I am running Mac OS X, Version 10.5.7 with a 1.66 GHz Intel Core Due, 2 GB memory, Macintosh HD. I am running Python 2.5.1, java version "1.5.0_16" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284) Java HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing).</p> <p>Thanks again,</p> <p>-Brian J. Stinar-</p>
0
2009-09-04T20:53:48Z
1,382,398
<p>It's certainly possible to write a Java application which doesn't display in the Dock... in fact, it's the default. If your application <em>is</em> showing up, it must be doing something which triggers window server access -- your best bet is to try and figure out what that is.</p>
0
2009-09-05T03:46:53Z
[ "java", "python", "osx" ]
Converting latex code to Images (or other displayble format) with Python
1,381,741
<p>I have a function I am consuming that returns a string of latex code. I need to generate an image from this. Most of the methods I have seen for doing so suggest calling an external application via say the <em>subprocess</em> module which will generate the image for me. </p> <p>However, management is not keen on this as it will require external users to install additional software in addition to our own which, with our user base, is not something we can assume to be a simple task.</p> <p>So are there any python libraries that will accomplish the task of taking latex into a format (such as an image file) which is displayable in a GUI?</p>
10
2009-09-04T22:04:56Z
1,381,791
<p>You're going to need to use LaTeX to process to string. The process of rendering LaTex/TeX is very involved (it generally takes a 100+MB package to do the work), you're just not going to be able toss in a little python module to get the work done.</p>
0
2009-09-04T22:25:54Z
[ "python", "latex" ]
Converting latex code to Images (or other displayble format) with Python
1,381,741
<p>I have a function I am consuming that returns a string of latex code. I need to generate an image from this. Most of the methods I have seen for doing so suggest calling an external application via say the <em>subprocess</em> module which will generate the image for me. </p> <p>However, management is not keen on this as it will require external users to install additional software in addition to our own which, with our user base, is not something we can assume to be a simple task.</p> <p>So are there any python libraries that will accomplish the task of taking latex into a format (such as an image file) which is displayable in a GUI?</p>
10
2009-09-04T22:04:56Z
1,381,806
<p>Maybe you could use an online service such as this one: <a href="http://www.codecogs.com/components/equationeditor/equationeditor.php" rel="nofollow">http://www.codecogs.com/components/equationeditor/equationeditor.php</a>.</p> <hr> <p>Following Joel A. Christophel's suggestion, here's a working similar website: <a href="http://arachnoid.com/latex/" rel="nofollow">http://arachnoid.com/latex/</a></p>
0
2009-09-04T22:34:23Z
[ "python", "latex" ]
Converting latex code to Images (or other displayble format) with Python
1,381,741
<p>I have a function I am consuming that returns a string of latex code. I need to generate an image from this. Most of the methods I have seen for doing so suggest calling an external application via say the <em>subprocess</em> module which will generate the image for me. </p> <p>However, management is not keen on this as it will require external users to install additional software in addition to our own which, with our user base, is not something we can assume to be a simple task.</p> <p>So are there any python libraries that will accomplish the task of taking latex into a format (such as an image file) which is displayable in a GUI?</p>
10
2009-09-04T22:04:56Z
1,382,067
<p>If it is just math equations that you need, you will probably have better luck finding a mathml renderer in python. This <a href="http://www.w3.org/Math/Software/mathml%5Fsoftware%5Fcat%5Fconverters.html#Itranslator%5Ffrom%5Ftex%5Flatex%5Fto%5Fmathml" rel="nofollow">page</a> might provide some clues, including some latex-mathml translators.</p>
0
2009-09-05T00:31:31Z
[ "python", "latex" ]
Converting latex code to Images (or other displayble format) with Python
1,381,741
<p>I have a function I am consuming that returns a string of latex code. I need to generate an image from this. Most of the methods I have seen for doing so suggest calling an external application via say the <em>subprocess</em> module which will generate the image for me. </p> <p>However, management is not keen on this as it will require external users to install additional software in addition to our own which, with our user base, is not something we can assume to be a simple task.</p> <p>So are there any python libraries that will accomplish the task of taking latex into a format (such as an image file) which is displayable in a GUI?</p>
10
2009-09-04T22:04:56Z
1,382,986
<p>Take a look at <a href="http://code.google.com/p/mathtex/" rel="nofollow">mathtex</a>.</p>
4
2009-09-05T10:37:59Z
[ "python", "latex" ]
Converting latex code to Images (or other displayble format) with Python
1,381,741
<p>I have a function I am consuming that returns a string of latex code. I need to generate an image from this. Most of the methods I have seen for doing so suggest calling an external application via say the <em>subprocess</em> module which will generate the image for me. </p> <p>However, management is not keen on this as it will require external users to install additional software in addition to our own which, with our user base, is not something we can assume to be a simple task.</p> <p>So are there any python libraries that will accomplish the task of taking latex into a format (such as an image file) which is displayable in a GUI?</p>
10
2009-09-04T22:04:56Z
29,922,912
<p>this answer might not have been available at the time when the question was asked, but i will add it for those seeking a solution as of 2015.</p> <p>you can use <code>matplotlib.pyplot</code> to render an equation in a graph with axes, and then remove the axes manually. you can also generate the latex with <code>sympy</code>:</p> <pre><code>#!/usr/bin/env python2.7 import matplotlib.pyplot as plt import sympy x = sympy.symbols('x') y = 1 + sympy.sin(sympy.sqrt(x**2 + 20)) lat = sympy.latex(y) #add text plt.text(0, 0.6, r"$%s$" % lat, fontsize = 50) #hide axes fig = plt.gca() fig.axes.get_xaxis().set_visible(False) fig.axes.get_yaxis().set_visible(False) plt.draw() #or savefig plt.show() </code></pre> <p>tested with sympy <code>0.7.6</code> and matplotlib <code>1.4.3</code></p>
6
2015-04-28T15:01:54Z
[ "python", "latex" ]
Converting latex code to Images (or other displayble format) with Python
1,381,741
<p>I have a function I am consuming that returns a string of latex code. I need to generate an image from this. Most of the methods I have seen for doing so suggest calling an external application via say the <em>subprocess</em> module which will generate the image for me. </p> <p>However, management is not keen on this as it will require external users to install additional software in addition to our own which, with our user base, is not something we can assume to be a simple task.</p> <p>So are there any python libraries that will accomplish the task of taking latex into a format (such as an image file) which is displayable in a GUI?</p>
10
2009-09-04T22:04:56Z
36,249,956
<p>SymPy has a builtin preview function that does this.</p> <pre><code>expr = sin(sqrt(x**2 + 20)) + 1 preview(expr, viewer='file', filename='output.png') </code></pre> <p>generates </p> <p><a href="http://i.stack.imgur.com/Js3gz.png" rel="nofollow"><img src="http://i.stack.imgur.com/Js3gz.png" alt="enter image description here"></a></p> <p>There are <a href="http://docs.sympy.org/latest/modules/printing.html#sympy.printing.preview.preview" rel="nofollow">lots of options</a> to <code>preview</code> to change the format of the output (for instance, if you don't like the Euler font you can set <code>euler=False</code>). </p> <p><code>preview</code> also accepts a LaTeX string instead of a SymPy expression if you have that</p> <pre><code>preview(r'$$\int_0^1 e^x\,dx$$', viewer='file', filename='test.png', euler=False) </code></pre> <p><a href="http://i.stack.imgur.com/RQYgf.png" rel="nofollow"><img src="http://i.stack.imgur.com/RQYgf.png" alt="enter image description here"></a></p>
3
2016-03-27T16:46:30Z
[ "python", "latex" ]
inserting a tuple into a mysql db
1,381,840
<p>can anyone show me the syntax for inserting a python tuple/list into a mysql database? i also need to know if it is possible for user to pass certain rows without inserting anything... for example: a function is returning this tuple:</p> <pre><code>return job(jcardnum, jreg, jcarddate, jcardtime, jcardserve, jdeliver) </code></pre> <p>suppose the user didnt enter anything in <code>jreg</code> would python itself enter null in to the related row in the DB or would i run in to trouble?</p>
0
2009-09-04T22:42:57Z
1,382,194
<p>As a comment says, the <code>job(...)</code> part is a function (or class) call -- whatever is returned from that call also gets returned from this <code>return</code> statement.</p> <p>Let's assume it's a tuple. What if "the user didn't enter anything in <code>jreg</code>" -- well then, depending on a lot of code you're not showing us, that could be a runtime error (name <code>jreg</code> being undefined), an empty string or other initial default value never altered, or <code>None</code>; in the latter case that would indeed eventually become a <code>NULL</code> in the DB (if acceptable per the DB schema, of course -- otherwise, the DB would reject the insert attempt).</p> <p>Once you DO finally have a correct and proper tuple <code>T</code> that you want to insert,</p> <pre><code>`mycursor.execute('INSERT INTO sometable VALUES(?, ?, ?, ?, ?, ?)', T) </code></pre> <p>is going to be close to the syntax you want -- if <code>T</code> has six items (and <code>sometable</code> has six columns, of course). Each <code>?</code> is a placeholder and gets replaced with the corresponding item. <code>mycursor</code> will need to be an instance of Cursor, presumably obtained by some earlier call to <code>myconnection.cursor</code> where <code>myconnection</code> is an instance of Connection, built by the proper call to <code>connect</code> from the DB API module you're using with the right argumentrs.</p> <p>If you show us about 100 times more code and DB schemas and tell us exactly WHAT you're trying to accomplish, we, collectively speaking, could no doubt be MUCH more useful and specific -- but based on the sub-epsilon amount of info you supply that's about as much as we, collectively speaking, can offer;-).</p>
6
2009-09-05T01:49:55Z
[ "python", "mysql" ]
inserting a tuple into a mysql db
1,381,840
<p>can anyone show me the syntax for inserting a python tuple/list into a mysql database? i also need to know if it is possible for user to pass certain rows without inserting anything... for example: a function is returning this tuple:</p> <pre><code>return job(jcardnum, jreg, jcarddate, jcardtime, jcardserve, jdeliver) </code></pre> <p>suppose the user didnt enter anything in <code>jreg</code> would python itself enter null in to the related row in the DB or would i run in to trouble?</p>
0
2009-09-04T22:42:57Z
1,383,289
<p>Maybe, cursor.executemany is what you need?</p> <blockquote> <p>suppose the user didnt enter anything in jreg would python itself enter null in to the related row in the DB or would i run in to trouble?</p> </blockquote> <p>I think you should just try, you probably see the warning or error if NULL is not allowed.</p>
0
2009-09-05T13:02:55Z
[ "python", "mysql" ]
Writing Interpreters in Python. Is isinstance considered harmful?
1,381,845
<p>I'm porting over the interpreter for a domain specific language I created from Scala to Python. In the process I tried to find a way that way pythonic to emulate the case class feature of Scala that I used extensively. In the end I resorted to using isinstance, but was left feeling that I was perhaps missing something.</p> <p>Articles such as <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">this one</a> attacking the use of isinstance made me wonder whether there was a better way to solve my problem that doesn't involve some fundamental rewrite.</p> <p>I've built up a number of Python classes that each represent a different type of abstract syntax tree node, such as For, While, Break, Return, Statement etc</p> <p>Scala allows for the handling of operator evaluation like this:</p> <pre><code>case EOp("==",EInt(l),EInt(r)) =&gt; EBool(l==r) case EOp("==",EBool(l),EBool(r)) =&gt; EBool(l==r) </code></pre> <p>So far for the port to Python I've made extensive use of elif blocks and isinstance calls to achieve the same effect, much more verbose and un-pythonic. Is there a better way?</p>
4
2009-09-04T22:45:13Z
1,381,883
<p>The article does not attack <code>isinstance</code>. It attacks the idea of making your code test for specific classes.</p> <p>And yes, there is a better way. Or several. You can for example make the handling of a type into a function, and then find the correct function by looking up per type. Like this:</p> <pre><code>def int_function(value): # Do what you mean to do here def str_function(value): # Do what you mean to do here type_function = {int: int_function, str: str_function, etc, etc} def handle_value(value): function = type_function[type(value)] result = function(value) print "Oh, lovely", result </code></pre> <p>If you don't want to do this registry yourself, you can look at the Zope Component Architecture, which handles this through interfaces and adapters, and it really cool. But that's probably overkill.</p> <p>Even better is if you can somehow avoid doing any type of type checking, but that may be tricky.</p>
1
2009-09-04T23:01:54Z
[ "python", "scala", "language-design", "interpreter" ]
Writing Interpreters in Python. Is isinstance considered harmful?
1,381,845
<p>I'm porting over the interpreter for a domain specific language I created from Scala to Python. In the process I tried to find a way that way pythonic to emulate the case class feature of Scala that I used extensively. In the end I resorted to using isinstance, but was left feeling that I was perhaps missing something.</p> <p>Articles such as <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">this one</a> attacking the use of isinstance made me wonder whether there was a better way to solve my problem that doesn't involve some fundamental rewrite.</p> <p>I've built up a number of Python classes that each represent a different type of abstract syntax tree node, such as For, While, Break, Return, Statement etc</p> <p>Scala allows for the handling of operator evaluation like this:</p> <pre><code>case EOp("==",EInt(l),EInt(r)) =&gt; EBool(l==r) case EOp("==",EBool(l),EBool(r)) =&gt; EBool(l==r) </code></pre> <p>So far for the port to Python I've made extensive use of elif blocks and isinstance calls to achieve the same effect, much more verbose and un-pythonic. Is there a better way?</p>
4
2009-09-04T22:45:13Z
1,381,936
<p>Yes.</p> <p>Instead of instance, just use <a href="http://en.wikipedia.org/wiki/Polymorphism%5Fin%5Fobject-oriented%5Fprogramming" rel="nofollow">Polymorphism</a>. It's simpler.</p> <pre><code>class Node( object ): def eval( self, context ): raise NotImplementedError class Add( object ): def eval( self, context ): return self.arg1.eval( context ) + self.arg2.eval( context ) </code></pre> <p>This kind of this is very simple, and never requires <code>isinstance</code>.</p> <p><hr /></p> <p>What about something like this where there is coercion required?</p> <pre><code>Add( Double(this), Integer(that) ) </code></pre> <p>This is still a polymorphism issue.</p> <pre><code>class MyType( object ): rank= None def coerce( self, another ): return NotImplemented class Double( object ): rank = 2 def coerce( self, another ): return another.toDouble() def toDouble( self ): return self def toInteger( self ): return int(self) class Integer( object ): rank = 1 def coerce( self, another ): return another.toInteger() def toDouble( self ): return float(self) def toInteger( self ): return self class Operation( Node ): def conform( self, another ): if self.rank &gt; another.rank: this, that = self, self.coerce( another ) else: this, that = another.coerce( self ), another return this, that def add( self, another ): this, that = self.coerce( another ) return this + that </code></pre>
2
2009-09-04T23:22:44Z
[ "python", "scala", "language-design", "interpreter" ]
Writing Interpreters in Python. Is isinstance considered harmful?
1,381,845
<p>I'm porting over the interpreter for a domain specific language I created from Scala to Python. In the process I tried to find a way that way pythonic to emulate the case class feature of Scala that I used extensively. In the end I resorted to using isinstance, but was left feeling that I was perhaps missing something.</p> <p>Articles such as <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">this one</a> attacking the use of isinstance made me wonder whether there was a better way to solve my problem that doesn't involve some fundamental rewrite.</p> <p>I've built up a number of Python classes that each represent a different type of abstract syntax tree node, such as For, While, Break, Return, Statement etc</p> <p>Scala allows for the handling of operator evaluation like this:</p> <pre><code>case EOp("==",EInt(l),EInt(r)) =&gt; EBool(l==r) case EOp("==",EBool(l),EBool(r)) =&gt; EBool(l==r) </code></pre> <p>So far for the port to Python I've made extensive use of elif blocks and isinstance calls to achieve the same effect, much more verbose and un-pythonic. Is there a better way?</p>
4
2009-09-04T22:45:13Z
1,382,013
<p>In a DSL I wrote using Python 3, I used the Composite design pattern so the nodes were all polymorphic in their use, as S. Lott is recommending.</p> <p>But, when I was reading in the input to create those nodes in the first place, I did use isinstance checks a lot (against abstract base classes like collections.Iterable, etc., which Python 3 provides, and which are in 2.6 as well I believe), as well as checks for hasattr <code>'__call__'</code> since callables were allowed in my input. This was the cleanest way I found to do it (particulary with recursion involved), rather than just trying operations against input and catching exceptions, which is the alternative that comes to mind. I was raising custom exceptions myself when the input was invalid to give as much precise failure information as possible.</p> <p>Using isinstance for such tests is more general than using type(), since isinstance will catch subclasses - and if you can test against the abstract base classes, that is all the better. See <a href="http://www.python.org/dev/peps/pep-3119/" rel="nofollow">http://www.python.org/dev/peps/pep-3119/</a> for info on the abstract base classes.</p>
0
2009-09-05T00:04:16Z
[ "python", "scala", "language-design", "interpreter" ]
Writing Interpreters in Python. Is isinstance considered harmful?
1,381,845
<p>I'm porting over the interpreter for a domain specific language I created from Scala to Python. In the process I tried to find a way that way pythonic to emulate the case class feature of Scala that I used extensively. In the end I resorted to using isinstance, but was left feeling that I was perhaps missing something.</p> <p>Articles such as <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">this one</a> attacking the use of isinstance made me wonder whether there was a better way to solve my problem that doesn't involve some fundamental rewrite.</p> <p>I've built up a number of Python classes that each represent a different type of abstract syntax tree node, such as For, While, Break, Return, Statement etc</p> <p>Scala allows for the handling of operator evaluation like this:</p> <pre><code>case EOp("==",EInt(l),EInt(r)) =&gt; EBool(l==r) case EOp("==",EBool(l),EBool(r)) =&gt; EBool(l==r) </code></pre> <p>So far for the port to Python I've made extensive use of elif blocks and isinstance calls to achieve the same effect, much more verbose and un-pythonic. Is there a better way?</p>
4
2009-09-04T22:45:13Z
1,382,058
<p>If you need Polymorphism on arguments (in addition to the receiver), for example to handle type conversions with binary operators as suggested by your example, you can use the following trick:</p> <pre><code>class EValue(object): def __init__(self, v): self.value = v def __str__(self): return str(self.value) def opequal(self, r): r.opequal_value(self) def opequal_int(self, l): print "(int)", l, "==", "(value)", self def opequal_bool(self, l): print "(bool)", l, "==", "(value)", self def opequal_value(self, l): print "(value)", l, "==", "(value)", self class EInt(EValue): def opequal(self, r): r.opequal_int(self) def opequal_int(self, l): print "(int)", l, "==", "(int)", self def opequal_bool(self, l): print "(bool)", l, "==", "(int)", self def opequal_value(self, l): print "(value)", l, "==", "(int)", self class EBool(EValue): def opequal(self, r): r.opequal_bool(self) def opequal_int(self, l): print "(int)", l, "==", "(bool)", self def opequal_bool(self, l): print "(bool)", l, "==", "(bool)", self def opequal_value(self, l): print "(value)", l, "==", "(bool)", self if __name__ == "__main__": v1 = EBool("true") v2 = EInt(5) v1.opequal(v2) </code></pre>
-1
2009-09-05T00:27:57Z
[ "python", "scala", "language-design", "interpreter" ]
Writing Interpreters in Python. Is isinstance considered harmful?
1,381,845
<p>I'm porting over the interpreter for a domain specific language I created from Scala to Python. In the process I tried to find a way that way pythonic to emulate the case class feature of Scala that I used extensively. In the end I resorted to using isinstance, but was left feeling that I was perhaps missing something.</p> <p>Articles such as <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">this one</a> attacking the use of isinstance made me wonder whether there was a better way to solve my problem that doesn't involve some fundamental rewrite.</p> <p>I've built up a number of Python classes that each represent a different type of abstract syntax tree node, such as For, While, Break, Return, Statement etc</p> <p>Scala allows for the handling of operator evaluation like this:</p> <pre><code>case EOp("==",EInt(l),EInt(r)) =&gt; EBool(l==r) case EOp("==",EBool(l),EBool(r)) =&gt; EBool(l==r) </code></pre> <p>So far for the port to Python I've made extensive use of elif blocks and isinstance calls to achieve the same effect, much more verbose and un-pythonic. Is there a better way?</p>
4
2009-09-04T22:45:13Z
1,383,559
<p>In this particular case, what you seem to be implementing is an operator overloading system that uses the types of the objects as the selection mechanism for the operator you intend to call. Your node types happen to fairly directly correspond to your language's types, but in reality you're writing an interpreter. The type of the node is just a piece of data.</p> <p>I don't know if people can add their own types to your domain specific language. But I would recommend a table driven design regardless.</p> <p>Make a table of data containing (binary_operator, type1, type2, result_type, evalfunc). Search through that table for matches using isinstance and have some criteria for preferring some matches over others. It may be possible to use a somewhat more sophisticated data structure than a table to make searching faster, but right now you're basically using long lists of ifelse statements to do a linear search anyway, so I'm betting a plain old table will be slightly faster than what you're doing now.</p> <p>I do not consider isinstance to be the wrong choice here largely because the type is just a piece of data your interpreter is working with to make a decision. Double dispatch and other techniques of that ilk are just going to obscure the real meat of what your program is doing.</p> <p>One of the neat things in Python is that since operator functions and types are all first class objects, you can just stuff them in the table (or whatever data structure you choose) directly.</p>
0
2009-09-05T15:13:07Z
[ "python", "scala", "language-design", "interpreter" ]
Writing Interpreters in Python. Is isinstance considered harmful?
1,381,845
<p>I'm porting over the interpreter for a domain specific language I created from Scala to Python. In the process I tried to find a way that way pythonic to emulate the case class feature of Scala that I used extensively. In the end I resorted to using isinstance, but was left feeling that I was perhaps missing something.</p> <p>Articles such as <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">this one</a> attacking the use of isinstance made me wonder whether there was a better way to solve my problem that doesn't involve some fundamental rewrite.</p> <p>I've built up a number of Python classes that each represent a different type of abstract syntax tree node, such as For, While, Break, Return, Statement etc</p> <p>Scala allows for the handling of operator evaluation like this:</p> <pre><code>case EOp("==",EInt(l),EInt(r)) =&gt; EBool(l==r) case EOp("==",EBool(l),EBool(r)) =&gt; EBool(l==r) </code></pre> <p>So far for the port to Python I've made extensive use of elif blocks and isinstance calls to achieve the same effect, much more verbose and un-pythonic. Is there a better way?</p>
4
2009-09-04T22:45:13Z
1,384,643
<p>There's a rule of thumb in python, if you find yourself writing a large block of if/elif statements, with similar conditions (a bunch of isinstance(...) for example) then you're probably solving the problem the wrong way.</p> <p>Better ways involve using classes and polymorphism, visitor pattern, dict lookup, etc. In your case making an Operators class with overloads for different types could work (as noted above), so could a dict with (type, operator) items.</p>
2
2009-09-06T01:15:23Z
[ "python", "scala", "language-design", "interpreter" ]
Writing Interpreters in Python. Is isinstance considered harmful?
1,381,845
<p>I'm porting over the interpreter for a domain specific language I created from Scala to Python. In the process I tried to find a way that way pythonic to emulate the case class feature of Scala that I used extensively. In the end I resorted to using isinstance, but was left feeling that I was perhaps missing something.</p> <p>Articles such as <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">this one</a> attacking the use of isinstance made me wonder whether there was a better way to solve my problem that doesn't involve some fundamental rewrite.</p> <p>I've built up a number of Python classes that each represent a different type of abstract syntax tree node, such as For, While, Break, Return, Statement etc</p> <p>Scala allows for the handling of operator evaluation like this:</p> <pre><code>case EOp("==",EInt(l),EInt(r)) =&gt; EBool(l==r) case EOp("==",EBool(l),EBool(r)) =&gt; EBool(l==r) </code></pre> <p>So far for the port to Python I've made extensive use of elif blocks and isinstance calls to achieve the same effect, much more verbose and un-pythonic. Is there a better way?</p>
4
2009-09-04T22:45:13Z
1,390,006
<p><strong>Summary</strong>: This is a common way to write compilers, and its just fine here.</p> <p>A very common way to handle this in other languages is by "pattern matching", which is exactly what you've described. I expect that's the name for that <code>case</code> statement in Scala. Its a very common idiom for writing programming language implementations and tools: compilers, interpreters etc. Why is it so good? Because the implementation is completely separated from the data (which is often bad, but generally desirable in compilers).</p> <p>The problem then is that this common idiom for programming language implementation is an anti-pattern in Python. Uh oh. As you can probably tell, this is more a political issue than a language issue. If other Pythonistas saw the code they would scream; if other language implementers saw it, they would understand it immediately.</p> <p>The reason this is an anti-pattern in Python is because Python encourages duck-typed interfaces: you shouldn't have behaviour based on type, but rather they should be defined by the methods that an object has available at run-time. <a href="http://stackoverflow.com/questions/1381845/writing-interpreters-in-python-is-isinstance-considered-harmful/1381936#1381936">S. Lott's answer</a> works fine if you want it to be idiomatic Python, but it adds little.</p> <p>I suspect that your design isn't really duck-typed - its a compiler after all, and classes defined using a name, with a static structure, are pretty common. If you prefer, you could think of your objects as having a "type" field, and <code>isinstance</code> is used to pattern-match based on that type. </p> <p><strong>Addenum:</strong></p> <p>Pattern-matching is probably the number one reason that people love writing compilers etc in functional languages.</p>
2
2009-09-07T16:04:00Z
[ "python", "scala", "language-design", "interpreter" ]
"WindowsError: exception: access violation..." - ctypes question
1,382,076
<p>Howdy all - Here is the prototype for a C function that resides in a DLL:</p> <pre><code>extern "C" void__stdcall__declspec(dllexport) ReturnPulse(double*,double*,double*,double*,double*); </code></pre> <p>In another thread, I asked about how to properly create and send the necessary arguments to this function.</p> <p>Here is the thread: <a href="http://stackoverflow.com/questions/1381016/how-do-i-wrap-this-c-function-with-multiple-arguments-with-ctypes">http://stackoverflow.com/questions/1381016/how-do-i-wrap-this-c-function-with-multiple-arguments-with-ctypes</a></p> <p>So I have used the good information in the thread above, but now I am getting this error: WindowsError: exception: access violation writing 0x00001001</p> <p>I am unsure as to how to proceed. I'm on Windows XP - if I log into the administrator account, would that fix the problem? Or is this a problem with Python's memory objects being immutable?</p> <p>Thanks all!</p> <p><strong>Edited with relevant Python:</strong></p> <pre><code>FROGPCGPMonitorDLL = windll.LoadLibrary('C:\Program Files\MesaPhotonics\VideoFROG 7.0\PCGPMonitor.dll') #Function argument:double* pulse sizePULSE = 2 ##Manual is super unclear here pulse = c_double * sizePULSE ptrpulse = pulse() #Function argument:double* tdl sizeTRACE = FROGPCGPMonitorDLL.GetSize() if sizeTRACE == 0 : sizeTRACE = 1 #Manually set size to 1 for testing purposes print "Size of FROG trace is zero. Probably not right." tdl = c_double*sizeTRACE ptrtdl = tdl() #Function argument:double* tdP sizeTRACE = FROGPCGPMonitorDLL.GetSize() if sizeTRACE==0: sizeTRACE=1 print "Size of FROG trace is zero. Probably not right." tdP = c_double*sizeTRACE ptrtdP = tdP() #Function Argument:double* fdl sizeTRACE = FROGPCGPMonitorDLL.GetSize() if sizeTRACE==0: sizeTRACE=1 print "Size of FROG trace is zero. Probably not right." fdl = c_double*sizeTRACE ptrfdl = fdl() #Function Argument: double* fdP sizeTRACE = FROGPCGPMonitorDLL.GetSize() if sizeTRACE==0: sizeTRACE=1 print "Size of FROG trace is zero. Probably not right." fdP = c_double*sizeTRACE ptrfdP = fdP() FROGPCGPMonitorDLL.ReturnPulse(ptrpulse, ptrtdl, ptrtdP,ptrfdl,ptrfdP) </code></pre> <p>Edited to add some relevant code! I'm just writing a simple script to get each of the device's functions working first. The variable sizeTRACE can be reused, I know, but its just test code right now and the device isn't hooked up, so GetSize() is returning zero. Multiplying by zero would kill my buzz, so I'm forcing it to 1 for now. If this isn't clear, I apologize and will try to edit this post.</p> <p>Second edit: It was suggested to plug in the device and see if that helped. I just plugged in the FROG, but I'm still getting the same error. Very strange, and I'm rather clueless. In any event, thanks again all!</p>
3
2009-09-05T00:35:26Z
1,403,195
<p>The error you're getting is not related to Administrative rights. The problem is you're using C and inadvertently performing illegal operations (the kind of operations that if went unchecked would probably crash your system).</p> <p>The error you get indicates that your program is trying to write to memory address 1001, but isn't supposed to be writing to that memory address.</p> <p>This could happen for any number of reasons.</p> <p>One possible reason is that the double* you're passing to ReturnPulse aren't as big as ReturnPulse expects them to be. You probably need to at least get GetSize to work properly... you might be able to work around it by just allocating a very large array instead of calling GetSize. i.e.</p> <pre><code>ptrfdP = (c_double*100000)() </code></pre> <p>That will allocate 100,000 doubles, which may be more appropriate for capturing a digital Pulse.</p> <p>The other issue is that the type conversion may not be happening as expected.</p> <p>You might have better luck if ctypes knows that ReturnPulse takes five double pointers. i.e.</p> <pre><code># sometime before calling ReturnPulse FROGPCGPMonitorDLL.ReturnPulse.argtypes = [POINTER(c_double), POINTER(c_double), POINTER(c_double), POINTER(c_double), POINTER(c_double)] </code></pre> <p>If neither of these techniques works, send the usage documentation on ReturnPulse, which should help us recognize the intended use.</p> <p>Or better yet, send sample code that's supposed to work in C and I'll translate that to the equivalent implementation in ctypes.</p> <p>Edit: adding example implementation of ReturnPulse and ctypes usage.</p> <p>I have implemented something like what I expect ReturnPulse to be doing in a C DLL:</p> <pre><code>void ReturnPulse(double *a, double*b,double*c,double*d,double*e) { // write some values to the memory pointed-to by a-e // a-e should have enough memory allocated for the loop for(int i = 0; i &lt; 20; i++) { a[i] = 1.0*i; b[i] = 3.0*i; c[i] = 5.0*i; d[i] = 7.0*i; e[i] = 13.0*i; } } </code></pre> <p>I compile this into a DLL (which I call examlib), and then call it using ctypes with the following code:</p> <pre><code>LP_c_double = ctypes.POINTER(ctypes.c_double) examlib.ReturnPulse.argtypes = [LP_c_double, LP_c_double, LP_c_double, LP_c_double, LP_c_double, ] a = (ctypes.c_double*20)() b = (ctypes.c_double*20)() c = (ctypes.c_double*20)() d = (ctypes.c_double*20)() e = (ctypes.c_double*20)() examlib.ReturnPulse(a,b,c,d,e) print 'values are' for array in (a,b,c,d,e): print '\t'.join(map(str, array[:5])) </code></pre> <p>The resulting output is</p> <pre><code>values are 0.0 1.0 2.0 3.0 4.0 0.0 3.0 6.0 9.0 12.0 0.0 5.0 10.0 15.0 20.0 0.0 7.0 14.0 21.0 28.0 0.0 13.0 26.0 39.0 52.0 </code></pre> <p>Indeed, even without setting ReturnPulse.argtypes, the code runs without errors.</p>
11
2009-09-10T03:18:18Z
[ "python", "ctypes", "access-violation", "windowserror" ]
"WindowsError: exception: access violation..." - ctypes question
1,382,076
<p>Howdy all - Here is the prototype for a C function that resides in a DLL:</p> <pre><code>extern "C" void__stdcall__declspec(dllexport) ReturnPulse(double*,double*,double*,double*,double*); </code></pre> <p>In another thread, I asked about how to properly create and send the necessary arguments to this function.</p> <p>Here is the thread: <a href="http://stackoverflow.com/questions/1381016/how-do-i-wrap-this-c-function-with-multiple-arguments-with-ctypes">http://stackoverflow.com/questions/1381016/how-do-i-wrap-this-c-function-with-multiple-arguments-with-ctypes</a></p> <p>So I have used the good information in the thread above, but now I am getting this error: WindowsError: exception: access violation writing 0x00001001</p> <p>I am unsure as to how to proceed. I'm on Windows XP - if I log into the administrator account, would that fix the problem? Or is this a problem with Python's memory objects being immutable?</p> <p>Thanks all!</p> <p><strong>Edited with relevant Python:</strong></p> <pre><code>FROGPCGPMonitorDLL = windll.LoadLibrary('C:\Program Files\MesaPhotonics\VideoFROG 7.0\PCGPMonitor.dll') #Function argument:double* pulse sizePULSE = 2 ##Manual is super unclear here pulse = c_double * sizePULSE ptrpulse = pulse() #Function argument:double* tdl sizeTRACE = FROGPCGPMonitorDLL.GetSize() if sizeTRACE == 0 : sizeTRACE = 1 #Manually set size to 1 for testing purposes print "Size of FROG trace is zero. Probably not right." tdl = c_double*sizeTRACE ptrtdl = tdl() #Function argument:double* tdP sizeTRACE = FROGPCGPMonitorDLL.GetSize() if sizeTRACE==0: sizeTRACE=1 print "Size of FROG trace is zero. Probably not right." tdP = c_double*sizeTRACE ptrtdP = tdP() #Function Argument:double* fdl sizeTRACE = FROGPCGPMonitorDLL.GetSize() if sizeTRACE==0: sizeTRACE=1 print "Size of FROG trace is zero. Probably not right." fdl = c_double*sizeTRACE ptrfdl = fdl() #Function Argument: double* fdP sizeTRACE = FROGPCGPMonitorDLL.GetSize() if sizeTRACE==0: sizeTRACE=1 print "Size of FROG trace is zero. Probably not right." fdP = c_double*sizeTRACE ptrfdP = fdP() FROGPCGPMonitorDLL.ReturnPulse(ptrpulse, ptrtdl, ptrtdP,ptrfdl,ptrfdP) </code></pre> <p>Edited to add some relevant code! I'm just writing a simple script to get each of the device's functions working first. The variable sizeTRACE can be reused, I know, but its just test code right now and the device isn't hooked up, so GetSize() is returning zero. Multiplying by zero would kill my buzz, so I'm forcing it to 1 for now. If this isn't clear, I apologize and will try to edit this post.</p> <p>Second edit: It was suggested to plug in the device and see if that helped. I just plugged in the FROG, but I'm still getting the same error. Very strange, and I'm rather clueless. In any event, thanks again all!</p>
3
2009-09-05T00:35:26Z
2,094,029
<p>ptrpulse and friends are python identifiers that point to various ctypes objects (I guess they are all c_double*2). They either need to be wrapped with a ctypes pointer object, or passed to the C function using ctypes.byref.</p>
0
2010-01-19T14:13:07Z
[ "python", "ctypes", "access-violation", "windowserror" ]
XCode 3.2 Ruby and Python templates
1,382,252
<p>Under xcode 3.2 my ObjectiveC + Python/Ruby projects can still be opened updated and compiled, but you cannot create new projects.</p> <p>Given that all traces of ruby and python are missing from xcode 3.2 (ie create project and add new ruby/python file), is there an easy way to get the templates installed again? </p> <p>I found some info about copying them into a folder somewhere, but I cant seem to get it to work, I suspect the folder location has changed for 3.2.</p>
6
2009-09-05T02:14:11Z
1,382,454
<p>Beginning with Xcode 3.2, Apple decided to not include project and file templates from 3rd party projects (including PyObjC, RubyCocoa or MacRuby). Since these template files were often updated more frequently than Xcode's release cycle, the templates shipped with Xcode were often out of date. Developers are now encouraged to install the templates directly from those projects' repositories. PyObjC templates are currently available only in SVN, though the PyObjC devs intend to make them available on the website "soon". <a href="http://stackoverflow.com/questions/589757/add-new-templates-in-xcode">This</a> question details how to install new templates.</p>
3
2009-09-05T04:23:48Z
[ "python", "ruby", "cocoa", "xcode", "pyobjc" ]
XCode 3.2 Ruby and Python templates
1,382,252
<p>Under xcode 3.2 my ObjectiveC + Python/Ruby projects can still be opened updated and compiled, but you cannot create new projects.</p> <p>Given that all traces of ruby and python are missing from xcode 3.2 (ie create project and add new ruby/python file), is there an easy way to get the templates installed again? </p> <p>I found some info about copying them into a folder somewhere, but I cant seem to get it to work, I suspect the folder location has changed for 3.2.</p>
6
2009-09-05T02:14:11Z
1,382,461
<p><a href="http://lists.apple.com/archives/Xcode-users/2009/Aug/msg00517.html" rel="nofollow">Here's the word</a> on this from Chris Espinosa on the Xcode-Users mailing list:</p> <blockquote> <p>We are deemphasizing Cocoa-Python and Cocoa-Ruby, though existing project will continue to build in Xcode. You can duplicate one of your existing projects and use the new Rename command to start a new project.</p> <p>Bugs filed against the removal of these templates will be duplicated to No Python/Ruby templates in Xcode, and we'll use that bug to gauge the need for that support in the future.</p> </blockquote> <p>I'd say file a bug report at <a href="https://bugreport.apple.com/cgi-bin/WebObjects/RadarWeb.woa" rel="nofollow">https://bugreport.apple.com</a> to voice your opinion on the subject.</p>
5
2009-09-05T04:27:54Z
[ "python", "ruby", "cocoa", "xcode", "pyobjc" ]
XCode 3.2 Ruby and Python templates
1,382,252
<p>Under xcode 3.2 my ObjectiveC + Python/Ruby projects can still be opened updated and compiled, but you cannot create new projects.</p> <p>Given that all traces of ruby and python are missing from xcode 3.2 (ie create project and add new ruby/python file), is there an easy way to get the templates installed again? </p> <p>I found some info about copying them into a folder somewhere, but I cant seem to get it to work, I suspect the folder location has changed for 3.2.</p>
6
2009-09-05T02:14:11Z
1,448,482
<p>The above coments were all good and helpful but didn't really help. Easiest thing I could find is to create an empty python/ruby project in xcode 3.1, then make copies of this project folder for every new project you work on.</p> <p>When you open the new/blank project, 3.2 has a new feature that lets you rename the project so you can have proper names for eacn new project.</p>
0
2009-09-19T12:40:03Z
[ "python", "ruby", "cocoa", "xcode", "pyobjc" ]
XCode 3.2 Ruby and Python templates
1,382,252
<p>Under xcode 3.2 my ObjectiveC + Python/Ruby projects can still be opened updated and compiled, but you cannot create new projects.</p> <p>Given that all traces of ruby and python are missing from xcode 3.2 (ie create project and add new ruby/python file), is there an easy way to get the templates installed again? </p> <p>I found some info about copying them into a folder somewhere, but I cant seem to get it to work, I suspect the folder location has changed for 3.2.</p>
6
2009-09-05T02:14:11Z
1,454,608
<p>The folder for application templates in 3.2 is: /Developer/Library/Xcode/Project Templates/Application</p> <p>Templates for python are at: <a href="http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-xcode/Project%20Templates/" rel="nofollow">http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-xcode/Project%20Templates/</a></p> <p>use:</p> <pre><code>$svn co &lt;address of template you want&gt; /Developer/Library/Xcode/Project Templates/Application/&lt;Folder you want it in&gt; </code></pre> <p>e.g.</p> <pre><code>$svn co http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-xcode/Project%20Templates/Cocoa-Python%20Document-based%20Application/ /Developer/Library/Xcode/Project\ Templates/Application/Cocoa-Python\ NSDocument\ based\ Application </code></pre>
6
2009-09-21T13:51:12Z
[ "python", "ruby", "cocoa", "xcode", "pyobjc" ]
XCode 3.2 Ruby and Python templates
1,382,252
<p>Under xcode 3.2 my ObjectiveC + Python/Ruby projects can still be opened updated and compiled, but you cannot create new projects.</p> <p>Given that all traces of ruby and python are missing from xcode 3.2 (ie create project and add new ruby/python file), is there an easy way to get the templates installed again? </p> <p>I found some info about copying them into a folder somewhere, but I cant seem to get it to work, I suspect the folder location has changed for 3.2.</p>
6
2009-09-05T02:14:11Z
2,633,955
<ul> <li>Download the <a href="http://rubycocoa.svn.sourceforge.net/viewvc/rubycocoa/trunk/src/template/ProjectBuilder/" rel="nofollow" title="Cocoa-Ruby Templates">Cocoa-Ruby Templates</a> to your '/Developer/Library/Xcode/Project Templates/Application/Ruby Application/' and '/Developer/Library/Xcode/File Templates/Ruby/' directories. </li> <li>Install the latest version of <a href="http://sourceforge.net/projects/rubycocoa/files/" rel="nofollow">Ruby Cocoa</a>.</li> </ul> <p>More info can be found on the <a href="http://rubycocoa.sourceforge.net/HomePage" rel="nofollow">Ruby Cocoa website</a>.</p>
1
2010-04-13T23:44:06Z
[ "python", "ruby", "cocoa", "xcode", "pyobjc" ]
sqlalchemy easy way to insert or update?
1,382,469
<p>I have a sequence of new objects. They all look like similar to this:</p> <p>Foo(pk_col1=x, pk_col2=y, val='bar')</p> <p>Some of those are Foo that exist (i.e. only val differs from the row in the db) and should generate update queries. The others should generate inserts.</p> <p>I can think of a few ways of doing this, the best being:</p> <pre><code>pk_cols = Foo.table.primary_key.keys() for f1 in foos: f2 = Foo.get([getattr(f1, c) for c in pk_cols]) if f2 is not None: f2.val = f1.val # update # XXX do we need to do session.add(f2) # (or at least keep f2 alive until after the commit?) else: session.add(f1) # insert session.commit() </code></pre> <p>Is there an easier way?</p>
22
2009-09-05T04:33:13Z
1,382,493
<pre><code>Session.save_or_update(model) </code></pre>
-5
2009-09-05T04:48:50Z
[ "python", "sqlalchemy" ]
sqlalchemy easy way to insert or update?
1,382,469
<p>I have a sequence of new objects. They all look like similar to this:</p> <p>Foo(pk_col1=x, pk_col2=y, val='bar')</p> <p>Some of those are Foo that exist (i.e. only val differs from the row in the db) and should generate update queries. The others should generate inserts.</p> <p>I can think of a few ways of doing this, the best being:</p> <pre><code>pk_cols = Foo.table.primary_key.keys() for f1 in foos: f2 = Foo.get([getattr(f1, c) for c in pk_cols]) if f2 is not None: f2.val = f1.val # update # XXX do we need to do session.add(f2) # (or at least keep f2 alive until after the commit?) else: session.add(f1) # insert session.commit() </code></pre> <p>Is there an easier way?</p>
22
2009-09-05T04:33:13Z
1,415,306
<p>I think you are after <a href="http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#merging">new_obj = session.merge(obj)</a>. This will merge an object in a detached state into the session if the primary keys match and will make a new one otherwise. So <code>session.save(new_obj)</code> will work for both insert and update.</p>
30
2009-09-12T14:55:50Z
[ "python", "sqlalchemy" ]
How do I do Debian packaging of a Python package?
1,382,569
<p>I need to write, or find, a script to create a Debian package, using python-support, from a Python package. The Python package will be pure Python with no C extensions.</p> <p>The Python package for testing purposes will just be a directory with an empty <code>__init__.py</code> file and a single Python module, <code>package_test.py</code>.</p> <p>The packaging script <em>must</em> use python-support to provide the correct bytecode for possible multiple installations of Python on a target platform, i.e. v2.5 and v2.6 on Ubuntu Jaunty.</p> <p>Most advice I find while googling are just examples of nasty hacks that don't even use python-support or python-central. </p> <p>I have spent hours researching this, and the best I can come up with is to hack around the script from an existing open source project, but I don't know which bits are required for what I'm doing.</p> <p>Has anyone here made a Debian package out of a Python package in a reasonably non-hacky way?</p> <p>I'm starting to think that it will take me more than a week to go from no knowledge of Debian packaging and python-support to getting a working script. How long has it taken others?</p>
39
2009-09-05T05:39:23Z
1,382,580
<p>First off, there are plenty of Python packages already in Debian; you can download the source (including all the packaging) for any of them either using <code>apt-get source</code> or by visiting <a href="http://packages.debian.org">http://packages.debian.org</a>.</p> <p>You may find the following resources of use:</p> <ul> <li><a href="http://www.debian.org/doc/maint-guide/">Debian New Maintainer's Guide</a></li> <li><a href="http://www.debian.org/doc/debian-policy/">Debian Policy Manual</a></li> <li><a href="http://www.debian.org/doc/packaging-manuals/python-policy/">Debian Python Policy</a></li> <li><a href="http://wiki.debian.org/Teams/PythonModulesTeam">Debian Python Modules Team</a></li> </ul>
5
2009-09-05T05:52:10Z
[ "python", "debian" ]
How do I do Debian packaging of a Python package?
1,382,569
<p>I need to write, or find, a script to create a Debian package, using python-support, from a Python package. The Python package will be pure Python with no C extensions.</p> <p>The Python package for testing purposes will just be a directory with an empty <code>__init__.py</code> file and a single Python module, <code>package_test.py</code>.</p> <p>The packaging script <em>must</em> use python-support to provide the correct bytecode for possible multiple installations of Python on a target platform, i.e. v2.5 and v2.6 on Ubuntu Jaunty.</p> <p>Most advice I find while googling are just examples of nasty hacks that don't even use python-support or python-central. </p> <p>I have spent hours researching this, and the best I can come up with is to hack around the script from an existing open source project, but I don't know which bits are required for what I'm doing.</p> <p>Has anyone here made a Debian package out of a Python package in a reasonably non-hacky way?</p> <p>I'm starting to think that it will take me more than a week to go from no knowledge of Debian packaging and python-support to getting a working script. How long has it taken others?</p>
39
2009-09-05T05:39:23Z
1,382,593
<p>I would take the sources of an existing Debian package, and replace the actual package in it with your package. To find a list of packages that depend on python-support, do</p> <pre><code> apt-cache rdepends python-support </code></pre> <p>Pick a package that is <code>Architecture: all</code>, so that it is a pure-Python package. Going through this list, I found that e.g. python-flup might be a good starting point. To get the source of one such package, do</p> <pre><code>apt-get source &lt;package&gt; </code></pre> <p>To build it, do</p> <pre><code>cd &lt;packagesrc&gt; dpkg-buildpackage -rfakeroot </code></pre> <p>When editing it, expect that you only need the files in the <code>debian</code> folder; replace all references to flup with your own package name.</p> <p>Once you get started, it should take you a day to complete.</p>
17
2009-09-05T06:00:43Z
[ "python", "debian" ]
How do I do Debian packaging of a Python package?
1,382,569
<p>I need to write, or find, a script to create a Debian package, using python-support, from a Python package. The Python package will be pure Python with no C extensions.</p> <p>The Python package for testing purposes will just be a directory with an empty <code>__init__.py</code> file and a single Python module, <code>package_test.py</code>.</p> <p>The packaging script <em>must</em> use python-support to provide the correct bytecode for possible multiple installations of Python on a target platform, i.e. v2.5 and v2.6 on Ubuntu Jaunty.</p> <p>Most advice I find while googling are just examples of nasty hacks that don't even use python-support or python-central. </p> <p>I have spent hours researching this, and the best I can come up with is to hack around the script from an existing open source project, but I don't know which bits are required for what I'm doing.</p> <p>Has anyone here made a Debian package out of a Python package in a reasonably non-hacky way?</p> <p>I'm starting to think that it will take me more than a week to go from no knowledge of Debian packaging and python-support to getting a working script. How long has it taken others?</p>
39
2009-09-05T05:39:23Z
2,796,210
<p>I think what you want is <a href="http://pypi.python.org/pypi/stdeb">http://pypi.python.org/pypi/stdeb</a>:</p> <blockquote> <p>stdeb produces Debian source packages from Python packages via a new distutils command, sdist_dsc. Automatic defaults are provided for the Debian package, but many aspects of the resulting package can be customized (see the customizing section, below). An additional command, bdist_deb, creates a Debian binary package, a .deb file.</p> </blockquote>
19
2010-05-09T00:50:12Z
[ "python", "debian" ]
How do I do Debian packaging of a Python package?
1,382,569
<p>I need to write, or find, a script to create a Debian package, using python-support, from a Python package. The Python package will be pure Python with no C extensions.</p> <p>The Python package for testing purposes will just be a directory with an empty <code>__init__.py</code> file and a single Python module, <code>package_test.py</code>.</p> <p>The packaging script <em>must</em> use python-support to provide the correct bytecode for possible multiple installations of Python on a target platform, i.e. v2.5 and v2.6 on Ubuntu Jaunty.</p> <p>Most advice I find while googling are just examples of nasty hacks that don't even use python-support or python-central. </p> <p>I have spent hours researching this, and the best I can come up with is to hack around the script from an existing open source project, but I don't know which bits are required for what I'm doing.</p> <p>Has anyone here made a Debian package out of a Python package in a reasonably non-hacky way?</p> <p>I'm starting to think that it will take me more than a week to go from no knowledge of Debian packaging and python-support to getting a working script. How long has it taken others?</p>
39
2009-09-05T05:39:23Z
14,423,375
<p>Most of the answers posted here are outdated, fortunately a great Debian wiki post has been made recently, which explains the current best practices and describes how to build Debian packages for Python modules and applications.</p> <ul> <li><a href="http://wiki.debian.org/Python/Packaging">http://wiki.debian.org/Python/Packaging</a></li> </ul>
13
2013-01-20T09:55:25Z
[ "python", "debian" ]
How do I do Debian packaging of a Python package?
1,382,569
<p>I need to write, or find, a script to create a Debian package, using python-support, from a Python package. The Python package will be pure Python with no C extensions.</p> <p>The Python package for testing purposes will just be a directory with an empty <code>__init__.py</code> file and a single Python module, <code>package_test.py</code>.</p> <p>The packaging script <em>must</em> use python-support to provide the correct bytecode for possible multiple installations of Python on a target platform, i.e. v2.5 and v2.6 on Ubuntu Jaunty.</p> <p>Most advice I find while googling are just examples of nasty hacks that don't even use python-support or python-central. </p> <p>I have spent hours researching this, and the best I can come up with is to hack around the script from an existing open source project, but I don't know which bits are required for what I'm doing.</p> <p>Has anyone here made a Debian package out of a Python package in a reasonably non-hacky way?</p> <p>I'm starting to think that it will take me more than a week to go from no knowledge of Debian packaging and python-support to getting a working script. How long has it taken others?</p>
39
2009-09-05T05:39:23Z
25,275,227
<p>The right way of building a deb package is using <code>dpkg-buildpackage</code> but sometimes it is a little bit complicated. Instead you can use <code>dpkg -b &lt;folder&gt;</code> and it will create your Debian package.</p> <p>These are the basics for creating a Debian package with <code>dpkg -b &lt;folder&gt;</code> with any binary or with any kind of script that runs automatically without needing manual compilation (Python, Bash, Pearl, Ruby):</p> <ol> <li>Create the files and folders in order to recreate the following structure: </li> </ol> <pre class="lang-none prettyprint-override"><code> ProgramName-Version/ ProgramName-Version/DEBIAN ProgramName-Version/DEBIAN/control ProgramName-Version/usr/ ProgramName-Version/usr/bin/ ProgramName-Version/usr/bin/your_script </code></pre> <p>The scripts placed at <code>/usr/bin/</code> are directly called from the terminal, note that I didn't add an extension to the script. Also you can notice that the structure of the deb package will be the structure of the program once it's installed. So if you follow this logic if your program has a single file, you can directly place it under <code>ProgramName-Version/usr/bin/your_script</code>, but if you have multiple files, you should place them under <code>ProgramName-Version/usr/share/ProgramName/all your files</code> and place only one file under <code>/usr/bin/</code> that will call your scripts from <code>/usr/share/ProgramName/</code></p> <ol start="2"> <li><p>Change all the folder permission to root: </p> <pre><code>chown root:root -R /path/to/ProgramName-Version </code></pre></li> <li><p>Change the script's permissions: </p> <pre><code>chmod 0755 /path/to/the/script </code></pre></li> <li><p>Finally, you can run: <code>dpkg -b /path/to/the/ProgramName-Version</code> and your deb package will be created! (You can also add the post/pre inst scripts and everything you want, it works like a normal Debian package)</p></li> </ol> <hr> <p>Here is an example of the <code>control</code> file. You only need to copy-paste it in to an empty file called "control" and put it in the DEBIAN folder</p> <pre class="lang-none prettyprint-override"><code>Package: ProgramName Version: VERSION Architecture: all Maintainer: YOUR NAME &lt;EMAIL&gt; Depends: python2.7, etc , etc, Installed-Size: in_kb Homepage: http://foo.com Description: Here you can put a one line description. This is the short Description. Here you put the long description, indented by 1 space. </code></pre> <hr> <p>If you want to build using <code>dpkg -b &lt;folder&gt;</code> you can use <a href="https://rsm.website/software/gnu-linux/software/build-deb" rel="nofollow">this program</a> that will do everything with one command. If you regularly build packages, it is a pain to do all the stuff that I mentioned!</p> <p>*The guide was taken from <a href="https://rafael.senties-martinelli.com/articles/debian-packages" rel="nofollow">Basics of Debian Packages</a></p>
9
2014-08-12T22:37:15Z
[ "python", "debian" ]
Which PEP's are must reads?
1,382,648
<p>I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?</p>
46
2009-09-05T06:43:05Z
1,382,661
<p>Definitely <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>, a Style Guide for Python.</p>
24
2009-09-05T06:51:34Z
[ "python", "pep" ]
Which PEP's are must reads?
1,382,648
<p>I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?</p>
46
2009-09-05T06:43:05Z
1,382,662
<p>I found that reading the declined ones can give some good insights into what's Pythonic and what isn't. This was a while ago so I don't have any specific examples.</p>
6
2009-09-05T06:53:07Z
[ "python", "pep" ]
Which PEP's are must reads?
1,382,648
<p>I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?</p>
46
2009-09-05T06:43:05Z
1,382,981
<p>It is now retrospective, but still interesting: I think <a href="http://www.python.org/dev/peps/pep-3099/">Things that will Not Change in Python 3000</a> is a good read, with lots of links to the discussions that preceded the decisions.</p>
8
2009-09-05T10:34:42Z
[ "python", "pep" ]
Which PEP's are must reads?
1,382,648
<p>I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?</p>
46
2009-09-05T06:43:05Z
1,383,045
<p>Also pep <a href="http://www.python.org/dev/peps/pep-0257/">0257</a> docstring convention</p>
9
2009-09-05T11:00:43Z
[ "python", "pep" ]
Which PEP's are must reads?
1,382,648
<p>I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?</p>
46
2009-09-05T06:43:05Z
1,383,659
<p>Although Python is incredibly intuitive, a lot of people do not comprehend his philosophy.</p> <blockquote> <p><a href="http://www.python.org/dev/peps/pep-0020/">Pep 20</a>: <strong>The Zen of Python</strong></p> <ul> <li>Beautiful is better than ugly.</li> <li>Explicit is better than implicit.</li> <li>Simple is better than complex.</li> <li>Complex is better than complicated.</li> <li>Flat is better than nested.</li> <li>Sparse is better than dense.</li> <li>Readability counts.</li> <li>Special cases aren't special enough to break the rules.</li> <li>Although practicality beats purity.</li> <li>Errors should never pass silently.</li> <li>Unless explicitly silenced.</li> <li>In the face of ambiguity, refuse the temptation to guess.</li> <li>There should be one-- and preferably only one --obvious way to do it.</li> <li>Although that way may not be obvious at first unless you're Dutch.</li> <li>Now is better than never.</li> <li>Although never is often better than <em>right</em> now.</li> <li>If the implementation is hard to explain, it's a bad idea.</li> <li>If the implementation is easy to explain, it may be a good idea.</li> <li>Namespaces are one honking great idea -- let's do more of those!</li> </ul> </blockquote>
13
2009-09-05T15:59:54Z
[ "python", "pep" ]
Which PEP's are must reads?
1,382,648
<p>I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?</p>
46
2009-09-05T06:43:05Z
21,502,630
<p>I'd also recommend PEPs 8 and 257. I know this deviates slightly from the original question, but I'd like to point out that PyCharm (probably the best Python IDE around in my opinion) automatically checks if you're following some of the most important PEP 8 guidelines, just in case anyone's interested...</p>
1
2014-02-01T19:39:02Z
[ "python", "pep" ]
Which PEP's are must reads?
1,382,648
<p>I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?</p>
46
2009-09-05T06:43:05Z
21,602,502
<p>Here is a index of PEP - <a href="http://www.python.org/dev/peps/" rel="nofollow">http://www.python.org/dev/peps/</a> </p> <p>when ever one has doubt about a topic, they can search in that</p>
2
2014-02-06T12:04:52Z
[ "python", "pep" ]
String formatting
1,382,663
<p>I have a list filter = ['a', 'b', 'c']. I need to frame the following string out of the list "item -a item -b item -c". Which is the most efficient way to do this? Usually the list filter contains 100 to 200 items and each would be of length 100 - 150. Wouldn't that lead to overflow? And what is the maximum length of the string supported?</p>
0
2009-09-05T06:53:57Z
1,382,685
<p>You can use <strong><a href="http://docs.python.org/library/stdtypes.html#str.join" rel="nofollow">join</a></strong> (I believe <code>join</code> is the same in Python 3.0):</p> <pre><code>&gt;&gt;&gt; l = ['a','b','c'] &gt;&gt;&gt; print ' item -'.join([''] + l) &gt;&gt;&gt; ' item -a item -b item -c' &gt;&gt;&gt; print ' item -'.join([''] + l).lstrip(' ') # eat the leading space &gt;&gt;&gt; 'item -a item -b item -c' </code></pre>
1
2009-09-05T07:11:36Z
[ "python-3.x", "python" ]
String formatting
1,382,663
<p>I have a list filter = ['a', 'b', 'c']. I need to frame the following string out of the list "item -a item -b item -c". Which is the most efficient way to do this? Usually the list filter contains 100 to 200 items and each would be of length 100 - 150. Wouldn't that lead to overflow? And what is the maximum length of the string supported?</p>
0
2009-09-05T06:53:57Z
1,382,748
<p>A cleaner way to do this:</p> <pre><code>filter = ['a', 'b', 'c'] " ".join(["item -%s" % val for val in filter]) </code></pre> <p>This works fine with large arrays, eg. <code>filter = ['a'*1000] * 1000</code>.</p>
4
2009-09-05T07:52:45Z
[ "python-3.x", "python" ]
How can I create a numpy array holding values of a multi-variable function?
1,382,846
<p>I want to create an array holding a function <code>f(x,y,z)</code>. If it were a function of one variable I'd do, for instance:</p> <pre><code>sinx = numpy.sin(numpy.linspace(-5,5,100)) </code></pre> <p>to get <code>sin(x)</code> for <code>x</code> in <code>[-5,5]</code></p> <p>How can I do the same to get, for instance <code>sin(x+y+z)</code>?</p>
2
2009-09-05T09:11:28Z
1,383,181
<p>I seem to have found a way:</p> <pre><code># define the range of x,y,z x_range = numpy.linspace(x_min,x_max,x_num) y_range = numpy.linspace(y_min,y_max,y_num) z_range = numpy.linspace(z_min,z_max,z_num) # create arrays x,y,z in the correct dimensions # so that they create the grid x,y,z = numpy.ix_(x_range,y_range,z_range) # calculate the function of x, y and z sinxyz = numpy.sin(x+y+z) </code></pre>
5
2009-09-05T12:00:49Z
[ "python", "function", "multidimensional-array", "numpy" ]
How can I create a numpy array holding values of a multi-variable function?
1,382,846
<p>I want to create an array holding a function <code>f(x,y,z)</code>. If it were a function of one variable I'd do, for instance:</p> <pre><code>sinx = numpy.sin(numpy.linspace(-5,5,100)) </code></pre> <p>to get <code>sin(x)</code> for <code>x</code> in <code>[-5,5]</code></p> <p>How can I do the same to get, for instance <code>sin(x+y+z)</code>?</p>
2
2009-09-05T09:11:28Z
2,288,142
<pre><code>xyz = numpy.mgrid[-5:5,-5:5,-5:5] sinxyz = numpy.sin(xyz[0]+xyz[1]+xyz[2]) </code></pre>
4
2010-02-18T11:20:02Z
[ "python", "function", "multidimensional-array", "numpy" ]
How can I create a numpy array holding values of a multi-variable function?
1,382,846
<p>I want to create an array holding a function <code>f(x,y,z)</code>. If it were a function of one variable I'd do, for instance:</p> <pre><code>sinx = numpy.sin(numpy.linspace(-5,5,100)) </code></pre> <p>to get <code>sin(x)</code> for <code>x</code> in <code>[-5,5]</code></p> <p>How can I do the same to get, for instance <code>sin(x+y+z)</code>?</p>
2
2009-09-05T09:11:28Z
15,777,259
<p>The numpy.mgrid function would work equally well:</p> <pre><code>x,y,z = numpy.mgrid[x_min:x_max:x_num, y_min:y_max:y_num, z_min:z_max:z_num] sinxyz = numpy.sin(x+y+z) </code></pre> <p>edit: to get it to work <code>x_num</code>, <code>y_num</code> and <code>z_num</code> have to be explicit numbers followed by <code>j</code>, e.g., <code>x,y = numpy.mgrid[-1:1:10j, -1:1:10j]</code></p>
-1
2013-04-03T01:16:44Z
[ "python", "function", "multidimensional-array", "numpy" ]
Dynamically attaching a method to an existing Python object generated with swig?
1,382,871
<p>I am working with a Python class, and I don't have write access to its declaration. How can I attach a custom method (such as <strong><code>__str__</code></strong>) to the objects created from that class without modifying the class declaration?</p> <p>EDIT: Thank you for all your answers. I tried them all but they haven't resolved my problem. Here is a minimal example that I hope will clarify the issue. I am using swig to wrap a C++ class, and the purpose is to override the <code>__str__</code> function of <strong>an object</strong> returned by the swig module. I use cmake to build the example:</p> <p><strong>test.py</strong></p> <pre><code>import example ex = example.generate_example(2) def prnt(self): return str(self.x) #How can I replace the __str__ function of object ex with prnt? print ex print prnt(ex) </code></pre> <p><strong>example.hpp</strong></p> <pre><code>struct example { int x; }; example generate_example(int x); </code></pre> <p><strong>example.cpp</strong></p> <pre><code>#include "example.hpp" #include &lt;iostream&gt; example generate_example(int x) { example ex; ex.x = x; return ex; } int main() { example ex = generate_example(2); std::cout &lt;&lt; ex.x &lt;&lt; "\n"; return 1; } </code></pre> <p><strong>example.i</strong></p> <pre><code>%module example %{ #include "example.hpp" %} %include "example.hpp" </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required(VERSION 2.6) find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) find_package(PythonLibs) include_directories(${PYTHON_INCLUDE_PATH}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) set_source_files_properties(example.i PROPERTIES CPLUSPLUS ON) swig_add_module(example python example.i example) swig_link_libraries(example ${PYTHON_LIBRARIES}) if(APPLE) set(CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS "${CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS} -flat_namespace") endif(APPLE) </code></pre> <p>To build and run test.py, copy all the files in a directory, and in that directory run</p> <pre><code>cmake . make python test.py </code></pre> <p>This results in the following output:</p> <pre><code>&lt;example.example; proxy of &lt;Swig Object of type 'example *' at 0x10021cc40&gt; &gt; 2 </code></pre> <p>As you can see the swig object has its own <strong>str</strong> function, and that is what I am trying to override. </p>
7
2009-09-05T09:30:59Z
1,382,883
<pre><code>&gt;&gt;&gt; class C(object): ... pass ... &gt;&gt;&gt; def spam(self): ... return 'spam' ... &gt;&gt;&gt; C.__str__ = spam &gt;&gt;&gt; print C() spam </code></pre> <p>It won't work on classes which use <a href="http://docs.python.org/reference/datamodel.html#slots" rel="nofollow"><code>__slots__</code></a>.</p>
3
2009-09-05T09:36:29Z
[ "python", "class", "dynamic", "methods" ]