title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
How frequently should Python decorators be used?
1,054,249
<p>I recently started experimenting with Python decorators (and higher-order functions) because it looked like they might make my Django unit tests more concise. e.g., instead of writing:</p> <pre><code>def visit1(): login() do_stuff() logout() </code></pre> <p>I could instead do</p> <pre><code>@handle_l...
3
2009-06-28T04:41:28Z
1,054,807
<p>Decorators are a way to hoist a common <strong>Aspect</strong> out of your code.</p> <p><a href="http://en.wikipedia.org/wiki/Aspect-oriented%5Fprogramming" rel="nofollow">Aspect-Oriented Programming</a> proponents will tell you that there are so many common aspects that AOP is essential and central. Indeed, you c...
3
2009-06-28T12:12:57Z
[ "python", "django", "decorator" ]
How to import a Python class that is in a directory above?
1,054,271
<p>I want to inherit from a class in a file that lies in a directory above the current one.</p> <p>Is it possible to relatively import that file?</p>
83
2009-06-28T04:56:25Z
1,054,281
<p>Inside a package hierarchy, use two dots, as the <a href="http://docs.python.org/reference/simple_stmts.html#the-import-statement">import statement</a> doc says:</p> <blockquote> <p>When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contai...
73
2009-06-28T05:01:14Z
[ "python", "module", "directory", "python-import" ]
How to import a Python class that is in a directory above?
1,054,271
<p>I want to inherit from a class in a file that lies in a directory above the current one.</p> <p>Is it possible to relatively import that file?</p>
83
2009-06-28T04:56:25Z
1,054,293
<p>@gimel's answer is correct <em>if</em> you can guarantee the package hierarchy he mentions. If you can't -- if your real need is as you expressed it, exclusively tied to directories and without any necessary relationship to packaging -- then you need to work on <code>__file__</code> to find out the parent directory ...
47
2009-06-28T05:07:01Z
[ "python", "module", "directory", "python-import" ]
How to import a Python class that is in a directory above?
1,054,271
<p>I want to inherit from a class in a file that lies in a directory above the current one.</p> <p>Is it possible to relatively import that file?</p>
83
2009-06-28T04:56:25Z
11,096,846
<pre><code>import sys sys.path.append("..") # Adds higher directory to python modules path. </code></pre>
32
2012-06-19T08:06:11Z
[ "python", "module", "directory", "python-import" ]
How to import a Python class that is in a directory above?
1,054,271
<p>I want to inherit from a class in a file that lies in a directory above the current one.</p> <p>Is it possible to relatively import that file?</p>
83
2009-06-28T04:56:25Z
23,103,505
<pre><code>from .. import module # Import module from a higher directory. </code></pre>
8
2014-04-16T08:05:59Z
[ "python", "module", "directory", "python-import" ]
How to import a Python class that is in a directory above?
1,054,271
<p>I want to inherit from a class in a file that lies in a directory above the current one.</p> <p>Is it possible to relatively import that file?</p>
83
2009-06-28T04:56:25Z
30,861,009
<p>I believe that when your code is all self contained in a module, you can always reference that module as a top level namespace.</p> <pre><code>foo/ __init__.py bar/ __init__.py baz/ __init__.py </code></pre> <p>.</p> <pre><code>foo/baz/__init__.py #!/usr/bin/env python2 import foo # or from foo imp...
-3
2015-06-16T07:10:50Z
[ "python", "module", "directory", "python-import" ]
How can you read keystrokes when the python program isn't in the foreground?
1,054,380
<p>I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses. </p> <p>I am the most comfortable coding this in python, but am open to other suggestions. Is this po...
4
2009-06-28T06:20:52Z
1,057,058
<p>Depending on what statistics you want to collect, maybe you do not have to write this yourself; the program <a href="http://www.workrave.org/" rel="nofollow">Workrave</a> is a program to remind you to take small breaks and does so by monitoring keyboard and mouse activity. It keeps statistics of this activity which ...
0
2009-06-29T07:53:03Z
[ "python", "keyboard", "background", "keylogger" ]
How can you read keystrokes when the python program isn't in the foreground?
1,054,380
<p>I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses. </p> <p>I am the most comfortable coding this in python, but am open to other suggestions. Is this po...
4
2009-06-28T06:20:52Z
1,191,072
<p>Unless you are planning on writing the interfaces yourself, you are going to require some library, since as other posters have pointed out, you need to access low-level key press events managed by the desktop environment.</p> <p>On Windows, the <a href="http://pypi.python.org/pypi/pyHook/1.4/" rel="nofollow">PyHook...
2
2009-07-27T22:47:08Z
[ "python", "keyboard", "background", "keylogger" ]
How can you read keystrokes when the python program isn't in the foreground?
1,054,380
<p>I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses. </p> <p>I am the most comfortable coding this in python, but am open to other suggestions. Is this po...
4
2009-06-28T06:20:52Z
1,267,515
<p>It looks like you need <a href="http://patorjk.com/keyboard-layout-analyzer/" rel="nofollow">http://patorjk.com/keyboard-layout-analyzer/</a></p> <p>This handy program will analyze a block of text and tell you how far your fingers had to travel to type it, then recommend your optimal layout.</p> <p>To answer your ...
4
2009-08-12T17:19:14Z
[ "python", "keyboard", "background", "keylogger" ]
How can you read keystrokes when the python program isn't in the foreground?
1,054,380
<p>I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses. </p> <p>I am the most comfortable coding this in python, but am open to other suggestions. Is this po...
4
2009-06-28T06:20:52Z
1,344,274
<p>As the current X server's <em>Record</em> extension seems to be broken, using <code>pykeylogger</code> for Linux doesn't really help. Take a look at <a href="http://svn.navi.cx/misc/trunk/python/evdev/" rel="nofollow"><code>evdev</code></a> and its <code>demo</code> function, instead. The solution is nastier, but it...
2
2009-08-27T23:28:23Z
[ "python", "keyboard", "background", "keylogger" ]
compound sorting in python
1,054,454
<p>I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits</p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.ac00.6703 IN...
1
2009-06-28T07:26:10Z
1,054,465
<pre><code>def lineKey (line): keyStr, rest = line.split(' ', 1) a, b = keyStr.split('/', 1) return (a, int(b)) sorted(lines, key=lineKey) </code></pre>
5
2009-06-28T07:35:28Z
[ "python", "sorting" ]
compound sorting in python
1,054,454
<p>I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits</p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.ac00.6703 IN...
1
2009-06-28T07:26:10Z
1,054,467
<p>You can define a <a href="http://docs.python.org/library/stdtypes.html#mutable-sequence-types" rel="nofollow"><code>cmp()</code> comparison function</a>, for <code>.sort([cmp[, key[, reverse]]])</code> calls:</p> <blockquote> <p>The sort() method takes optional arguments for controlling the comparisons.</p> ...
1
2009-06-28T07:36:43Z
[ "python", "sorting" ]
compound sorting in python
1,054,454
<p>I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits</p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.ac00.6703 IN...
1
2009-06-28T07:26:10Z
1,054,473
<p>to sort split each line such that you have two tuple, part before / and integer part after that, so each line should be sorted on something like ('Gi6', 12), see example below</p> <pre><code>s="""Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.a...
4
2009-06-28T07:40:41Z
[ "python", "sorting" ]
compound sorting in python
1,054,454
<p>I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits</p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.ac00.6703 IN...
1
2009-06-28T07:26:10Z
1,054,474
<p>If you are working in a unix environment, you can use "sort" to sort such lists.</p> <p>Another possibility is to use some kind of bucket sort in your python script, which should be a lot faster.</p>
0
2009-06-28T07:40:46Z
[ "python", "sorting" ]
Django official tutorial for the absolute beginner, absolutely failed!
1,054,494
<p>Not that level of failure indeed. I just completed the 4 part tutorial from djangoproject.com, my administration app works fine and my entry point url (/polls/) works well, with the exception that I get this http response: </p> <p><strong>No polls are available.</strong></p> <p>Even if the database has one registr...
2
2009-06-28T07:59:10Z
1,054,535
<p>You overlooked this paragraph in the 4. part of the tutorial:</p> <blockquote> <p>In previous parts of the tutorial, the templates have been provided with a context that contains the poll and <code>latest_poll_list</code> context variables. However, the generic views provide the variables <code>object</code> and ...
12
2009-06-28T08:40:02Z
[ "python", "django" ]
Consuming Python COM Server from .NET
1,054,849
<p>I wanted to implement python com server using win32com extensions. Then consume the server from within the .NET. I used the following example to implement the com server and it runs without a problem but when I try to consume it using C# I got FileNotFoundException with the following message "Retrieving the COM clas...
1
2009-06-28T12:36:51Z
1,054,861
<p>You need run <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow">Process Monitor</a> on your C# Executable to track down the file that is not found.</p>
0
2009-06-28T12:45:08Z
[ ".net", "python", "com" ]
Consuming Python COM Server from .NET
1,054,849
<p>I wanted to implement python com server using win32com extensions. Then consume the server from within the .NET. I used the following example to implement the com server and it runs without a problem but when I try to consume it using C# I got FileNotFoundException with the following message "Retrieving the COM clas...
1
2009-06-28T12:36:51Z
1,054,986
<p>A COM server is just a piece of software (a DLL or an executable) that will accept remote procedure calls (RPC) through a defined protocol. Part of the protocol says that the server must have a unique ID, stored in the Windows' registry. In our case, this means that you have "registered" a server that is not existin...
3
2009-06-28T14:07:55Z
[ ".net", "python", "com" ]
Recursive delete in google app engine
1,054,868
<p>I'm using google app engine with django 1.0.2 (and the django-helper) and wonder how people go about doing recursive delete. Suppose you have a model that's something like this:</p> <pre> class Top(BaseModel): pass class Bottom(BaseModel): daddy = db.ReferenceProperty(Top) </pre> <p>Now, when I delete an ...
6
2009-06-28T12:48:36Z
1,054,927
<p>Actually that behavior is GAE-specific. Django's ORM simulates "ON DELETE CASCADE" on .delete().</p> <p>I know that this is not an answer to your question, but maybe it can help you from looking in the wrong places.</p>
2
2009-06-28T13:23:27Z
[ "python", "django", "google-app-engine" ]
Recursive delete in google app engine
1,054,868
<p>I'm using google app engine with django 1.0.2 (and the django-helper) and wonder how people go about doing recursive delete. Suppose you have a model that's something like this:</p> <pre> class Top(BaseModel): pass class Bottom(BaseModel): daddy = db.ReferenceProperty(Top) </pre> <p>Now, when I delete an ...
6
2009-06-28T12:48:36Z
1,055,009
<p>If your hierarchy is only a small number of levels deep, then you might be able to do something with a field that looks like a file path:</p> <pre><code>daddy.ancestry = "greatgranddaddy/granddaddy/daddy/" me.ancestry = daddy.ancestry + me.uniquename + "/" </code></pre> <p>sort of thing. You do need unique names, ...
1
2009-06-28T14:20:07Z
[ "python", "django", "google-app-engine" ]
Recursive delete in google app engine
1,054,868
<p>I'm using google app engine with django 1.0.2 (and the django-helper) and wonder how people go about doing recursive delete. Suppose you have a model that's something like this:</p> <pre> class Top(BaseModel): pass class Bottom(BaseModel): daddy = db.ReferenceProperty(Top) </pre> <p>Now, when I delete an ...
6
2009-06-28T12:48:36Z
1,058,125
<p>You need to implement this manually, by looking up affected records and deleting them at the same time as you delete the parent record. You can simplify this, if you wish, by overriding the .delete() method on your parent class to automatically delete all related records.</p> <p>For performance reasons, you almost ...
6
2009-06-29T12:55:02Z
[ "python", "django", "google-app-engine" ]
Recursive delete in google app engine
1,054,868
<p>I'm using google app engine with django 1.0.2 (and the django-helper) and wonder how people go about doing recursive delete. Suppose you have a model that's something like this:</p> <pre> class Top(BaseModel): pass class Bottom(BaseModel): daddy = db.ReferenceProperty(Top) </pre> <p>Now, when I delete an ...
6
2009-06-28T12:48:36Z
25,092,119
<p>Reconsider the data structure. If the relationship will never change on the record lifetime, you could use "ancestors" feature of GAE:</p> <pre><code>class Top(db.Model): pass class Middle(db.Model): pass class Bottom(db.Model): pass top = Top() middles = [Middle(parent=top) for i in range(0,10)] bottoms = [Bottom...
1
2014-08-02T05:52:04Z
[ "python", "django", "google-app-engine" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out...
30
2009-06-28T13:11:38Z
1,060,706
<p>Python docs are now generated using Sphynx framework. This framework does not have texinfo output format. Currently it has:</p> <ol> <li>HTML</li> <li>latex</li> <li>plain text</li> </ol> <p>Maybe you can get what you want using the Latex output. With the text output you will lost the cross ref.</p> <p>Personnaly...
1
2009-06-29T21:34:56Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out...
30
2009-06-28T13:11:38Z
1,068,731
<p>Another "workaround" is to execute <code>pydoc</code> as suggested by Nikokrock directly in Emacs:</p> <pre><code>(defun pydoc (&amp;optional arg) (interactive) (when (not (stringp arg)) (setq arg (thing-at-point 'word))) (setq cmd (concat "pydoc " arg)) (ad-activate-regexp "auto-compile-yes-or-no-p-al...
2
2009-07-01T11:54:06Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out...
30
2009-06-28T13:11:38Z
1,080,974
<p>Michael Ernst used to maintain Info formats of Python docs:</p> <p><a href="http://www.cs.washington.edu/homes/mernst/software/#python-info" rel="nofollow">http://www.cs.washington.edu/homes/mernst/software/#python-info</a></p> <p>You can try using his makefile and html2texi script to generate an updated version. ...
2
2009-07-03T21:55:21Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out...
30
2009-06-28T13:11:38Z
3,673,619
<p>For those following this question in the hope of an answer, I found another rst2texinfo implementation which you might like to try:</p> <p><a href="http://bitbucket.org/jonwaltman/rst2texinfo/src" rel="nofollow">http://bitbucket.org/jonwaltman/rst2texinfo/src</a></p>
2
2010-09-09T03:43:26Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out...
30
2009-06-28T13:11:38Z
3,952,588
<p>Jon Waltman <a href="http://bitbucket.org/jonwaltman/sphinx-info">http://bitbucket.org/jonwaltman/sphinx-info</a> has forked sphinx and written a texinfo builder, it can build the python documentation (I've yet done it). It seems that it will be merged soon into sphinx.</p> <p>Here's the quick links for the downloa...
22
2010-10-17T08:48:56Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out...
30
2009-06-28T13:11:38Z
18,847,967
<p>I've packaged up the <a href="https://github.com/wilfred/python-info">Python docs as a texinfo file</a>. </p> <p>If you're using Emacs with MELPA, you can simply install this with <code>M-x package-install python-info</code>.</p>
7
2013-09-17T10:56:02Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
Unable to make a MySQL database of SO questions by Python
1,054,964
<p><a href="http://meta.stackexchange.com/questions/73/is-the-fastest-gun-in-the-west-solved/106#106">Brent's answer</a> suggests me that has made a database of SO questions such that he can fast analyze the questions.</p> <p>I am interested in making a similar database by MySQL such that I can practice MySQL with sim...
0
2009-06-28T13:52:05Z
1,054,985
<p>I don't know the details of how to import the data into MySQL, but the raw data of Stack Overflow is freely available: <a href="http://blog.stackoverflow.com/2009/06/stack-overflow-creative-commons-data-dump/" rel="nofollow">http://blog.stackoverflow.com/2009/06/stack-overflow-creative-commons-data-dump/</a></p> <p...
1
2009-06-28T14:06:56Z
[ "python", "mysql", "database" ]
Unable to make a MySQL database of SO questions by Python
1,054,964
<p><a href="http://meta.stackexchange.com/questions/73/is-the-fastest-gun-in-the-west-solved/106#106">Brent's answer</a> suggests me that has made a database of SO questions such that he can fast analyze the questions.</p> <p>I am interested in making a similar database by MySQL such that I can practice MySQL with sim...
0
2009-06-28T13:52:05Z
1,055,057
<p>I'm sure it's possible to work directly with the XML data dump @RichieHindle mentions, but I was much happier with @nobody_'s <a href="http://modos.org/so-export-sqlite-2009-05.torrent" rel="nofollow">sqlite</a> version -- especially after adding the indices as the README file in that sqlite version says.</p> <p>If...
1
2009-06-28T14:55:16Z
[ "python", "mysql", "database" ]
fast and easy way to template xml files in python
1,055,108
<p>Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. </p> <p>What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?</p>
2
2009-06-28T15:28:44Z
1,055,111
<p>My ancient <a href="http://code.activestate.com/recipes/52305/" rel="nofollow">YAPTU</a> and Palmer's <a href="http://code.activestate.com/recipes/465508/" rel="nofollow">yaptoo</a> variant on it should be usable if you want something very simple and lightweight -- but there are many, many other general and powerful...
1
2009-06-28T15:34:40Z
[ "python", "xml" ]
fast and easy way to template xml files in python
1,055,108
<p>Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. </p> <p>What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?</p>
2
2009-06-28T15:28:44Z
1,055,115
<p>You asked for the easiest and quickest, so see this post: <a href="http://simonwillison.net/2003/Jul/28/simpleTemplates/" rel="nofollow">http://simonwillison.net/2003/Jul/28/simpleTemplates/</a></p> <p>If you want something smarter, take a look <a href="http://www.webwareforpython.org/Papers/Templates/" rel="nofoll...
1
2009-06-28T15:37:20Z
[ "python", "xml" ]
fast and easy way to template xml files in python
1,055,108
<p>Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. </p> <p>What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?</p>
2
2009-06-28T15:28:44Z
1,055,121
<p>Two choices.</p> <ol> <li><p>A template tool, for example <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a>.</p></li> <li><p>Build the DOM object. Not as bad as it sounds. ElementTree has a pleasant factory for building XML tags and creating the necessary structure. </p></li> </ol>
3
2009-06-28T15:43:44Z
[ "python", "xml" ]
fast and easy way to template xml files in python
1,055,108
<p>Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. </p> <p>What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?</p>
2
2009-06-28T15:28:44Z
1,055,122
<p>A lightweight option is <a href="http://docs.python.org/library/xml.dom.minidom.html#module-xml.dom.minidom" rel="nofollow">xml.dom.minidom</a></p> <blockquote> <p>xml.dom.minidom is a light-weight implementation of the Document Object Model interface. It is intended to be simpler than the full DOM and also signi...
3
2009-06-28T15:44:20Z
[ "python", "xml" ]
fast and easy way to template xml files in python
1,055,108
<p>Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. </p> <p>What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?</p>
2
2009-06-28T15:28:44Z
1,055,145
<p><strong>Short answer is:</strong> You should be focusing, and dealing with, the data (i.e., python object) and not the raw XML</p> <p><strong>Basic story:</strong> XML is supposed to be a representation of some data, or data set. You don't have a lot of detail in your question about the type of data, what it repres...
1
2009-06-28T15:58:22Z
[ "python", "xml" ]
How to modify a NumPy.recarray using its two views
1,055,131
<p>I am new to Python and Numpy, and I am facing a problem, that I can not modify a numpy.recarray, when applying to masked views. I read recarray from a file, then create two masked views, then try to modify the values in for loop. Here is an example code.</p> <pre><code>import numpy as np import matplotlib.mlab as m...
1
2009-06-28T15:47:55Z
1,055,180
<p>I think you have a misconception in this term "masked views" and should (re-)read <a href="http://www.tramy.us/numpybook.pdf" rel="nofollow">The Book</a> (now freely downloadable) to clarify your understanding.</p> <p>I quote from section 3.4.2:</p> <blockquote> <p>Advanced selection is triggered when the sele...
3
2009-06-28T16:13:37Z
[ "python", "numpy", "matplotlib" ]
Unicode friendly alphabetic pattern for python regex?
1,055,160
<p>I'm looking for a pattern equivalent to \w, and which doesn't match numeric pattern. I cannot use [a-zA-Z] because I would like it to match japanese kanjis as well.</p> <p>Is there a way to write something like [\w^[0-9]] ? Is there an equivalent of [:alpha:] in python regex?</p>
4
2009-06-28T16:04:58Z
1,055,173
<pre><code>[^\W\d] </code></pre> <p>Throw out non-word characters and throw out digits. Keep the rest.</p>
11
2009-06-28T16:09:44Z
[ "python", "regex" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("...
37
2009-06-28T17:45:28Z
1,055,378
<p>Use isinstance (I don't see why it's bad practice)</p> <pre><code>import types if not isinstance(arg, types.StringTypes): </code></pre> <p>Note the use of StringTypes. It ensures that we don't forget about some obscure type of string.</p> <p>On the upside, this also works for derived string classes.</p> <pre><c...
29
2009-06-28T17:56:28Z
[ "python" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("...
37
2009-06-28T17:45:28Z
1,055,402
<p>As you point out correctly, a single string is a character sequence.</p> <p>So the thing you really want to do is to find out what kind of sequence <code>arg</code> is by using isinstance or type(a)==str.</p> <p>If you want to realize a function that takes a variable amount of parameters, you should do it like thi...
1
2009-06-28T18:09:15Z
[ "python" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("...
37
2009-06-28T17:45:28Z
1,055,540
<p>Since Python 2.6, with the introduction of abstract base classes, <code>isinstance</code> (used on ABCs, not concrete classes) is now considered perfectly acceptable. Specifically:</p> <pre><code>from abc import ABCMeta, abstractmethod class NonStringIterable: __metaclass__ = ABCMeta @abstractmethod ...
14
2009-06-28T19:11:24Z
[ "python" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("...
37
2009-06-28T17:45:28Z
17,222,092
<p>I realise this is an old post but thought it was worth adding my approach for Internet posterity. The function below seems to work for me under most circumstances with both Python 2 and 3:</p> <pre><code>def is_collection(obj): """ Returns true for any iterable which is not a string or byte sequence. """ ...
3
2013-06-20T19:23:32Z
[ "python" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("...
37
2009-06-28T17:45:28Z
27,537,028
<p>By combining previous replies, I'm using:</p> <pre><code>import types import collections #[...] if isinstance(var, types.StringTypes ) \ or not isinstance(var, collections.Iterable): #[Do stuff...] </code></pre> <p>Not 100% fools proof, but if an object is not an iterable you still can let it pass and fall ...
0
2014-12-18T00:00:41Z
[ "python" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("...
37
2009-06-28T17:45:28Z
32,496,618
<p>huh, don't get it... what's wrong with going </p> <pre><code>hasattr( x, '__iter__' ) </code></pre> <p>?</p> <p>... NB elgehelge puts this in a comment here, saying "look at my more detailed answer" but I couldn't find his/her detailed answer</p> <p><strong><em>later</em></strong></p> <p>In view of David Charle...
1
2015-09-10T08:19:34Z
[ "python" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict[...
1
2009-06-28T18:11:53Z
1,055,423
<p>Short answer is you can't.</p> <p>The assigned expression is evaluated <a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Strict_evaluation" rel="nofollow">strictly</a> when it's encountered so any changes to the terms later on don't matter.</p> <p>You could solve this with a custom dict class that overwrit...
3
2009-06-28T18:18:19Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict[...
1
2009-06-28T18:11:53Z
1,055,436
<p>Seems like an abuse of a dictionary structure. Why not create a simple class?</p> <pre><code>class Entity(object): def __init__(self, mass, volume): self.mass = mass self.volume = volume def _density(self): return self.mass / self.volume density = property(_density) </code></pre...
9
2009-06-28T18:23:36Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict[...
1
2009-06-28T18:11:53Z
1,055,438
<p>A class would do this better:</p> <pre><code>class Thing: def __init__(self, mass, volume): self._mass = mass self._volume = volume self._update_density() def _update_density(self): self._density = self._mass / self._volume def get_density(self): return self._de...
4
2009-06-28T18:24:42Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict[...
1
2009-06-28T18:11:53Z
1,055,439
<p>You would be best off creating a class for this in this case and using a dynamic property. e.g.:</p> <pre> <code> class Body(object): def __init__(self): self.mass=1.0 self.volume=0.5 @property def density(self): return self.mass/self.volume </code> </pre> <p>This will give yo...
6
2009-06-28T18:25:19Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict[...
1
2009-06-28T18:11:53Z
1,055,440
<p>Here's a quick hack on how to subclass <code>dict</code> to meet your specs, but probably not to meet Python's specs for a dictionary:</p> <pre><code>class MyDict(dict): def __getitem__(self, key): if key == 'density': return self['mass'] / self['volume'] else: return dict...
-2
2009-06-28T18:25:58Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict[...
1
2009-06-28T18:11:53Z
1,055,441
<p>The problem is that dictionaries aren't the right tool for your problem. Your question is like "how can I hammer a nail in with a screwdriver" ;-)</p> <p>Dictionaries are supposed to map keys to values and don't care about other values in the dictionary. What you want is a class</p> <pre><code>class PhysicalObject...
3
2009-06-28T18:26:23Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict[...
1
2009-06-28T18:11:53Z
1,055,457
<p>This is so easy:</p> <pre><code>&gt;&gt;&gt; mydict = {'mass':100, 'volume': 2, 'density': lambda: mydict['mass']/mydict['volume']} &gt;&gt;&gt; mydict['density']() 50 &gt;&gt;&gt; mydict['mass']=200 &gt;&gt;&gt; mydict['density']() 100 &gt;&gt;&gt; mydict['volume'] = 4 &gt;&gt;&gt; mydict['density']() 50 </code></...
1
2009-06-28T18:32:50Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict[...
1
2009-06-28T18:11:53Z
39,757,186
<p>A self-referential dictionary would almost match your second attempt (from 7 years ago) and would play nicely with any other code that uses this dictionary. In other words it will still look and act like a duck.</p> <pre><code>class MyDict(dict): def __getitem__(self,key): value=dict.__getitem__...
0
2016-09-28T20:35:33Z
[ "python", "variables", "dictionary" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have ...
7
2009-06-28T18:27:35Z
1,055,453
<p>From the Python REPL (the command-line interpreter / Read-Eval-Print-Loop), type <code>help("modules")</code> to see a list of all your available libs.</p> <p>Then to see functions within a module, do <code>help("posix")</code>, for example. If you haven't <code>import</code>ed the library yet, you have to put quo...
31
2009-06-28T18:31:07Z
[ "python" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have ...
7
2009-06-28T18:27:35Z
1,055,463
<p>Every standard python distribution has <a href="http://docs.python.org/library/index.html" rel="nofollow">these</a> libraries, which cover most of what you will need in a project.</p> <p>In case you need to find out if a library exists at runtime, you do it like this</p> <pre><code>try: import ObscureModule ex...
2
2009-06-28T18:34:55Z
[ "python" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have ...
7
2009-06-28T18:27:35Z
1,055,474
<p>On Leopard, depending on the python package you're using and the version number, the modules can be found in /Library/Python:</p> <p>/Library/Python/2.5/site-packages</p> <p>or in /Library/Frameworks</p> <p>/Library/Frameworks/Python.framework/Versions/Current/lib/python2.6/site-packages</p> <p>(it could also be...
2
2009-06-28T18:39:30Z
[ "python" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have ...
7
2009-06-28T18:27:35Z
1,055,520
<p>You can install another library: yolk.</p> <p>yolk is a python package manager and will show you everything you have added via pypi. But it will also show you site-packages added through whatever local package manager you run.</p>
3
2009-06-28T18:59:23Z
[ "python" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have ...
7
2009-06-28T18:27:35Z
1,055,554
<p>just run the Python interpeter and type the command import "lib_name" if it gives an error, you don't have the lib installed...else you are good to go</p>
1
2009-06-28T19:17:19Z
[ "python" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have ...
7
2009-06-28T18:27:35Z
1,055,787
<p>For the web server, you can run the <code>pydoc</code> module that is included in the python distribution as a script:</p> <pre><code>python /path/to/pydoc.py -p 1234 </code></pre> <p>where <code>1234</code> is the port you want the server to run at. You can then visit <code>http://localhost:1234/</code> and brows...
4
2009-06-28T21:10:09Z
[ "python" ]
item frequency in a python list of dictionaries
1,055,646
<p>Ok, so I have a list of dicts:</p> <pre><code>[{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] </code><...
7
2009-06-28T20:15:42Z
1,055,662
<p><code>collections.defaultdict</code> from the standard library to the rescue:</p> <pre><code>from collections import defaultdict LofD = [{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surna...
13
2009-06-28T20:23:10Z
[ "python", "dictionary" ]
item frequency in a python list of dictionaries
1,055,646
<p>Ok, so I have a list of dicts:</p> <pre><code>[{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] </code><...
7
2009-06-28T20:15:42Z
1,055,664
<p>This?</p> <pre><code>from collections import defaultdict fq = { 'name': defaultdict(int), 'surname': defaultdict(int), 'age': defaultdict(int) } for row in listOfDicts: for field in fq: fq[field][row[field]] += 1 print fq </code></pre>
1
2009-06-28T20:23:47Z
[ "python", "dictionary" ]
item frequency in a python list of dictionaries
1,055,646
<p>Ok, so I have a list of dicts:</p> <pre><code>[{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] </code><...
7
2009-06-28T20:15:42Z
1,055,673
<pre><code>items = [{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}] global_dict = {} for item in items: ...
2
2009-06-28T20:26:59Z
[ "python", "dictionary" ]
item frequency in a python list of dictionaries
1,055,646
<p>Ok, so I have a list of dicts:</p> <pre><code>[{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] </code><...
7
2009-06-28T20:15:42Z
1,055,680
<p>New in Python 3.1: The <code>collections.Counter</code> class:</p> <pre><code>mydict=[{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surnam...
1
2009-06-28T20:33:07Z
[ "python", "dictionary" ]
JSON serialization in Spidermonkey
1,055,805
<p>I'm using <code>python-spidermonkey</code> to run JavaScript code.</p> <p>In order to pass objects (instead of just strings) to Python, I'm thinking of returning a JSON string.</p> <p>This seems like a common issue, so I wonder whether there are any facilities for this built into either Spidermonkey or <code>pytho...
3
2009-06-28T21:19:17Z
1,056,753
<p>I would use JSON.stringify. It's part of the ECMAScript 5 standard, and it's implemented in the current version of spidermonkey. I don't know if it's in the version used by python-spidermonkey, but if it isn't, you can get a JavaScript implementation from <a href="http://www.json.org/js.html">http://www.json.org/js....
6
2009-06-29T05:54:28Z
[ "javascript", "python", "json", "spidermonkey" ]
file I/O in Spidermonkey
1,055,850
<p>Thanks to <code>python-spidermonkey</code>, using JavaScript code from Python is really easy.</p> <p>However, instead of using Python to read JS code from a file and passing the string to Spidermonkey, is there a way to read the file from within Spidermonkey (or pass the filepath as an argument, as in Rhino)?</p>
2
2009-06-28T21:40:29Z
1,057,949
<p>The SpiderMonkey as a library allows that by calling the <a href="https://developer.mozilla.org/en/SpiderMonkey/JSAPI%5FReference/JS%5FEvaluateScript" rel="nofollow"><code>JS_EvaluateScript</code></a> with a non-NULL <code>filename</code> argument.</p> <p>However, the <a href="http://code.google.com/p/python-spider...
2
2009-06-29T12:07:18Z
[ "javascript", "python", "spidermonkey" ]
file I/O in Spidermonkey
1,055,850
<p>Thanks to <code>python-spidermonkey</code>, using JavaScript code from Python is really easy.</p> <p>However, instead of using Python to read JS code from a file and passing the string to Spidermonkey, is there a way to read the file from within Spidermonkey (or pass the filepath as an argument, as in Rhino)?</p>
2
2009-06-28T21:40:29Z
1,087,978
<p>Turns out you can just bind a Python function and use it from within Spidermonkey: <a href="http://davisp.lighthouseapp.com/projects/26898/tickets/23-support-for-file-io-js_evaluatescript" rel="nofollow">http://davisp.lighthouseapp.com/projects/26898/tickets/23-support-for-file-io-js_evaluatescript</a></p> <pre><co...
2
2009-07-06T16:41:40Z
[ "javascript", "python", "spidermonkey" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,055,921
<p>We've always logged data to a <em>separate</em> database.</p> <p>This lets us query without impacting the application database. It also simplifies things if we realize that we need to disable logging or change the amount of what we log.</p> <p>But most modern logging libraries support embedding the logging into yo...
1
2009-06-28T22:26:42Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,056,010
<p>Mix file.log + db would be the best. Log into db information that you eventually might need to analyse, for example average number of users per day etc. And use file.log to store some debug information.</p>
2
2009-06-28T23:12:36Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,056,119
<p>If you decide on a log file format that is parseable, then you can log to a file and then have an external process (perhaps run by cron) that processes your log files and inserts the details into your database. This can be arranged to happen at a time when your application and database load is low.</p> <p>I always ...
1
2009-06-29T00:25:06Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,056,139
<p>Log to the DB only if it generates revenue.</p> <p>For example, for one site, we logged all advertisements placed in a web site to a database. It generated revenue. No reason to be parsing log files for something that important.</p> <p>Everything else goes to the file system.</p> <p>Log to the file system for d...
1
2009-06-29T00:37:02Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,056,213
<p>First, use a logging library like SLF4J/Logback that allows you to make this decision dynamically. Then you can tweak a configuration file and route some or all of your log messages to each of several different destinations.</p> <p>Be very careful before logging to your application database, you can easily overwhe...
10
2009-06-29T01:21:13Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,056,983
<p>Just in case you consider to tweak the standard Python logger to log to a database, this recipe might give you a head start: <a href="http://code.activestate.com/recipes/498158/" rel="nofollow">Logging to a Jabber account</a>.</p>
0
2009-06-29T07:28:01Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,057,729
<p>I would primarily use filesystem logging, just as most other answers recommend. With Python's logging package, you can easily create a database handler, by adapting the suggestion made <a href="http://stackoverflow.com/questions/935930/creating-a-logging-handler-to-connect-to-oracle/1014450#1014450">here</a>. You ca...
0
2009-06-29T11:02:58Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,057,771
<p>The type of logging depends upon what you're going to do with the data and how you are going to do it. Logging to db is advantageous if you are going to build a reporting system based upon this log db. Else you can log things in a specific format which you can parse later if you want to utilize the data for some ana...
0
2009-06-29T11:13:34Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,058,093
<p>We do both.</p> <p>We log operational information/progress/etc. to the logfile. Standard logfile stuff.</p> <p>In the database, we log statuses of operations. E.g. each item that's processed, so we can do queries on throughput/elapsed time/etc. This data is particularly useful when trending and detecting anomal...
0
2009-06-29T12:45:35Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,142,704
<p>Indeed it seems important that you can later switch between DB/File logging. Database logging seems to be much slower than plain text file logging which may become important with high log traffic. I've made a library (which can act standalone or as a handler) when I had the same requirement. It logs into database an...
0
2009-07-17T11:27:59Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests t...
10
2009-06-28T22:23:18Z
1,289,740
<p>It looks like many of you are logging some of the events to a database. I am doing the same, but its adding a bit of delay. Do any of you log to database through a message queue? If so, what do you use for queuing and what is your logging architecture like? I am using Java/J2EE.</p>
0
2009-08-17T18:53:02Z
[ "python", "logging" ]
Can two versions of the same library coexist in the same Python install?
1,055,926
<p>The C libraries have a nice form of late binding, where the exact version of the library that was used during linking is recorded, and thus an executable can find the correct file, even when several versions of the same library are installed.</p> <p>Can the same be done in Python?</p> <p>To be more specific, I wor...
2
2009-06-28T22:30:09Z
1,055,966
<p>You may want to take a look at <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a></p>
8
2009-06-28T22:52:20Z
[ "python", "shared-libraries" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involvin...
29
2009-06-28T23:37:19Z
1,056,057
<p>I recommend the <a href="http://www.linuxjournal.com/article/8497" rel="nofollow">approaches detailed here</a>. It starts by explaining how to execute strings of Python code, then from there details how to set up a Python environment to interact with your C program, call Python functions from your C code, manipulat...
9
2009-06-28T23:42:27Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involvin...
29
2009-06-28T23:37:19Z
1,056,067
<p>See the relevant chapter in the manual: <a href="http://docs.python.org/extending/" rel="nofollow">http://docs.python.org/extending/</a></p> <p>Essentially you'll have to embed the python interpreter into your program.</p>
4
2009-06-28T23:48:34Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involvin...
29
2009-06-28T23:37:19Z
1,056,087
<p>Have you considered just wrapping your python application in a shell script and invoking it from with in your C application?</p> <p>Not the most elegant solution, but it is very simple.</p>
4
2009-06-29T00:00:42Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involvin...
29
2009-06-28T23:37:19Z
1,056,105
<p>I haven't used an IPC approach for Python&lt;->C communication but it should work pretty well. I would have the C program do a standard fork-exec and use redirected <code>stdin</code> and <code>stdout</code> in the child process for the communication. A nice text-based communication will make it very easy to develop...
1
2009-06-29T00:15:01Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involvin...
29
2009-06-28T23:37:19Z
1,056,365
<p>If I had decided to go with IPC, I'd probably splurge with <a href="http://www.xmlrpc.com/" rel="nofollow">XML-RPC</a> -- cross-platform, lets you easily put the Python server project on a different node later if you want, has many excellent implementations (see <a href="http://www.xmlrpc.com/directory/1568/implemen...
1
2009-06-29T02:44:04Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involvin...
29
2009-06-28T23:37:19Z
1,621,442
<p>apparently Python need to be able to compile to win32 dll, it will solve the problem</p> <p>In such a way that converting c# code to win32 dlls will make it usable by any development tool</p>
0
2009-10-25T17:16:09Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involvin...
29
2009-06-28T23:37:19Z
32,536,011
<p>This seems quite nice <a href="http://thrift.apache.org/" rel="nofollow">http://thrift.apache.org/</a>, there is even a book about it.</p> <p>Details:</p> <blockquote> <p>The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation e...
0
2015-09-12T06:40:06Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involvin...
29
2009-06-28T23:37:19Z
33,875,127
<p>I've used the "standard" approach of <a href="https://docs.python.org/2/extending/embedding.html#embedding-python-in-another-application" rel="nofollow">Embedding Python in Another Application</a>. But it's complicated/tedious. Each new function in Python is painful to implement.</p> <p>I saw an example of <a href=...
0
2015-11-23T15:51:23Z
[ "python", "c", "interop", "cross-domain" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in ...
31
2009-06-29T00:46:06Z
1,056,154
<p>This would work:</p> <pre><code>random.choice([k for k in d for x in d[k]]) </code></pre>
32
2009-06-29T00:48:31Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in ...
31
2009-06-29T00:46:06Z
1,056,155
<p>Make a list in which each key is repeated a number of times equal to the length of its value. In your example: <code>['a', 'a', 'a', 'b', 'c', 'c']</code>. Then use <code>random.choice()</code>.</p> <p>Edit: or, less elegantly but more efficiently, try this: take the sum of the lengths of all values in the dictio...
3
2009-06-29T00:48:57Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in ...
31
2009-06-29T00:46:06Z
1,056,187
<p>Do you always know the total number of values in the dictionary? If so, this might be easy to do with the following algorithm, which can be used whenever you want to make a probabilistic selection of some items from an ordered list:</p> <ol> <li>Iterate over your list of keys.</li> <li>Generate a uniformly distribu...
17
2009-06-29T01:08:17Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in ...
31
2009-06-29T00:46:06Z
1,056,201
<p>Given that your dict fits in memory, the random.choice method should be reasonable. But assuming otherwise, the next technique is to use a list of increasing weights, and use bisect to find a randomly chosen weight.</p> <pre><code>&gt;&gt;&gt; import random, bisect &gt;&gt;&gt; items, total = [], 0 &gt;&gt;&gt; fo...
6
2009-06-29T01:17:05Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in ...
31
2009-06-29T00:46:06Z
1,056,301
<p>Here is some code that is based on a previous answer I gave for <a href="http://stackoverflow.com/questions/526255/probability-distribution-in-python/526585#526585">probability distribution in python</a> but is using the length to set the weight. It uses an iterative markov chain so that it does not need to know wha...
1
2009-06-29T02:09:23Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in ...
31
2009-06-29T00:46:06Z
1,144,955
<p>I'd say this:</p> <pre><code>random.choice("".join([k * len(d[k]) for k in d])) </code></pre> <p>This makes it clear that each k in d gets as many chances as the length of its value. Of course, it is relying on dictionary keys of length 1 that are characters....</p> <hr> <p>Much later:</p> <pre><code>table = ""...
1
2009-07-17T18:31:58Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in ...
31
2009-06-29T00:46:06Z
2,321,466
<p>Without constructing a new, possibly big list with repeated values:</p> <pre><code>def select_weighted(d): offset = random.randint(0, sum(d.itervalues())-1) for k, v in d.iteritems(): if offset &lt; v: return k offset -= v </code></pre>
8
2010-02-23T20:28:04Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in ...
31
2009-06-29T00:46:06Z
6,619,814
<p>I modified some of the other answers to come up with this. It's a bit more configurable. It takes 2 arguments, a list and a lambda function to tell it how to generate a key.</p> <pre><code>def select_weighted(lst, weight): """ Usage: select_weighted([0,1,10], weight=lambda x: x) """ thesum = sum([weight(x) fo...
0
2011-07-08T03:59:16Z
[ "python", "random", "dictionary" ]
Python 2.4 plistlib on Linux
1,056,593
<p>According to <a href="http://docs.python.org/dev/library/plistlib.html" rel="nofollow">http://docs.python.org/dev/library/plistlib.html</a>, plistlib is available to non-Mac platforms only since 2.6, but I'm wondering if there's a way to get it work on 2.4 on Linux.</p>
2
2009-06-29T04:47:15Z
1,056,644
<p>Download it and give it a try:</p> <p><a href="http://svn.python.org/projects/python/trunk/Lib/plistlib.py" rel="nofollow">http://svn.python.org/projects/python/trunk/Lib/plistlib.py</a></p> <p>(If that doesn't work, you may have more luck with the <a href="http://svn.python.org/projects/python/branches/release24-...
3
2009-06-29T05:05:20Z
[ "python", "linux" ]
Cherrypy server does not accept incoming http request on MS Windows if output (stdout) is not redirected
1,056,642
<p>It is a rather strange 'bug'. </p> <p>I have written a cherrypy based server. If I run it this way:</p> <pre><code>python simple_server.py &gt; out.txt </code></pre> <p>It works as expected. </p> <p>Without the the redirection at the end, however, the server will not accept any connection at all.</p> <p>Anyone ...
0
2009-06-29T05:05:17Z
1,056,670
<p>Are you running the script in an XP "command window"? Otherwise (if there's neither redirection nor command window available), standard output might simply be closed, which might inhibit the script (or rather its underlying framework).</p>
1
2009-06-29T05:17:07Z
[ "python", "cherrypy" ]
Cherrypy server does not accept incoming http request on MS Windows if output (stdout) is not redirected
1,056,642
<p>It is a rather strange 'bug'. </p> <p>I have written a cherrypy based server. If I run it this way:</p> <pre><code>python simple_server.py &gt; out.txt </code></pre> <p>It works as expected. </p> <p>Without the the redirection at the end, however, the server will not accept any connection at all.</p> <p>Anyone ...
0
2009-06-29T05:05:17Z
1,059,551
<p>CherryPy runs in a "development" mode by default, which includes logging startup messages to stdout. If stdout is not available, I would assume the server is not able to start successfully.</p> <p>You can change this by setting 'log.screen: False' in config (and replacing it with 'log.error_file: "/path/to/error.lo...
0
2009-06-29T17:48:07Z
[ "python", "cherrypy" ]
Python Scrapy , how to define a pipeline for an item?
1,056,651
<p>I am using scrapy to crawl different sites, for each site I have an Item (different information is extracted)</p> <p>Well, for example I have a generic pipeline (most of information is the same) but now I am crawling some google search response and the pipeline must be different.</p> <p>For example:</p> <p><code>...
12
2009-06-29T05:09:33Z
1,330,564
<p>Now only one way - check Item type in pipeline and process it or return "as is"</p> <p><em>pipelines.py</em>:</p> <pre><code>from grabbers.items import FeedItem class StoreFeedPost(object): def process_item(self, domain, item): if isinstance(item, FeedItem): #process it... return...
14
2009-08-25T19:54:00Z
[ "python", "screen-scraping", "scrapy" ]
Django failing to find apps
1,056,675
<p>I have been working on a django app on my local computer for some time now and i am trying to move it to a mediatemple container and im having a problem when i try to start up django. it gives me this traceback:</p> <pre><code>application failed to start, starting manage.py fastcgi failed:Traceback (most recent cal...
0
2009-06-29T05:19:30Z
1,057,244
<p>Steps I would take would be </p> <ol> <li>Run the dev server on your Media Template instance. If that runs successfully, it obviously is an error with your apache/nginx/whaever setup.</li> <li>I dont have experience running apps as FCGI, which it looks to em you are trying to do. It looks to me that somehow when Fc...
3
2009-06-29T08:46:50Z
[ "python", "django" ]
How to analyze IE activity when opening a specific web page
1,056,739
<p>I'd like to retrieve data from a specific webpage by using urllib library. The problem is that in order to open this page some data should be sent to the server before. If I do it with IE, i need to update first some checkboxes and then press "display data" button, which opens the desired page. Looking into the so...
1
2009-06-29T05:50:57Z
1,056,819
<p>You can use a <em>web debugging proxy</em> (e.g. <a href="http://www.fiddler2.com/fiddler2/" rel="nofollow">Fiddler</a>, <a href="http://www.charlesproxy.com/" rel="nofollow">Charles</a>) or a <em>browser addon</em> (e.g. <a href="https://addons.mozilla.org/en-US/firefox/addon/6647" rel="nofollow">HttpFox</a>, <a hr...
0
2009-06-29T06:19:28Z
[ "python", "html", "internet-explorer", "information-retrieval" ]
How to analyze IE activity when opening a specific web page
1,056,739
<p>I'd like to retrieve data from a specific webpage by using urllib library. The problem is that in order to open this page some data should be sent to the server before. If I do it with IE, i need to update first some checkboxes and then press "display data" button, which opens the desired page. Looking into the so...
1
2009-06-29T05:50:57Z
1,056,898
<p>An HTML debugging proxy would be the best tool to use in this situation. As you're using IE, I recommend <a href="http://fiddler2.com" rel="nofollow">Fiddler</a>, as it is developed by Microsoft and automatically integrates with Internet Explorer through a plugin. I personally use Fiddler all the time, and it is a r...
3
2009-06-29T06:59:13Z
[ "python", "html", "internet-explorer", "information-retrieval" ]
Python, Django, datetime
1,056,934
<p>In my model, I have 2 datetime properties:</p> <pre><code>start_date end_date </code></pre> <p>I would like to count the end date as a one week after the start_date. </p> <p>How can I accomplish this?</p>
1
2009-06-29T07:10:05Z
1,056,959
<pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; start_date = datetime.datetime.now() &gt;&gt;&gt; end_date = start_date + datetime.timedelta(7) &gt;&gt;&gt; print end_date </code></pre>
5
2009-06-29T07:19:09Z
[ "python", "django", "datetime" ]
Python, Django, datetime
1,056,934
<p>In my model, I have 2 datetime properties:</p> <pre><code>start_date end_date </code></pre> <p>I would like to count the end date as a one week after the start_date. </p> <p>How can I accomplish this?</p>
1
2009-06-29T07:10:05Z
1,056,971
<p>If you always want your end_date to be one week after the start_date, what you could do, is to make a custom save method for your model. Another option would be to use signals instead. The result would be the same, but since you are dealing with the models data, I would suggest that you go for the custom save method...
8
2009-06-29T07:24:21Z
[ "python", "django", "datetime" ]