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
sequence
MVC and django fundamentals
364,015
<p>Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before. Any insight / help would be greatly appreciated!</p>
8
2008-12-12T20:22:29Z
364,074
<p>"data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before"</p> <p>Django imposes best practices on you. You don't have a lot of choices and can't make a lot of mistakes.</p> <p>MVC (while a noble aspiration) is implemented as follows:</p> <ul> <li>Data is defined in "models.py" files using the Django ORM models.</li> <li>urls.py file maps URL to view function. Pick your URL's wisely.</li> <li>View function does all processing, making use of models and methods in models</li> <li>Presentation (via HTML templates) invoked by View function. Essentially no processing can be done in presentation, just lightweight iteration and decision-making</li> </ul> <p>The model is defined for you. Just stick to what Django does naturally and you'll be happy.</p> <p>Architecturally, you usually have a stack like this.</p> <ul> <li><p>Apache does two things.</p> <ul> <li>serves static content directly and immediately </li> <li>hands dynamic URL to Django (via mod_python, mod_wsgi or mod_fastcgi). Django apps map URL to view functions (which access to database (via ORM/model) and display via templates.</li> </ul></li> <li><p>Database used by Django view functions.</p></li> </ul> <p>The architecture is well-defined for you. Just stick to what Django does naturally and you'll be happy.</p> <p>Feel free to read the <a href="http://docs.djangoproject.com/en/dev/">Django documentation</a>. It's excellent; perhaps the best there is.</p>
15
2008-12-12T20:37:36Z
[ "python", "django", "django-models", "django-templates" ]
MVC and django fundamentals
364,015
<p>Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before. Any insight / help would be greatly appreciated!</p>
8
2008-12-12T20:22:29Z
364,157
<p><a href="http://martinfowler.com/eaaDev/uiArchs.html" rel="nofollow">This link</a> will explain the MVC and the likes. <a href="http://djangoproject.com" rel="nofollow">This link</a> has all the django related documentation, starter kits etc.</p>
1
2008-12-12T21:11:13Z
[ "python", "django", "django-models", "django-templates" ]
MVC and django fundamentals
364,015
<p>Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before. Any insight / help would be greatly appreciated!</p>
8
2008-12-12T20:22:29Z
364,161
<p>first, forget all MVC mantra. it's important to have a good layered structure, but MVC (as defined originally) isn't one, it was a <strong>modular</strong> structure, where each <strong>GUI</strong> module is split in these tree submodules. nothing to use on the web here.</p> <p>in web development, it really pays to have a layered structure, where the most important layer is the storage/modelling one, which came to be called <em>model layer</em>. on top of that, you need a few other layers but they're really not anything like views and controllers in the GUI world.</p> <p>the Django layers are roughly:</p> <ul> <li>storage/modelling: models.py, obviously. try to put most of the 'working' concepts there. all the relationships, all the operations should be implemented here.</li> <li>dispatching: mostly in urls.py. here you turn your URL scheme into code paths. think of it like a big switch() statement. try hard to have readable URLs, which map into user intentions. it will help a lot to add new functionality, or new ways to do the same things (like an AJAX UI later).</li> <li>gathering: mostly the view functions, both yours and the prebuilt generic views. here you simply gather all the from the models to satisfy a user request. in surprisingly many cases, it just have to pick a single model instance, and everything else can be retrieved from relationships. for these URLs, a generic view is enough.</li> <li>presentation: the templates. if the view gives you the data you need, it's simple enough to turn it into a webpage. it's here where you'll thank that the model classes have good accessors to get any kind of relevant data from any given instance.</li> </ul>
5
2008-12-12T21:12:11Z
[ "python", "django", "django-models", "django-templates" ]
MVC and django fundamentals
364,015
<p>Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before. Any insight / help would be greatly appreciated!</p>
8
2008-12-12T20:22:29Z
364,433
<p>To understand django fundementals and the django take on MVC, consult the following: <a href="http://www.djangobook.com/" rel="nofollow">http://www.djangobook.com/</a></p> <p>As a starting point to getting your hands dirty with ... "...trying to find some comparable data / architectural models"</p> <p>Here is a quick and dirty way to reverse engineer a database to get a models.py file, which you can then inspect to see how django would handle it.</p> <p>1.) get an er diagram that closely matches your target. For example something like this <a href="http://www.databaseanswers.org/data_models/product_catalogs/index.htm" rel="nofollow">http://www.databaseanswers.org/data_models/product_catalogs/index.htm</a></p> <p>2.) create an sql script from the er diagram and create the database, I suggest Postgre, as some MySQL table type will not have forgien key constraints, but in a pinch MySQL or SQLITE will do</p> <p>3.) create and configure a django app to use that database. Then run: python manage.py inspectdb</p> <p>This will at least give you a models.py file which you can read to see how django attempts to model it.</p> <p>Note that the inspect command is intended to be a shortcut for dealing with legacy database when developing in django, and as such is not perfect. Be sure to read the following before attempting this: <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/#ref-django-admin" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/django-admin/#ref-django-admin</a></p>
0
2008-12-12T22:56:05Z
[ "python", "django", "django-models", "django-templates" ]
Markup-based GUI for python
364,327
<p>I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them. </p> <p>I think GUI design should be done in a separate text-based file in some markup format, which is read and rendered (e.g. HTML), so that the design of the interface is not tightly coupled with the rest of the code.</p> <p>I've seen <a href="http://www.terrainformatica.com/htmlayout/" rel="nofollow">HTMLayout</a> and I love the idea, but so far it seems be only in C++. </p> <p>I'm looking for a python library (or even a WIP project) for doing markup-based gui.</p> <p><strong>UPDATE</strong></p> <p>The reason I can't accept QT's xml is the same reason I hate the programatic approach; you're assembling each widget separately, and specifying each property of it on a separate line. It doesn't provide any advantage over doing it the programatic way.</p>
7
2008-12-12T22:10:08Z
364,338
<p>It's XML, not Python, but look at <a href="http://www.openlaszlo.org/" rel="nofollow">Open Laszlo</a></p>
-1
2008-12-12T22:14:46Z
[ "python", "user-interface", "markup" ]
Markup-based GUI for python
364,327
<p>I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them. </p> <p>I think GUI design should be done in a separate text-based file in some markup format, which is read and rendered (e.g. HTML), so that the design of the interface is not tightly coupled with the rest of the code.</p> <p>I've seen <a href="http://www.terrainformatica.com/htmlayout/" rel="nofollow">HTMLayout</a> and I love the idea, but so far it seems be only in C++. </p> <p>I'm looking for a python library (or even a WIP project) for doing markup-based gui.</p> <p><strong>UPDATE</strong></p> <p>The reason I can't accept QT's xml is the same reason I hate the programatic approach; you're assembling each widget separately, and specifying each property of it on a separate line. It doesn't provide any advantage over doing it the programatic way.</p>
7
2008-12-12T22:10:08Z
364,340
<p>You should look into Qt, which you can use from Python using the excellent PyQt interface (why they didn't name it QtPy --- cutiepie, get it ? --- I will never understand).</p> <p>With Qt, you can have the choice of constructing your GUI's programmatically (which you don't want), or using XML markup. This XML file can either be compiled to code beforehand, or loaded with a short command. The latter is the normal way to work using PyQt.</p> <p>Qt is versatile, high-quality, cross-platform, and you're likely using it already without knowing it. The official Skype client application is written in Qt if I remember correctly.</p> <p><strong>Edit:</strong> Just adding some links so the OP get get some feel for it ...</p> <ul> <li><a href="http://sector.ynet.sk/qt4-tutorial/my-first-qt-gui-application.html" rel="nofollow">Short intro to Qt programming with C++</a> -- notice the use of the Qt Designer, which outputs .ui files, which is an XML format which I remember was also quite easy to work with by hand. PyQt programming is very similar, except for being in a much easier programming language of course :-)</li> <li><a href="http://wiki.python.org/moin/PyQt4" rel="nofollow">Info about PyQt on the Python wiki</a></li> <li><a href="http://www.commandprompt.com/community/pyqt/" rel="nofollow">Online book on PyQt programming</a></li> </ul>
3
2008-12-12T22:15:19Z
[ "python", "user-interface", "markup" ]
Markup-based GUI for python
364,327
<p>I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them. </p> <p>I think GUI design should be done in a separate text-based file in some markup format, which is read and rendered (e.g. HTML), so that the design of the interface is not tightly coupled with the rest of the code.</p> <p>I've seen <a href="http://www.terrainformatica.com/htmlayout/" rel="nofollow">HTMLayout</a> and I love the idea, but so far it seems be only in C++. </p> <p>I'm looking for a python library (or even a WIP project) for doing markup-based gui.</p> <p><strong>UPDATE</strong></p> <p>The reason I can't accept QT's xml is the same reason I hate the programatic approach; you're assembling each widget separately, and specifying each property of it on a separate line. It doesn't provide any advantage over doing it the programatic way.</p>
7
2008-12-12T22:10:08Z
364,363
<p>windows?</p> <p>you can use the WinForms editor in Visual Studio and then talk to the assembly from IronPython.</p>
-2
2008-12-12T22:23:33Z
[ "python", "user-interface", "markup" ]
Markup-based GUI for python
364,327
<p>I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them. </p> <p>I think GUI design should be done in a separate text-based file in some markup format, which is read and rendered (e.g. HTML), so that the design of the interface is not tightly coupled with the rest of the code.</p> <p>I've seen <a href="http://www.terrainformatica.com/htmlayout/" rel="nofollow">HTMLayout</a> and I love the idea, but so far it seems be only in C++. </p> <p>I'm looking for a python library (or even a WIP project) for doing markup-based gui.</p> <p><strong>UPDATE</strong></p> <p>The reason I can't accept QT's xml is the same reason I hate the programatic approach; you're assembling each widget separately, and specifying each property of it on a separate line. It doesn't provide any advantage over doing it the programatic way.</p>
7
2008-12-12T22:10:08Z
364,393
<p>How about wxPython? I'm just now beginning to work with it, but there's a tool -- XRC Resource Editor -- that allows you to assemble your GUI, which is then written to an XML file. As I understand it, your Python application loads the XML file, rather than having a whole bunch of GUI-layout code mixed in with your Python code.</p>
2
2008-12-12T22:36:16Z
[ "python", "user-interface", "markup" ]
Markup-based GUI for python
364,327
<p>I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them. </p> <p>I think GUI design should be done in a separate text-based file in some markup format, which is read and rendered (e.g. HTML), so that the design of the interface is not tightly coupled with the rest of the code.</p> <p>I've seen <a href="http://www.terrainformatica.com/htmlayout/" rel="nofollow">HTMLayout</a> and I love the idea, but so far it seems be only in C++. </p> <p>I'm looking for a python library (or even a WIP project) for doing markup-based gui.</p> <p><strong>UPDATE</strong></p> <p>The reason I can't accept QT's xml is the same reason I hate the programatic approach; you're assembling each widget separately, and specifying each property of it on a separate line. It doesn't provide any advantage over doing it the programatic way.</p>
7
2008-12-12T22:10:08Z
364,398
<p>If you use <a href="http://www.pygtk.org/" rel="nofollow">GTK</a>, you can use <a href="http://glade.gnome.org/" rel="nofollow">Glade</a>, which is an XML file. </p>
1
2008-12-12T22:38:32Z
[ "python", "user-interface", "markup" ]
Markup-based GUI for python
364,327
<p>I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them. </p> <p>I think GUI design should be done in a separate text-based file in some markup format, which is read and rendered (e.g. HTML), so that the design of the interface is not tightly coupled with the rest of the code.</p> <p>I've seen <a href="http://www.terrainformatica.com/htmlayout/" rel="nofollow">HTMLayout</a> and I love the idea, but so far it seems be only in C++. </p> <p>I'm looking for a python library (or even a WIP project) for doing markup-based gui.</p> <p><strong>UPDATE</strong></p> <p>The reason I can't accept QT's xml is the same reason I hate the programatic approach; you're assembling each widget separately, and specifying each property of it on a separate line. It doesn't provide any advantage over doing it the programatic way.</p>
7
2008-12-12T22:10:08Z
768,465
<p>You can try Mozilla's XUL. It supports Python via XPCOM.</p> <p>See this project: <a href="http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html">pyxpcomext</a></p> <p>XUL isn't compiled, it is packaged and loaded at runtime. Firefox and many other great applications use it, but most of them use Javascript for scripting instead of Python. There are one or 2 using Python though.</p>
7
2009-04-20T14:18:21Z
[ "python", "user-interface", "markup" ]
Markup-based GUI for python
364,327
<p>I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them. </p> <p>I think GUI design should be done in a separate text-based file in some markup format, which is read and rendered (e.g. HTML), so that the design of the interface is not tightly coupled with the rest of the code.</p> <p>I've seen <a href="http://www.terrainformatica.com/htmlayout/" rel="nofollow">HTMLayout</a> and I love the idea, but so far it seems be only in C++. </p> <p>I'm looking for a python library (or even a WIP project) for doing markup-based gui.</p> <p><strong>UPDATE</strong></p> <p>The reason I can't accept QT's xml is the same reason I hate the programatic approach; you're assembling each widget separately, and specifying each property of it on a separate line. It doesn't provide any advantage over doing it the programatic way.</p>
7
2008-12-12T22:10:08Z
768,701
<p>As a GUI programmer who has gained some <strong>experience</strong>, you should probably just roll your own sweet little toolkit for automating tasks you find yourself doing over and over again.</p>
0
2009-04-20T15:09:56Z
[ "python", "user-interface", "markup" ]
Markup-based GUI for python
364,327
<p>I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them. </p> <p>I think GUI design should be done in a separate text-based file in some markup format, which is read and rendered (e.g. HTML), so that the design of the interface is not tightly coupled with the rest of the code.</p> <p>I've seen <a href="http://www.terrainformatica.com/htmlayout/" rel="nofollow">HTMLayout</a> and I love the idea, but so far it seems be only in C++. </p> <p>I'm looking for a python library (or even a WIP project) for doing markup-based gui.</p> <p><strong>UPDATE</strong></p> <p>The reason I can't accept QT's xml is the same reason I hate the programatic approach; you're assembling each widget separately, and specifying each property of it on a separate line. It doesn't provide any advantage over doing it the programatic way.</p>
7
2008-12-12T22:10:08Z
768,777
<p>If you choose a language like Tcl or Python and Tk for your application development it becomes fairly trivial to write your own DSL for describing the interface. You can, for instance, write a DSL that lets you create menus like this:</p> <pre><code>menubar { File =&gt; { Open =&gt; cmd.open Save =&gt; cmd.save Exit =&gt; cmd.exit } Edit =&gt; { Cut =&gt; cmd.cut Copy =&gt; cmd.copy Paste =&gt; cmd.paste } } </code></pre> <p>... and your main GUI forms like this:</p> <pre><code>form PropertiesForm { Font: [fontchooser] Foreground: [foregroundChooser] Background: [backgroundChooser] } form NewUserForm { username [_____________________] [] administrator enable the following features: () feature 1 () feature 2 () feature 3 } notebook { Properties =&gt; PropertiesForm New User =&gt; NewUserForm } </code></pre> <p>... and so on. Tcl really excels at letting you write DSLs like this. Note that this capability isn't built in to Tcl per se, but the language makes DSLs trivial. Some of this type of thing exists on the Tcler's wiki, for example there's code to create menus similar to what I described at <a href="http://wiki.tcl.tk/827" rel="nofollow">Menus Made Easy</a>. </p> <p>I think, though, that after a while you'll find it really, really hard to make professional grade UIs in this manner.</p>
2
2009-04-20T15:26:43Z
[ "python", "user-interface", "markup" ]
Threaded code on mod_python
364,358
<p>I have written a Django app that makes use of Python threading to create a web spider, the spider operates as a series of threads to check links.</p> <p>When I run this app using the django test server (built in), the app runs fine and the threads seem to start and stop on time.</p> <p>However, running the app on Apache it seems the threads aren't kicking off and running (after about 80 seconds there should be a queued database update and these changes aren't occuring).</p> <p>Does anyone have an idea what I'm missing here?</p> <p>-- Edit: My question is, how does Apache handle threaded applications, i.e. is there a limit on how many threads can be run from a single app?</p> <p>Any help would be appreciated!</p>
1
2008-12-12T22:21:53Z
364,427
<p>Most likely, you are missing the creation of new processes. Apache will not run in a single process, but fork new processes for requests every now and then (depending on a <a href="http://httpd.apache.org/docs/2.2/mod/worker.html" rel="nofollow">dozen or so configuration parameters</a>). If you run django in each process, they will share no memory, and the results produced in one worker won't be visible to any of the others. In addition, the Apache process might terminate (on idle, or after a certain time), discarding your in-memory results.</p>
3
2008-12-12T22:51:37Z
[ "python", "django", "multithreading", "apache" ]
Which Eclipse distribution is good for web development using Python, PHP, or Perl?
364,486
<p>I'd like to try out Eclipse, but I'm a bit baffled with all the different distributions of it. I mainly program in Python doing web development, but I also need to maintain PHP and Perl apps. It looks like EasyEclipse is a bit behind. Should I just grab the base Eclipse and start loading plug-ins?</p>
4
2008-12-12T23:26:53Z
364,494
<p>Maybe try Aptana (<a href="http://www.aptana.com/" rel="nofollow">http://www.aptana.com/</a>) - you can then plug in as many extra modules as you require.</p>
3
2008-12-12T23:31:45Z
[ "php", "python", "perl", "eclipse" ]
Which Eclipse distribution is good for web development using Python, PHP, or Perl?
364,486
<p>I'd like to try out Eclipse, but I'm a bit baffled with all the different distributions of it. I mainly program in Python doing web development, but I also need to maintain PHP and Perl apps. It looks like EasyEclipse is a bit behind. Should I just grab the base Eclipse and start loading plug-ins?</p>
4
2008-12-12T23:26:53Z
364,502
<p>PDT 2.0 is vey good Eclipse <a href="http://www.eclipse.org/pdt/" rel="nofollow">PHP Ide</a> . It is created with cooperation with Zend, so there a lot of featuers from Zend Studio. I also use it with Subeclipse(for SVN) and Target Management (for work on FTP remotely). I will also advice to use Aptana plugins fot HTML and Js - they are much better than standard Web Tools from Eclipse.</p>
1
2008-12-12T23:40:19Z
[ "php", "python", "perl", "eclipse" ]
Which Eclipse distribution is good for web development using Python, PHP, or Perl?
364,486
<p>I'd like to try out Eclipse, but I'm a bit baffled with all the different distributions of it. I mainly program in Python doing web development, but I also need to maintain PHP and Perl apps. It looks like EasyEclipse is a bit behind. Should I just grab the base Eclipse and start loading plug-ins?</p>
4
2008-12-12T23:26:53Z
364,515
<p>I develop Python applications at work and find Eclipse Classic and Eclipse for Java Devs a good fit because I don't do any plugin or Java EE Stuff. We use Eclipse for Java, Python, and NSIS (nullsoft installer) scripting. </p> <p>The Python development I do requires the pydev plugin (see: <a href="http://pydev.sourceforge.net/" rel="nofollow">http://pydev.sourceforge.net/</a>) which so far has been fantastic on a Windows machine. I found some instability on a Fedora 9 machine, but that is not the general consensus among my linuxier colleagues :) </p> <p>The pydev plugin comes with a very minimal set of customizable features including a short list of syntax for colouring, and it's very easy to create a dark colour scheme (black bg, bright text) for python development (if that matters to you). The debugger has been pretty good so far, but I have problems when my applications hit threading in PyQt. I don't know if that is a problem with QThread (a Qt Thread) or python threads in general.</p> <p>I can't offer any advice regarding PERL or PHP but basically like you said, download an Eclipse version and find some good plugins for your development environment.</p>
1
2008-12-12T23:52:43Z
[ "php", "python", "perl", "eclipse" ]
Which Eclipse distribution is good for web development using Python, PHP, or Perl?
364,486
<p>I'd like to try out Eclipse, but I'm a bit baffled with all the different distributions of it. I mainly program in Python doing web development, but I also need to maintain PHP and Perl apps. It looks like EasyEclipse is a bit behind. Should I just grab the base Eclipse and start loading plug-ins?</p>
4
2008-12-12T23:26:53Z
364,517
<p>PyDev is pretty decent as I'm sure you know. It can fit on top of all the Eclipse distributions (provided they meet the minimum version requirements). If you're doing webdev stuff, you'll probably find the closest fit with Aptana. </p> <p>That said, I find Aptana hideously clunky when compared to a decent text editor. I build sites using django and for that I use Eclipse (pure) and PyDev to do the python and gedit (gnome's souped up notepad) for writing the HTML for templates/CSS/JS/etc.</p> <p>At the end of the day, whatever suits <em>you</em> best is what you'll go with.</p>
0
2008-12-12T23:54:48Z
[ "php", "python", "perl", "eclipse" ]
Which Eclipse distribution is good for web development using Python, PHP, or Perl?
364,486
<p>I'd like to try out Eclipse, but I'm a bit baffled with all the different distributions of it. I mainly program in Python doing web development, but I also need to maintain PHP and Perl apps. It looks like EasyEclipse is a bit behind. Should I just grab the base Eclipse and start loading plug-ins?</p>
4
2008-12-12T23:26:53Z
367,322
<p><a href="http://www.epic-ide.org/" rel="nofollow">EPIC</a> is the only Eclipse Perl plugin I know for Perl. </p> <p>The integration is okay. Offers a graphical debugger, but watch out for inspecting data that contains cycles, as the perl exec could just go into an infinite loop</p>
0
2008-12-15T02:11:48Z
[ "php", "python", "perl", "eclipse" ]
Which Eclipse distribution is good for web development using Python, PHP, or Perl?
364,486
<p>I'd like to try out Eclipse, but I'm a bit baffled with all the different distributions of it. I mainly program in Python doing web development, but I also need to maintain PHP and Perl apps. It looks like EasyEclipse is a bit behind. Should I just grab the base Eclipse and start loading plug-ins?</p>
4
2008-12-12T23:26:53Z
6,481,753
<p>I develop in PHP, python, C(python modules), SQL and JS/HTML/CSS all on eclipse. I do this by installing PDT, CDT, pydev and SQL tools onto the eclipse-platform, and then using different workspaces for mixed projects. </p> <p>Two workspaces to be specific, one for PHP web development and another for Python/C. I do run it on a rather powerful machine so I allow eclipse the luxury of added memory (2G).</p> <p>Works like a charm and it is very nice to be able to use the same IDE for everything :)</p>
0
2011-06-26T02:17:07Z
[ "php", "python", "perl", "eclipse" ]
Which Eclipse distribution is good for web development using Python, PHP, or Perl?
364,486
<p>I'd like to try out Eclipse, but I'm a bit baffled with all the different distributions of it. I mainly program in Python doing web development, but I also need to maintain PHP and Perl apps. It looks like EasyEclipse is a bit behind. Should I just grab the base Eclipse and start loading plug-ins?</p>
4
2008-12-12T23:26:53Z
18,023,885
<p>I use the javascript eclipse helios and added pydev plugin to it for django support it seems to do everything I need.</p>
0
2013-08-02T18:36:53Z
[ "php", "python", "perl", "eclipse" ]
In Python, how do I iterate over a dictionary in sorted order?
364,519
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
136
2008-12-12T23:57:05Z
364,521
<p>Use the <a href="http://pydoc.org/2.5.1/__builtin__.html#-sorted"><code>sorted()</code></a> function:</p> <pre><code>return sorted(dict.iteritems()) </code></pre> <p>If you want an actual iterator over the sorted results, since <code>sorted()</code> returns a list, use:</p> <pre><code>return iter(sorted(dict.iteritems())) </code></pre>
63
2008-12-12T23:57:53Z
[ "python", "dictionary" ]
In Python, how do I iterate over a dictionary in sorted order?
364,519
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
136
2008-12-12T23:57:05Z
364,524
<p>Greg's answer is right. Note that in Python 3.0 you'll have to do </p> <pre><code>sorted(dict.items()) </code></pre> <p>as <code>iteritems</code> will be gone.</p>
25
2008-12-13T00:00:20Z
[ "python", "dictionary" ]
In Python, how do I iterate over a dictionary in sorted order?
364,519
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
136
2008-12-12T23:57:05Z
364,588
<p>A dict's keys are stored in a hashtable so that is their 'natural order', i.e. psuedo-random. Any other ordering is a concept of the consumer of the dict.</p> <p>sorted() always returns a list, not a dict. If you pass it a dict.items() (which produces a list of tuples), it will return a list of tuples [(k1,v1), (k2,v2), ...] which can be used in a loop in a way very much like a dict, but <em>it is not in anyway a dict</em>!</p> <pre><code>foo = { 'a': 1, 'b': 2, 'c': 3, } print foo &gt;&gt;&gt; {'a': 1, 'c': 3, 'b': 2} print foo.items() &gt;&gt;&gt; [('a', 1), ('c', 3), ('b', 2)] print sorted(foo.items()) &gt;&gt;&gt; [('a', 1), ('b', 2), ('c', 3)] </code></pre> <p>The following feels like a dict in a loop, but it's not, it's a list of tuples being unpacked into k,v:</p> <pre><code>for k,v in sorted(foo.items()): print k, v </code></pre> <p>Roughly equivalent to:</p> <pre><code>for k in sorted(foo.keys()): print k, foo[k] </code></pre>
35
2008-12-13T00:44:32Z
[ "python", "dictionary" ]
In Python, how do I iterate over a dictionary in sorted order?
364,519
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
136
2008-12-12T23:57:05Z
364,599
<p>Haven't tested this very extensively, but works in Python 2.5.2.</p> <pre><code>&gt;&gt;&gt; d = {"x":2, "h":15, "a":2222} &gt;&gt;&gt; it = iter(sorted(d.iteritems())) &gt;&gt;&gt; it.next() ('a', 2222) &gt;&gt;&gt; it.next() ('h', 15) &gt;&gt;&gt; it.next() ('x', 2) &gt;&gt;&gt; </code></pre>
100
2008-12-13T00:49:38Z
[ "python", "dictionary" ]
In Python, how do I iterate over a dictionary in sorted order?
364,519
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
136
2008-12-12T23:57:05Z
364,627
<p>sorted returns a list, hence your error when you try to iterate over it, but because you can't order a dict you will have to deal with a list.</p> <p>I have no idea what the larger context of your code is, but you could try adding an iterator to the resulting list. like this maybe?:</p> <pre><code>return iter(sorted(dict.iteritems())) </code></pre> <p>of course you will be getting back tuples now because sorted turned your dict into a list of tuples</p> <p>ex: say your dict was: <code>{'a':1,'c':3,'b':2}</code> sorted turns it into a list:</p> <pre><code>[('a',1),('b',2),('c',3)] </code></pre> <p>so when you actually iterate over the list you get back (in this example) a tuple composed of a string and an integer, but at least you will be able to iterate over it.</p>
3
2008-12-13T01:27:02Z
[ "python", "dictionary" ]
In Python, how do I iterate over a dictionary in sorted order?
364,519
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
136
2008-12-12T23:57:05Z
8,444,119
<p>If you want to sort by the order that items were inserted instead of of the order of the keys, you should have a look to Python's <a href="http://docs.python.org/py3k/library/collections.html?highlight=collections.ordereddict#collections.OrderedDict" rel="nofollow">collections.OrderedDict</a>. (Python 3 only)</p>
3
2011-12-09T10:25:31Z
[ "python", "dictionary" ]
In Python, how do I iterate over a dictionary in sorted order?
364,519
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
136
2008-12-12T23:57:05Z
11,080,546
<p>Assuming you are using CPython 2.x and have a large dictionary mydict, then using sorted(mydict) is going to be slow because sorted builds a sorted list of the keys of mydict.</p> <p>In that case you might want to look at my ordereddict package which includes a C implementation of <code>sorteddict</code> in C. Especially if you have to go over the sorted list of keys multiple times at different stages (ie. number of elements) of the dictionaries lifetime.</p> <p><a href="http://anthon.home.xs4all.nl/Python/ordereddict/" rel="nofollow">http://anthon.home.xs4all.nl/Python/ordereddict/</a></p>
2
2012-06-18T09:57:20Z
[ "python", "dictionary" ]
In Python, how do I iterate over a dictionary in sorted order?
364,519
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
136
2008-12-12T23:57:05Z
15,257,786
<p>In general, one may sort a dict like so:</p> <pre><code>for k in sorted(d): print k, d[k] </code></pre> <p>For the specific case in the question, having a "drop in replacement" for d.iteritems(), add a function like:</p> <pre><code>def sortdict(d, **opts): # **opts so any currently supported sorted() options can be passed for k in sorted(d, **opts): yield k, d[k] </code></pre> <p>and so the ending line changes from</p> <pre><code>return dict.iteritems() </code></pre> <p>to</p> <pre><code>return sortdict(dict) </code></pre> <p>or</p> <pre><code>return sortdict(dict, reverse = True) </code></pre>
5
2013-03-06T20:53:01Z
[ "python", "dictionary" ]
In Python, how do I iterate over a dictionary in sorted order?
364,519
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
136
2008-12-12T23:57:05Z
15,940,903
<pre><code>&gt;&gt;&gt; import heapq &gt;&gt;&gt; d = {"c": 2, "b": 9, "a": 4, "d": 8} &gt;&gt;&gt; def iter_sorted(d): keys = list(d) heapq.heapify(keys) # Transforms to heap in O(N) time while keys: k = heapq.heappop(keys) # takes O(log n) time yield (k, d[k]) &gt;&gt;&gt; i = iter_sorted(d) &gt;&gt;&gt; for x in i: print x ('a', 4) ('b', 9) ('c', 2) ('d', 8) </code></pre> <p>This method still has an O(N log N) sort, however, after a short linear heapify, it yields the items in sorted order as it goes, making it theoretically more efficient when you do not always need the whole list. </p>
3
2013-04-11T04:39:35Z
[ "python", "dictionary" ]
In Python, how do I iterate over a dictionary in sorted order?
364,519
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
136
2008-12-12T23:57:05Z
17,532,913
<p>You can now use <code>OrderedDict</code> in Python 2.7 as well:</p> <pre><code>&gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; d = OrderedDict([('first', 1), ... ('second', 2), ... ('third', 3)]) &gt;&gt;&gt; d.items() [('first', 1), ('second', 2), ('third', 3)] </code></pre> <p>Here you have the <a href="http://docs.python.org/dev/whatsnew/2.7.html">what's new</a> page for 2.7 version and the <a href="http://docs.python.org/dev/library/collections.html#collections.OrderedDict">OrderedDict API</a>.</p>
5
2013-07-08T17:49:52Z
[ "python", "dictionary" ]
How to get item's position in a list?
364,621
<p>I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?</p> <p>Example: </p> <pre><code>testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position </code></pre>
103
2008-12-13T01:20:32Z
364,638
<pre><code>for i in xrange(len(testlist)): if testlist[i] == 1: print i </code></pre> <p>xrange instead of range as requested (see comments).</p>
8
2008-12-13T01:33:30Z
[ "python", "list" ]
How to get item's position in a list?
364,621
<p>I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?</p> <p>Example: </p> <pre><code>testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position </code></pre>
103
2008-12-13T01:20:32Z
364,641
<p>Use enumerate:</p> <pre><code>testlist = [1,2,3,5,3,1,2,1,6] for position, item in enumerate(testlist): if item == 1: print position </code></pre>
36
2008-12-13T01:37:46Z
[ "python", "list" ]
How to get item's position in a list?
364,621
<p>I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?</p> <p>Example: </p> <pre><code>testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position </code></pre>
103
2008-12-13T01:20:32Z
364,742
<p>If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code <em>could</em> execute much faster because you don't have to iterate every value in the list.</p> <pre><code>lookingFor = 1 i = 0 index = 0 try: while i &lt; len(testlist): index = testlist.index(lookingFor,i) i = index + 1 print index except ValueError: #testlist.index() cannot find lookingFor pass </code></pre> <p>If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.</p>
0
2008-12-13T03:14:50Z
[ "python", "list" ]
How to get item's position in a list?
364,621
<p>I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?</p> <p>Example: </p> <pre><code>testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position </code></pre>
103
2008-12-13T01:20:32Z
364,769
<p>Hmmm. There was an answer with a list comprehension here, but it's disappeared.</p> <p>Here:</p> <pre><code> [i for i,x in enumerate(testlist) if x == 1] </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; testlist [1, 2, 3, 5, 3, 1, 2, 1, 6] &gt;&gt;&gt; [i for i,x in enumerate(testlist) if x == 1] [0, 5, 7] </code></pre> <p>Update:</p> <p>Okay, you want a generator expression, we'll have a generator expression. Here's the list comprehension again, in a for loop:</p> <pre><code>&gt;&gt;&gt; for i in [i for i,x in enumerate(testlist) if x == 1]: ... print i ... 0 5 7 </code></pre> <p>Now we'll construct a generator...</p> <pre><code>&gt;&gt;&gt; (i for i,x in enumerate(testlist) if x == 1) &lt;generator object at 0x6b508&gt; &gt;&gt;&gt; for i in (i for i,x in enumerate(testlist) if x == 1): ... print i ... 0 5 7 </code></pre> <p>and niftily enough, we can assign that to a variable, and use it from there...</p> <pre><code>&gt;&gt;&gt; gen = (i for i,x in enumerate(testlist) if x == 1) &gt;&gt;&gt; for i in gen: print i ... 0 5 7 </code></pre> <p>And to think I used to write FORTRAN.</p>
168
2008-12-13T03:28:26Z
[ "python", "list" ]
How to get item's position in a list?
364,621
<p>I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?</p> <p>Example: </p> <pre><code>testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position </code></pre>
103
2008-12-13T01:20:32Z
1,799,718
<pre><code>testlist = [1,2,3,5,3,1,2,1,6] for id, value in enumerate(testlist): if id == 1: print testlist[id] </code></pre> <p>I guess that it's exacly what you want. ;-) 'id' will be always the index of the values on the list.</p>
-1
2009-11-25T20:24:35Z
[ "python", "list" ]
How to get item's position in a list?
364,621
<p>I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?</p> <p>Example: </p> <pre><code>testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position </code></pre>
103
2008-12-13T01:20:32Z
10,125,837
<p>Here is another way to do this:</p> <pre><code>try: id = testlist.index('1') print testlist[id] except: print "Not Found" </code></pre>
3
2012-04-12T14:36:57Z
[ "python", "list" ]
How to get item's position in a list?
364,621
<p>I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?</p> <p>Example: </p> <pre><code>testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position </code></pre>
103
2008-12-13T01:20:32Z
10,266,829
<p>What about the following?</p> <pre><code>print testlist.index(element) </code></pre> <p>If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like</p> <pre><code>if element in testlist: print testlist.index(element) </code></pre> <p>or</p> <pre><code>print(testlist.index(element) if element in testlist else None) </code></pre>
82
2012-04-22T09:35:15Z
[ "python", "list" ]
How to get item's position in a list?
364,621
<p>I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?</p> <p>Example: </p> <pre><code>testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position </code></pre>
103
2008-12-13T01:20:32Z
12,731,878
<pre><code>[x for x in range(len(testlist)) if testlist[x]==1] </code></pre>
1
2012-10-04T16:41:33Z
[ "python", "list" ]
How to get item's position in a list?
364,621
<p>I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?</p> <p>Example: </p> <pre><code>testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position </code></pre>
103
2008-12-13T01:20:32Z
17,224,675
<p>I think that it might be useful to use the curselection() method from thte Tkinter library:</p> <pre><code>from Tkinter import * listbox.curselection() </code></pre> <p>This method works on Tkinter listbox widgets, so you'll need to construct one of them instead of a list.</p> <p>This will return a position like this:</p> <p><strong>('0',)</strong> (although later versions of Tkinter may return a list of ints instead)</p> <p>Which is for the first position and the number will change according to the item position.</p> <p>For more information, see this page: <a href="http://effbot.org/tkinterbook/listbox.htm" rel="nofollow">http://effbot.org/tkinterbook/listbox.htm</a></p> <p>Greetings.</p>
0
2013-06-20T22:06:41Z
[ "python", "list" ]
How do I use my standard python path when running python scripts from xcode macros
364,655
<p>I'm trying to run Python scripts using Xcode's User Scripts menu.</p> <p>The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them at the Terminal (or with IPython). All I get is the default path, which means I can't do things like</p> <pre><code>#!/usr/bin/python import myScript myScript.foo() </code></pre> <p>Where myScript is a module in a folder I've added to my path.</p> <p>I can append a specific path to os.sys.path manually easily enough, but I have to do it in every single script for every single path I want to use modules from</p> <p>Is there a way to set this up so it uses the same path I use everywhere else?</p> <p>EDIT: After looking into things a bit more, it seems like scripts executed from Xcode use a completely different PATH than normal. The path I get by running a script in Xcode is:</p> <pre><code>PATH=/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin </code></pre> <p>and I'm sure my regular path doesn't have /Developer/usr/bin in it. Does anybody have any idea where this path is coming from?</p>
3
2008-12-13T01:50:38Z
364,691
<p>A quick but hackish way is to have a wrapper script for python.</p> <pre><code>cat &gt; $HOME/bin/mypython &lt;&lt; EOF #!/usr/bin/python import os os.path = ['/list/of/paths/you/want'] EOF </code></pre> <p>and then start all your XCode scripts with</p> <pre><code>#!/Users/you/bin/mypython </code></pre>
1
2008-12-13T02:16:06Z
[ "python", "xcode", "osx", "path" ]
How do I use my standard python path when running python scripts from xcode macros
364,655
<p>I'm trying to run Python scripts using Xcode's User Scripts menu.</p> <p>The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them at the Terminal (or with IPython). All I get is the default path, which means I can't do things like</p> <pre><code>#!/usr/bin/python import myScript myScript.foo() </code></pre> <p>Where myScript is a module in a folder I've added to my path.</p> <p>I can append a specific path to os.sys.path manually easily enough, but I have to do it in every single script for every single path I want to use modules from</p> <p>Is there a way to set this up so it uses the same path I use everywhere else?</p> <p>EDIT: After looking into things a bit more, it seems like scripts executed from Xcode use a completely different PATH than normal. The path I get by running a script in Xcode is:</p> <pre><code>PATH=/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin </code></pre> <p>and I'm sure my regular path doesn't have /Developer/usr/bin in it. Does anybody have any idea where this path is coming from?</p>
3
2008-12-13T01:50:38Z
364,746
<p>Just add the paths to sys,path.</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', ... lots of stuff deleted....] &gt;&gt;&gt; for i in sys.path: ... print i ... /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload /Library/Python/2.5/site-packages /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/PyObjC &gt;&gt;&gt; sys.path.append("/Users/crm/lib") &gt;&gt;&gt; for i in sys.path: ... print i ... /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload /Library/Python/2.5/site-packages /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/PyObjC /Users/crm/lib &gt;&gt;&gt; </code></pre>
1
2008-12-13T03:18:11Z
[ "python", "xcode", "osx", "path" ]
How do I use my standard python path when running python scripts from xcode macros
364,655
<p>I'm trying to run Python scripts using Xcode's User Scripts menu.</p> <p>The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them at the Terminal (or with IPython). All I get is the default path, which means I can't do things like</p> <pre><code>#!/usr/bin/python import myScript myScript.foo() </code></pre> <p>Where myScript is a module in a folder I've added to my path.</p> <p>I can append a specific path to os.sys.path manually easily enough, but I have to do it in every single script for every single path I want to use modules from</p> <p>Is there a way to set this up so it uses the same path I use everywhere else?</p> <p>EDIT: After looking into things a bit more, it seems like scripts executed from Xcode use a completely different PATH than normal. The path I get by running a script in Xcode is:</p> <pre><code>PATH=/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin </code></pre> <p>and I'm sure my regular path doesn't have /Developer/usr/bin in it. Does anybody have any idea where this path is coming from?</p>
3
2008-12-13T01:50:38Z
364,759
<p>Forgive me if my answer seems ignorant, I'm not totally familiar with Mac and I also may have misunderstood your question.</p> <p>On Windows and Linux, when I want to refer to a script I've written, I set the PYTHONPATH environment variable. It is what os.sys.path gets its values from, if I remember correctly.</p> <p>Let's say myScript.py is in /Somewhere. Set PYTHONPATH to:</p> <pre><code>PYTHONPATH = /Somewhere </code></pre> <p>Now you should be able to "import myScript".</p> <p>If you start doing sub-folders as python packages, look into usage of <strong>init</strong>.py files in each folder.</p> <p>If you plan on re-using this and other scripts all the time, you should leave PYTHONPATH set as an environment variable.</p>
0
2008-12-13T03:22:09Z
[ "python", "xcode", "osx", "path" ]
How do I use my standard python path when running python scripts from xcode macros
364,655
<p>I'm trying to run Python scripts using Xcode's User Scripts menu.</p> <p>The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them at the Terminal (or with IPython). All I get is the default path, which means I can't do things like</p> <pre><code>#!/usr/bin/python import myScript myScript.foo() </code></pre> <p>Where myScript is a module in a folder I've added to my path.</p> <p>I can append a specific path to os.sys.path manually easily enough, but I have to do it in every single script for every single path I want to use modules from</p> <p>Is there a way to set this up so it uses the same path I use everywhere else?</p> <p>EDIT: After looking into things a bit more, it seems like scripts executed from Xcode use a completely different PATH than normal. The path I get by running a script in Xcode is:</p> <pre><code>PATH=/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin </code></pre> <p>and I'm sure my regular path doesn't have /Developer/usr/bin in it. Does anybody have any idea where this path is coming from?</p>
3
2008-12-13T01:50:38Z
364,835
<p>On the mac, environment variables in your .profile aren't visible to applications outside of the terminal. </p> <p>If you want an environment variable (like PATH, PYTHONPATH, etc) to be available to xcode apps, you should add it to a new plist file that you create at ~/.MacOSX/environment.plist.</p> <p>See the <a href="http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html">EnvironmentVars</a> doc on the apple developer website for more details.</p>
5
2008-12-13T04:23:46Z
[ "python", "xcode", "osx", "path" ]
How do I use my standard python path when running python scripts from xcode macros
364,655
<p>I'm trying to run Python scripts using Xcode's User Scripts menu.</p> <p>The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them at the Terminal (or with IPython). All I get is the default path, which means I can't do things like</p> <pre><code>#!/usr/bin/python import myScript myScript.foo() </code></pre> <p>Where myScript is a module in a folder I've added to my path.</p> <p>I can append a specific path to os.sys.path manually easily enough, but I have to do it in every single script for every single path I want to use modules from</p> <p>Is there a way to set this up so it uses the same path I use everywhere else?</p> <p>EDIT: After looking into things a bit more, it seems like scripts executed from Xcode use a completely different PATH than normal. The path I get by running a script in Xcode is:</p> <pre><code>PATH=/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin </code></pre> <p>and I'm sure my regular path doesn't have /Developer/usr/bin in it. Does anybody have any idea where this path is coming from?</p>
3
2008-12-13T01:50:38Z
1,685,231
<p>I tend to use <a href="http://docs.python.org/install/index.html" rel="nofollow">pth</a> files. From the docs.</p> <blockquote> <p>The most convenient way is to add a path configuration file to a directory that’s already on Python’s path, usually to the .../site-packages/ directory. Path configuration files have an extension of .pth, and each line must contain a single path that will be appended to sys.path. (Because the new paths are appended to sys.path, modules in the added directories will not override standard modules. This means you can’t use this mechanism for installing fixed versions of standard modules.)</p> </blockquote> <p>So the simplest thing to do is to do the following:</p> <pre><code>echo "/some/path/I/want/to/add" &gt; /Library/Python/2.5/site-packages/custom.pth </code></pre> <p>HTH</p>
1
2009-11-06T03:28:58Z
[ "python", "xcode", "osx", "path" ]
How do I use my standard python path when running python scripts from xcode macros
364,655
<p>I'm trying to run Python scripts using Xcode's User Scripts menu.</p> <p>The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them at the Terminal (or with IPython). All I get is the default path, which means I can't do things like</p> <pre><code>#!/usr/bin/python import myScript myScript.foo() </code></pre> <p>Where myScript is a module in a folder I've added to my path.</p> <p>I can append a specific path to os.sys.path manually easily enough, but I have to do it in every single script for every single path I want to use modules from</p> <p>Is there a way to set this up so it uses the same path I use everywhere else?</p> <p>EDIT: After looking into things a bit more, it seems like scripts executed from Xcode use a completely different PATH than normal. The path I get by running a script in Xcode is:</p> <pre><code>PATH=/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin </code></pre> <p>and I'm sure my regular path doesn't have /Developer/usr/bin in it. Does anybody have any idea where this path is coming from?</p>
3
2008-12-13T01:50:38Z
8,054,281
<p>Not sure if Xcode counts as launching the script through Finder or not, but if it does, apparently Finder doesn't read <code>.profile</code> or <code>.cshrc</code> files when it starts for a user the way Terminal does. </p> <p>If your question is unanswered still, check out Apple's knowledge base: <a href="http://developer.apple.com/library/mac/#qa/qa1067/_index.html" rel="nofollow">QA1067</a> and set up your environment using the <code>plist</code>.</p>
0
2011-11-08T17:06:47Z
[ "python", "xcode", "osx", "path" ]
generator comprehension
364,802
<p>What does generator comprehension do? How does it work? I couldn't find a tutorial about it.</p>
37
2008-12-13T03:55:44Z
364,816
<p>A generator comprehension is the lazy version of a list comprehension.</p> <p>It is just like a list comprehension except that it returns an iterator instead of the list ie an object with a next() method that will yield the next element.</p> <p>If you are not familiar with list comprehensions see <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">here</a> and for generators see <a href="http://docs.python.org/tutorial/classes.html#generators">here</a>.</p>
10
2008-12-13T04:08:34Z
[ "python" ]
generator comprehension
364,802
<p>What does generator comprehension do? How does it work? I couldn't find a tutorial about it.</p>
37
2008-12-13T03:55:44Z
364,818
<p>List/generator comprehension is a construct which you can use to create a new list/generator from an existing one.</p> <p>Let's say you want to generate the list of squares of each number from 1 to 10. You can do this in Python:</p> <pre><code>&gt;&gt;&gt; [x**2 for x in range(1,11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] </code></pre> <p>here, <code>range(1,11)</code> generates the list <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code>, but the <code>range</code> function is not a generator before Python 3.0, and therefore the construct I've used is a list comprehension.</p> <p>If I wanted to create a generator that does the same thing, I could do it like this:</p> <pre><code>&gt;&gt;&gt; (x**2 for x in xrange(1,11)) &lt;generator object at 0x7f0a79273488&gt; </code></pre> <p>In Python 3, however, <code>range</code> is a generator, so the outcome depends only on the syntax you use (square brackets or round brackets).</p>
2
2008-12-13T04:09:29Z
[ "python" ]
generator comprehension
364,802
<p>What does generator comprehension do? How does it work? I couldn't find a tutorial about it.</p>
37
2008-12-13T03:55:44Z
364,824
<p>Do you understand list comprehensions? If so, a generator expression is like a list comprehension, but instead of finding all the items you're interested and packing them into list, it waits, and yields each item out of the expression, one by one.</p> <pre><code>&gt;&gt;&gt; my_list = [1, 3, 5, 9, 2, 6] &gt;&gt;&gt; filtered_list = [item for item in my_list if item &gt; 3] &gt;&gt;&gt; print filtered_list [5, 9, 6] &gt;&gt;&gt; len(filtered_list) 3 &gt;&gt;&gt; # compare to generator expression ... &gt;&gt;&gt; filtered_gen = (item for item in my_list if item &gt; 3) &gt;&gt;&gt; print filtered_gen # notice it's a generator object &lt;generator object at 0xb7d5e02c&gt; &gt;&gt;&gt; len(filtered_gen) # So technically, it has no length Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: object of type 'generator' has no len() &gt;&gt;&gt; # We extract each item out individually. We'll do it manually first. ... &gt;&gt;&gt; filtered_gen.next() 5 &gt;&gt;&gt; filtered_gen.next() 9 &gt;&gt;&gt; filtered_gen.next() 6 &gt;&gt;&gt; filtered_gen.next() # Should be all out of items and give an error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; # Yup, the generator is spent. No values for you! ... &gt;&gt;&gt; # Let's prove it gives the same results as our list comprehension ... &gt;&gt;&gt; filtered_gen = (item for item in my_list if item &gt; 3) &gt;&gt;&gt; gen_to_list = list(filtered_gen) &gt;&gt;&gt; print gen_to_list [5, 9, 6] &gt;&gt;&gt; filtered_list == gen_to_list True &gt;&gt;&gt; </code></pre> <p>Because a generator expression only has to yield one item at a time, it can lead to big savings in memory usage. Generator expressions make the most sense in scenarios where you need to take one item at a time, do a lot of calculations based on that item, and then move on to the next item. If you need more than one value, you can also use a generator expression and grab a few at a time. If you need all the values before your program proceeds, use a list comprehension instead.</p>
76
2008-12-13T04:14:04Z
[ "python" ]
generator comprehension
364,802
<p>What does generator comprehension do? How does it work? I couldn't find a tutorial about it.</p>
37
2008-12-13T03:55:44Z
20,820,350
<p>Generator comprehension is an easy way of creating generators with a certain structure. Lets say you want a <code>generator</code> that outputs one by one all the even numbers in <code>your_list</code>. If you create it by using the function style it would be like this:</p> <pre><code>def allEvens( L ): for number in L: if number % 2 is 0: yield number evens = allEvens( yourList ) </code></pre> <p>You could achieve the same result with this generator comprehension expression:</p> <pre><code>evens = ( number for number in your_list if number % 2 == 0 ) </code></pre> <p>In both cases, when you call <code>next(evens)</code> you get the next even number in <code>your_list</code>. </p>
0
2013-12-28T23:06:29Z
[ "python" ]
generator comprehension
364,802
<p>What does generator comprehension do? How does it work? I couldn't find a tutorial about it.</p>
37
2008-12-13T03:55:44Z
27,446,011
<p>Generator comprehension is an approach to create iterables, something like a cursor which moves on a resource. If you know mysql cursor or mongodb cursor, you may be aware of that the whole actual data never gets loaded into the memory at once, but one at a time. Your cursor moves back and forth, but there is always a one row/list element in memory. </p> <p>In short, by using generators comprehension you can easily create cursors in python.</p>
0
2014-12-12T14:42:21Z
[ "python" ]
Detect windows logout in Python
365,058
<p>How can I detect, or be notified, when windows is logging out in python?</p> <p>Edit: Martin v. Löwis' answer is good, and works for a full logout but it does not work for a 'fast user switching' event like pressing win+L which is what I really need it for. <br /><br />Edit: im not using a gui this is running as a service</p>
5
2008-12-13T09:55:16Z
365,096
<p>In a console application, you can use win32api.SetConsoleCtrlHandler and look for CTRL_LOGOFF_EVENT. In a GUI application, you need a window open and wait for the WM_QUERYENDSESSION message. How precisely that works (and if it works at all) depends on your GUI library.</p>
3
2008-12-13T10:50:02Z
[ "python", "winapi" ]
Detect windows logout in Python
365,058
<p>How can I detect, or be notified, when windows is logging out in python?</p> <p>Edit: Martin v. Löwis' answer is good, and works for a full logout but it does not work for a 'fast user switching' event like pressing win+L which is what I really need it for. <br /><br />Edit: im not using a gui this is running as a service</p>
5
2008-12-13T09:55:16Z
365,232
<p>You can detect fast user switching events using the Terminal Services API, which you can access from Python using the <code>win32ts</code> module from <a href="http://sourceforge.net/projects/pywin32/">pywin32</a>. In a GUI application, call <a href="http://msdn.microsoft.com/en-us/library/aa383841.aspx">WTSRegisterSessionNotification</a> to receive notification messages, <a href="http://msdn.microsoft.com/en-us/library/aa383847.aspx">WTSUnRegisterSessionNotification</a> to stop receiving notifications, and handle the <a href="http://msdn.microsoft.com/en-us/library/aa383828.aspx"><code>WM_WTSSESSION_CHANGE</code></a> message in your window procedure.</p> <p>If you're writing a Windows service in Python, use the <a href="http://msdn.microsoft.com/en-us/library/ms685058.aspx"><code>RegisterServiceCtrlHandlerEx</code></a> function to detect fast user switching events. This is available in the pywin32 library as the <code>RegisterServiceCtrlHandler</code> function in the <code>servicemanager</code> module. In your <a href="http://msdn.microsoft.com/en-us/library/ms683241.aspx">handler function</a>, look for the <code>SERVICE_CONTROL_SESSIONCHANGE</code> notification. See also the <a href="http://msdn.microsoft.com/en-us/library/aa383828.aspx"><code>WM_WTSSESSION_CHANGE</code></a> documentation for details of the specific notification codes.</p> <p>There's some more detail in <a href="http://mail.python.org/pipermail/python-win32/2008-January/006736.html">this thread</a> from the python-win32 mailing list, which may be useful.</p> <p>I hope this helps!</p>
6
2008-12-13T13:53:12Z
[ "python", "winapi" ]
Can you change a field label in the Django Admin application?
365,082
<p>As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information?</p>
19
2008-12-13T10:30:41Z
365,236
<p>the <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#verbose-field-names">verbose name</a> of the field is the (optional) first parameter at field construction.</p>
37
2008-12-13T13:59:40Z
[ "python", "django", "django-admin", "django-forms" ]
Can you change a field label in the Django Admin application?
365,082
<p>As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information?</p>
19
2008-12-13T10:30:41Z
365,431
<p>Building on Javier's answer; if you need one label in forms (on the front-end) and another label on admin it is best to set internal (admin) one in the model and overwrite it on forms. Admin will of course use the label in the model field automatically.</p>
4
2008-12-13T16:56:52Z
[ "python", "django", "django-admin", "django-forms" ]
Can you change a field label in the Django Admin application?
365,082
<p>As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information?</p>
19
2008-12-13T10:30:41Z
14,743,532
<p>If your field is a property (a method) then you should use short_description:</p> <pre><code>class Person(models.Model): ... def address_report(self, instance): ... # short_description functions like a model field's verbose_name address_report.short_description = "Address" </code></pre>
12
2013-02-07T04:25:28Z
[ "python", "django", "django-admin", "django-forms" ]
Can you change a field label in the Django Admin application?
365,082
<p>As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information?</p>
19
2008-12-13T10:30:41Z
24,121,475
<p>As Javier suggested you can use verbose name in your fields in model.py. Example as below,</p> <pre><code>class Employee(models.Model): name = models.CharField(max_length = 100) dob = models.DateField('Date Of Birth') doj = models.DateField(verbose_name='Date Of Joining') mobile=models.IntegerField(max_length = 12) email = models.EmailField(max_length=50) bill = models.BooleanField(db_index=True,default=False) proj = models.ForeignKey(Project, verbose_name='Project') </code></pre> <p>Here the dob,doj and proj files will display its name in admin form as per the verbose_name mentioned to those fields. </p>
2
2014-06-09T13:36:37Z
[ "python", "django", "django-admin", "django-forms" ]
Can you change a field label in the Django Admin application?
365,082
<p>As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information?</p>
19
2008-12-13T10:30:41Z
40,016,382
<p><strong>Meta options</strong>¶</p> <p>Give your model metadata by using an inner class Meta, like so:</p> <pre><code>from django.db import models class MyClassName(models.Model): class Meta: verbose_name = "Question" verbose_name_plural = "Questions" </code></pre> <p>human-readable singular and plural names (verbose_name and verbose_name_plural). None are required, and adding class Meta to a model is completely optional.</p>
0
2016-10-13T08:51:27Z
[ "python", "django", "django-admin", "django-forms" ]
Cross platform keylogger
365,110
<p>I'm looking for ways to watch mouse and keyboard events on Windows, Linux and Mac from Python.</p> <p>My application is a time tracker. I'm not looking into the event, I just record the time when it happens. If there are no events for a certain time, say 10 minutes, I assume that the user has left and stop the current project.</p> <p>When the user returns (events come in again), I wait a moment (so this doesn't get triggered by the cleaning crew or your pets or an earthquake). If the events persist over a longer period of time, I assume that the user has returned and I pop up a small, inactive window where she can choose to add the time interval to "break", the current project (meeting, etc) or a different project.</p> <p>I've solved the keylogger for Windows using the <a href="http://sourceforge.net/projects/pyhook/">pyHook</a>.</p> <p>On Linux, I have found a solution but I don't like it: I can watch all device nodes in /etc/input and update a timestamp somewhere in /var or /tmp every time I see an event. There are two drawbacks: 1. I can't tell whether the event if from the user who is running the time tracker and 2. this little program needs to be run as root (not good).</p> <p>On Mac, I have no idea, yet.</p> <p>Questions:</p> <ol> <li><p>Is there a better way to know whether the user is creating events than watching the event devices on Linux?</p></li> <li><p>Any pointers how to do that on a Mac?</p></li> </ol>
9
2008-12-13T11:10:29Z
365,225
<p>There are couple of open source apps that might give you some pointers:</p> <ul> <li><a href="http://sourceforge.net/p/pykeylogger/wiki/Main_Page/" rel="nofollow">PyKeylogger</a> is python keylogger for windows and linux</li> <li><a href="http://code.google.com/p/logkext/" rel="nofollow">logKext</a> is a c++ keylogger for mac</li> </ul>
10
2008-12-13T13:46:12Z
[ "python", "cross-platform", "time-management", "keylogger" ]
Cross platform keylogger
365,110
<p>I'm looking for ways to watch mouse and keyboard events on Windows, Linux and Mac from Python.</p> <p>My application is a time tracker. I'm not looking into the event, I just record the time when it happens. If there are no events for a certain time, say 10 minutes, I assume that the user has left and stop the current project.</p> <p>When the user returns (events come in again), I wait a moment (so this doesn't get triggered by the cleaning crew or your pets or an earthquake). If the events persist over a longer period of time, I assume that the user has returned and I pop up a small, inactive window where she can choose to add the time interval to "break", the current project (meeting, etc) or a different project.</p> <p>I've solved the keylogger for Windows using the <a href="http://sourceforge.net/projects/pyhook/">pyHook</a>.</p> <p>On Linux, I have found a solution but I don't like it: I can watch all device nodes in /etc/input and update a timestamp somewhere in /var or /tmp every time I see an event. There are two drawbacks: 1. I can't tell whether the event if from the user who is running the time tracker and 2. this little program needs to be run as root (not good).</p> <p>On Mac, I have no idea, yet.</p> <p>Questions:</p> <ol> <li><p>Is there a better way to know whether the user is creating events than watching the event devices on Linux?</p></li> <li><p>Any pointers how to do that on a Mac?</p></li> </ol>
9
2008-12-13T11:10:29Z
2,074,117
<p>There's a great article on <b>Writing Linux Kernel Keyloggers</b> <br> <a href="http://www.phrack.com/issues.html?issue=59&amp;id=14#article">http://www.phrack.com/issues.html?issue=59&amp;id=14#article</a></p> <p>If you are attempting to run a honeypot, then definitely give Sebek a try:<br> <a href="https://projects.honeynet.org/sebek/">https://projects.honeynet.org/sebek/</a></p> <blockquote> <p>Sebek is a data capture tool designed to capture attacker's activities on a honeypot, without the attacker (hopefully) knowing it. It has two components. The first is a client that runs on the honeypots, its purpose is to capture all of the attackers activities (keystrokes, file uploads, passwords) then covertly send the data to the server. The second component is the server which collects the data from the honeypots. The server normally runs on the Honeywall gateway, but can also run independently. For more information on Sebek, please see <a href="http://www.honeynet.org/tools/sebek">http://www.honeynet.org/tools/sebek</a></p> </blockquote> <p>But, if you'd rather follow the script kiddie route / not learn, then try out the following apps:</p> <p>LINUX<br> <a href="http://sourceforge.net/projects/lkl/">http://sourceforge.net/projects/lkl/</a></p> <p>WINDOWS<br> <a href="http://www.rohos.com/kid-logger/">http://www.rohos.com/kid-logger/</a><br> <a href="http://code.google.com/p/freelogger/">http://code.google.com/p/freelogger/</a> <br></p> <hr> <p>ADVICE: You're better off writing your own for learning-and-profit purposes.</p>
7
2010-01-15T19:16:24Z
[ "python", "cross-platform", "time-management", "keylogger" ]
run a function in another function in N times
365,384
<p>I have ask this kind of question before, but it seems my previous question is a bit misleading due to my poor English. I'm asking again to make clear. I am really confused about it. Thanks in advance.</p> <p>Suppose I have a function A for generating the state of a cell in a certain rule, and I have another function which generates the state of a cell for N times, and each time the rule is as same as the fist function. And, yeah, don't know how to do it...</p> <pre><code>def 1st_funtion(a_matrixA) #apply some rule on a_matrixA and return a new matrix(next state of the cell) return new_matrix def 2nd_funtion(a_matrixB,repeat_times=n) #how to import the 1st_funtion and run for n times and return the final_matrix? #I know if n=1, just make final_matrix=1st_funtion(a_matrixB) return final_matrix </code></pre>
0
2008-12-13T16:24:07Z
365,404
<pre><code>def 1st_funtion(a_matrixA) #apply some rule on a_matrixA and return a new matrix(next state of the cell) return new_matrix def 2nd_funtion(a_matrixB,repeat_times) for i in range(repeat_times): a_matrixB = 1st_funtion(a_matrixB) return a_matrixB </code></pre>
2
2008-12-13T16:37:41Z
[ "python" ]
How to truncate matrix using NumPy (Python)
365,395
<p>just a quick question, if I have a matrix has n rows and m columns, how can I cut off the 4 sides of the matrix and return a new matrix? (the new matrix would have n-2 rows m-2 columns).</p> <p>Thanks in advance</p>
0
2008-12-13T16:30:16Z
365,399
<pre><code>a[1:-1, 1:-1] </code></pre>
10
2008-12-13T16:32:17Z
[ "python", "numpy" ]
How to truncate matrix using NumPy (Python)
365,395
<p>just a quick question, if I have a matrix has n rows and m columns, how can I cut off the 4 sides of the matrix and return a new matrix? (the new matrix would have n-2 rows m-2 columns).</p> <p>Thanks in advance</p>
0
2008-12-13T16:30:16Z
365,983
<p>A more general answer is:</p> <pre><code>a[[slice(1, -1) for _ in a.shape]] </code></pre>
3
2008-12-14T00:20:57Z
[ "python", "numpy" ]
best way to print data in columnar format?
365,601
<p>I am using Python to read in data in a user-unfriendly format and transform it into an easier-to-read format. The records I am outputting are usually going to be just a last name, first name, and room code. I</p> <p>I would <em>like</em> to output a series of pages, each containing a contiguous subset of the total records, divided into multiple columns, each of which contains a contiguous subset of the total records on the page. (So in other words, you'd read down the first column, move to the next column, move to the next column, etc., and then start over on the next page...)</p> <p>The problem I am facing now is that for output formats, I'm almost certainly limited to HTML (and Javascript, CSS, etc.) What is the best way to get the data into this columnar format? If I knew for certain that the printable area of the paper would hold 20 records vertically and five horizontally, for instance, I could easily print tables of 5x20, but I don't know if there's a way to indicate a page break -- and I don't know if there's any way to calculate programmatically how many records will fit on the page.</p> <p>How would you approach this?</p> <p><strong>EDIT:</strong> The reason I said that I was limited in output: I have to produce the file on one computer, then bring it to a different computer upon which we cannot install new software and on which the selection of existing software is not optimal. The file itself is only going to be used to make a physical printout (which is what the end users will actually work with), but my time on the computer that I can print from is going to be limited, so I need to have the file all ready to go and print right away without a lot of tweaking.</p> <p>Right now I've managed to find a word processor that I can use on the target machine, so I'm going to see if I can target a format that the word processor uses.</p> <p><strong>EDIT:</strong> Once I knew there was a word processor I could use, I made a simple skeleton file with the settings that I wanted (column and tab settings, monospaced font in a small point size, etc.) and then measured how many characters I got per line of a column and how many lines I got per column. I've watched the runs pretty carefully to make sure that there weren't some strange lines that somehow overflowed the characters-per-line guideline (which shouldn't happen with monospaced font, of course, but how many times do you end up having to figure out why that thing that "shouldn't" happen is happening anyways?)</p> <p>If there hadn't been a word processor on the target machine that I could use, I probably would have looked at PDF as an output format.</p>
0
2008-12-13T19:33:09Z
367,099
<p>"If I knew for certain that the printable area of the paper would hold 20 records vertically and five horizontally"</p> <p>You do know that.</p> <p>You know the size of your paper. You know the size of your font. You can easily do the math.</p> <p>"almost certainly limited to HTML..." doesn't make much sense. Is this a web application? The page can have a "Previous" and "Next" button to step through the pages? Pick a size that looks good to you and display one page full with "Previous" and "Next" buttons.</p> <p>If it's supposed to be one HTML page that prints correctly, that's hard. There are CSS things you can do, but you'll be happier creating a PDF file.</p> <p>Get <a href="http://pyx.sourceforge.net/" rel="nofollow">PyX</a> or <a href="http://www.reportlab.com/" rel="nofollow">ReportLab</a> and create a PDF that prints properly.</p> <p>I -- personally -- have no patience with any of this. I try put this kind of thing into a CSV file. My users can then open CSV with a tool spreadsheet (Open Office Org has a good one) and then adjust the columns and print with it.</p>
3
2008-12-14T22:39:53Z
[ "python", "html", "css", "formatting" ]
Tracking redirects and cookies with Python
366,037
<p>I would like to do be able to follow and track redirects and the cookies that are set by the different webpages with Python (a bit like the tamper plugin for Firefox).</p> <p>So if website1 redirects to website2 which then redirects to website3, I would like to follow that and also see what cookies each website sets. I have been looking at Urllib2 but it redirects by itself and I haven't seen a way to track the redirects.</p>
5
2008-12-14T01:26:04Z
366,424
<p>there are detailed turorial on this. In <a href="http://diveintopython.net/http_web_services/redirects.html" rel="nofollow">dive into python</a> and in <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml" rel="nofollow">voidspace</a>. The short version is that urllib2 provide handlers (That you can override ) to control redirects and cookies.</p>
2
2008-12-14T11:25:19Z
[ "python", "redirect", "urllib2" ]
how to browse to a external url from turbogears/cherrypy application?
366,421
<p>I am writing a tinyurl clone to learn turbogears. I am wondering how do i redirect my browser to the external website (say www.yahoo.com) from my cherrypy/turbogears app?</p> <p>I googled about it, but could not find much useful info.</p>
0
2008-12-14T11:23:21Z
366,433
<p>Just raise a HTTPRedirect exception, which lives in the cherrypy namespace. Like this:</p> <pre><code>raise cherrypy.HTTPRedirect("http://www.yahoo.com") </code></pre>
2
2008-12-14T11:32:32Z
[ "python", "url-routing", "cherrypy", "turbogears" ]
What is the pythonic way to avoid default parameters that are empty lists?
366,422
<p>Sometimes it seems natural to have a default parameter which is an empty list. Yet Python gives unexpected behavior in these situations. </p> <p>If for example, I have a function:</p> <pre><code>def myFunc(working_list = []): working_list.append("a") print working_list </code></pre> <p>The first time it is called with the default will work, but calls after that will use a constantly updating list.</p> <p>So, what is the pythonic way to get the behavior I desire (a fresh list on each call)?</p>
34
2008-12-14T11:23:54Z
366,430
<pre><code>def myFunc(working_list=None): if working_list is None: working_list = [] working_list.append("a") print working_list </code></pre> <p>is how I do it.</p>
68
2008-12-14T11:27:30Z
[ "python" ]
What is the pythonic way to avoid default parameters that are empty lists?
366,422
<p>Sometimes it seems natural to have a default parameter which is an empty list. Yet Python gives unexpected behavior in these situations. </p> <p>If for example, I have a function:</p> <pre><code>def myFunc(working_list = []): working_list.append("a") print working_list </code></pre> <p>The first time it is called with the default will work, but calls after that will use a constantly updating list.</p> <p>So, what is the pythonic way to get the behavior I desire (a fresh list on each call)?</p>
34
2008-12-14T11:23:54Z
366,446
<p>Not that it matters in this case, but you can use object identity to test for None:</p> <pre><code>if working_list is None: working_list = [] </code></pre> <p>You could also take advantage of how the boolean operator or is defined in python:</p> <pre><code>working_list = working_list or [] </code></pre> <p>Though this will behave unexpectedly if the caller gives you an empty list (which counts as false) as working_list and expects your function to modify the list he gave it. </p>
9
2008-12-14T11:43:57Z
[ "python" ]
What is the pythonic way to avoid default parameters that are empty lists?
366,422
<p>Sometimes it seems natural to have a default parameter which is an empty list. Yet Python gives unexpected behavior in these situations. </p> <p>If for example, I have a function:</p> <pre><code>def myFunc(working_list = []): working_list.append("a") print working_list </code></pre> <p>The first time it is called with the default will work, but calls after that will use a constantly updating list.</p> <p>So, what is the pythonic way to get the behavior I desire (a fresh list on each call)?</p>
34
2008-12-14T11:23:54Z
367,774
<p>I might be off-topic, but remember that if you just want to pass a variable number of arguments, the pythonic way is to pass a tuple <code>*args</code> or a dictionary <code>**kargs</code>. These are optional and are better than the syntax <code>myFunc([1, 2, 3])</code>.</p> <p>If you want to pass a tuple:</p> <pre><code>def myFunc(arg1, *args): print args w = [] w += args print w &gt;&gt;&gt;myFunc(1, 2, 3, 4, 5, 6, 7) (2, 3, 4, 5, 6, 7) [2, 3, 4, 5, 6, 7] </code></pre> <p>If you want to pass a dictionary:</p> <pre><code>def myFunc(arg1, **kargs): print kargs &gt;&gt;&gt;myFunc(1, option1=2, option2=3) {'option2' : 2, 'option1' : 3} </code></pre>
0
2008-12-15T08:33:39Z
[ "python" ]
What is the pythonic way to avoid default parameters that are empty lists?
366,422
<p>Sometimes it seems natural to have a default parameter which is an empty list. Yet Python gives unexpected behavior in these situations. </p> <p>If for example, I have a function:</p> <pre><code>def myFunc(working_list = []): working_list.append("a") print working_list </code></pre> <p>The first time it is called with the default will work, but calls after that will use a constantly updating list.</p> <p>So, what is the pythonic way to get the behavior I desire (a fresh list on each call)?</p>
34
2008-12-14T11:23:54Z
2,021,717
<p>If the intent of the function is to <em>modify</em> the parameter passed as <code>working_list</code>, see HenryR's answer (=None, check for None inside).</p> <p>But if you didn't intend to mutate the argument, just use it as starting point for a list, you can simply copy it:</p> <pre><code>def myFunc(starting_list = []): starting_list = list(starting_list) starting_list.append("a") print starting_list </code></pre> <p>(or in this simple case just <code>print starting_list + ["a"]</code> but I guess that was just a toy example)</p> <p>In general, mutating your arguments is bad style in Python. The only functions that are fully expected to mutate an object are methods of the object.</p> <ul> <li><p>If you do it from the C habit of "output arguments", that's completely unnecessary - you can always return multiple values as a tuple.</p></li> <li><p>If you do this to efficiently build a long list of results without building intermediate lists, consider writing it as a generator and using <code>result_list.extend(myFunc())</code> when you are calling it. This way your calling conventions remains very clean.</p></li> </ul>
7
2010-01-07T16:09:07Z
[ "python" ]
How to limit execution time of a function call in Python
366,682
<p>There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.</p>
37
2008-12-14T16:20:24Z
366,745
<p>You don't have to use threads. You can use another process to do the blocking work, for instance, maybe using the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module. If you want to share data structures between different parts of your program then <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> is a great library for giving yourself control of this, and I'd recommend it if you care about blocking and expect to have this trouble a lot. The bad news with Twisted is you have to rewrite your code to avoid any blocking, and there is a fair learning curve. </p> <p>You <em>can</em> use threads to avoid blocking, but I'd regard this as a last resort, since it exposes you to a whole world of pain. Read a good book on concurrency before even thinking about using threads in production, e.g. Jean Bacon's "Concurrent Systems". I work with a bunch of people who do really cool high performance stuff with threads, and we don't introduce threads into projects unless we really need them. </p>
3
2008-12-14T17:13:12Z
[ "python", "multithreading" ]
How to limit execution time of a function call in Python
366,682
<p>There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.</p>
37
2008-12-14T16:20:24Z
366,754
<p>The only "safe" way to do this, in any language, is to use a secondary process to do that timeout-thing, otherwise you need to build your code in such a way that it will time out safely by itself, for instance by checking the time elapsed in a loop or similar. If changing the method isn't an option, a thread will not suffice.</p> <p>Why? Because you're risking leaving things in a bad state when you do. If the thread is simply killed mid-method, locks being held, etc. will just be held, and cannot be released.</p> <p>So look at the process way, do <em>not</em> look at the thread way.</p>
4
2008-12-14T17:20:18Z
[ "python", "multithreading" ]
How to limit execution time of a function call in Python
366,682
<p>There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.</p>
37
2008-12-14T16:20:24Z
366,763
<p>I'm not sure how cross-platform this might be, but using signals and alarm might be a good way of looking at this. With a little work you could make this completely generic as well and usable in any situation.</p> <p><a href="http://docs.python.org/library/signal.html">http://docs.python.org/library/signal.html</a></p> <p>So your code is going to look something like this.</p> <pre><code>import signal def signal_handler(signum, frame): raise Exception("Timed out!") signal.signal(signal.SIGALRM, signal_handler) signal.alarm(10) # Ten seconds try: long_function_call() except Exception, msg: print "Timed out!" </code></pre>
29
2008-12-14T17:27:50Z
[ "python", "multithreading" ]
How to limit execution time of a function call in Python
366,682
<p>There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.</p>
37
2008-12-14T16:20:24Z
367,490
<p>Here's a timeout function I think I found via google and it works for me.</p> <p>From: <a href="http://code.activestate.com/recipes/473878/" rel="nofollow">http://code.activestate.com/recipes/473878/</a></p> <pre><code>def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None): '''This function will spwan a thread and run the given function using the args, kwargs and return the given default value if the timeout_duration is exceeded ''' import threading class InterruptableThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result = default def run(self): try: self.result = func(*args, **kwargs) except: self.result = default it = InterruptableThread() it.start() it.join(timeout_duration) if it.isAlive(): return it.result else: return it.result </code></pre>
2
2008-12-15T04:41:19Z
[ "python", "multithreading" ]
How to limit execution time of a function call in Python
366,682
<p>There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.</p>
37
2008-12-14T16:20:24Z
601,168
<p>An improvement on @rik.the.vik's answer would be to use the <a href="http://www.python.org/dev/peps/pep-0343/"><code>with</code> statement</a> to give the timeout function some syntactic sugar:</p> <pre><code>from __future__ import with_statement # Required in 2.5 import signal from contextlib import contextmanager class TimeoutException(Exception): pass @contextmanager def time_limit(seconds): def signal_handler(signum, frame): raise TimeoutException, "Timed out!" signal.signal(signal.SIGALRM, signal_handler) signal.alarm(seconds) try: yield finally: signal.alarm(0) try: with time_limit(10): long_function_call() except TimeoutException, msg: print "Timed out!" </code></pre>
46
2009-03-02T03:14:25Z
[ "python", "multithreading" ]
How to limit execution time of a function call in Python
366,682
<p>There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.</p>
37
2008-12-14T16:20:24Z
1,114,567
<p>Doing this from within a signal handler is dangerous: you might be inside an exception handler at the time the exception is raised, and leave things in a broken state. For example,</p> <pre><code>def function_with_enforced_timeout(): f = open_temporary_file() try: ... finally: here() unlink(f.filename) </code></pre> <p>If your exception is raised here(), the temporary file will never be deleted.</p> <p>The solution here is for asynchronous exceptions to be postponed until the code is not inside exception-handling code (an except or finally block), but Python doesn't do that.</p> <p>Note that this won't interrupt anything while executing native code; it'll only interrupt it when the function returns, so this may not help this particular case. (SIGALRM itself might interrupt the call that's blocking--but socket code typically simply retries after an EINTR.)</p> <p>Doing this with threads is a better idea, since it's more portable than signals. Since you're starting a worker thread and blocking until it finishes, there are none of the usual concurrency worries. Unfortunately, there's no way to deliver an exception asynchronously to another thread in Python (other thread APIs can do this). It'll also have the same issue with sending an exception during an exception handler, and require the same fix.</p>
7
2009-07-11T20:30:32Z
[ "python", "multithreading" ]
How to limit execution time of a function call in Python
366,682
<p>There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.</p>
37
2008-12-14T16:20:24Z
26,664,130
<p>Here's a Linux/OSX way to limit a function's running time. This is in case you don't want to use threads, and want your program to wait until the function ends, or the time limit expires.</p> <pre><code>from multiprocessing import Process from time import sleep def f(time): sleep(time) def run_with_limited_time(func, args, kwargs, time): """Runs a function with time limit :param func: The function to run :param args: The functions args, given as tuple :param kwargs: The functions keywords, given as dict :param time: The time limit in seconds :return: True if the function ended successfully. False if it was terminated. """ p = Process(target=func, args=args, kwargs=kwargs) p.start() p.join(time) if p.is_alive(): p.terminate() return False return True if __name__ == '__main__': print run_with_limited_time(f, (1.5, ), {}, 2.5) # True print run_with_limited_time(f, (3.5, ), {}, 2.5) # False </code></pre>
13
2014-10-30T22:05:02Z
[ "python", "multithreading" ]
How to limit execution time of a function call in Python
366,682
<p>There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.</p>
37
2008-12-14T16:20:24Z
35,038,906
<p>I would usually prefer using a contextmanager as suggested by @josh-lee</p> <p>But in case someone is interested in having this implemented as a decorator, here's an alternative.</p> <p>Here's how it would look like:</p> <pre class="lang-py prettyprint-override"><code>import time from timeout import timeout class Test(object): @timeout(2) def test_a(self, foo, bar): print foo time.sleep(1) print bar return 'A Done' @timeout(2) def test_b(self, foo, bar): print foo time.sleep(3) print bar return 'B Done' t = Test() print t.test_a('python', 'rocks') print t.test_b('timing', 'out') </code></pre> <p>And this is the <code>timeout.py</code> module:</p> <pre class="lang-py prettyprint-override"><code>import threading class TimeoutError(Exception): pass class InterruptableThread(threading.Thread): def __init__(self, func, *args, **kwargs): threading.Thread.__init__(self) self._func = func self._args = args self._kwargs = kwargs self._result = None def run(self): self._result = self._func(*self._args, **self._kwargs) @property def result(self): return self._result class timeout(object): def __init__(self, sec): self._sec = sec def __call__(self, f): def wrapped_f(*args, **kwargs): it = InterruptableThread(f, *args, **kwargs) it.start() it.join(self._sec) if not it.is_alive(): return it.result raise TimeoutError('execution expired') return wrapped_f </code></pre> <p>The output:</p> <pre class="lang-none prettyprint-override"><code>python rocks A Done timing Traceback (most recent call last): ... timeout.TimeoutError: execution expired out </code></pre> <p>Notice that even if the <code>TimeoutError</code> is thrown, the decorated method will continue to run in a different thread. If you would also want this thread to be "stopped" see: <a href="http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python">Is there any way to kill a Thread in Python?</a></p>
0
2016-01-27T13:38:35Z
[ "python", "multithreading" ]
How to limit execution time of a function call in Python
366,682
<p>There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.</p>
37
2008-12-14T16:20:24Z
37,648,512
<p>I prefer a context manager approach because it allows the execution of multiple python statements within a <code>with time_limit</code> statement. Because windows system does not have <code>SIGALARM</code>, a more portable and perhaps more straightforward method could be using a <code>Timer</code></p> <pre><code>from contextlib import contextmanager import threading import _thread class TimeoutException(Exception): def __init__(self, msg=''): self.msg = msg @contextmanager def time_limit(seconds, msg=''): timer = threading.Timer(seconds, lambda: _thread.interrupt_main()) timer.start() try: yield except KeyboardInterrupt: raise TimeoutException("Timed out for operation {}".format(msg)) finally: # if the action ends in specified time, timer is canceled timer.cancel() import time # ends after 5 seconds with time_limit(5, 'sleep'): for i in range(10): time.sleep(1) # this will actually end after 10 seconds with time_limit(5, 'sleep'): time.sleep(10) </code></pre> <p>The key technique here is the use of <code>_thread.interrupt_main</code> to interrupt the main thread from the timer thread. One caveat is that the main thread does not always respond to the <code>KeyboardInterrupt</code> raised by the <code>Timer</code> quickly. For example, <code>time.sleep()</code> calls a system function so a <code>KeyboardInterrupt</code> will be handled after the <code>sleep</code> call.</p>
0
2016-06-06T01:41:39Z
[ "python", "multithreading" ]
Bitwise subtraction in Python
366,706
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator">my question yesterday</a>:</p> <p>CMS kindly provided this example of using bitwise operators to add two numbers in C:</p> <pre><code>#include&lt;stdio.h&gt; int add(int x, int y) { int a, b; do { a = x &amp; y; b = x ^ y; x = a &lt;&lt; 1; y = b; } while (a); return b; } int main( void ){ printf( "6 + 3 = %d", add(6,3)); printf( "6 - 3 = %d", add(6,-3)); return 0; } </code></pre> <p>It works great and I then ported it to Python as follows:</p> <pre><code>def add(x, y): while True: a = x &amp; y b = x ^ y x = a &lt;&lt; 1 y = b if a == 0: break return b print "6 + 3 = %d" % add(6,3) print "6 - 3 = %d" % add(6,-3) </code></pre> <p>They both work for addition and the C program works for subtraction as well. However, the Python program enters an infinite loop for subtraction. I am trying to get to the bottom of this and have posted the program here for further experimentation: <a href="http://codepad.org/pb8IuLnY">http://codepad.org/pb8IuLnY</a></p> <p>Can anyone advise why there would be a difference between the way C handles this and the way CPython handles this?</p>
9
2008-12-14T16:41:28Z
366,734
<p>Shifting negative numbers doesn't have consistent interpretation between python and C.</p>
2
2008-12-14T17:04:34Z
[ "python", "low-level" ]
Bitwise subtraction in Python
366,706
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator">my question yesterday</a>:</p> <p>CMS kindly provided this example of using bitwise operators to add two numbers in C:</p> <pre><code>#include&lt;stdio.h&gt; int add(int x, int y) { int a, b; do { a = x &amp; y; b = x ^ y; x = a &lt;&lt; 1; y = b; } while (a); return b; } int main( void ){ printf( "6 + 3 = %d", add(6,3)); printf( "6 - 3 = %d", add(6,-3)); return 0; } </code></pre> <p>It works great and I then ported it to Python as follows:</p> <pre><code>def add(x, y): while True: a = x &amp; y b = x ^ y x = a &lt;&lt; 1 y = b if a == 0: break return b print "6 + 3 = %d" % add(6,3) print "6 - 3 = %d" % add(6,-3) </code></pre> <p>They both work for addition and the C program works for subtraction as well. However, the Python program enters an infinite loop for subtraction. I am trying to get to the bottom of this and have posted the program here for further experimentation: <a href="http://codepad.org/pb8IuLnY">http://codepad.org/pb8IuLnY</a></p> <p>Can anyone advise why there would be a difference between the way C handles this and the way CPython handles this?</p>
9
2008-12-14T16:41:28Z
366,735
<p>As I pointed out in my response to CMS' answer yesterday, left-shifting a negative number is undefined behavior in C so this isn't even guaranteed to work in C (the problem is how to handle the signed bit, do you shift it like a value bit or is it not affected by a shift? The standards committee couldn't agree on a behavior so it was left undefined). </p> <p>When this happens to work in C it relies on fixed bit-width integers so that the leftmost bit gets pushed off the end when you do a shift (it also requires the sign bit to be treated as a value bit for shifting purposes). All integer types in C are fixed-bit but Python numbers can be arbitrarily large. Left-shifting a number in Python just causes it to keep getting larger:</p> <pre><code>&gt;&gt;&gt; 1 &lt;&lt; 100 1267650600228229401496703205376L </code></pre> <p>You could try something like this:</p> <pre><code>x = (a &lt;&lt; 1) &amp; 0xffffffff </code></pre> <p>To limit the result to 32-bits, the problem is that the left shift operator in Python doesn't shift the sign bit of a signed number (which is part of what is required to make this particular solution work). There might be a way to change the behavior of the shift operator but I don't know how.</p>
9
2008-12-14T17:06:34Z
[ "python", "low-level" ]
Bitwise subtraction in Python
366,706
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator">my question yesterday</a>:</p> <p>CMS kindly provided this example of using bitwise operators to add two numbers in C:</p> <pre><code>#include&lt;stdio.h&gt; int add(int x, int y) { int a, b; do { a = x &amp; y; b = x ^ y; x = a &lt;&lt; 1; y = b; } while (a); return b; } int main( void ){ printf( "6 + 3 = %d", add(6,3)); printf( "6 - 3 = %d", add(6,-3)); return 0; } </code></pre> <p>It works great and I then ported it to Python as follows:</p> <pre><code>def add(x, y): while True: a = x &amp; y b = x ^ y x = a &lt;&lt; 1 y = b if a == 0: break return b print "6 + 3 = %d" % add(6,3) print "6 - 3 = %d" % add(6,-3) </code></pre> <p>They both work for addition and the C program works for subtraction as well. However, the Python program enters an infinite loop for subtraction. I am trying to get to the bottom of this and have posted the program here for further experimentation: <a href="http://codepad.org/pb8IuLnY">http://codepad.org/pb8IuLnY</a></p> <p>Can anyone advise why there would be a difference between the way C handles this and the way CPython handles this?</p>
9
2008-12-14T16:41:28Z
3,487,601
<p>if <code>i</code>, <code>j</code> are two integers:</p> <p>addition:</p> <pre><code>printf("%d",(i^j)|((i&amp;j)&lt;&lt;1)); </code></pre>
1
2010-08-15T13:43:38Z
[ "python", "low-level" ]
Bitwise subtraction in Python
366,706
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator">my question yesterday</a>:</p> <p>CMS kindly provided this example of using bitwise operators to add two numbers in C:</p> <pre><code>#include&lt;stdio.h&gt; int add(int x, int y) { int a, b; do { a = x &amp; y; b = x ^ y; x = a &lt;&lt; 1; y = b; } while (a); return b; } int main( void ){ printf( "6 + 3 = %d", add(6,3)); printf( "6 - 3 = %d", add(6,-3)); return 0; } </code></pre> <p>It works great and I then ported it to Python as follows:</p> <pre><code>def add(x, y): while True: a = x &amp; y b = x ^ y x = a &lt;&lt; 1 y = b if a == 0: break return b print "6 + 3 = %d" % add(6,3) print "6 - 3 = %d" % add(6,-3) </code></pre> <p>They both work for addition and the C program works for subtraction as well. However, the Python program enters an infinite loop for subtraction. I am trying to get to the bottom of this and have posted the program here for further experimentation: <a href="http://codepad.org/pb8IuLnY">http://codepad.org/pb8IuLnY</a></p> <p>Can anyone advise why there would be a difference between the way C handles this and the way CPython handles this?</p>
9
2008-12-14T16:41:28Z
30,786,721
<p>I've noticed that you're assuming that python works with numbers the same way as C does.<br> Thats not entirely true. Meaning C's int numbres have a fixed length of 16 bits. For detailed info on C datatypes you can refer to <a href="http://en.wikipedia.org/wiki/C_data_types" rel="nofollow">C_data_types on en.wikipedia.org</a> <br> Pyhton, on the other hand, is said to have a virtually infinite lenght for int numbers.<br> Adding positive integers may work the same way. But subtracting or adding negative integers shouldn't be a simple mapping translation. <br> An easy way to understand this is a little example on negative numbers: Imagine a fixed length integer representation of 3 bits:<br></p> <h1>Unsigned</h1> <ul> <li><code>000</code> : 0</li> <li><code>001</code> : 1</li> <li><code>010</code> : 2</li> <li><code>011</code> : 3</li> <li><code>100</code> : 4</li> <li><code>101</code> : 5</li> <li><code>110</code> : 6</li> <li><code>111</code> : 7</li> </ul> <h1>Signed:</h1> <ul> <li><code>000</code> : 0</li> <li><code>001</code> : 1</li> <li><code>010</code> : 2</li> <li><code>011</code> : 3</li> <li><code>100</code> : -4</li> <li><code>101</code> : -3</li> <li><code>110</code> : -2</li> <li><code>111</code> : -1</li> </ul> <p>This works cool because you can see that <code>1-3=1+(-3)</code>, -3 is <code>101</code> that's 5 if unsigned. So <code>1+5=6</code>, 6 : <code>110</code> : -2. This means that <code>1-3=-2</code>. <br> it also becomes buggy when overflowing: - <code>-4 + -1 = 3</code> not -5 because it's out of range! - <code>3 + 1 = -4</code> not 4 because it's out of range!</p> <p>As you may see this works for fixed length but it doesnt work this way in Python.</p>
0
2015-06-11T16:46:23Z
[ "python", "low-level" ]
How to organize python test in a way that I can run all tests in a single command?
366,720
<p>Currently my code is organized in the following tree structure:</p> <pre><code>src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_moduleA.py test_moduleB.py </code></pre> <p>Where the <code>module*.py</code> files contains the source code and the <code>test_module*.py</code> contains the <code>TestCase</code>s for the relevant module.</p> <p>With the following comands I can run the tests contained in a single file, for example:</p> <pre><code>$ cd src $ nosetests test_filesystem.py .................. ---------------------------------------------------------------------- Ran 18 tests in 0.390s OK </code></pre> <p>How can I run all tests? I tried with <code>nosetests -m 'test_.*'</code> but it doesn't work.</p> <pre><code>$cd src $ nosetests -m 'test_.*' ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK </code></pre> <p>Thanks</p>
14
2008-12-14T16:52:50Z
366,770
<p>This is probably a hotly-contested topic, but I would suggest that you separate your tests out from your modules. Set up something like this...</p> <p>Use <code>setup.py</code> to install these into the system path (or you may be able to modify environment variables to avoid the need for an "install" step).</p> <pre><code>foo/ module1.py module2.py subpackage1/ __init__.py moduleA.py moduleB.py </code></pre> <p>Now any python script anywhere can access those modules, instead of depending on finding them in the local directory. Put your tests all off to the side like this:</p> <pre><code>tests/ test_module1.py test_module2.py test_subpackage1_moduleA,py test_subpackage2_moduleB.py </code></pre> <p>I'm not sure about your <code>nosetests</code> command, but now that your tests are all in the same directory, it becomes much easier to write a wrapper script that simply imports all of the other tests in the same directory. Or if that's not possible, you can at least get away with a simple <code>bash</code> loop that gets your test files one by one:</p> <pre><code>#!/bin/bash cd tests/ for TEST_SCRIPT in test_*.py ; do nosetests -m $TEST_SCRIPT done </code></pre>
2
2008-12-14T17:37:18Z
[ "python", "unit-testing", "python-nose" ]
How to organize python test in a way that I can run all tests in a single command?
366,720
<p>Currently my code is organized in the following tree structure:</p> <pre><code>src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_moduleA.py test_moduleB.py </code></pre> <p>Where the <code>module*.py</code> files contains the source code and the <code>test_module*.py</code> contains the <code>TestCase</code>s for the relevant module.</p> <p>With the following comands I can run the tests contained in a single file, for example:</p> <pre><code>$ cd src $ nosetests test_filesystem.py .................. ---------------------------------------------------------------------- Ran 18 tests in 0.390s OK </code></pre> <p>How can I run all tests? I tried with <code>nosetests -m 'test_.*'</code> but it doesn't work.</p> <pre><code>$cd src $ nosetests -m 'test_.*' ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK </code></pre> <p>Thanks</p>
14
2008-12-14T16:52:50Z
366,819
<p>I'll give a <a href="http://www.testoob.org" rel="nofollow">Testoob</a> answer.</p> <p>Running tests in a single file is like Nose:</p> <pre><code>testoob test_foo.py </code></pre> <p>To run tests in many files you can create suites with the Testoob collectors (in each subpackage)</p> <pre><code># src/subpackage?/__init__.py def suite(): import testoob return testoob.collecting.collect_from_files("test_*.py") </code></pre> <p>and</p> <pre><code># src/alltests.py test_modules = [ 'subpackage1.suite', 'subpackage2.suite', ] def suite(): import unittest return unittest.TestLoader().loadTestsFromNames(test_modules) if __name__ == "__main__": import testoob testoob.main(defaultTest="suite") </code></pre> <p>I haven't tried your specific scenario.</p>
0
2008-12-14T18:32:47Z
[ "python", "unit-testing", "python-nose" ]
How to organize python test in a way that I can run all tests in a single command?
366,720
<p>Currently my code is organized in the following tree structure:</p> <pre><code>src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_moduleA.py test_moduleB.py </code></pre> <p>Where the <code>module*.py</code> files contains the source code and the <code>test_module*.py</code> contains the <code>TestCase</code>s for the relevant module.</p> <p>With the following comands I can run the tests contained in a single file, for example:</p> <pre><code>$ cd src $ nosetests test_filesystem.py .................. ---------------------------------------------------------------------- Ran 18 tests in 0.390s OK </code></pre> <p>How can I run all tests? I tried with <code>nosetests -m 'test_.*'</code> but it doesn't work.</p> <pre><code>$cd src $ nosetests -m 'test_.*' ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK </code></pre> <p>Thanks</p>
14
2008-12-14T16:52:50Z
366,828
<p>Whether you seperate or mix tests and modules is probably a matter of taste, although I would strongly advocate for keeping them apart (setup reasons, code stats etc).</p> <p>When you're using nosetests, make sure that all directories with tests are real packages:</p> <pre><code>src/ module1.py module2.py subpackage1/ __init__.py moduleA.py moduleB.py tests/ __init__.py test_module1.py test_module2.py subpackage1/ __init__.py test_moduleA.py test_moduleB.py </code></pre> <p>This way, you can just run <code>nosetests</code> in the toplevel directory and all tests will be found. You need to make sure that <code>src/</code> is on the <code>PYTHONPATH</code>, however, otherwise all the tests will fail due to missing imports.</p>
10
2008-12-14T18:41:31Z
[ "python", "unit-testing", "python-nose" ]
How to organize python test in a way that I can run all tests in a single command?
366,720
<p>Currently my code is organized in the following tree structure:</p> <pre><code>src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_moduleA.py test_moduleB.py </code></pre> <p>Where the <code>module*.py</code> files contains the source code and the <code>test_module*.py</code> contains the <code>TestCase</code>s for the relevant module.</p> <p>With the following comands I can run the tests contained in a single file, for example:</p> <pre><code>$ cd src $ nosetests test_filesystem.py .................. ---------------------------------------------------------------------- Ran 18 tests in 0.390s OK </code></pre> <p>How can I run all tests? I tried with <code>nosetests -m 'test_.*'</code> but it doesn't work.</p> <pre><code>$cd src $ nosetests -m 'test_.*' ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK </code></pre> <p>Thanks</p>
14
2008-12-14T16:52:50Z
367,748
<p>I don't know about nosetests, but you can achieve that with the standard unittest module. You just need to create a <code>test_all.py</code> file under your root directory, then import all your test modules. In your case:</p> <pre><code>import unittest import test_module1 import test_module2 import subpackage1 if __name__ == "__main__": allsuites = unittest.TestSuite([test_module1.suite(), \ test_module2.suite(), \ subpackage1.test_moduleA.suite(), \ subpackage1.test_moduleB.suite()]) </code></pre> <p>each module should provide the following function (example with a module with two unit tests: <code>Class1</code> and <code>Class2</code>):</p> <pre><code>def suite(): """ This defines all the tests of a module""" suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(Class1)) suite.addTest(unittest.makeSuite(Class2)) return suite if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite()) </code></pre>
4
2008-12-15T08:15:09Z
[ "python", "unit-testing", "python-nose" ]
How to organize python test in a way that I can run all tests in a single command?
366,720
<p>Currently my code is organized in the following tree structure:</p> <pre><code>src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_moduleA.py test_moduleB.py </code></pre> <p>Where the <code>module*.py</code> files contains the source code and the <code>test_module*.py</code> contains the <code>TestCase</code>s for the relevant module.</p> <p>With the following comands I can run the tests contained in a single file, for example:</p> <pre><code>$ cd src $ nosetests test_filesystem.py .................. ---------------------------------------------------------------------- Ran 18 tests in 0.390s OK </code></pre> <p>How can I run all tests? I tried with <code>nosetests -m 'test_.*'</code> but it doesn't work.</p> <pre><code>$cd src $ nosetests -m 'test_.*' ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK </code></pre> <p>Thanks</p>
14
2008-12-14T16:52:50Z
373,150
<p>If they all begin with <code>test</code> then just <code>nosetest</code> should work. Nose automatically searches for any files beginning with 'test'.</p>
7
2008-12-16T23:28:39Z
[ "python", "unit-testing", "python-nose" ]
How to localize Content of a Django application
366,838
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
9
2008-12-14T18:48:49Z
367,026
<p>It depends on who will provide the translations. If you want to provide a web interface to translation, then you need to develop that yourself, and also represent the translations in the database.</p> <p>If the same translators who translated the site will also translate the data, you can provide them with the same model that they use for the site (presumably gettext), and you can then also use gettext for this content.</p>
0
2008-12-14T21:43:39Z
[ "python", "django", "localization", "internationalization" ]
How to localize Content of a Django application
366,838
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
9
2008-12-14T18:48:49Z
367,120
<p>"i must provide a way of translating theses names and descriptions to the users."</p> <p>"Is there a natural way in django to do this?"</p> <p>Are you asking if Django can translate from language to language? Are you asking about something like <a href="http://translate.google.com/" rel="nofollow">http://translate.google.com/</a> ?</p> <p>I don't think Django can translate user input into another language.</p> <p>If you are going to do the translation for your users, this must be part of your data model.</p> <p>Django's i18n filter allows you to have a table of translation strings. The <a href="http://docs.djangoproject.com/en/dev/topics/i18n/#topics-i18n" rel="nofollow">documentation</a> says this.</p> <ol> <li>Embed translation strings in your Python code and templates. </li> <li>Get translations for those strings, in whichever languages you want to support. <strong>This is something you do manually, by hiring translators or knowing a lot of languages yourself.</strong></li> <li>Activate the locale middleware in your Django settings.</li> </ol>
1
2008-12-14T23:00:27Z
[ "python", "django", "localization", "internationalization" ]
How to localize Content of a Django application
366,838
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
9
2008-12-14T18:48:49Z
367,698
<p>I would suggest checking out <a href="http://code.google.com/p/django-multilingual/">django-multilingual</a>. It is a third party app that lets you define translation fields on your models.</p> <p>Of course, you still have to type in the actual translations, but they are stored transparently in the database (as opposed to in static PO files), which is what I believe you are asking about.</p>
10
2008-12-15T07:40:50Z
[ "python", "django", "localization", "internationalization" ]
How to localize Content of a Django application
366,838
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
9
2008-12-14T18:48:49Z
367,700
<p>There are two projects of note for translatable content in Django: <a href="http://code.google.com/p/django-multilingual/" rel="nofollow">http://code.google.com/p/django-multilingual/</a> <a href="http://code.google.com/p/transdb/" rel="nofollow">http://code.google.com/p/transdb/</a></p>
4
2008-12-15T07:42:14Z
[ "python", "django", "localization", "internationalization" ]
How to localize Content of a Django application
366,838
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
9
2008-12-14T18:48:49Z
370,889
<p>I use <a href="http://code.google.com/p/django-multilingual/" rel="nofollow">django-multilingual</a> for localize content and <a href="http://code.google.com/p/django-localeurl/" rel="nofollow">django-localeurl</a> for choosing language based on url (for example mypage/en/).</p> <p>You can see how multilingua and localeurl work on <a href="http://www.jewishkrakow.nwt/" rel="nofollow">JewishKrakow.net</a> page.</p>
5
2008-12-16T10:15:17Z
[ "python", "django", "localization", "internationalization" ]
How to localize Content of a Django application
366,838
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
9
2008-12-14T18:48:49Z
1,325,190
<p>Also looking for content localization plugin, or how to write it. Can add to the list <a href="http://github.com/foxbunny/django-i18n-model/tree/master" rel="nofollow">django-i18n-model</a></p>
0
2009-08-24T22:46:21Z
[ "python", "django", "localization", "internationalization" ]
How to localize Content of a Django application
366,838
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
9
2008-12-14T18:48:49Z
3,870,634
<p>I think you should operate in two steps:</p> <ol> <li>Get translations</li> <li>Show translated strings</li> </ol> <p>For the first step, you should tell Django that the user-inserted strings are to be translated. I think there is no native way to do so. Maybe you can extract the strings from your db putting them in locale-specific files, run 'makemessages' on them, obtaint django.po files and translate.</p> <p>Second, use ugettext to show those strings on your web application.</p> <p>Hope this can help the ones with your same problem.</p>
0
2010-10-06T08:22:18Z
[ "python", "django", "localization", "internationalization" ]
How to localize Content of a Django application
366,838
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
9
2008-12-14T18:48:49Z
3,896,455
<p>Or try this:</p> <p><a href="http://packages.python.org/django-easymode/i18n/index.html" rel="nofollow">http://packages.python.org/django-easymode/i18n/index.html</a></p> <p>It stays very close to how you would normally do a django model, you just add 1 decorator above your model. It has admin support for the translated fields, including inlines and generic inlines. Almost anything you can do with regular models and admin classes you can do with the internationalized versions.</p>
0
2010-10-09T07:32:44Z
[ "python", "django", "localization", "internationalization" ]
How to localize Content of a Django application
366,838
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
9
2008-12-14T18:48:49Z
12,482,331
<p>I have 2 languages on my site: English and Arabic Users can switch between languages clicking on a flag. In models i use a proxy model:</p> <pre><code>class Product(models.Model): name=models.CharField(max_length=100) name_ar=models.CharField(max_length=100, default='') def __unicode__(self): return self.name class Product_ar(Product): def __unicode__(self): return self.name_ar class Meta: proxy=True </code></pre> <p>In forms I use 2 forms instead of one:</p> <pre><code>class CollectionEditForm_en(forms.Form): name = forms.CharField(label=_('Name'), max_length=100, widget=forms.TextInput(attrs={'size':'50'})) product = forms.ModelChoiceField(label=_('product'), queryset=Product.objects.filter(enabled=True), empty_label=None) class CollectionEditForm_ar(forms.Form): name = forms.CharField(label=_('Name'), max_length=100, widget=forms.TextInput(attrs={'size':'50'})) product = forms.ModelChoiceField(label=_('product'), queryset=Product_ar.objects.filter(enabled=True), empty_label=None) </code></pre> <p>In code check language this way:</p> <pre><code>if request.LANGUAGE_CODE=='ar': CollectionEditForm=CollectionEditForm_ar else: CollectionEditForm=CollectionEditForm_en </code></pre> <p>So in templates i check:</p> <pre><code>{% if LANGUAGE_CODE == "ar" %} &lt;a href="/product/{{product.alias}}/"&gt;{{product.name_ar}}&lt;/a&gt; {% else %} &lt;a href="/product/{{product.alias}}/"&gt;{{product.name}}&lt;/a&gt; {% endif %} </code></pre> <p>Hope this solution will help somebody</p>
1
2012-09-18T17:49:24Z
[ "python", "django", "localization", "internationalization" ]
Deleting erroneous ReferenceProperty properties in AppEngine
367,029
<p>Most of the time, the errors you get from your model properties will happen when you're saving data. For instance, if you try saving a string as an IntegerProperty, that will result in an error.</p> <p>The one exception (no pun intended) is ReferenceProperty. If you have lots of references and you're not completely careful about leaving in bad references, it's common to be greeted with an error like "TemplateSyntaxError: Caught an exception while rendering: ReferenceProperty failed to be resolved".</p> <p>And this is if there's only one bad reference in the view. D'oh. </p> <p>I could write a try/except block to try to access all the reference properties and delete them if an exception is raised, but this functionality could surely be useful to many other developers if there was a more generic method than the one I'd be capable of writing. I imagine it would take a list of model types and try to access each reference property of each entity in each model, setting the property to None if an exception is raised.</p> <p>I'll see if I can do this myself, but it would definitely help to have some suggestions/snippets to get me started.</p>
0
2008-12-14T21:45:21Z
367,334
<p>I'm having similar difficulties for my project. As I code the beta version of my application, I do create a lot of dead link and its trully a pain to untangle things afterward. Ideally, this tool would have to also report of the offending reference so that you could pin-point problems in the code.</p>
1
2008-12-15T02:18:47Z
[ "python", "google-app-engine", "model", "referenceproperty" ]
Deleting erroneous ReferenceProperty properties in AppEngine
367,029
<p>Most of the time, the errors you get from your model properties will happen when you're saving data. For instance, if you try saving a string as an IntegerProperty, that will result in an error.</p> <p>The one exception (no pun intended) is ReferenceProperty. If you have lots of references and you're not completely careful about leaving in bad references, it's common to be greeted with an error like "TemplateSyntaxError: Caught an exception while rendering: ReferenceProperty failed to be resolved".</p> <p>And this is if there's only one bad reference in the view. D'oh. </p> <p>I could write a try/except block to try to access all the reference properties and delete them if an exception is raised, but this functionality could surely be useful to many other developers if there was a more generic method than the one I'd be capable of writing. I imagine it would take a list of model types and try to access each reference property of each entity in each model, setting the property to None if an exception is raised.</p> <p>I'll see if I can do this myself, but it would definitely help to have some suggestions/snippets to get me started.</p>
0
2008-12-14T21:45:21Z
374,241
<p>You could extend and customize ReferenceProperty to not throw this exception, but then it'll need to return something - presumably None - in which case your template will simply throw an exception when it attempts to access properties on the returned object.</p> <p>A better approach is to fetch the referenceproperty and check it's valid before rendering the template. ReferenceProperties cache their references, so prefetching won't result in extra datastore calls.</p>
0
2008-12-17T11:07:12Z
[ "python", "google-app-engine", "model", "referenceproperty" ]
Deleting erroneous ReferenceProperty properties in AppEngine
367,029
<p>Most of the time, the errors you get from your model properties will happen when you're saving data. For instance, if you try saving a string as an IntegerProperty, that will result in an error.</p> <p>The one exception (no pun intended) is ReferenceProperty. If you have lots of references and you're not completely careful about leaving in bad references, it's common to be greeted with an error like "TemplateSyntaxError: Caught an exception while rendering: ReferenceProperty failed to be resolved".</p> <p>And this is if there's only one bad reference in the view. D'oh. </p> <p>I could write a try/except block to try to access all the reference properties and delete them if an exception is raised, but this functionality could surely be useful to many other developers if there was a more generic method than the one I'd be capable of writing. I imagine it would take a list of model types and try to access each reference property of each entity in each model, setting the property to None if an exception is raised.</p> <p>I'll see if I can do this myself, but it would definitely help to have some suggestions/snippets to get me started.</p>
0
2008-12-14T21:45:21Z
2,152,183
<p>That exception is actually a bug that's been waiting to be fixed for a while (see <a href="http://code.google.com/p/googleappengine/issues/detail?id=426" rel="nofollow">http://code.google.com/p/googleappengine/issues/detail?id=426</a>). Ideally you should be able to test whether the reference is valid like this(from app engine documentation): </p> <pre><code>obj1 = db.get(obj2.reference) if not obj1: # Referenced entity was deleted. </code></pre>
0
2010-01-28T03:51:19Z
[ "python", "google-app-engine", "model", "referenceproperty" ]
No print output from child multiprocessing.Process unless the program crashes
367,053
<p>I am having trouble with the Python multiprocessing module. I am using the <code>Process</code> class to spawn a new process in order to utilize my second core. This second process loads a bunch of data into RAM and then waits patiently instead of consuming. </p> <p>I wanted to see what that process printed with the <code>print</code> command, however, I do not see anything that it prints. I only see what the parent process prints. Now this makes sense to me since they live in two different process. The second process doesn't spawn its own shell/standard output window, nor is its output sent to the parent. Yet when this process crashs, it prints everything that my script told it to print, plus the stack trace and error. </p> <p>I am wondering if there is a simple way to send the child process's print output to the first process, or have it spawn a shell/standard output so that I may debug it. I know I could create a <code>multiprocessing.Queue</code> dedicated to transmitting prints to the parent so that it may print these to standard output, but I do not feel like doing this if a simpler solution exists.</p>
12
2008-12-14T22:07:56Z
367,065
<p>Have you tried flushing stdout?</p> <pre><code>import sys print "foo" sys.stdout.flush() </code></pre>
21
2008-12-14T22:18:22Z
[ "python", "multithreading", "io", "multiprocessing" ]