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 to strip decorators from a function in python
1,166,118
<p>Let's say I have the following:</p> <pre><code>def with_connection(f): def decorated(*args, **kwargs): f(get_connection(...), *args, **kwargs) return decorated @with_connection def spam(connection): # Do something </code></pre> <p>I want to test the <code>spam</code> function without going through the hassle of setting up a connection (or whatever the decorator is doing).</p> <p>Given <code>spam</code>, how do I strip the decorator from it and get the underlying "undecorated" function?</p>
34
2009-07-22T15:29:41Z
1,448,145
<p>Add a do-nothing decorator:</p> <pre><code>def do_nothing(f): return f </code></pre> <p>After defining or importing with_connection but before you get to the methods that use it as a decorator, add:</p> <pre><code>if TESTING: with_connection = do_nothing </code></pre> <p>Then if you set the global TESTING to True, you will have replaced with_connection with a do-nothing decorator.</p>
0
2009-09-19T08:23:38Z
[ "python", "decorator" ]
How to strip decorators from a function in python
1,166,118
<p>Let's say I have the following:</p> <pre><code>def with_connection(f): def decorated(*args, **kwargs): f(get_connection(...), *args, **kwargs) return decorated @with_connection def spam(connection): # Do something </code></pre> <p>I want to test the <code>spam</code> function without going through the hassle of setting up a connection (or whatever the decorator is doing).</p> <p>Given <code>spam</code>, how do I strip the decorator from it and get the underlying "undecorated" function?</p>
34
2009-07-22T15:29:41Z
33,024,739
<p>There's been a bit of an update for this question. If you're using Python 3, you can use <code>__wrapped__</code> property that returns wrapped function.</p> <p>Here's an example from <a href="https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch09s03.html" rel="nofollow">Python Cookbook, 3rd edition</a></p> <pre><code>&gt;&gt;&gt; @somedecorator &gt;&gt;&gt; def add(x, y): ... return x + y ... &gt;&gt;&gt; orig_add = add.__wrapped__ &gt;&gt;&gt; orig_add(3, 4) 7 &gt;&gt;&gt; </code></pre> <p>See the discussion for more detailed use of that attribute.</p>
4
2015-10-08T19:48:06Z
[ "python", "decorator" ]
How to strip decorators from a function in python
1,166,118
<p>Let's say I have the following:</p> <pre><code>def with_connection(f): def decorated(*args, **kwargs): f(get_connection(...), *args, **kwargs) return decorated @with_connection def spam(connection): # Do something </code></pre> <p>I want to test the <code>spam</code> function without going through the hassle of setting up a connection (or whatever the decorator is doing).</p> <p>Given <code>spam</code>, how do I strip the decorator from it and get the underlying "undecorated" function?</p>
34
2009-07-22T15:29:41Z
35,418,639
<p>You can now use the <a href="https://pypi.python.org/pypi/undecorated" rel="nofollow">undecorated</a> package:</p> <pre><code>&gt;&gt;&gt; from undecorated import undecorated &gt;&gt;&gt; undecorated(spam) </code></pre> <p>It goes through the hassle of digging through all the layers of different decorators until it reaches the bottom function and doesn't require changing the original decorators. Works on both python2 and python3.</p>
0
2016-02-15T20:38:56Z
[ "python", "decorator" ]
Python textwrap Library - How to Preserve Line Breaks?
1,166,317
<p>When using Python's textwrap library, how can I turn this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>into this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx </code></pre> <p>I tried:</p> <pre><code>w = textwrap.TextWrapper(width=90,break_long_words=False) body = '\n'.join(w.wrap(body)) </code></pre> <p>But I get:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>(spacing not exact in my examples)</p>
8
2009-07-22T15:55:52Z
1,166,367
<p>try</p> <pre><code>w = textwrap.TextWrapper(width=90,break_long_words=False,replace_whitespace=False) </code></pre> <p>that seemed to fix the problem for me</p> <p>I worked that out from what I read <a href="http://docs.python.org/library/textwrap.html#textwrap.TextWrapper">here</a> (I've never used textwrap before)</p>
13
2009-07-22T16:05:14Z
[ "python", "newline", "textwrapping" ]
Python textwrap Library - How to Preserve Line Breaks?
1,166,317
<p>When using Python's textwrap library, how can I turn this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>into this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx </code></pre> <p>I tried:</p> <pre><code>w = textwrap.TextWrapper(width=90,break_long_words=False) body = '\n'.join(w.wrap(body)) </code></pre> <p>But I get:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>(spacing not exact in my examples)</p>
8
2009-07-22T15:55:52Z
1,166,382
<p>How about wrap only lines longer then 90 characters?</p> <pre><code>new_body = "" lines = body.split("\n") for line in lines: if len(line) &gt; 90: w = textwrap.TextWrapper(width=90, break_long_words=False) line = '\n'.join(w.wrap(line)) new_body += line + "\n" </code></pre>
3
2009-07-22T16:08:01Z
[ "python", "newline", "textwrapping" ]
Python textwrap Library - How to Preserve Line Breaks?
1,166,317
<p>When using Python's textwrap library, how can I turn this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>into this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx </code></pre> <p>I tried:</p> <pre><code>w = textwrap.TextWrapper(width=90,break_long_words=False) body = '\n'.join(w.wrap(body)) </code></pre> <p>But I get:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>(spacing not exact in my examples)</p>
8
2009-07-22T15:55:52Z
1,166,398
<p>It looks like it doesn't support that. This code will extend it to do what I need though:</p> <p><a href="http://code.activestate.com/recipes/358228/" rel="nofollow">http://code.activestate.com/recipes/358228/</a></p>
1
2009-07-22T16:09:25Z
[ "python", "newline", "textwrapping" ]
Python textwrap Library - How to Preserve Line Breaks?
1,166,317
<p>When using Python's textwrap library, how can I turn this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>into this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx </code></pre> <p>I tried:</p> <pre><code>w = textwrap.TextWrapper(width=90,break_long_words=False) body = '\n'.join(w.wrap(body)) </code></pre> <p>But I get:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>(spacing not exact in my examples)</p>
8
2009-07-22T15:55:52Z
1,166,402
<pre><code>lines = text.split("\n") lists = (textwrap.TextWrapper(width=90,break_long_words=False).wrap(line) for line in lines) body = "\n".join("\n".join(list) for list in lists) </code></pre>
0
2009-07-22T16:09:41Z
[ "python", "newline", "textwrapping" ]
Python textwrap Library - How to Preserve Line Breaks?
1,166,317
<p>When using Python's textwrap library, how can I turn this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>into this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx </code></pre> <p>I tried:</p> <pre><code>w = textwrap.TextWrapper(width=90,break_long_words=False) body = '\n'.join(w.wrap(body)) </code></pre> <p>But I get:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>(spacing not exact in my examples)</p>
8
2009-07-22T15:55:52Z
26,538,082
<pre><code>body = '\n'.join(['\n'.join(textwrap.wrap(line, 90, break_long_words=False, replace_whitespace=False)) for line in body.splitlines() if line.strip() != '']) </code></pre>
7
2014-10-23T21:51:52Z
[ "python", "newline", "textwrapping" ]
Python textwrap Library - How to Preserve Line Breaks?
1,166,317
<p>When using Python's textwrap library, how can I turn this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>into this:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx </code></pre> <p>I tried:</p> <pre><code>w = textwrap.TextWrapper(width=90,break_long_words=False) body = '\n'.join(w.wrap(body)) </code></pre> <p>But I get:</p> <pre><code>short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </code></pre> <p>(spacing not exact in my examples)</p>
8
2009-07-22T15:55:52Z
39,134,215
<p>I had to a similar problem formatting dynamically generated docstrings. I wanted to preserve the newlines put in place by hand <em>and</em> split any lines over a certain length. Reworking the answer by <a href="http://stackoverflow.com/users/2044053/far">@far</a> a bit, this solution worked for me. I only include it here for posterity:</p> <pre><code>import textwrap wrapArgs = {'width': 90, 'break_long_words': True, 'replace_whitespace': False} fold = lambda line, wrapArgs: textwrap.fill(line, **wrapArgs) body = '\n'.join([fold(line, wrapArgs) for line in body.splitlines()]) </code></pre>
0
2016-08-24T22:54:57Z
[ "python", "newline", "textwrapping" ]
Running Python code in different processors
1,166,392
<p>In order to do quality assurance in a critical multicore (8) workstation, I want to run the same code in different processors but not in parallel or concurrently. </p> <p>I need to run it 8 times, one run for each processor. </p> <p>What I don't know is how to select the processor I want. </p> <p>How can this be accomplished in Python?</p>
4
2009-07-22T16:08:50Z
1,166,531
<p>Which process goes on which core is normaly decided by your OS. On linux there is taskset from the schedutils package to explicitly run a program on a processor.</p> <p>Python 2.6 has a <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module that takes python functions and runs them in seperate processes, <em>probably</em> moving each new process to a different core.</p>
3
2009-07-22T16:31:32Z
[ "python", "qa", "multicore" ]
Running Python code in different processors
1,166,392
<p>In order to do quality assurance in a critical multicore (8) workstation, I want to run the same code in different processors but not in parallel or concurrently. </p> <p>I need to run it 8 times, one run for each processor. </p> <p>What I don't know is how to select the processor I want. </p> <p>How can this be accomplished in Python?</p>
4
2009-07-22T16:08:50Z
1,166,607
<p>In Linux with <a href="http://schedutils.sourceforge.net/" rel="nofollow">schedutils</a>, I believe you'd use <a href="http://linuxcommand.org/man%5Fpages/taskset1.html" rel="nofollow">taskset</a> <code>-c X python foo.py</code> to run that specific Python process on CPU <code>X</code> (exactly how you identify your CPUs may vary, but I believe numbers such as 1, 2, 3, ... should work anywhere). I'm sure Windows, BSD versions, etc, have similar commands to support direct processor assignment, but I don't know them.</p>
3
2009-07-22T16:45:28Z
[ "python", "qa", "multicore" ]
python distutils win32 version question
1,166,503
<p>So you can use distutils to create a file, such as</p> <pre><code>PIL-1.1.6.win32-py2.5.exe </code></pre> <p>which you can run and use to easily install something. However, the installation requires user input to proceed (you have to click 'OK' three times). I want to create an easily installable windows version that you can just run as a cmd line program, that doesn't require input from the user. Is this possible? Do these .exe files do it already, but you need to pass them a magic cmd line argument to work?</p>
3
2009-07-22T16:26:41Z
1,166,775
<p>You get the executable by running "setup.py bdist_wininst". You can have something simpler by running "setup.py bdist_dumb". This will produce a .zip file which, unzipped at the root of the drive where Python is installed, provided that it's installed in the same directory as the machine you've build it, will install the library.</p> <p>Now I don't know if there is an unzip command-line utility under Windows that can be used to do that; I usually have Cygwin installed on all my Windows boxes, but it may prove quite simple to just ship it with the .zip.</p>
0
2009-07-22T17:10:23Z
[ "python", "installer", "installation", "windows-installer", "distutils" ]
python distutils win32 version question
1,166,503
<p>So you can use distutils to create a file, such as</p> <pre><code>PIL-1.1.6.win32-py2.5.exe </code></pre> <p>which you can run and use to easily install something. However, the installation requires user input to proceed (you have to click 'OK' three times). I want to create an easily installable windows version that you can just run as a cmd line program, that doesn't require input from the user. Is this possible? Do these .exe files do it already, but you need to pass them a magic cmd line argument to work?</p>
3
2009-07-22T16:26:41Z
1,167,297
<p>I have done this before using a simple batch file to call setuptools' install script passing the egg file path as an argument to it. The only trouble is that you need to ensure that script is in the PATH, which it might not be.</p> <p>Assuming Python itself is in the PATH you can try something like this in a python script you would distribute with your egg (call it install.py or somesuch).</p> <pre><code>import sys from pkg_resources import load_entry_point def install_egg(egg_file_path): sys.argv[1] = egg_file_path easy_install = load_entry_point( 'setuptools==0.6c9', 'console_scripts', 'easy_install' ) easy_install() if __name__ == "__main__": install_egg("PIL-1.1.6.win32-py2.5.egg") </code></pre> <p>Essentially this does the same as the "easy_install.py" script. You're locating the entrypoint for that script, and setting up sys.argv so that the first argument points at your egg file. It should do the rest for you.</p> <p>HTH</p>
0
2009-07-22T18:40:03Z
[ "python", "installer", "installation", "windows-installer", "distutils" ]
python distutils win32 version question
1,166,503
<p>So you can use distutils to create a file, such as</p> <pre><code>PIL-1.1.6.win32-py2.5.exe </code></pre> <p>which you can run and use to easily install something. However, the installation requires user input to proceed (you have to click 'OK' three times). I want to create an easily installable windows version that you can just run as a cmd line program, that doesn't require input from the user. Is this possible? Do these .exe files do it already, but you need to pass them a magic cmd line argument to work?</p>
3
2009-07-22T16:26:41Z
1,178,338
<p>See <a href="http://mail.python.org/pipermail/distutils-sig/2007-July/007874.html" rel="nofollow">this post</a> which describes an idea to modify the stub installer like this:</p> <p>It also mentions another alternative: use <code>setup.py bdist_msi</code> instead, which will produce an msi package, that can be installed unattended</p>
1
2009-07-24T15:16:46Z
[ "python", "installer", "installation", "windows-installer", "distutils" ]
How do I filter the choices in a ModelForm that has a CharField with the choices attribute (and hence a Select Field)
1,166,649
<p>I understand I am able to filter queryset of Foreignkey or Many2ManyFields, however, how do I do that for a simple CharField that is a Select Widget (Select Tag).</p> <p>For example:</p> <pre><code>PRODUCT_STATUS = ( ("unapproved", "Unapproved"), ("approved", "Listed"), #("Backorder","Backorder"), #("oos","Out of Stock"), #("preorder","Preorder"), ("userdisabled", "User Disabled"), ("disapproved", "Disapproved by admin"), ) </code></pre> <p>and the Field:</p> <pre><code>o_status = models.CharField(max_length=100, choices=PRODUCT_STATUS, verbose_name="Product Status", default="approved") </code></pre> <p>Suppose I wish to limit it to just "approved" and "userdisabled" instead showing the full array (which is what I want to show in the admin), how do I do it?</p> <p>Thanks!</p>
1
2009-07-22T16:52:44Z
1,166,711
<pre><code>class YourModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(YourModelForm, self).__init__(*args, **kwargs) self.fields['your_field'].choices = (('a', 'A'), ('b', 'B')) class Meta: model = YourModel </code></pre> <p>I guess this ain't too different from overriding a queryset from a ForeignKey or M2M attribute.</p> <p>PS: Thanks peritus from #django at irc.freenode.net</p>
0
2009-07-22T17:03:34Z
[ "python", "django" ]
Installing usual libraries inside Google App Engine
1,166,685
<p>How should I install (or where should I put and organize) usual python libraries in Google App Engine.</p> <p>Some libraries require to be installed using setuptools. How can I install that libraries.</p>
2
2009-07-22T16:59:18Z
1,168,312
<p>Most of them can be installed using the <a href="http://pip.openplans.org/" rel="nofollow">pip</a>. </p> <p>Follow 3 first points from the <a href="http://code.google.com/p/appengine-monkey/wiki/Pylons" rel="nofollow">Google wiki</a>.</p>
3
2009-07-22T21:17:56Z
[ "python", "google-app-engine" ]
Installing usual libraries inside Google App Engine
1,166,685
<p>How should I install (or where should I put and organize) usual python libraries in Google App Engine.</p> <p>Some libraries require to be installed using setuptools. How can I install that libraries.</p>
2
2009-07-22T16:59:18Z
1,170,396
<p>You need to unpack the libraries into a subdirectory of your app, and add the library directory to the Python path in your request handler module. Any steps required by setup scripts, you'll have to execute manually, but there generally aren't any unless the library bundles a native module (which aren't supported on App Engine anyway).</p> <p>If your library contains many files, it's possible to zip them and use zipimport, but that's somewhat more complex, and has performance implications.</p> <p>For example, suppose you put a library in lib/mylibrary, under your app's directory. In your request handler module, add the following before any of your other imports:</p> <pre><code>import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "lib/mylibrary")) </code></pre> <p><em>(Note that this assumes that your request handler is in the root directory of your app.)</em></p>
5
2009-07-23T08:21:25Z
[ "python", "google-app-engine" ]
Intercept slice operations in Python
1,166,839
<p>I want to imitate a normal python list, except whenever elements are added or removed via slicing, I want to 'save' the list. Is this possible? This was my attempt but it will never print 'saving'.</p> <pre><code>class InterceptedList(list): def addSave(func): def newfunc(self, *args): func(self, *args) print 'saving' return newfunc __setslice__ = addSave(list.__setslice__) __delslice__ = addSave(list.__delslice__) &gt;&gt;&gt; l = InterceptedList() &gt;&gt;&gt; l.extend([1,2,3,4]) &gt;&gt;&gt; l [1, 2, 3, 4] &gt;&gt;&gt; l[3:] = [5] # note: 'saving' is not printed &gt;&gt;&gt; l [1, 2, 3, 5] </code></pre> <p>This does work for other methods like <code>append</code> and <code>extend</code>, just not for the slice operations.</p> <p><em>EDIT: The real problem is I'm using Jython and not Python and forgot it. The comments on the question are correct. This code does work fine in Python (2.6). However, the code nor the answers work in Jython.</em></p>
10
2009-07-22T17:18:30Z
1,166,983
<p>From the <a href="http://docs.python.org/3.1/whatsnew/3.0.html#operators-and-special-methods">Python 3 docs</a>:</p> <pre><code>__getslice__(), __setslice__() and __delslice__() were killed. The syntax a[i:j] now translates to a.__getitem__(slice(i, j)) (or __setitem__() or __delitem__(), when used as an assignment or deletion target, respectively). </code></pre>
5
2009-07-22T17:42:44Z
[ "python", "methods", "jython", "slice", "intercept" ]
Intercept slice operations in Python
1,166,839
<p>I want to imitate a normal python list, except whenever elements are added or removed via slicing, I want to 'save' the list. Is this possible? This was my attempt but it will never print 'saving'.</p> <pre><code>class InterceptedList(list): def addSave(func): def newfunc(self, *args): func(self, *args) print 'saving' return newfunc __setslice__ = addSave(list.__setslice__) __delslice__ = addSave(list.__delslice__) &gt;&gt;&gt; l = InterceptedList() &gt;&gt;&gt; l.extend([1,2,3,4]) &gt;&gt;&gt; l [1, 2, 3, 4] &gt;&gt;&gt; l[3:] = [5] # note: 'saving' is not printed &gt;&gt;&gt; l [1, 2, 3, 5] </code></pre> <p>This does work for other methods like <code>append</code> and <code>extend</code>, just not for the slice operations.</p> <p><em>EDIT: The real problem is I'm using Jython and not Python and forgot it. The comments on the question are correct. This code does work fine in Python (2.6). However, the code nor the answers work in Jython.</em></p>
10
2009-07-22T17:18:30Z
1,167,000
<p>"setslice" and "delslice" are deprecated, if you want to do the interception you need to work with python slice objects passed to "setitem" and "delitem". If you want to intecept both slices and ordinary accesses this code works perfectly in python 2.6.2.</p> <pre><code>class InterceptedList(list): def addSave(func): def newfunc(self, *args): func(self, *args) print 'saving' return newfunc def __setitem__(self, key, value): print 'saving' list.__setitem__(self, key, value) def __delitem__(self, key): print 'saving' list.__delitem__(self, key) </code></pre>
5
2009-07-22T17:44:57Z
[ "python", "methods", "jython", "slice", "intercept" ]
Intercept slice operations in Python
1,166,839
<p>I want to imitate a normal python list, except whenever elements are added or removed via slicing, I want to 'save' the list. Is this possible? This was my attempt but it will never print 'saving'.</p> <pre><code>class InterceptedList(list): def addSave(func): def newfunc(self, *args): func(self, *args) print 'saving' return newfunc __setslice__ = addSave(list.__setslice__) __delslice__ = addSave(list.__delslice__) &gt;&gt;&gt; l = InterceptedList() &gt;&gt;&gt; l.extend([1,2,3,4]) &gt;&gt;&gt; l [1, 2, 3, 4] &gt;&gt;&gt; l[3:] = [5] # note: 'saving' is not printed &gt;&gt;&gt; l [1, 2, 3, 5] </code></pre> <p>This does work for other methods like <code>append</code> and <code>extend</code>, just not for the slice operations.</p> <p><em>EDIT: The real problem is I'm using Jython and not Python and forgot it. The comments on the question are correct. This code does work fine in Python (2.6). However, the code nor the answers work in Jython.</em></p>
10
2009-07-22T17:18:30Z
1,167,311
<p>the circumstances where <code>__getslice__</code> and <code>__setslice__</code> are called are pretty narrow. Specifically, slicing only occurs when you use a regular slice, where the first and end elements are mentioned exactly once. for any other slice syntax, or no slices at all, <code>__getitem__</code> or <code>__setitem__</code> is called. </p>
4
2009-07-22T18:41:17Z
[ "python", "methods", "jython", "slice", "intercept" ]
Intercept slice operations in Python
1,166,839
<p>I want to imitate a normal python list, except whenever elements are added or removed via slicing, I want to 'save' the list. Is this possible? This was my attempt but it will never print 'saving'.</p> <pre><code>class InterceptedList(list): def addSave(func): def newfunc(self, *args): func(self, *args) print 'saving' return newfunc __setslice__ = addSave(list.__setslice__) __delslice__ = addSave(list.__delslice__) &gt;&gt;&gt; l = InterceptedList() &gt;&gt;&gt; l.extend([1,2,3,4]) &gt;&gt;&gt; l [1, 2, 3, 4] &gt;&gt;&gt; l[3:] = [5] # note: 'saving' is not printed &gt;&gt;&gt; l [1, 2, 3, 5] </code></pre> <p>This does work for other methods like <code>append</code> and <code>extend</code>, just not for the slice operations.</p> <p><em>EDIT: The real problem is I'm using Jython and not Python and forgot it. The comments on the question are correct. This code does work fine in Python (2.6). However, the code nor the answers work in Jython.</em></p>
10
2009-07-22T17:18:30Z
1,170,410
<p>That's enough speculation. Let's start using facts instead shall we? As far as I can tell, the bottom line is that you must override both set of methods. </p> <p>If you want to implement undo/redo you probably should try using undo stack and set of actions that can do()/undo() themselves. </p> <h2>Code</h2> <pre><code>import profile import sys print sys.version class InterceptedList(list): def addSave(func): def newfunc(self, *args): func(self, *args) print 'saving' return newfunc __setslice__ = addSave(list.__setslice__) __delslice__ = addSave(list.__delslice__) class InterceptedList2(list): def __setitem__(self, key, value): print 'saving' list.__setitem__(self, key, value) def __delitem__(self, key): print 'saving' list.__delitem__(self, key) print("------------Testing setslice------------------") l = InterceptedList() l.extend([1,2,3,4]) profile.run("l[3:] = [5]") profile.run("l[2:6] = [12, 4]") profile.run("l[-1:] = [42]") profile.run("l[::2] = [6,6]") print("-----------Testing setitem--------------------") l2 = InterceptedList2() l2.extend([1,2,3,4]) profile.run("l2[3:] = [5]") profile.run("l2[2:6] = [12,4]") profile.run("l2[-1:] = [42]") profile.run("l2[::2] = [6,6]") </code></pre> <h2>Jython 2.5</h2> <pre><code>C:\Users\wuu-local.pyza\Desktop&gt;c:\jython2.5.0\jython.bat intercept.py 2.5.0 (Release_2_5_0:6476, Jun 16 2009, 13:33:26) [Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] ------------Testing setslice------------------ saving 3 function calls in 0.035 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:0(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc) 1 0.034 0.034 0.035 0.035 profile:0(l[3:] = [5]) 0 0.000 0.000 profile:0(profiler) saving 3 function calls in 0.005 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.001 0.001 &lt;string&gt;:0(&lt;module&gt;) 1 0.001 0.001 0.001 0.001 intercept.py:9(newfunc) 1 0.004 0.004 0.005 0.005 profile:0(l[2:6] = [12, 4]) 0 0.000 0.000 profile:0(profiler) saving 3 function calls in 0.012 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:0(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc) 1 0.012 0.012 0.012 0.012 profile:0(l[-1:] = [42]) 0 0.000 0.000 profile:0(profiler) 2 function calls in 0.004 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:0(&lt;module&gt;) 1 0.004 0.004 0.004 0.004 profile:0(l[::2] = [6,6]) 0 0.000 0.000 profile:0(profiler) -----------Testing setitem-------------------- 2 function calls in 0.004 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:0(&lt;module&gt;) 1 0.004 0.004 0.004 0.004 profile:0(l2[3:] = [5]) 0 0.000 0.000 profile:0(profiler) 2 function calls in 0.006 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:0(&lt;module&gt;) 1 0.006 0.006 0.006 0.006 profile:0(l2[2:6] = [12,4]) 0 0.000 0.000 profile:0(profiler) 2 function calls in 0.004 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:0(&lt;module&gt;) 1 0.004 0.004 0.004 0.004 profile:0(l2[-1:] = [42]) 0 0.000 0.000 profile:0(profiler) saving 3 function calls in 0.007 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.002 0.002 &lt;string&gt;:0(&lt;module&gt;) 1 0.001 0.001 0.001 0.001 intercept.py:20(__setitem__) 1 0.005 0.005 0.007 0.007 profile:0(l2[::2] = [6,6]) 0 0.000 0.000 profile:0(profiler) </code></pre> <h2>Python 2.6.2</h2> <pre><code>C:\Users\wuu-local.pyza\Desktop&gt;python intercept.py 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] ------------Testing setslice------------------ saving 4 function calls in 0.002 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.002 0.002 0.002 0.002 :0(setprofile) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc) 1 0.000 0.000 0.002 0.002 profile:0(l[3:] = [5]) 0 0.000 0.000 profile:0(profiler) saving 4 function calls in 0.000 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc) 1 0.000 0.000 0.000 0.000 profile:0(l[2:6] = [12, 4]) 0 0.000 0.000 profile:0(profiler) saving 4 function calls in 0.000 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc) 1 0.000 0.000 0.000 0.000 profile:0(l[-1:] = [42]) 0 0.000 0.000 profile:0(profiler) 3 function calls in 0.000 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 profile:0(l[::2] = [6,6]) 0 0.000 0.000 profile:0(profiler) -----------Testing setitem-------------------- 3 function calls in 0.000 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 profile:0(l2[3:] = [5]) 0 0.000 0.000 profile:0(profiler) 3 function calls in 0.000 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 profile:0(l2[2:6] = [12,4]) 0 0.000 0.000 profile:0(profiler) 3 function calls in 0.000 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 profile:0(l2[-1:] = [42]) 0 0.000 0.000 profile:0(profiler) saving 4 function calls in 0.003 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.003 0.003 &lt;string&gt;:1(&lt;module&gt;) 1 0.002 0.002 0.002 0.002 intercept.py:20(__setitem__) 1 0.000 0.000 0.003 0.003 profile:0(l2[::2] = [6,6]) 0 0.000 0.000 profile:0(profiler) </code></pre>
5
2009-07-23T08:28:12Z
[ "python", "methods", "jython", "slice", "intercept" ]
Autocompletion not working with PyQT4 and PyKDE4 in most of the IDEs
1,167,065
<p>I am trying to develop a plasmoid using python. I have tried eclipse with pydev, vim with pythoncomplete, PIDA and also Komodo, but none of them could give me autocmpletion for method names or members for the classes belonging to PyQT4 or PyKDE4. I added the folders in /usr/share/pyshare in the PYTHONPATH list for the IDEs. </p> <p>Do I need to do something else ?</p>
3
2009-07-22T17:56:15Z
1,167,292
<p>There is a number of ways to do it, PyQt4 provides enough information about method names for any object inspecting IDE:</p> <pre><code>&gt;&gt;&gt; from PyQt4 import QtGui &gt;&gt;&gt; dir(QtGui.QToolBox) ['Box', ... contextMenuPolicy', 'count', 'create', 'currentChanged'...] </code></pre> <p>All those functions are built-in. This means that you have to <a href="http://www.saltycrane.com/blog/2007/06/how-to-get-code-completion-for-pyqt/">push some IDEs slightly</a> to notice them. Be aware that there are no docstrings in compiled PyQt and methods have a funny signature.</p> <p>Other possibility is using QScintilla2 and.api file generated during PyQt4 build process. <a href="http://blog.saturnlaboratories.co.za/2009/03/11/pyqt4_code_completion_in_eric4.html">Eric4 IDE is prepared exactly for that.</a></p> <p>&lt;shameless-plug&gt;<br> You can also try <a href="http://www.activestate.com/komodo/downloads">Komodo IDE</a>/<a href="http://www.activestate.com/komodo-edit/downloads">Komodo Edit</a> and a CIX file (<a href="http://wuub.net/pyqt-komodo/PyQt4.5-wuub.zip">download here</a>) that I hacked together not so long ago:</p> <p><img src="http://i.stack.imgur.com/zNgGH.png" alt="Screenshot 1"></p> <p>and,</p> <p><img src="http://i.stack.imgur.com/7TJRC.png" alt="Screenshot 2"></p> <p>Edit: Installation instructions for Komodo 5:</p> <ol> <li>Edit -> Preferences -> Code Intelligence</li> <li>Add an API Catalog...</li> <li>Select CIX file, press Open</li> <li>There is no point 4.</li> </ol> <p>&lt;/shameless-plug&gt;</p>
4
2009-07-22T18:38:20Z
[ "python", "pyqt4", "pykde", "plasmoid" ]
Autocompletion not working with PyQT4 and PyKDE4 in most of the IDEs
1,167,065
<p>I am trying to develop a plasmoid using python. I have tried eclipse with pydev, vim with pythoncomplete, PIDA and also Komodo, but none of them could give me autocmpletion for method names or members for the classes belonging to PyQT4 or PyKDE4. I added the folders in /usr/share/pyshare in the PYTHONPATH list for the IDEs. </p> <p>Do I need to do something else ?</p>
3
2009-07-22T17:56:15Z
1,168,895
<p>What about <a href="http://www.wingware.com" rel="nofollow">WingIDE</a>, It's not free but it's <a href="http://www.wingware.com/wingide/features" rel="nofollow">Feature List</a> has "auto-completion for wxPython, PyGTK, and PyQt "</p>
0
2009-07-22T23:58:37Z
[ "python", "pyqt4", "pykde", "plasmoid" ]
Automatically determine the natural language of a website page given its URL
1,167,262
<p>I'm looking for a way to automatically determine the natural language used by a website page, given its URL.</p> <p>In Python, a function like:</p> <pre><code>def LanguageUsed (url): #stuff </code></pre> <p>Which returns a language specifier (e.g. 'en' for English, 'jp' for Japanese, etc...)</p> <p>Summary of Results: I have a reasonable solution working in Python using <a href="http://pypi.python.org/pypi/oice.langdet/1.0dev-r781">code from the PyPi for oice.langdet</a>. It does a decent job in discriminating English vs. Non-English, which is all I require at the moment. Note that you have to fetch the html using Python urllib. Also, oice.langdet is GPL license.</p> <p>For a more general solution using Trigrams in Python as others have suggested, see this <a href="http://code.activestate.com/recipes/326576/">Python Cookbook Recipe from ActiveState</a>.</p> <p>The Google Natural Language Detection API works very well (if not the best I've seen). However, it is Javascript and their TOS forbids automating its use.</p>
9
2009-07-22T18:33:46Z
1,167,408
<p><a href="http://www.nltk.org/" rel="nofollow">nltk</a> might help (if you have to get down to dealing with the page's text, i.e. if the headers and the url itself don't determine the language sufficiently well for your purposes); I don't think NLTK directly offers a "tell me which language this text is in" function (though NLTK is large and continuously growing, so it might in fact have it), but you can try parsing the given text according to various possible natural languages and checking which ones give the most sensible parse, wordset, &amp;c, according to the rules for each language.</p>
1
2009-07-22T18:53:26Z
[ "python", "url", "website", "nlp" ]
Automatically determine the natural language of a website page given its URL
1,167,262
<p>I'm looking for a way to automatically determine the natural language used by a website page, given its URL.</p> <p>In Python, a function like:</p> <pre><code>def LanguageUsed (url): #stuff </code></pre> <p>Which returns a language specifier (e.g. 'en' for English, 'jp' for Japanese, etc...)</p> <p>Summary of Results: I have a reasonable solution working in Python using <a href="http://pypi.python.org/pypi/oice.langdet/1.0dev-r781">code from the PyPi for oice.langdet</a>. It does a decent job in discriminating English vs. Non-English, which is all I require at the moment. Note that you have to fetch the html using Python urllib. Also, oice.langdet is GPL license.</p> <p>For a more general solution using Trigrams in Python as others have suggested, see this <a href="http://code.activestate.com/recipes/326576/">Python Cookbook Recipe from ActiveState</a>.</p> <p>The Google Natural Language Detection API works very well (if not the best I've seen). However, it is Javascript and their TOS forbids automating its use.</p>
9
2009-07-22T18:33:46Z
1,167,451
<p>There's no general method that will work solely on URLs. You can check the <a href="http://en.wikipedia.org/wiki/List%5Fof%5FInternet%5Ftop-level%5Fdomains" rel="nofollow">top-level domain</a> to get some idea, and look for portions of the URL that might be indicative of a language (like "en" or "es" between two slashes), and assume anything unknown is in English, but it isn't a perfect solution.</p> <p>So far as I know, the only general way to determine the natural language used by a page is to grab the page's text and check for certain common words in each language. For example, if "a", "an", and "the" appear several times in the page, it's likely that it includes English text; "el" and "la" might suggest Spanish; and so on.</p>
0
2009-07-22T19:00:32Z
[ "python", "url", "website", "nlp" ]
Automatically determine the natural language of a website page given its URL
1,167,262
<p>I'm looking for a way to automatically determine the natural language used by a website page, given its URL.</p> <p>In Python, a function like:</p> <pre><code>def LanguageUsed (url): #stuff </code></pre> <p>Which returns a language specifier (e.g. 'en' for English, 'jp' for Japanese, etc...)</p> <p>Summary of Results: I have a reasonable solution working in Python using <a href="http://pypi.python.org/pypi/oice.langdet/1.0dev-r781">code from the PyPi for oice.langdet</a>. It does a decent job in discriminating English vs. Non-English, which is all I require at the moment. Note that you have to fetch the html using Python urllib. Also, oice.langdet is GPL license.</p> <p>For a more general solution using Trigrams in Python as others have suggested, see this <a href="http://code.activestate.com/recipes/326576/">Python Cookbook Recipe from ActiveState</a>.</p> <p>The Google Natural Language Detection API works very well (if not the best I've seen). However, it is Javascript and their TOS forbids automating its use.</p>
9
2009-07-22T18:33:46Z
1,167,561
<p>Your best bet really is to use <a href="http://www.google.com/uds/samples/language/detect.html" rel="nofollow">Google's natural language detection</a> api. It returns an iso code for the page language, with a probability index. </p> <p>See <a href="http://code.google.com/apis/ajaxlanguage/documentation/" rel="nofollow">http://code.google.com/apis/ajaxlanguage/documentation/</a></p>
6
2009-07-22T19:19:06Z
[ "python", "url", "website", "nlp" ]
Automatically determine the natural language of a website page given its URL
1,167,262
<p>I'm looking for a way to automatically determine the natural language used by a website page, given its URL.</p> <p>In Python, a function like:</p> <pre><code>def LanguageUsed (url): #stuff </code></pre> <p>Which returns a language specifier (e.g. 'en' for English, 'jp' for Japanese, etc...)</p> <p>Summary of Results: I have a reasonable solution working in Python using <a href="http://pypi.python.org/pypi/oice.langdet/1.0dev-r781">code from the PyPi for oice.langdet</a>. It does a decent job in discriminating English vs. Non-English, which is all I require at the moment. Note that you have to fetch the html using Python urllib. Also, oice.langdet is GPL license.</p> <p>For a more general solution using Trigrams in Python as others have suggested, see this <a href="http://code.activestate.com/recipes/326576/">Python Cookbook Recipe from ActiveState</a>.</p> <p>The Google Natural Language Detection API works very well (if not the best I've seen). However, it is Javascript and their TOS forbids automating its use.</p>
9
2009-07-22T18:33:46Z
1,167,571
<p>There is nothing about the URL itself that will indicate language.</p> <p>One option would be to use a <a href="http://www.nltk.org/" rel="nofollow">natural language toolkit</a> to try to identify the language based on the content, but even if you can get the NLP part of it working, it'll be pretty slow. Also, it may not be reliable. Remember, most user agents pass something like</p> <pre><code>Accept-Language: en-US </code></pre> <p>with each request, and many large websites will serve different content based on that header. Smaller sites will be more reliable because they won't pay attention to the language headers. </p> <p>You could also use server location (i.e. which country the server is in) as a proxy for language using <a href="http://code.google.com/p/python-geoip/" rel="nofollow">GeoIP</a>. It's obviously not perfect, but it is much better than using the TLD.</p>
3
2009-07-22T19:20:11Z
[ "python", "url", "website", "nlp" ]
Automatically determine the natural language of a website page given its URL
1,167,262
<p>I'm looking for a way to automatically determine the natural language used by a website page, given its URL.</p> <p>In Python, a function like:</p> <pre><code>def LanguageUsed (url): #stuff </code></pre> <p>Which returns a language specifier (e.g. 'en' for English, 'jp' for Japanese, etc...)</p> <p>Summary of Results: I have a reasonable solution working in Python using <a href="http://pypi.python.org/pypi/oice.langdet/1.0dev-r781">code from the PyPi for oice.langdet</a>. It does a decent job in discriminating English vs. Non-English, which is all I require at the moment. Note that you have to fetch the html using Python urllib. Also, oice.langdet is GPL license.</p> <p>For a more general solution using Trigrams in Python as others have suggested, see this <a href="http://code.activestate.com/recipes/326576/">Python Cookbook Recipe from ActiveState</a>.</p> <p>The Google Natural Language Detection API works very well (if not the best I've seen). However, it is Javascript and their TOS forbids automating its use.</p>
9
2009-07-22T18:33:46Z
1,167,633
<p>This is usually accomplished by using character n-gram models. You can find <a href="http://alias-i.com/lingpipe/demos/tutorial/langid/read-me.html">here</a> a state of the art language identifier for Java. If you need some help converting it to Python, just ask. Hope it helps.</p>
8
2009-07-22T19:28:33Z
[ "python", "url", "website", "nlp" ]
Automatically determine the natural language of a website page given its URL
1,167,262
<p>I'm looking for a way to automatically determine the natural language used by a website page, given its URL.</p> <p>In Python, a function like:</p> <pre><code>def LanguageUsed (url): #stuff </code></pre> <p>Which returns a language specifier (e.g. 'en' for English, 'jp' for Japanese, etc...)</p> <p>Summary of Results: I have a reasonable solution working in Python using <a href="http://pypi.python.org/pypi/oice.langdet/1.0dev-r781">code from the PyPi for oice.langdet</a>. It does a decent job in discriminating English vs. Non-English, which is all I require at the moment. Note that you have to fetch the html using Python urllib. Also, oice.langdet is GPL license.</p> <p>For a more general solution using Trigrams in Python as others have suggested, see this <a href="http://code.activestate.com/recipes/326576/">Python Cookbook Recipe from ActiveState</a>.</p> <p>The Google Natural Language Detection API works very well (if not the best I've seen). However, it is Javascript and their TOS forbids automating its use.</p>
9
2009-07-22T18:33:46Z
1,167,708
<p>You might want to try ngram based detection.</p> <p><a href="http://www.let.rug.nl/~vannoord/TextCat/Demo/textcat%5Fsrc.html" rel="nofollow">TextCat <strong>DEMO</strong></a> (LGPL) seems to work pretty well (recognizes almost 70 languages). There is a python port provided by <a href="http://thomas.mangin.me.uk/" rel="nofollow">Thomas Mangin</a> <a href="http://thomas.mangin.me.uk/data/source/ngram.py" rel="nofollow">here</a> using the same corpus.</p> <p>Edit: TextCat <a href="http://www.let.rug.nl/~vannoord/TextCat/competitors.html" rel="nofollow">competitors page</a> provides some interesting links too. </p> <p>Edit2: I wonder if making a python wrapper for <a href="http://www.mnogosearch.org/guesser/" rel="nofollow">http://www.mnogosearch.org/guesser/</a> would be difficult...</p>
3
2009-07-22T19:38:32Z
[ "python", "url", "website", "nlp" ]
Python: access class property from string
1,167,398
<p>I have a class like the following:</p> <pre><code>class User: def __init__(self): self.data = [] self.other_data = [] def doSomething(self, source): // if source = 'other_data' how to access self.other_data </code></pre> <p>I want to pass a string for the source variable in <code>doSomething</code> and access the class member of the same name.</p> <p>I have tried <code>getattr</code> which only works on functions (from what I can tell) as well as having <code>User</code> extend <code>dict</code> and using <code>self.__getitem__</code>, but that doesn't work either. What is the best way to do this?</p>
65
2009-07-22T18:52:14Z
1,167,419
<p><code>x = getattr(self, source)</code> will work just perfectly if <code>source</code> names ANY attribute of self, include the <code>other_data</code> in your example.</p>
110
2009-07-22T18:55:55Z
[ "python", "syntax" ]
Python: access class property from string
1,167,398
<p>I have a class like the following:</p> <pre><code>class User: def __init__(self): self.data = [] self.other_data = [] def doSomething(self, source): // if source = 'other_data' how to access self.other_data </code></pre> <p>I want to pass a string for the source variable in <code>doSomething</code> and access the class member of the same name.</p> <p>I have tried <code>getattr</code> which only works on functions (from what I can tell) as well as having <code>User</code> extend <code>dict</code> and using <code>self.__getitem__</code>, but that doesn't work either. What is the best way to do this?</p>
65
2009-07-22T18:52:14Z
1,167,797
<p>Extending Alex's answer slightly:</p> <pre><code>class User: def __init__(self): self.data = [1,2,3] self.other_data = [4,5,6] def doSomething(self, source): dataSource = getattr(self,source) return dataSource A = User() print A.doSomething("data") print A.doSomething("other_data") </code></pre> will yield:<pre> [1, 2, 3] [4, 5, 6] </pre> <p>However, personally I don't think that's great style - <code>getattr</code> will let you access any attribute of the instance, including things like the <code>doSomething</code> method itself, or even the <code>__dict__</code> of the instance. I would suggest that instead you implement a dictionary of data sources, like so:</p> <pre><code>class User: def __init__(self): self.data_sources = { "data": [1,2,3], "other_data":[4,5,6], } def doSomething(self, source): dataSource = self.data_sources[source] return dataSource A = User() print A.doSomething("data") print A.doSomething("other_data") </code></pre> again yielding:<pre> [1, 2, 3] [4, 5, 6] </pre>
2
2009-07-22T19:50:52Z
[ "python", "syntax" ]
Python: access class property from string
1,167,398
<p>I have a class like the following:</p> <pre><code>class User: def __init__(self): self.data = [] self.other_data = [] def doSomething(self, source): // if source = 'other_data' how to access self.other_data </code></pre> <p>I want to pass a string for the source variable in <code>doSomething</code> and access the class member of the same name.</p> <p>I have tried <code>getattr</code> which only works on functions (from what I can tell) as well as having <code>User</code> extend <code>dict</code> and using <code>self.__getitem__</code>, but that doesn't work either. What is the best way to do this?</p>
65
2009-07-22T18:52:14Z
1,168,132
<p>A picture's worth a thousand words:</p> <pre><code>&gt;&gt;&gt; class c: pass o = c() &gt;&gt;&gt; setattr(o, "foo", "bar") &gt;&gt;&gt; o.foo 'bar' &gt;&gt;&gt; getattr(o, "foo") 'bar' </code></pre>
79
2009-07-22T20:45:36Z
[ "python", "syntax" ]
Python: access class property from string
1,167,398
<p>I have a class like the following:</p> <pre><code>class User: def __init__(self): self.data = [] self.other_data = [] def doSomething(self, source): // if source = 'other_data' how to access self.other_data </code></pre> <p>I want to pass a string for the source variable in <code>doSomething</code> and access the class member of the same name.</p> <p>I have tried <code>getattr</code> which only works on functions (from what I can tell) as well as having <code>User</code> extend <code>dict</code> and using <code>self.__getitem__</code>, but that doesn't work either. What is the best way to do this?</p>
65
2009-07-22T18:52:14Z
39,951,135
<ul> <li><strong><code>getattr(x, 'y')</code></strong> is equivalent to <strong><code>x.y</code></strong></li> <li><strong><code>setattr(x, 'y', v)</code></strong> is equivalent to <strong><code>x.y = v</code></strong></li> <li><strong><code>delattr(x, 'y')</code></strong> is equivalent to <strong><code>del x.y</code></strong></li> </ul>
0
2016-10-10T04:01:30Z
[ "python", "syntax" ]
Executing code for a custom Django 404 page
1,167,434
<p>I am getting ready to deploy my first Django application and am hitting a bit of a roadblock. My base template relies on me passing in the session object so that it can read out the currently logged in user's name. This isn't a problem when I control the code that is calling a template.</p> <p>However, as part of getting this app ready to be deployed, I need to create a 404.html page. I extended my base template just like I've done with my other pages, but I don't see a way to pass in the session object so that I can utilize it. Is there a way to have Django call a custom method to render your 404 rather than just rendering your 404.html for you?</p>
5
2009-07-22T18:58:17Z
1,167,480
<p>You need to override the default view handler for the 404 error. Here is the documentation on how to create your own custom 404 view function:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views">http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views</a></p>
11
2009-07-22T19:05:11Z
[ "python", "django" ]
Executing code for a custom Django 404 page
1,167,434
<p>I am getting ready to deploy my first Django application and am hitting a bit of a roadblock. My base template relies on me passing in the session object so that it can read out the currently logged in user's name. This isn't a problem when I control the code that is calling a template.</p> <p>However, as part of getting this app ready to be deployed, I need to create a 404.html page. I extended my base template just like I've done with my other pages, but I don't see a way to pass in the session object so that I can utilize it. Is there a way to have Django call a custom method to render your 404 rather than just rendering your 404.html for you?</p>
5
2009-07-22T18:58:17Z
1,167,496
<p>Define your own 404 handler. See <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/" rel="nofollow">Django URLs</a>, specifically the part about <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#handler404" rel="nofollow">handler404</a>.</p>
3
2009-07-22T19:08:17Z
[ "python", "django" ]
In Python, how do I indicate I'm overriding a method?
1,167,617
<p>In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?</p>
61
2009-07-22T19:26:48Z
1,167,640
<p>As far as I know, there is no special way to indicate an override in Python. You just define the method and include a docstring, like always.</p>
3
2009-07-22T19:29:19Z
[ "python", "inheritance", "override", "self-documenting-code" ]
In Python, how do I indicate I'm overriding a method?
1,167,617
<p>In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?</p>
61
2009-07-22T19:26:48Z
1,167,664
<p>Python ain't Java. There's of course no such thing really as compile-time checking. </p> <p>I think a comment in the docstring is plenty. This allows any user of your method to type <code>help(obj.method)</code> and see that the method is an override. </p> <p>You can also explicitly extend an interface with <code>class Foo(Interface)</code>, which will allow users to type <code>help(Interface.method)</code> to get an idea about the functionality your method is intended to provide.</p>
9
2009-07-22T19:32:09Z
[ "python", "inheritance", "override", "self-documenting-code" ]
In Python, how do I indicate I'm overriding a method?
1,167,617
<p>In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?</p>
61
2009-07-22T19:26:48Z
1,168,677
<p>If you want this for documentation purposes only, you can define your own override decorator:</p> <pre><code>def override(f): return f class MyClass (BaseClass): @override def method(self): pass </code></pre> <p>This is really nothing but eye-candy, unless you create override(f) in such a way that is actually checks for an override.</p> <p>But then, this is Python, why write it like it was Java?</p>
4
2009-07-22T22:33:35Z
[ "python", "inheritance", "override", "self-documenting-code" ]
In Python, how do I indicate I'm overriding a method?
1,167,617
<p>In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?</p>
61
2009-07-22T19:26:48Z
8,313,042
<p><strong>UPDATE (23.05.2015): Based on this and fwc:s answer I created a pip installable package <a href="https://github.com/mkorpela/overrides">https://github.com/mkorpela/overrides</a></strong></p> <p>From time to time I end up here looking at this question. Mainly this happens after (again) seeing the same bug in our code base: Someone has forgotten some "interface" implementing class while renaming a method in the "interface"..</p> <p>Well Python ain't Java but Python has power -- and explicit is better than implicit -- and there are real concrete cases in the real world where this thing would have helped me.</p> <p>So here is a sketch of overrides decorator. This will check that the class given as a parameter has the same method (or something) name as the method being decorated.</p> <p>If you can think of a better solution please post it here!</p> <pre><code>def overrides(interface_class): def overrider(method): assert(method.__name__ in dir(interface_class)) return method return overrider </code></pre> <p>It works as follows:</p> <pre><code>class MySuperInterface(object): def my_method(self): print 'hello world!' class ConcreteImplementer(MySuperInterface): @overrides(MySuperInterface) def my_method(self): print 'hello kitty!' </code></pre> <p>and if you do a faulty version it will raise an assertion error during class loading:</p> <pre><code>class ConcreteFaultyImplementer(MySuperInterface): @overrides(MySuperInterface) def your_method(self): print 'bye bye!' &gt;&gt; AssertionError!!!!!!! </code></pre>
110
2011-11-29T15:07:19Z
[ "python", "inheritance", "override", "self-documenting-code" ]
In Python, how do I indicate I'm overriding a method?
1,167,617
<p>In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?</p>
61
2009-07-22T19:26:48Z
14,631,397
<p>Here's an implementation that doesn't require specification of the interface_class name.</p> <pre><code>import inspect import re def overrides(method): # actually can't do this because a method is really just a function while inside a class def'n #assert(inspect.ismethod(method)) stack = inspect.stack() base_classes = re.search(r'class.+\((.+)\)\s*\:', stack[2][4][0]).group(1) # handle multiple inheritance base_classes = [s.strip() for s in base_classes.split(',')] if not base_classes: raise ValueError('overrides decorator: unable to determine base class') # stack[0]=overrides, stack[1]=inside class def'n, stack[2]=outside class def'n derived_class_locals = stack[2][0].f_locals # replace each class name in base_classes with the actual class type for i, base_class in enumerate(base_classes): if '.' not in base_class: base_classes[i] = derived_class_locals[base_class] else: components = base_class.split('.') # obj is either a module or a class obj = derived_class_locals[components[0]] for c in components[1:]: assert(inspect.ismodule(obj) or inspect.isclass(obj)) obj = getattr(obj, c) base_classes[i] = obj assert( any( hasattr(cls, method.__name__) for cls in base_classes ) ) return method </code></pre>
19
2013-01-31T17:13:53Z
[ "python", "inheritance", "override", "self-documenting-code" ]
In Python, how do I indicate I'm overriding a method?
1,167,617
<p>In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?</p>
61
2009-07-22T19:26:48Z
18,193,306
<p>Like others have said unlike Java there is not @Overide tag however above you can create your own using decorators however I would suggest using the getattrib() global method instead of using the internal dict so you get something like the following:</p> <pre><code>def Override(superClass): def method(func) getattr(superClass,method.__name__) return method </code></pre> <p>If you wanted to you could catch getattr() in your own try catch raise your own error but I think getattr method is better in this case.</p> <p>Also this catches all items bound to a class including class methods and vairables</p>
1
2013-08-12T17:43:44Z
[ "python", "inheritance", "override", "self-documenting-code" ]
In Python, how do I indicate I'm overriding a method?
1,167,617
<p>In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?</p>
61
2009-07-22T19:26:48Z
20,203,242
<p>Hear is simplest and working under Jython with Java classes:</p> <pre><code>class MyClass(SomeJavaClass): def __init__(self): setattr(self, "name_of_method_to_override", __method_override__) def __method_override__(self, some_args): some_thing_to_do() </code></pre>
0
2013-11-25T21:02:37Z
[ "python", "inheritance", "override", "self-documenting-code" ]
Middleware for both Django and Pylons
1,167,903
<p>It appears to me that Django and Pylons have different ideas on how middleware should work. I like that Pylons follows the standardized <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">PEP 333</a>, but Django seems to have more widespread adoption. Is it possible to write middleware to be used in both?</p> <p>The project that involves said middleware is porting a security toolkit called ESAPI from Java to Python. Because Java is so standards oriented, it is pretty easy to be framework agnostic. In Python, different frameworks have different ideas on how basic things like HttpRequest objects and middleware work, so this seems more difficult.</p> <p>Apparently, new users cannot post more than one hyperlink. See below for links to Django and Pylons middleware info.</p>
3
2009-07-22T20:06:26Z
1,168,128
<p>Pylons uses standard WSGI middleware. If you deploy Django via WSGI, you can also use WSGI middleware at that point. You can't, however, currently use WSGI middleware via the standard Django MIDDLEWARE_CLASSES option in settings.py.</p> <p>That said, there is currently a Google Summer of Code project to enable the use of WSGI middleware in Django itself. I haven't been following the status of this project, but the code is available in the <a href="http://code.djangoproject.com/browser/django/branches/soc2009/http-wsgi-improvements" rel="nofollow">Http WSGI improvements branch</a>.</p>
3
2009-07-22T20:45:09Z
[ "python", "django", "pylons", "middleware" ]
Middleware for both Django and Pylons
1,167,903
<p>It appears to me that Django and Pylons have different ideas on how middleware should work. I like that Pylons follows the standardized <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">PEP 333</a>, but Django seems to have more widespread adoption. Is it possible to write middleware to be used in both?</p> <p>The project that involves said middleware is porting a security toolkit called ESAPI from Java to Python. Because Java is so standards oriented, it is pretty easy to be framework agnostic. In Python, different frameworks have different ideas on how basic things like HttpRequest objects and middleware work, so this seems more difficult.</p> <p>Apparently, new users cannot post more than one hyperlink. See below for links to Django and Pylons middleware info.</p>
3
2009-07-22T20:06:26Z
1,168,130
<p>For Pylons the term middleware means WSGI (<a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">PEP 333</a>) middleware, whereas Django means its own internal mechanism for middleware.</p> <p>However, if you run Django under apache+<a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> (instead of e.g. mod_python or lighttpd+flup) you can also include WSGI middleware in Django. This isn't typically done though because much of the functionality you'll find in WSGI middleware is already built-in to Django proper or Django middleware.</p> <p>The differences between WSGI and Django middleware are small enough that it should be easy enough to convert code between the two. The tougher problem is when they use external libraries like ORM's.</p> <p>The <a href="http://www.wsgi.org/wsgi/WsgiStart" rel="nofollow">WSGI Wiki</a> has a good list of <a href="http://www.wsgi.org/wsgi/Middleware_and_Utilities" rel="nofollow">WSGI middleware</a>.</p>
0
2009-07-22T20:45:29Z
[ "python", "django", "pylons", "middleware" ]
How to return an alternate column element from the intersect command?
1,167,908
<p>I am currently using the following code to get the intersection date column of two sets of financial data. The arrays include date, o,h,l,cl</p> <pre><code>#find intersection of date strings def intersect(seq1, seq2): res = [] # start empty for x in seq1: # scan seq1 if x in seq2: # common item? res.append(x) return res x = intersect(seta[:,0], setb[:,0]) # mixed types print x </code></pre> <p>The problem is it only returns the column for which it found the intersection of both, namely the date column. I would like it to somehow return a different column array including both the cls values of each set ... ie.. if date is common to both return a 2X1 array of the two corresponding cls columns. Any ideas? thanks.</p>
1
2009-07-22T20:06:46Z
1,168,062
<p>Okay, here is a complete solution.</p> <p>Get a <a href="http://www.goldb.org/ystockquote.html" rel="nofollow">python library to download stocks quotes</a></p> <p>Get some quotes</p> <pre><code>start_date, end_date = '20090309', '20090720' ibm_data = get_historical_prices('IBM', start_date, end_date) msft_data = get_historical_prices('MSFT', start_date, end_date) </code></pre> <p>Convert rows into date-keyed dictionaries of dictionaries</p> <pre><code>def quote_series(series): columns = ['open', 'high', 'low', 'close', 'volume'] return dict((item[0], dict(zip(columns, item[1:]))) for item in series[1:]) ibm = quote_series(ibm_data) msft = quote_series(msft_data) </code></pre> <p>Do the intersection of dates thing</p> <pre><code>ibm_dates = set(ibm.keys()) msft_dates = set(msft.keys()) both = ibm_dates.intersection(msft_dates) for d in sorted(both): print d, ibm[d], msft[d] </code></pre>
0
2009-07-22T20:31:33Z
[ "python", "intersection" ]
How to return an alternate column element from the intersect command?
1,167,908
<p>I am currently using the following code to get the intersection date column of two sets of financial data. The arrays include date, o,h,l,cl</p> <pre><code>#find intersection of date strings def intersect(seq1, seq2): res = [] # start empty for x in seq1: # scan seq1 if x in seq2: # common item? res.append(x) return res x = intersect(seta[:,0], setb[:,0]) # mixed types print x </code></pre> <p>The problem is it only returns the column for which it found the intersection of both, namely the date column. I would like it to somehow return a different column array including both the cls values of each set ... ie.. if date is common to both return a 2X1 array of the two corresponding cls columns. Any ideas? thanks.</p>
1
2009-07-22T20:06:46Z
1,168,068
<p>How's that:</p> <pre><code>def intersect(seq1, seq2): if seq1[0] == seq2[0]: # compare the date columns return (seq1[4], seq2[4]) # return 2-tuple with the cls values </code></pre>
0
2009-07-22T20:33:36Z
[ "python", "intersection" ]
Python scripts in /usr/bin
1,168,042
<p>I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?</p> <p>For example, instead of running</p> <pre><code>python htswap.py args </code></pre> <p>from the directory where it currently is, I want to be able to cd to any directory and do</p> <pre><code>htswap args </code></pre> <p>Thanks in advance!</p>
8
2009-07-22T20:27:38Z
1,168,048
<p>The first line of the file should be</p> <pre><code>#!/usr/bin/env python </code></pre> <p>You should remove the <code>.py</code> extension, and make the file executable, using</p> <pre><code>chmod ugo+x htswap </code></pre> <p><strong>EDIT:</strong> <a href="http://stackoverflow.com/users/14637/thomas">Thomas</a> points out correctly that such scripts should be placed in <code>/usr/local/bin</code> rather than in <code>/usr/bin</code>. Please upvote his answer (at the expense of mine, perhaps. Seven upvotes (as we speak) for this kind of stuff is ridiculous)</p>
12
2009-07-22T20:29:55Z
[ "python", "unix", "scripting" ]
Python scripts in /usr/bin
1,168,042
<p>I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?</p> <p>For example, instead of running</p> <pre><code>python htswap.py args </code></pre> <p>from the directory where it currently is, I want to be able to cd to any directory and do</p> <pre><code>htswap args </code></pre> <p>Thanks in advance!</p>
8
2009-07-22T20:27:38Z
1,168,053
<p>Shebang?</p> <pre><code>#!/usr/bin/env python </code></pre> <p>Put that at the beginning of your file and you're set</p>
2
2009-07-22T20:30:36Z
[ "python", "unix", "scripting" ]
Python scripts in /usr/bin
1,168,042
<p>I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?</p> <p>For example, instead of running</p> <pre><code>python htswap.py args </code></pre> <p>from the directory where it currently is, I want to be able to cd to any directory and do</p> <pre><code>htswap args </code></pre> <p>Thanks in advance!</p>
8
2009-07-22T20:27:38Z
1,168,057
<p>add <code>#!/usr/bin/env python</code> to the very top of <code>htswap.py</code> and rename <code>htswap.py</code> to <code>htswap</code> then do a command: <code>chmod +x htswap</code> to make htswap executable.</p>
1
2009-07-22T20:30:55Z
[ "python", "unix", "scripting" ]
Python scripts in /usr/bin
1,168,042
<p>I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?</p> <p>For example, instead of running</p> <pre><code>python htswap.py args </code></pre> <p>from the directory where it currently is, I want to be able to cd to any directory and do</p> <pre><code>htswap args </code></pre> <p>Thanks in advance!</p>
8
2009-07-22T20:27:38Z
1,168,065
<p>Simply strip off the <code>.py</code> extension by renaming the file. Then, you have to put the following line at the top of your file:</p> <pre><code>#!/usr/bin/env python </code></pre> <p><code>env</code> is a little program that sets up the environment so that the right <code>python</code> interpreter is executed.</p> <p>You also have to make your file executable, with the command</p> <pre><code>chmod a+x htswap </code></pre> <p>And dump it into <code>/usr/local/bin</code>. This is cleaner than <code>/usr/bin</code>, because the contents of that directory are usually managed by the operating system.</p>
21
2009-07-22T20:32:43Z
[ "python", "unix", "scripting" ]
Python scripts in /usr/bin
1,168,042
<p>I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?</p> <p>For example, instead of running</p> <pre><code>python htswap.py args </code></pre> <p>from the directory where it currently is, I want to be able to cd to any directory and do</p> <pre><code>htswap args </code></pre> <p>Thanks in advance!</p>
8
2009-07-22T20:27:38Z
1,168,351
<p>I see in the official Python tutorials, <a href="http://docs.python.org/tutorial/index.html" rel="nofollow">http://docs.python.org/tutorial/index.html</a>, that </p> <pre><code>#! /usr/bin/env python </code></pre> <p>is used just as the answers above suggest. Note that you can also use the following</p> <pre><code>#!/usr/bin/python </code></pre> <p>This is the style you'll see for in shell scripts, like bash scripts. For example</p> <pre><code>#!/bin/bash </code></pre> <p>Seeing that the official tuts go with the first option that is probably your best bet. Consistency in code is something to strive for!</p>
-1
2009-07-22T21:26:28Z
[ "python", "unix", "scripting" ]
Boolean evaluation in a lambda
1,168,236
<p>Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?</p> <pre><code>def isodd(number): if (number%2 == 0): return False else: return True </code></pre> <p>Elementary, yes. But I'm interested to know...</p>
4
2009-07-22T21:03:36Z
1,168,249
<pre><code>lambda num: num % 2 != 0 </code></pre>
6
2009-07-22T21:06:53Z
[ "python", "lambda" ]
Boolean evaluation in a lambda
1,168,236
<p>Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?</p> <pre><code>def isodd(number): if (number%2 == 0): return False else: return True </code></pre> <p>Elementary, yes. But I'm interested to know...</p>
4
2009-07-22T21:03:36Z
1,168,251
<pre><code>isodd = lambda number: number %2 != 0 </code></pre>
4
2009-07-22T21:07:26Z
[ "python", "lambda" ]
Boolean evaluation in a lambda
1,168,236
<p>Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?</p> <pre><code>def isodd(number): if (number%2 == 0): return False else: return True </code></pre> <p>Elementary, yes. But I'm interested to know...</p>
4
2009-07-22T21:03:36Z
1,168,261
<p>Yes you can:</p> <pre><code>isodd = lambda x: x % 2 != 0 </code></pre>
6
2009-07-22T21:08:26Z
[ "python", "lambda" ]
Boolean evaluation in a lambda
1,168,236
<p>Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?</p> <pre><code>def isodd(number): if (number%2 == 0): return False else: return True </code></pre> <p>Elementary, yes. But I'm interested to know...</p>
4
2009-07-22T21:03:36Z
1,168,311
<p>And if you don't really need a function you can replace it even without a lambda. :)</p> <pre><code>(number % 2 != 0) </code></pre> <p>by itself is an expression that evaluates to True or False. Or even plainer,</p> <pre><code>bool(number % 2) </code></pre> <p>which you can simplify like so:</p> <pre><code>if number % 2: print "Odd!" else: print "Even!" </code></pre> <p>But if that's readable or not is probably in the eye of the beholder.</p>
9
2009-07-22T21:17:27Z
[ "python", "lambda" ]
Boolean evaluation in a lambda
1,168,236
<p>Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?</p> <pre><code>def isodd(number): if (number%2 == 0): return False else: return True </code></pre> <p>Elementary, yes. But I'm interested to know...</p>
4
2009-07-22T21:03:36Z
1,168,394
<p>Others already gave you replies that cover your particular case. In general, however, when you actually <em>need</em> an <code>if</code>-statement, you can use the conditional expression. For example, if you'd have to return strings <code>"False"</code> and <code>"True"</code> rather than boolean values, you could do this:</p> <pre><code>lambda num: "False" if num%2==0 else "True" </code></pre> <p>The <a href="http://docs.python.org/reference/expressions.html#boolean-operations" rel="nofollow">definition</a> of this expression in Python language reference is as follows:</p> <blockquote> <p>The expression <code>x if C else y</code> first evaluates <code>C</code> (not <code>x</code>); if <code>C</code> is true, <code>x</code> is evaluated and its value is returned; otherwise, <code>y</code> is evaluated and its value is returned.</p> </blockquote>
5
2009-07-22T21:34:59Z
[ "python", "lambda" ]
Boolean evaluation in a lambda
1,168,236
<p>Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?</p> <pre><code>def isodd(number): if (number%2 == 0): return False else: return True </code></pre> <p>Elementary, yes. But I'm interested to know...</p>
4
2009-07-22T21:03:36Z
1,168,497
<p>And also don't forget that you can emulate complex conditional sentences with simple short-circuit logic, taking advantage that "and" and "or" return some of their ellements (the last one evaluated)... for example, in this case, supposing you'd want to return something different than True or False</p> <pre><code>lambda x: x%2 and "Odd" or "Even" </code></pre>
3
2009-07-22T21:49:45Z
[ "python", "lambda" ]
Boolean evaluation in a lambda
1,168,236
<p>Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?</p> <pre><code>def isodd(number): if (number%2 == 0): return False else: return True </code></pre> <p>Elementary, yes. But I'm interested to know...</p>
4
2009-07-22T21:03:36Z
1,168,917
<p><code>isodd = lambda number: (False, True)[number &amp; 1]</code></p>
1
2009-07-23T00:06:49Z
[ "python", "lambda" ]
Boolean evaluation in a lambda
1,168,236
<p>Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?</p> <pre><code>def isodd(number): if (number%2 == 0): return False else: return True </code></pre> <p>Elementary, yes. But I'm interested to know...</p>
4
2009-07-22T21:03:36Z
1,169,093
<p>Any time you see yourself writing:</p> <pre><code>if (some condition): return True else: return False </code></pre> <p>you should replace it with a single line:</p> <pre><code>return (some condition) </code></pre> <p>Your function then becomes:</p> <pre><code>def isodd(number): return number % 2 != 0 </code></pre> <p>You should be able to see how to get from there to the lambda solution that others have provided.</p>
0
2009-07-23T01:15:11Z
[ "python", "lambda" ]
To build a similar reputation tracker as Jon's by Python
1,168,452
<p>Jon Skeet has the following <a href="http://csharpindepth.com/StackOverflow/ReputationTracker.aspx" rel="nofollow">reputation tracker</a> which is built by C#.</p> <p>I am interested in building a similar app by Python such that at least the following modules are used</p> <ul> <li>beautiful soup</li> <li>defaultdict</li> </ul> <p>We apparently need </p> <ul> <li>to parse the reputation from the site '<a href="http://stackoverflow.com/users/#user-id#">http://stackoverflow.com/users/#user-id#</a>' by Bautiful soup</li> <li>to store the data by defaultdict</li> </ul> <p><strong>How can you build a similar reputation system as Jon's one by Python?</strong></p>
0
2009-07-22T21:43:23Z
1,169,864
<p>The screenscraping is easy, if I understand the SO HTML format correctly, e.g., to get my rep (as I'm user 95810):</p> <pre><code>import urllib import BeautifulSoup page = urllib.urlopen('http://stackoverflow.com/users/95810') soup = BeautifulSoup.BeautifulSoup(page) therep = str(soup.find(text='Reputation').parent.previous.previous).strip() print int(therep.replace(',','')) </code></pre> <p>I'm not sure what you want to do with <code>defaultdict</code> here, though -- what further processing do you desire to perform on this int, that would somehow require storing it in a defaultdict?</p>
3
2009-07-23T06:00:56Z
[ "python" ]
Using map() to get number of times list elements exist in a string in Python
1,168,517
<p>I'm trying to get the number of times each item in a list is in a string in Python:</p> <pre><code>paragraph = "I eat bananas and a banana" def tester(x): return len(re.findall(x,paragraph)) map(tester, ['banana', 'loganberry', 'passion fruit']) </code></pre> <p>Returns [2, 0, 0] </p> <p>What I'd like to do however is extend this so I can feed the paragraph value into the map() function. Right now, the tester() function has paragraph hardcoded. Does anybody have a way to do this (perhaps make an n-length list of paragraph values)? Any other ideas here?</p> <p>Keep in mind that each of the array values will have a weight at some point in the future - hence the need to keep the values in a list rather than crunching them all together.</p> <p>UPDATE: The paragraph will often be 20K and the list will often have 200+ members. My thinking is that map operates in parallel - so it will be much more efficient than any serial methods.</p>
1
2009-07-22T21:53:13Z
1,168,527
<p>A closure would be a quick solution:</p> <pre><code>paragraph = "I eat bananas and a banana" def tester(s): def f(x): return len(re.findall(x,s)) return f print map(tester(paragraph), ['banana', 'loganberry', 'passion fruit']) </code></pre>
8
2009-07-22T21:57:41Z
[ "python", "regex", "mapreduce" ]
Using map() to get number of times list elements exist in a string in Python
1,168,517
<p>I'm trying to get the number of times each item in a list is in a string in Python:</p> <pre><code>paragraph = "I eat bananas and a banana" def tester(x): return len(re.findall(x,paragraph)) map(tester, ['banana', 'loganberry', 'passion fruit']) </code></pre> <p>Returns [2, 0, 0] </p> <p>What I'd like to do however is extend this so I can feed the paragraph value into the map() function. Right now, the tester() function has paragraph hardcoded. Does anybody have a way to do this (perhaps make an n-length list of paragraph values)? Any other ideas here?</p> <p>Keep in mind that each of the array values will have a weight at some point in the future - hence the need to keep the values in a list rather than crunching them all together.</p> <p>UPDATE: The paragraph will often be 20K and the list will often have 200+ members. My thinking is that map operates in parallel - so it will be much more efficient than any serial methods.</p>
1
2009-07-22T21:53:13Z
1,168,679
<p>I know you didn't ask for list comprehension, but here it is anyway:</p> <pre><code>paragraph = "I eat bananas and a banana" words = ['banana', 'loganberry', 'passion fruit'] [len(re.findall(word, paragraph)) for word in words] </code></pre> <p>This returns [2, 0, 0] as well.</p>
2
2009-07-22T22:34:55Z
[ "python", "regex", "mapreduce" ]
Using map() to get number of times list elements exist in a string in Python
1,168,517
<p>I'm trying to get the number of times each item in a list is in a string in Python:</p> <pre><code>paragraph = "I eat bananas and a banana" def tester(x): return len(re.findall(x,paragraph)) map(tester, ['banana', 'loganberry', 'passion fruit']) </code></pre> <p>Returns [2, 0, 0] </p> <p>What I'd like to do however is extend this so I can feed the paragraph value into the map() function. Right now, the tester() function has paragraph hardcoded. Does anybody have a way to do this (perhaps make an n-length list of paragraph values)? Any other ideas here?</p> <p>Keep in mind that each of the array values will have a weight at some point in the future - hence the need to keep the values in a list rather than crunching them all together.</p> <p>UPDATE: The paragraph will often be 20K and the list will often have 200+ members. My thinking is that map operates in parallel - so it will be much more efficient than any serial methods.</p>
1
2009-07-22T21:53:13Z
1,168,777
<pre><code>targets = ['banana', 'loganberry', 'passion fruit'] paragraph = "I eat bananas and a banana" print [paragraph.count(target) for target in targets] </code></pre> <p>No idea why you would use map() here.</p>
3
2009-07-22T23:06:47Z
[ "python", "regex", "mapreduce" ]
Using map() to get number of times list elements exist in a string in Python
1,168,517
<p>I'm trying to get the number of times each item in a list is in a string in Python:</p> <pre><code>paragraph = "I eat bananas and a banana" def tester(x): return len(re.findall(x,paragraph)) map(tester, ['banana', 'loganberry', 'passion fruit']) </code></pre> <p>Returns [2, 0, 0] </p> <p>What I'd like to do however is extend this so I can feed the paragraph value into the map() function. Right now, the tester() function has paragraph hardcoded. Does anybody have a way to do this (perhaps make an n-length list of paragraph values)? Any other ideas here?</p> <p>Keep in mind that each of the array values will have a weight at some point in the future - hence the need to keep the values in a list rather than crunching them all together.</p> <p>UPDATE: The paragraph will often be 20K and the list will often have 200+ members. My thinking is that map operates in parallel - so it will be much more efficient than any serial methods.</p>
1
2009-07-22T21:53:13Z
1,168,795
<p>Here's my version. </p> <pre><code>paragraph = "I eat bananas and a banana" def tester(paragraph, x): return len(re.findall(x,paragraph)) print lambda paragraph: map( lambda x: tester(paragraph, x) , ['banana', 'loganberry', 'passion fruit'] )(paragraph) </code></pre>
0
2009-07-22T23:16:55Z
[ "python", "regex", "mapreduce" ]
Using map() to get number of times list elements exist in a string in Python
1,168,517
<p>I'm trying to get the number of times each item in a list is in a string in Python:</p> <pre><code>paragraph = "I eat bananas and a banana" def tester(x): return len(re.findall(x,paragraph)) map(tester, ['banana', 'loganberry', 'passion fruit']) </code></pre> <p>Returns [2, 0, 0] </p> <p>What I'd like to do however is extend this so I can feed the paragraph value into the map() function. Right now, the tester() function has paragraph hardcoded. Does anybody have a way to do this (perhaps make an n-length list of paragraph values)? Any other ideas here?</p> <p>Keep in mind that each of the array values will have a weight at some point in the future - hence the need to keep the values in a list rather than crunching them all together.</p> <p>UPDATE: The paragraph will often be 20K and the list will often have 200+ members. My thinking is that map operates in parallel - so it will be much more efficient than any serial methods.</p>
1
2009-07-22T21:53:13Z
1,168,801
<p>This is basically just going out of your way to avoid a list comprehension, but if you like functional style programming, then you'll like <a href="http://docs.python.org/library/functools.html#functools.partial" rel="nofollow">functools.partial</a>.</p> <pre><code>&gt;&gt;&gt; from functools import partial &gt;&gt;&gt; def counter(text, paragraph): return len(re.findall(text, paragraph)) &gt;&gt;&gt; tester = partial(counter, paragraph="I eat bananas and a banana") &gt;&gt;&gt; map(tester, ['banana', 'loganberry', 'passion fruit']) [2, 0, 0] </code></pre>
2
2009-07-22T23:19:36Z
[ "python", "regex", "mapreduce" ]
Using map() to get number of times list elements exist in a string in Python
1,168,517
<p>I'm trying to get the number of times each item in a list is in a string in Python:</p> <pre><code>paragraph = "I eat bananas and a banana" def tester(x): return len(re.findall(x,paragraph)) map(tester, ['banana', 'loganberry', 'passion fruit']) </code></pre> <p>Returns [2, 0, 0] </p> <p>What I'd like to do however is extend this so I can feed the paragraph value into the map() function. Right now, the tester() function has paragraph hardcoded. Does anybody have a way to do this (perhaps make an n-length list of paragraph values)? Any other ideas here?</p> <p>Keep in mind that each of the array values will have a weight at some point in the future - hence the need to keep the values in a list rather than crunching them all together.</p> <p>UPDATE: The paragraph will often be 20K and the list will often have 200+ members. My thinking is that map operates in parallel - so it will be much more efficient than any serial methods.</p>
1
2009-07-22T21:53:13Z
1,172,778
<p>For Q query words of average length L bytes on large texts of size T bytes, you need something that's NOT O(QLT). You need a DFA-style approach which can give you O(T) ... after setup costs. If your query set is rather static, then the setup cost can be ignored.</p> <p>E.g. <code>http://en.wikipedia.org/wiki/Aho-Corasick_algorithm</code><br /> which points to a C-extension for Python:<br /> <code>http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/</code></p>
1
2009-07-23T15:58:19Z
[ "python", "regex", "mapreduce" ]
Using map() to get number of times list elements exist in a string in Python
1,168,517
<p>I'm trying to get the number of times each item in a list is in a string in Python:</p> <pre><code>paragraph = "I eat bananas and a banana" def tester(x): return len(re.findall(x,paragraph)) map(tester, ['banana', 'loganberry', 'passion fruit']) </code></pre> <p>Returns [2, 0, 0] </p> <p>What I'd like to do however is extend this so I can feed the paragraph value into the map() function. Right now, the tester() function has paragraph hardcoded. Does anybody have a way to do this (perhaps make an n-length list of paragraph values)? Any other ideas here?</p> <p>Keep in mind that each of the array values will have a weight at some point in the future - hence the need to keep the values in a list rather than crunching them all together.</p> <p>UPDATE: The paragraph will often be 20K and the list will often have 200+ members. My thinking is that map operates in parallel - so it will be much more efficient than any serial methods.</p>
1
2009-07-22T21:53:13Z
1,175,599
<p>Here's a response to the movement of the goalposts ("I probably need the regex because I'll need word delimiters in the near future"):</p> <p>This method parses the text once to obtain a list of all the "words". Each word is looked up in a dictionary of the target words, and if it is a target word it is counted. The time taken is O(P) + O(T) where P is the size of the paragraph and T is the number of target words. All other solutions to date (including the currently accepted solution) except my Aho-Corasick solution are O(PT).</p> <pre><code>def counts_all(targets, paragraph, word_regex=r"\w+"): tally = dict((target, 0) for target in targets) for word in re.findall(word_regex, paragraph): if word in tally: tally[word] += 1 return [tally[target] for target in targets] def counts_iter(targets, paragraph, word_regex=r"\w+"): tally = dict((target, 0) for target in targets) for matchobj in re.finditer(word_regex, paragraph): word = matchobj.group() if word in tally: tally[word] += 1 return [tally[target] for target in targets] </code></pre> <p>The finditer version is a strawman -- it's much slower than the findall version.</p> <p>Here's the currently accepted solution expressed in a standardised form and augmented with word delimiters:</p> <pre><code>def currently_accepted_solution_augmented(targets, paragraph): def tester(s): def f(x): return len(re.findall(r"\b" + x + r"\b", s)) return f return map(tester(paragraph), targets) </code></pre> <p>which goes overboard on closures and could be reduced to:</p> <pre><code># acknowledgement: # this is structurally the same as one of hughdbrown's benchmark functions def currently_accepted_solution_augmented_without_extra_closure(targets, paragraph): def tester(x): return len(re.findall(r"\b" + x + r"\b", paragraph)) return map(tester, targets) </code></pre> <p>All variations on the currently accepted solution are O(PT). Unlike the currently accepted solution, the regex search with word delimiters is not equivalent to a simple <code>paragraph.find(target)</code>. Because the re engine doesn't use the "fast search" in this case, adding the word delimiters changes it fron slow to <strong>very</strong> slow.</p>
1
2009-07-24T03:21:15Z
[ "python", "regex", "mapreduce" ]
Recommended ways to split some functionality into functions, modules and packages?
1,168,565
<p>There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project).</p> <p>The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.</p>
6
2009-07-22T22:05:47Z
1,168,597
<p>IMHO this should probably one of the things you do earlier in the development process. I have never worked on a large-scale project, but it would make sense that you make a roadmap of what's going to be done and where. (Not trying to rib you for asking about it like you made a mistake :D )</p> <p>Modules are generally grouped somehow, by purpose or functionality. You could try each implementation of an interface, or other connections.</p>
1
2009-07-22T22:12:49Z
[ "python", "module", "package" ]
Recommended ways to split some functionality into functions, modules and packages?
1,168,565
<p>There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project).</p> <p>The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.</p>
6
2009-07-22T22:05:47Z
1,168,598
<p>Take out a pen and piece of paper. Try to draw how your software interacts on a high level. Draw the different layers of the software etc. Group items by functionality and purpose, maybe even by what sort of technology they use. If your software has multiple abstraction layers, I would say to group them by that. On a high level, the elements of a specific layer all share the same general purpose. Now that you have your software in layers, you can divide these layers into different projects based on specific functionality or specialization. </p> <p>As for a certain stage that you reach in which you should do this? I'd say when you have multiple people working on the code base or if you want to keep your project as modular as possible. Hopefully your code is modular enough to do this with. If you are unable to break apart your software on a high level, then your software is probably spaghetti code and you should look at refactoring it. </p> <p>Hopefully that will give you something to work with.</p>
3
2009-07-22T22:13:07Z
[ "python", "module", "package" ]
Recommended ways to split some functionality into functions, modules and packages?
1,168,565
<p>There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project).</p> <p>The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.</p>
6
2009-07-22T22:05:47Z
1,168,613
<p>Actually it varies for each project you create but here is an example:</p> <ol> <li><code>core</code> package contains modules that are your project cant live without. this may contain the main functionality of your application.</li> <li><code>ui</code> package contains modules that deals with the user interface. that is if you split the UI from your console.</li> </ol> <p>This is just an example. and it would really you that would be deciding which and what to go where.</p>
0
2009-07-22T22:16:23Z
[ "python", "module", "package" ]
Recommended ways to split some functionality into functions, modules and packages?
1,168,565
<p>There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project).</p> <p>The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.</p>
6
2009-07-22T22:05:47Z
1,168,652
<p>There's a classic paper by David Parnas called "On the criteria to be used in decomposing systems into modules". It's a classic (and has a certain age, so can be a little outdated).</p> <p>Maybe you can start from there, a PDF is available here</p> <p><a href="http://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf">http://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf</a></p>
6
2009-07-22T22:27:58Z
[ "python", "module", "package" ]
Recommended ways to split some functionality into functions, modules and packages?
1,168,565
<p>There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project).</p> <p>The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.</p>
6
2009-07-22T22:05:47Z
1,169,182
<p>See <a href="http://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file">http://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file</a></p> <p>Sketch your overall set of class definitions.</p> <p>Partition these class definitions into "modules".</p> <p>Implement and test the modules separately from each other.</p> <p>Knit the modules together to create your final application.</p> <p><strong>Note</strong>. It's almost impossible to decompose a working application that evolved organically. So don't do that. </p> <p>Decompose your design early and often. Build separate modules. Integrate to build an application.</p>
2
2009-07-23T01:52:10Z
[ "python", "module", "package" ]
Recommended ways to split some functionality into functions, modules and packages?
1,168,565
<p>There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project).</p> <p>The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.</p>
6
2009-07-22T22:05:47Z
2,360,690
<p>I sympathize with you. You are suffering from self-doubt. Don't worry. If you can speak any language, including your mother tongue, you are qualified to do modularization on your own. For evidence, you may read "The Language Instinct," or "The Math Instinct."</p> <p>Look around, but not too much. You can learn a lot from them, but you can learn many bad things from them too. </p> <ol> <li><p>Some projects/framework get a lot fo hype. Yet, some of their groupings of functionality, even names given to modules are misleading. They don't "reveal intention" of the programmers. They fail the "high cohesiveness" test.</p></li> <li><p>Books are no better. Please apply 80/20 rule in your book selection. Even a good, very complete, well-researched book like Capers Jones' 2010 "Software Engineering Best Practices" is clueless. It says 10-man Agile/XP team would take 12 years to do Windows Vista or 25 years to do an ERP package! It says there is no method till 2009 for segmentation, its term for modularization. I don't think it will help you.</p></li> </ol> <p>My point is: You must pick your model/reference/source of examples very carefully. Don't over-estimate famous names and under-estimate yourself.</p> <p>Here is my help, proven in my experience.</p> <ol> <li><p>It is a lot like deciding what attributes go to which DB table, what properties/methods go to which class/object etc? On a deeper level, it is a lot like arranging furniture at home, or books in a shelf. You have done such things already. Software is the same, no big deal!</p></li> <li><p>Worry about "cohesion" first. e.g. Books (Leo Tolstoy, James Joyce, DE Lawrence) is choesive .(HTML, CSS, John Keats. jQuery, tinymce) is not. And there are many ways to arrange things. Even taxonomists are still in serious feuds over this.</p></li> <li><p>Then worry about "coupling." Be "shy". "Don't talk to strangers." Don't be over-friendly. Try to make your package/DB table/class/object/module/bookshelf as self-contained, as independent as possible. Joel has talked about his admiration for the Excel team that abhor all external dependencies and that even built their own compiler.</p></li> </ol>
1
2010-03-02T03:18:55Z
[ "python", "module", "package" ]
To make a plan for my first MySQL project
1,168,701
<p>I need to complete the plan of a <a href="http://translate.google.com/translate?hl=en&amp;sl=fi&amp;tl=en&amp;u=http%3A%2F%2Fwww.cs.helsinki.fi%2Fu%2Flaine%2Finfoht%2Faiheet%2Fis97je1.html">ask-a-question site for my uni.</a> in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.</p> <p><strong>Questions about the project which do not fit here</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to make efficient tables</a></li> <li><a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database">to improve a relation figure</a></li> <li><a href="http://stackoverflow.com/questions/1182910/to-improve-a-sequence-diagram">to improve a ERD diagram</a></li> <li><a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python">to SHA1-hash you password in a MySQL database by Python</a></li> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to have a revision history for the questions</a></li> <li><a href="http://stackoverflow.com/questions/1184634/which-is-the-right-way-of-designing-a-database">to get the right way in designing databases</a></li> <li><a href="http://stackoverflow.com/questions/1184857/to-get-primary-and-foreign-keys-right-in-erd">to get primary and foreign keys right in ERD</a></li> <li><a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session">to understand login -variable in cookies/URL</a></li> <li><a href="http://stackoverflow.com/questions/1187473/to-know-whether-my-uni-can-run-python-web-applications">to get info about my Uni's servers</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-postgresql">to improve SQL -queries</a></li> <li><a href="http://stackoverflow.com/questions/1196034/is-there-any-iso-standard-of-how-to-write-sql-queries-in-ddl">to write SQL queries in DDL correctly</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to prevent to use of duplicate tags in a question</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl">to improve SQL queries in DDL</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to have no duplicate tags in a table</a></li> <li><a href="http://stackoverflow.com/questions/1197031/to-separate-answers-in-a-database">to separate answers in a databse</a></li> </ul> <p><hr /></p> <p>My <a href="http://translate.google.com/translate?prev=hp&amp;hl=en&amp;js=y&amp;u=http%3A%2F%2Fcs.helsinki.fi%2Fu%2Flaine%2Ftikas%2Fmaterial%2Fohjeita.html&amp;sl=fi&amp;tl=en&amp;history%5Fstate0=">uni. offers little support</a> for tools which I selected:</p> <p><strong>Tools in building the backend</strong></p> <ul> <li><strong>Python</strong> in building the database schema??? <em>(I am not sure which components I can build by Python)</em></li> <li><strong>MySQL</strong> to store data </li> <li>I am not sure <strong>which tool to use in building login and logout -system</strong>. <em>They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.</em></li> </ul> <p><strong>Tools in building the frontend</strong></p> <ul> <li>Django <em>(if we can use MySQL in Django)</em></li> </ul> <p><strong>Tools for Planning</strong></p> <ul> <li><strong>Google Do
3
2009-07-22T22:41:51Z
1,168,750
<p>First, this is all a lot to work with in a week. But here it goes.</p> <p>Tools for the backend:</p> <ol> <li>SQLAlchemy - This is an ORM toolkit that is plenty powerful for most smaller tasks when using a MySQL database built with Python. To my knowledge, it is the best for this job. <a href="http://www.sqlalchemy.org/" rel="nofollow">http://www.sqlalchemy.org/</a></li> <li>Django - "...is a high-level Python Web framework..." This might be better for rapid development of a site with login/logout methods included and a minimal learning curve for someone with web/Python understanding.</li> </ol> <p>Tools in building the frontend:</p> <p>If you already plan on using Django for the backend, I'd recommend using it for the frontend as well.</p> <p>Things about which you are uncertain:</p> <ol> <li>The users can be specified in MySQL and their permissions can be set accordingly.</li> <li>From some of the requirements you listed, most of these sound like they can be contained within the capabilities of Django.</li> </ol>
4
2009-07-22T23:00:16Z
[ "python", "mysql" ]
To make a plan for my first MySQL project
1,168,701
<p>I need to complete the plan of a <a href="http://translate.google.com/translate?hl=en&amp;sl=fi&amp;tl=en&amp;u=http%3A%2F%2Fwww.cs.helsinki.fi%2Fu%2Flaine%2Finfoht%2Faiheet%2Fis97je1.html">ask-a-question site for my uni.</a> in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.</p> <p><strong>Questions about the project which do not fit here</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to make efficient tables</a></li> <li><a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database">to improve a relation figure</a></li> <li><a href="http://stackoverflow.com/questions/1182910/to-improve-a-sequence-diagram">to improve a ERD diagram</a></li> <li><a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python">to SHA1-hash you password in a MySQL database by Python</a></li> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to have a revision history for the questions</a></li> <li><a href="http://stackoverflow.com/questions/1184634/which-is-the-right-way-of-designing-a-database">to get the right way in designing databases</a></li> <li><a href="http://stackoverflow.com/questions/1184857/to-get-primary-and-foreign-keys-right-in-erd">to get primary and foreign keys right in ERD</a></li> <li><a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session">to understand login -variable in cookies/URL</a></li> <li><a href="http://stackoverflow.com/questions/1187473/to-know-whether-my-uni-can-run-python-web-applications">to get info about my Uni's servers</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-postgresql">to improve SQL -queries</a></li> <li><a href="http://stackoverflow.com/questions/1196034/is-there-any-iso-standard-of-how-to-write-sql-queries-in-ddl">to write SQL queries in DDL correctly</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to prevent to use of duplicate tags in a question</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl">to improve SQL queries in DDL</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to have no duplicate tags in a table</a></li> <li><a href="http://stackoverflow.com/questions/1197031/to-separate-answers-in-a-database">to separate answers in a databse</a></li> </ul> <p><hr /></p> <p>My <a href="http://translate.google.com/translate?prev=hp&amp;hl=en&amp;js=y&amp;u=http%3A%2F%2Fcs.helsinki.fi%2Fu%2Flaine%2Ftikas%2Fmaterial%2Fohjeita.html&amp;sl=fi&amp;tl=en&amp;history%5Fstate0=">uni. offers little support</a> for tools which I selected:</p> <p><strong>Tools in building the backend</strong></p> <ul> <li><strong>Python</strong> in building the database schema??? <em>(I am not sure which components I can build by Python)</em></li> <li><strong>MySQL</strong> to store data </li> <li>I am not sure <strong>which tool to use in building login and logout -system</strong>. <em>They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.</em></li> </ul> <p><strong>Tools in building the frontend</strong></p> <ul> <li>Django <em>(if we can use MySQL in Django)</em></li> </ul> <p><strong>Tools for Planning</strong></p> <ul> <li><strong>Google Do
3
2009-07-22T22:41:51Z
1,168,831
<p>I'm guessing that you wouldn't be allowed to use an ORM, since you call this a "MySQL project".</p> <p>If this is an incorrect assumption, I'd agree with N Arnold's recommendation of using Django. Rather than using SQLAlchemy, I think you'd find that Django's ORM is good enough (especially if you use v1.1rc or trunk).</p> <p>Like some of the comments to your initial question, this does seem like a large amount of work if you have to learn a framework as well as produce a project in it. On the other hand, someone who knew Django could crack out the base of such a project in a day or two.</p>
1
2009-07-22T23:35:03Z
[ "python", "mysql" ]
To make a plan for my first MySQL project
1,168,701
<p>I need to complete the plan of a <a href="http://translate.google.com/translate?hl=en&amp;sl=fi&amp;tl=en&amp;u=http%3A%2F%2Fwww.cs.helsinki.fi%2Fu%2Flaine%2Finfoht%2Faiheet%2Fis97je1.html">ask-a-question site for my uni.</a> in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.</p> <p><strong>Questions about the project which do not fit here</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to make efficient tables</a></li> <li><a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database">to improve a relation figure</a></li> <li><a href="http://stackoverflow.com/questions/1182910/to-improve-a-sequence-diagram">to improve a ERD diagram</a></li> <li><a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python">to SHA1-hash you password in a MySQL database by Python</a></li> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to have a revision history for the questions</a></li> <li><a href="http://stackoverflow.com/questions/1184634/which-is-the-right-way-of-designing-a-database">to get the right way in designing databases</a></li> <li><a href="http://stackoverflow.com/questions/1184857/to-get-primary-and-foreign-keys-right-in-erd">to get primary and foreign keys right in ERD</a></li> <li><a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session">to understand login -variable in cookies/URL</a></li> <li><a href="http://stackoverflow.com/questions/1187473/to-know-whether-my-uni-can-run-python-web-applications">to get info about my Uni's servers</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-postgresql">to improve SQL -queries</a></li> <li><a href="http://stackoverflow.com/questions/1196034/is-there-any-iso-standard-of-how-to-write-sql-queries-in-ddl">to write SQL queries in DDL correctly</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to prevent to use of duplicate tags in a question</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl">to improve SQL queries in DDL</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to have no duplicate tags in a table</a></li> <li><a href="http://stackoverflow.com/questions/1197031/to-separate-answers-in-a-database">to separate answers in a databse</a></li> </ul> <p><hr /></p> <p>My <a href="http://translate.google.com/translate?prev=hp&amp;hl=en&amp;js=y&amp;u=http%3A%2F%2Fcs.helsinki.fi%2Fu%2Flaine%2Ftikas%2Fmaterial%2Fohjeita.html&amp;sl=fi&amp;tl=en&amp;history%5Fstate0=">uni. offers little support</a> for tools which I selected:</p> <p><strong>Tools in building the backend</strong></p> <ul> <li><strong>Python</strong> in building the database schema??? <em>(I am not sure which components I can build by Python)</em></li> <li><strong>MySQL</strong> to store data </li> <li>I am not sure <strong>which tool to use in building login and logout -system</strong>. <em>They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.</em></li> </ul> <p><strong>Tools in building the frontend</strong></p> <ul> <li>Django <em>(if we can use MySQL in Django)</em></li> </ul> <p><strong>Tools for Planning</strong></p> <ul> <li><strong>Google Do
3
2009-07-22T22:41:51Z
1,168,872
<p>Use the django Model to create the Object-Relational Mapping (ORM) that injects and retrieve your data. </p> <p>For login/logout, django has an AuthenticationMiddleware feature you can probably use, although I am not sure if you can solve your problem with it.</p> <p>In any case, your project, with the given deadlines is totally unrealistic. Be prepared to miss the deadline, and hear the whooshing sound they do as they fly by.</p>
2
2009-07-22T23:48:27Z
[ "python", "mysql" ]
To make a plan for my first MySQL project
1,168,701
<p>I need to complete the plan of a <a href="http://translate.google.com/translate?hl=en&amp;sl=fi&amp;tl=en&amp;u=http%3A%2F%2Fwww.cs.helsinki.fi%2Fu%2Flaine%2Finfoht%2Faiheet%2Fis97je1.html">ask-a-question site for my uni.</a> in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.</p> <p><strong>Questions about the project which do not fit here</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to make efficient tables</a></li> <li><a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database">to improve a relation figure</a></li> <li><a href="http://stackoverflow.com/questions/1182910/to-improve-a-sequence-diagram">to improve a ERD diagram</a></li> <li><a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python">to SHA1-hash you password in a MySQL database by Python</a></li> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to have a revision history for the questions</a></li> <li><a href="http://stackoverflow.com/questions/1184634/which-is-the-right-way-of-designing-a-database">to get the right way in designing databases</a></li> <li><a href="http://stackoverflow.com/questions/1184857/to-get-primary-and-foreign-keys-right-in-erd">to get primary and foreign keys right in ERD</a></li> <li><a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session">to understand login -variable in cookies/URL</a></li> <li><a href="http://stackoverflow.com/questions/1187473/to-know-whether-my-uni-can-run-python-web-applications">to get info about my Uni's servers</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-postgresql">to improve SQL -queries</a></li> <li><a href="http://stackoverflow.com/questions/1196034/is-there-any-iso-standard-of-how-to-write-sql-queries-in-ddl">to write SQL queries in DDL correctly</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to prevent to use of duplicate tags in a question</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl">to improve SQL queries in DDL</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to have no duplicate tags in a table</a></li> <li><a href="http://stackoverflow.com/questions/1197031/to-separate-answers-in-a-database">to separate answers in a databse</a></li> </ul> <p><hr /></p> <p>My <a href="http://translate.google.com/translate?prev=hp&amp;hl=en&amp;js=y&amp;u=http%3A%2F%2Fcs.helsinki.fi%2Fu%2Flaine%2Ftikas%2Fmaterial%2Fohjeita.html&amp;sl=fi&amp;tl=en&amp;history%5Fstate0=">uni. offers little support</a> for tools which I selected:</p> <p><strong>Tools in building the backend</strong></p> <ul> <li><strong>Python</strong> in building the database schema??? <em>(I am not sure which components I can build by Python)</em></li> <li><strong>MySQL</strong> to store data </li> <li>I am not sure <strong>which tool to use in building login and logout -system</strong>. <em>They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.</em></li> </ul> <p><strong>Tools in building the frontend</strong></p> <ul> <li>Django <em>(if we can use MySQL in Django)</em></li> </ul> <p><strong>Tools for Planning</strong></p> <ul> <li><strong>Google Do
3
2009-07-22T22:41:51Z
1,170,069
<p>You can build your database with MySQL, go read the <a href="http://dev.mysql.com/doc/" rel="nofollow">official docs</a>. It really doesn't matter what language you use to program a front-end whether it be a website, command line interface, gui interface, most languages handle this pretty well but it seems you're set on building a web application and this can be achieved very easily with <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>, which is a Python web framework.</p> <p>Doing what I've told you, if you keep at it you'll be done in under 16 hours. Good luck. Btw. your project seems to focus on a lot of irrelevant things. You're creating a database application, unless you already know CSS and JQuery, why don't you just create it in simple unstyled XHTML; that way you have less work to do!</p>
1
2009-07-23T06:58:39Z
[ "python", "mysql" ]
To make a plan for my first MySQL project
1,168,701
<p>I need to complete the plan of a <a href="http://translate.google.com/translate?hl=en&amp;sl=fi&amp;tl=en&amp;u=http%3A%2F%2Fwww.cs.helsinki.fi%2Fu%2Flaine%2Finfoht%2Faiheet%2Fis97je1.html">ask-a-question site for my uni.</a> in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.</p> <p><strong>Questions about the project which do not fit here</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to make efficient tables</a></li> <li><a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database">to improve a relation figure</a></li> <li><a href="http://stackoverflow.com/questions/1182910/to-improve-a-sequence-diagram">to improve a ERD diagram</a></li> <li><a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python">to SHA1-hash you password in a MySQL database by Python</a></li> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to have a revision history for the questions</a></li> <li><a href="http://stackoverflow.com/questions/1184634/which-is-the-right-way-of-designing-a-database">to get the right way in designing databases</a></li> <li><a href="http://stackoverflow.com/questions/1184857/to-get-primary-and-foreign-keys-right-in-erd">to get primary and foreign keys right in ERD</a></li> <li><a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session">to understand login -variable in cookies/URL</a></li> <li><a href="http://stackoverflow.com/questions/1187473/to-know-whether-my-uni-can-run-python-web-applications">to get info about my Uni's servers</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-postgresql">to improve SQL -queries</a></li> <li><a href="http://stackoverflow.com/questions/1196034/is-there-any-iso-standard-of-how-to-write-sql-queries-in-ddl">to write SQL queries in DDL correctly</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to prevent to use of duplicate tags in a question</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl">to improve SQL queries in DDL</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to have no duplicate tags in a table</a></li> <li><a href="http://stackoverflow.com/questions/1197031/to-separate-answers-in-a-database">to separate answers in a databse</a></li> </ul> <p><hr /></p> <p>My <a href="http://translate.google.com/translate?prev=hp&amp;hl=en&amp;js=y&amp;u=http%3A%2F%2Fcs.helsinki.fi%2Fu%2Flaine%2Ftikas%2Fmaterial%2Fohjeita.html&amp;sl=fi&amp;tl=en&amp;history%5Fstate0=">uni. offers little support</a> for tools which I selected:</p> <p><strong>Tools in building the backend</strong></p> <ul> <li><strong>Python</strong> in building the database schema??? <em>(I am not sure which components I can build by Python)</em></li> <li><strong>MySQL</strong> to store data </li> <li>I am not sure <strong>which tool to use in building login and logout -system</strong>. <em>They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.</em></li> </ul> <p><strong>Tools in building the frontend</strong></p> <ul> <li>Django <em>(if we can use MySQL in Django)</em></li> </ul> <p><strong>Tools for Planning</strong></p> <ul> <li><strong>Google Do
3
2009-07-22T22:41:51Z
1,170,964
<p><strong>About Moderators and Users</strong></p> <p>What is the difference between moderators and users? Moderators can modify text, but how? Are they planning you to practise permissions, fs or some open-source system to differentiate users from moderators? </p> <p>Very odd that they do not allow Google products, but they allow open-source. Interestingly, <a href="http://www.cs.usfca.edu/courses/cs682/assignments/lab-5.html" rel="nofollow">USFCA</a> encourages Google products in similar projects. Perhaps, there are some users, who could help you with userspaces.</p> <p>Good luck!</p>
0
2009-07-23T10:48:47Z
[ "python", "mysql" ]
To make a plan for my first MySQL project
1,168,701
<p>I need to complete the plan of a <a href="http://translate.google.com/translate?hl=en&amp;sl=fi&amp;tl=en&amp;u=http%3A%2F%2Fwww.cs.helsinki.fi%2Fu%2Flaine%2Finfoht%2Faiheet%2Fis97je1.html">ask-a-question site for my uni.</a> in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.</p> <p><strong>Questions about the project which do not fit here</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to make efficient tables</a></li> <li><a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database">to improve a relation figure</a></li> <li><a href="http://stackoverflow.com/questions/1182910/to-improve-a-sequence-diagram">to improve a ERD diagram</a></li> <li><a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python">to SHA1-hash you password in a MySQL database by Python</a></li> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to have a revision history for the questions</a></li> <li><a href="http://stackoverflow.com/questions/1184634/which-is-the-right-way-of-designing-a-database">to get the right way in designing databases</a></li> <li><a href="http://stackoverflow.com/questions/1184857/to-get-primary-and-foreign-keys-right-in-erd">to get primary and foreign keys right in ERD</a></li> <li><a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session">to understand login -variable in cookies/URL</a></li> <li><a href="http://stackoverflow.com/questions/1187473/to-know-whether-my-uni-can-run-python-web-applications">to get info about my Uni's servers</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-postgresql">to improve SQL -queries</a></li> <li><a href="http://stackoverflow.com/questions/1196034/is-there-any-iso-standard-of-how-to-write-sql-queries-in-ddl">to write SQL queries in DDL correctly</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to prevent to use of duplicate tags in a question</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl">to improve SQL queries in DDL</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to have no duplicate tags in a table</a></li> <li><a href="http://stackoverflow.com/questions/1197031/to-separate-answers-in-a-database">to separate answers in a databse</a></li> </ul> <p><hr /></p> <p>My <a href="http://translate.google.com/translate?prev=hp&amp;hl=en&amp;js=y&amp;u=http%3A%2F%2Fcs.helsinki.fi%2Fu%2Flaine%2Ftikas%2Fmaterial%2Fohjeita.html&amp;sl=fi&amp;tl=en&amp;history%5Fstate0=">uni. offers little support</a> for tools which I selected:</p> <p><strong>Tools in building the backend</strong></p> <ul> <li><strong>Python</strong> in building the database schema??? <em>(I am not sure which components I can build by Python)</em></li> <li><strong>MySQL</strong> to store data </li> <li>I am not sure <strong>which tool to use in building login and logout -system</strong>. <em>They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.</em></li> </ul> <p><strong>Tools in building the frontend</strong></p> <ul> <li>Django <em>(if we can use MySQL in Django)</em></li> </ul> <p><strong>Tools for Planning</strong></p> <ul> <li><strong>Google Do
3
2009-07-22T22:41:51Z
1,171,064
<p>Django can use many different database backends one of which is MySQL, to help support this it provides an ORM (Object Relational Mapping) layer which abstracts away the SQL code and storage medium and allows you to write Models containing storage fields and logic as necessary without worrying about how they are stored in the persistence layer.</p> <p>Django also contains basic authentication (login/logout) functionality and has the concept of users and admin-users built into it.</p> <p>As an example using the built in user models and the ORM would allow you to get all questions asked by a user with something like the following code:</p> <pre><code>Question.objects.all.filter(asker=request.user) </code></pre> <p>Where Questions is the model you have defined to hold your questions (with a field called 'asker' which is a foreign key to the user) and the request.user is the user logged into the website.</p> <p>I suggest you read up on the <a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">Django ORM</a>.</p> <p>As far as hosting it, you could use Ubuntu on a desktop computer, or if you need an external host then would recommend <a href="http://webfaction.com" rel="nofollow">Webfaction</a> or <a href="http://Djangohosting.ch" rel="nofollow">Djangohosting.ch</a> as two of the most 'Django Friendly' Hosts.</p>
1
2009-07-23T11:11:06Z
[ "python", "mysql" ]
To make a plan for my first MySQL project
1,168,701
<p>I need to complete the plan of a <a href="http://translate.google.com/translate?hl=en&amp;sl=fi&amp;tl=en&amp;u=http%3A%2F%2Fwww.cs.helsinki.fi%2Fu%2Flaine%2Finfoht%2Faiheet%2Fis97je1.html">ask-a-question site for my uni.</a> in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.</p> <p><strong>Questions about the project which do not fit here</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to make efficient tables</a></li> <li><a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database">to improve a relation figure</a></li> <li><a href="http://stackoverflow.com/questions/1182910/to-improve-a-sequence-diagram">to improve a ERD diagram</a></li> <li><a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python">to SHA1-hash you password in a MySQL database by Python</a></li> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to have a revision history for the questions</a></li> <li><a href="http://stackoverflow.com/questions/1184634/which-is-the-right-way-of-designing-a-database">to get the right way in designing databases</a></li> <li><a href="http://stackoverflow.com/questions/1184857/to-get-primary-and-foreign-keys-right-in-erd">to get primary and foreign keys right in ERD</a></li> <li><a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session">to understand login -variable in cookies/URL</a></li> <li><a href="http://stackoverflow.com/questions/1187473/to-know-whether-my-uni-can-run-python-web-applications">to get info about my Uni's servers</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-postgresql">to improve SQL -queries</a></li> <li><a href="http://stackoverflow.com/questions/1196034/is-there-any-iso-standard-of-how-to-write-sql-queries-in-ddl">to write SQL queries in DDL correctly</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to prevent to use of duplicate tags in a question</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl">to improve SQL queries in DDL</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to have no duplicate tags in a table</a></li> <li><a href="http://stackoverflow.com/questions/1197031/to-separate-answers-in-a-database">to separate answers in a databse</a></li> </ul> <p><hr /></p> <p>My <a href="http://translate.google.com/translate?prev=hp&amp;hl=en&amp;js=y&amp;u=http%3A%2F%2Fcs.helsinki.fi%2Fu%2Flaine%2Ftikas%2Fmaterial%2Fohjeita.html&amp;sl=fi&amp;tl=en&amp;history%5Fstate0=">uni. offers little support</a> for tools which I selected:</p> <p><strong>Tools in building the backend</strong></p> <ul> <li><strong>Python</strong> in building the database schema??? <em>(I am not sure which components I can build by Python)</em></li> <li><strong>MySQL</strong> to store data </li> <li>I am not sure <strong>which tool to use in building login and logout -system</strong>. <em>They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.</em></li> </ul> <p><strong>Tools in building the frontend</strong></p> <ul> <li>Django <em>(if we can use MySQL in Django)</em></li> </ul> <p><strong>Tools for Planning</strong></p> <ul> <li><strong>Google Do
3
2009-07-22T22:41:51Z
1,171,353
<p>They give us only <a href="http://db.cs.helsinki.fi/~laine/php/lahja2.txt" rel="nofollow">this example</a> of the <a href="http://db.cs.helsinki.fi/~laine/php/lahjax.php" rel="nofollow">web app</a>. The code is not useful for me, since the code is in Finnish and it is written in PHP. It is also not open-source such that I cannot paste the code here.</p> <p>I would like to see similar examples in Python. Please, put links to the comments. </p>
0
2009-07-23T12:15:06Z
[ "python", "mysql" ]
To make a plan for my first MySQL project
1,168,701
<p>I need to complete the plan of a <a href="http://translate.google.com/translate?hl=en&amp;sl=fi&amp;tl=en&amp;u=http%3A%2F%2Fwww.cs.helsinki.fi%2Fu%2Flaine%2Finfoht%2Faiheet%2Fis97je1.html">ask-a-question site for my uni.</a> in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.</p> <p><strong>Questions about the project which do not fit here</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to make efficient tables</a></li> <li><a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database">to improve a relation figure</a></li> <li><a href="http://stackoverflow.com/questions/1182910/to-improve-a-sequence-diagram">to improve a ERD diagram</a></li> <li><a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python">to SHA1-hash you password in a MySQL database by Python</a></li> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to have a revision history for the questions</a></li> <li><a href="http://stackoverflow.com/questions/1184634/which-is-the-right-way-of-designing-a-database">to get the right way in designing databases</a></li> <li><a href="http://stackoverflow.com/questions/1184857/to-get-primary-and-foreign-keys-right-in-erd">to get primary and foreign keys right in ERD</a></li> <li><a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session">to understand login -variable in cookies/URL</a></li> <li><a href="http://stackoverflow.com/questions/1187473/to-know-whether-my-uni-can-run-python-web-applications">to get info about my Uni's servers</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-postgresql">to improve SQL -queries</a></li> <li><a href="http://stackoverflow.com/questions/1196034/is-there-any-iso-standard-of-how-to-write-sql-queries-in-ddl">to write SQL queries in DDL correctly</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to prevent to use of duplicate tags in a question</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl">to improve SQL queries in DDL</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to have no duplicate tags in a table</a></li> <li><a href="http://stackoverflow.com/questions/1197031/to-separate-answers-in-a-database">to separate answers in a databse</a></li> </ul> <p><hr /></p> <p>My <a href="http://translate.google.com/translate?prev=hp&amp;hl=en&amp;js=y&amp;u=http%3A%2F%2Fcs.helsinki.fi%2Fu%2Flaine%2Ftikas%2Fmaterial%2Fohjeita.html&amp;sl=fi&amp;tl=en&amp;history%5Fstate0=">uni. offers little support</a> for tools which I selected:</p> <p><strong>Tools in building the backend</strong></p> <ul> <li><strong>Python</strong> in building the database schema??? <em>(I am not sure which components I can build by Python)</em></li> <li><strong>MySQL</strong> to store data </li> <li>I am not sure <strong>which tool to use in building login and logout -system</strong>. <em>They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.</em></li> </ul> <p><strong>Tools in building the frontend</strong></p> <ul> <li>Django <em>(if we can use MySQL in Django)</em></li> </ul> <p><strong>Tools for Planning</strong></p> <ul> <li><strong>Google Do
3
2009-07-22T22:41:51Z
1,184,936
<p>I think this can all be accomplished in django. See the <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">official tutorial</a>.</p>
2
2009-07-26T16:11:37Z
[ "python", "mysql" ]
To make a plan for my first MySQL project
1,168,701
<p>I need to complete the plan of a <a href="http://translate.google.com/translate?hl=en&amp;sl=fi&amp;tl=en&amp;u=http%3A%2F%2Fwww.cs.helsinki.fi%2Fu%2Flaine%2Finfoht%2Faiheet%2Fis97je1.html">ask-a-question site for my uni.</a> in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks.</p> <p><strong>Questions about the project which do not fit here</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to make efficient tables</a></li> <li><a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database">to improve a relation figure</a></li> <li><a href="http://stackoverflow.com/questions/1182910/to-improve-a-sequence-diagram">to improve a ERD diagram</a></li> <li><a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python">to SHA1-hash you password in a MySQL database by Python</a></li> <li><a href="http://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data">to have a revision history for the questions</a></li> <li><a href="http://stackoverflow.com/questions/1184634/which-is-the-right-way-of-designing-a-database">to get the right way in designing databases</a></li> <li><a href="http://stackoverflow.com/questions/1184857/to-get-primary-and-foreign-keys-right-in-erd">to get primary and foreign keys right in ERD</a></li> <li><a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session">to understand login -variable in cookies/URL</a></li> <li><a href="http://stackoverflow.com/questions/1187473/to-know-whether-my-uni-can-run-python-web-applications">to get info about my Uni's servers</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-postgresql">to improve SQL -queries</a></li> <li><a href="http://stackoverflow.com/questions/1196034/is-there-any-iso-standard-of-how-to-write-sql-queries-in-ddl">to write SQL queries in DDL correctly</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to prevent to use of duplicate tags in a question</a></li> <li><a href="http://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl">to improve SQL queries in DDL</a></li> <li><a href="http://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database">to have no duplicate tags in a table</a></li> <li><a href="http://stackoverflow.com/questions/1197031/to-separate-answers-in-a-database">to separate answers in a databse</a></li> </ul> <p><hr /></p> <p>My <a href="http://translate.google.com/translate?prev=hp&amp;hl=en&amp;js=y&amp;u=http%3A%2F%2Fcs.helsinki.fi%2Fu%2Flaine%2Ftikas%2Fmaterial%2Fohjeita.html&amp;sl=fi&amp;tl=en&amp;history%5Fstate0=">uni. offers little support</a> for tools which I selected:</p> <p><strong>Tools in building the backend</strong></p> <ul> <li><strong>Python</strong> in building the database schema??? <em>(I am not sure which components I can build by Python)</em></li> <li><strong>MySQL</strong> to store data </li> <li>I am not sure <strong>which tool to use in building login and logout -system</strong>. <em>They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.</em></li> </ul> <p><strong>Tools in building the frontend</strong></p> <ul> <li>Django <em>(if we can use MySQL in Django)</em></li> </ul> <p><strong>Tools for Planning</strong></p> <ul> <li><strong>Google Do
3
2009-07-22T22:41:51Z
1,184,941
<p>Ehh, what is the purpose of this development? To build a real production-ready system, or to pass an exam by building a mini-project that will never see real use?</p> <p>If your purpose is to pass an exam, then build what your teachers like to see. Take you cues from the material they have been using in classes, and also ask them outright what they think is good.</p> <p>If you want to build a production system, then Django would be a great choice. Respectfully however, given the limited understanding of Django you demonstrate, you will most likely not complete the project in time.</p> <p>Django has pre-existing functionality for:</p> <ul> <li>Building the database schema. The DB tables will be buildt when you define your model classes in Django and run manage.py syncdb.</li> <li>A login system. Django has a login system with cookies etc build into it; and several 3rd party Django addons extend this system.</li> <li>Encrypting passwords in the database, Django uses SHA-1 with a salt if memory serves.</li> </ul> <p>Thus your teachers could legitimately say that you haven't demonstrated your own skills at modeling a DB schema, you have just used Djangos pre-existing functionality. Will they be OK with this, or will they fail you on this exam?</p> <p>If you need to demonstrate understanding of the core concepts, perhaps you would be better off by staying with a system you know well already, instead of mixing in Django as another complexity, another thing you'll need to learn in very little time...</p>
1
2009-07-26T16:15:36Z
[ "python", "mysql" ]
Why does this Python script only read the last RSS post into the file?
1,168,844
<p>Im trying to fix a Python script which takes the posts from a specific RSS feed and strips them down and inputs them into a text file. As you can see beneath, there are two main print functions. One prints only to the shell once run, but it shows <em>all</em> of the posts, which is what I want it to do. Now, the second part is where the problem lies. It only prints out the <em>last</em> post of the RSS feed into a text, not the whole thing, as the first function does. I've also tried to make the second function (f = open()) the same way as the first with the %s instead of a new print-line pr. variable.</p> <p>If anyone could tell me why the script doesnt post more than one (the last) post of the RSS feed into the text, but the whole thing in the shell, and what modifications I need to fix it, I would really appreciate it :)</p> <p>Here is the code:</p> <pre><code>import urllib import sys import xml.dom.minidom #The url of the feed address = 'http://www.vg.no/export/Alle/rdf.hbs?kat=nyheter' #Our actual xml document document = xml.dom.minidom.parse(urllib.urlopen(address)) for item in document.getElementsByTagName('item'): title = item.getElementsByTagName('title')[0].firstChild.data link = item.getElementsByTagName('link')[0].firstChild.data description = item.getElementsByTagName('description')[0].firstChild.data str = link.strip("http://go.vg.no/cgi-bin/go.cgi/rssart/") print "\n" print "------------------------------------------------------------------" print '''"%s"\n\n%s\n\n(%s)''' % (title.encode('UTF8', 'replace'), description.encode('UTF8','replace'), str.encode('UTF8','replace')) print "------------------------------------------------------------------" print "\n" f = open('lawl.txt','w') print &gt;&gt;f, "----------------------Nyeste paa VG-------------------------------" print &gt;&gt;f, title.encode('UTF8','replace') print &gt;&gt;f, description.encode('UTF8','replace') print &gt;&gt;f, str.encode('UTF8','replace') print &gt;&gt;f, "------------------------------------------------------------------" print &gt;&gt;f, "\n" </code></pre>
0
2009-07-22T23:40:00Z
1,168,865
<p>Your <code>print &gt;&gt;f</code> are after the <code>for</code> loop, so they are run once, and operate on the data that you last saved to <code>title</code>, <code>description</code>, and <code>str</code>.</p> <p>You should open the file before the <code>for</code> loop and then put the <code>print &gt;&gt;f</code> lines inside the loop.</p> <pre><code>import urllib import sys import xml.dom.minidom #The url of the feed address = 'http://www.vg.no/export/Alle/rdf.hbs?kat=nyheter' f = open('lawl.txt','w') #Our actual xml document document = xml.dom.minidom.parse(urllib.urlopen(address)) for item in document.getElementsByTagName('item'): title = item.getElementsByTagName('title')[0].firstChild.data link = item.getElementsByTagName('link')[0].firstChild.data description = item.getElementsByTagName('description')[0].firstChild.data str = link.strip("http://go.vg.no/cgi-bin/go.cgi/rssart/") print "\n" print "------------------------------------------------------------------" print '''"%s"\n\n%s\n\n(%s)''' % (title.encode('UTF8', 'replace'), description.encode('UTF8','replace'), str.encode('UTF8','replace')) print "------------------------------------------------------------------" print "\n" print &gt;&gt;f, "----------------------Nyeste paa VG-------------------------------" print &gt;&gt;f, title.encode('UTF8','replace') print &gt;&gt;f, description.encode('UTF8','replace') print &gt;&gt;f, str.encode('UTF8','replace') print &gt;&gt;f, "------------------------------------------------------------------" print &gt;&gt;f, "\n" </code></pre>
2
2009-07-22T23:45:46Z
[ "python", "xml", "rss" ]
Why does this Python script only read the last RSS post into the file?
1,168,844
<p>Im trying to fix a Python script which takes the posts from a specific RSS feed and strips them down and inputs them into a text file. As you can see beneath, there are two main print functions. One prints only to the shell once run, but it shows <em>all</em> of the posts, which is what I want it to do. Now, the second part is where the problem lies. It only prints out the <em>last</em> post of the RSS feed into a text, not the whole thing, as the first function does. I've also tried to make the second function (f = open()) the same way as the first with the %s instead of a new print-line pr. variable.</p> <p>If anyone could tell me why the script doesnt post more than one (the last) post of the RSS feed into the text, but the whole thing in the shell, and what modifications I need to fix it, I would really appreciate it :)</p> <p>Here is the code:</p> <pre><code>import urllib import sys import xml.dom.minidom #The url of the feed address = 'http://www.vg.no/export/Alle/rdf.hbs?kat=nyheter' #Our actual xml document document = xml.dom.minidom.parse(urllib.urlopen(address)) for item in document.getElementsByTagName('item'): title = item.getElementsByTagName('title')[0].firstChild.data link = item.getElementsByTagName('link')[0].firstChild.data description = item.getElementsByTagName('description')[0].firstChild.data str = link.strip("http://go.vg.no/cgi-bin/go.cgi/rssart/") print "\n" print "------------------------------------------------------------------" print '''"%s"\n\n%s\n\n(%s)''' % (title.encode('UTF8', 'replace'), description.encode('UTF8','replace'), str.encode('UTF8','replace')) print "------------------------------------------------------------------" print "\n" f = open('lawl.txt','w') print &gt;&gt;f, "----------------------Nyeste paa VG-------------------------------" print &gt;&gt;f, title.encode('UTF8','replace') print &gt;&gt;f, description.encode('UTF8','replace') print &gt;&gt;f, str.encode('UTF8','replace') print &gt;&gt;f, "------------------------------------------------------------------" print &gt;&gt;f, "\n" </code></pre>
0
2009-07-22T23:40:00Z
1,168,866
<p>You iterate over all posts, assign their attributes to the variables and print to terminal.</p> <p>Then you print the variables (which happen to hold the results of the last assignment) to file. So you get a single post here.</p> <p>Need to iterate too if you want more than one.</p>
1
2009-07-22T23:45:55Z
[ "python", "xml", "rss" ]
Python Unicode Regular Expression
1,168,894
<p>I am using python 2.4 and I am having some problems with unicode regular expressions. I have tried to put together a very clear and concise example of my problem. It looks as though there is some problem with how Python is recognizing the different character encodings, or a problem with my understanding. Thank you very much for taking a look! </p> <pre><code>#!/usr/bin/python # # This is a simple python program designed to show my problems with regular expressions and character encoding in python # Written by Brian J. Stinar # Thanks for the help! import urllib # To get files off the Internet import chardet # To identify charactor encodings import re # Python Regular Expressions #import ponyguruma # Python Onyguruma Regular Expressions - this can be uncommented if you feel like messing with it, but I have the same issue no matter which RE's I'm using rawdata = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read() print (chardet.detect(rawdata)) #print (rawdata) ISO_8859_2_encoded = rawdata.decode('ISO-8859-2') # Let's grab this as text UTF_8_encoded = ISO_8859_2_encoded.encode('utf-8') # and encode the text as UTF-8 print(chardet.detect(UTF_8_encoded)) # Looks good # This totally doesn't work, even though you can see UNSUBSCRIBE in the HTML # Eventually, I want to recognize the entire physical address and UNSUBSCRIBE above it re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE) print (str(re_UNSUB_amsterdam.match(UTF_8_encoded)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on UTF-8") print (str(re_UNSUB_amsterdam.match(rawdata)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on raw data") re_amsterdam = re.compile(".*Adobe.*", re.UNICODE) print (str(re_amsterdam.match(rawdata)) + "\t--- RE for 'Adobe' on raw data") # However, this work?!? print (str(re_amsterdam.match(UTF_8_encoded)) + "\t--- RE for 'Adobe' on UTF-8") ''' # In additon, I tried this regular expression library much to the same unsatisfactory result new_re = ponyguruma.Regexp(".*UNSUBSCRIBE.*") if new_re.match(UTF_8_encoded) != None: print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on UTF-8") else: print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on UTF-8") if new_re.match(rawdata) != None: print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on raw data") else: print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on raw data") new_re = ponyguruma.Regexp(".*Adobe.*") if new_re.match(UTF_8_encoded) != None: print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on UTF-8") else: print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on UTF-8") new_re = ponyguruma.Regexp(".*Adobe.*") if new_re.match(rawdata) != None: print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on raw data") else: print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on raw data") ''' </code></pre> <p>I am working on a substitution project, and am having a difficult time with the non-ASCII encoded files. This problem is part of a bigger project - eventually I would like to substitute the text with other text (I got this working in ASCII, but I can't identify occurrences in other encodings yet.) Thanks again. </p> <p><a href="http://brian-stinar.blogspot.com" rel="nofollow">http://brian-stinar.blogspot.com</a></p> <p>-Brian J. Stinar-</p>
0
2009-07-22T23:57:26Z
1,168,904
<p>this might help: <a href="http://www.daa.com.au/pipermail/pygtk/2009-July/017299.html" rel="nofollow">http://www.daa.com.au/pipermail/pygtk/2009-July/017299.html</a></p>
0
2009-07-23T00:02:25Z
[ "python", "regex", "character-encoding" ]
Python Unicode Regular Expression
1,168,894
<p>I am using python 2.4 and I am having some problems with unicode regular expressions. I have tried to put together a very clear and concise example of my problem. It looks as though there is some problem with how Python is recognizing the different character encodings, or a problem with my understanding. Thank you very much for taking a look! </p> <pre><code>#!/usr/bin/python # # This is a simple python program designed to show my problems with regular expressions and character encoding in python # Written by Brian J. Stinar # Thanks for the help! import urllib # To get files off the Internet import chardet # To identify charactor encodings import re # Python Regular Expressions #import ponyguruma # Python Onyguruma Regular Expressions - this can be uncommented if you feel like messing with it, but I have the same issue no matter which RE's I'm using rawdata = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read() print (chardet.detect(rawdata)) #print (rawdata) ISO_8859_2_encoded = rawdata.decode('ISO-8859-2') # Let's grab this as text UTF_8_encoded = ISO_8859_2_encoded.encode('utf-8') # and encode the text as UTF-8 print(chardet.detect(UTF_8_encoded)) # Looks good # This totally doesn't work, even though you can see UNSUBSCRIBE in the HTML # Eventually, I want to recognize the entire physical address and UNSUBSCRIBE above it re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE) print (str(re_UNSUB_amsterdam.match(UTF_8_encoded)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on UTF-8") print (str(re_UNSUB_amsterdam.match(rawdata)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on raw data") re_amsterdam = re.compile(".*Adobe.*", re.UNICODE) print (str(re_amsterdam.match(rawdata)) + "\t--- RE for 'Adobe' on raw data") # However, this work?!? print (str(re_amsterdam.match(UTF_8_encoded)) + "\t--- RE for 'Adobe' on UTF-8") ''' # In additon, I tried this regular expression library much to the same unsatisfactory result new_re = ponyguruma.Regexp(".*UNSUBSCRIBE.*") if new_re.match(UTF_8_encoded) != None: print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on UTF-8") else: print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on UTF-8") if new_re.match(rawdata) != None: print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on raw data") else: print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on raw data") new_re = ponyguruma.Regexp(".*Adobe.*") if new_re.match(UTF_8_encoded) != None: print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on UTF-8") else: print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on UTF-8") new_re = ponyguruma.Regexp(".*Adobe.*") if new_re.match(rawdata) != None: print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on raw data") else: print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on raw data") ''' </code></pre> <p>I am working on a substitution project, and am having a difficult time with the non-ASCII encoded files. This problem is part of a bigger project - eventually I would like to substitute the text with other text (I got this working in ASCII, but I can't identify occurrences in other encodings yet.) Thanks again. </p> <p><a href="http://brian-stinar.blogspot.com" rel="nofollow">http://brian-stinar.blogspot.com</a></p> <p>-Brian J. Stinar-</p>
0
2009-07-22T23:57:26Z
1,168,943
<p>You probably want to either enable the DOTALL flag or you want to use the <code>search</code> method instead of the <code>match</code> method. ie:</p> <pre><code># DOTALL makes . match newlines re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE | re.DOTALL) </code></pre> <p>or:</p> <pre><code># search will find matches even if they aren't at the start of the string ... re_UNSUB_amsterdam.search(foo) ... </code></pre> <p>These will give you different results, but both should give you matches. (See which one is the type you want.)</p> <p>As an aside: You seem to be getting the encoded text (which is bytes) and decoded text (characters) confused. This isn't uncommon, especially in pre-3.x Python. In particular, this is very suspicious:</p> <pre><code>ISO_8859_2_encoded = rawdata.decode('ISO-8859-2') </code></pre> <p>You're <strong>de</strong>-coding with ISO-8859-2, not <strong>en</strong>-coding, so call this variable "decoded". (Why not "ISO_8859_2_decoded"? Because ISO_8859_2 is an encoding. A decoded string doesn't have an encoding anymore.)</p> <p>The rest of your code is trying to do matches on rawdata and on UTF_8_encoded (both encoded strings) when it should probably be using the decoded unicode string instead.</p>
2
2009-07-23T00:14:40Z
[ "python", "regex", "character-encoding" ]
Python Unicode Regular Expression
1,168,894
<p>I am using python 2.4 and I am having some problems with unicode regular expressions. I have tried to put together a very clear and concise example of my problem. It looks as though there is some problem with how Python is recognizing the different character encodings, or a problem with my understanding. Thank you very much for taking a look! </p> <pre><code>#!/usr/bin/python # # This is a simple python program designed to show my problems with regular expressions and character encoding in python # Written by Brian J. Stinar # Thanks for the help! import urllib # To get files off the Internet import chardet # To identify charactor encodings import re # Python Regular Expressions #import ponyguruma # Python Onyguruma Regular Expressions - this can be uncommented if you feel like messing with it, but I have the same issue no matter which RE's I'm using rawdata = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read() print (chardet.detect(rawdata)) #print (rawdata) ISO_8859_2_encoded = rawdata.decode('ISO-8859-2') # Let's grab this as text UTF_8_encoded = ISO_8859_2_encoded.encode('utf-8') # and encode the text as UTF-8 print(chardet.detect(UTF_8_encoded)) # Looks good # This totally doesn't work, even though you can see UNSUBSCRIBE in the HTML # Eventually, I want to recognize the entire physical address and UNSUBSCRIBE above it re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE) print (str(re_UNSUB_amsterdam.match(UTF_8_encoded)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on UTF-8") print (str(re_UNSUB_amsterdam.match(rawdata)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on raw data") re_amsterdam = re.compile(".*Adobe.*", re.UNICODE) print (str(re_amsterdam.match(rawdata)) + "\t--- RE for 'Adobe' on raw data") # However, this work?!? print (str(re_amsterdam.match(UTF_8_encoded)) + "\t--- RE for 'Adobe' on UTF-8") ''' # In additon, I tried this regular expression library much to the same unsatisfactory result new_re = ponyguruma.Regexp(".*UNSUBSCRIBE.*") if new_re.match(UTF_8_encoded) != None: print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on UTF-8") else: print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on UTF-8") if new_re.match(rawdata) != None: print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on raw data") else: print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on raw data") new_re = ponyguruma.Regexp(".*Adobe.*") if new_re.match(UTF_8_encoded) != None: print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on UTF-8") else: print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on UTF-8") new_re = ponyguruma.Regexp(".*Adobe.*") if new_re.match(rawdata) != None: print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on raw data") else: print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on raw data") ''' </code></pre> <p>I am working on a substitution project, and am having a difficult time with the non-ASCII encoded files. This problem is part of a bigger project - eventually I would like to substitute the text with other text (I got this working in ASCII, but I can't identify occurrences in other encodings yet.) Thanks again. </p> <p><a href="http://brian-stinar.blogspot.com" rel="nofollow">http://brian-stinar.blogspot.com</a></p> <p>-Brian J. Stinar-</p>
0
2009-07-22T23:57:26Z
1,169,218
<p>With default flag settings, .* doesn't match newlines. UNSUBSCRIBE appears only once, after the first newline. Adobe occurs before the first newline. You could fix that by using re.DOTALL. </p> <p>HOWEVER you haven't inspected what you got with the Adobe match: it's 1478 bytes wide! Turn on re.DOTALL and it (and the corresponding UNSUBSCRIBE pattern) will match the whole text!!</p> <p>You definitely need to lose the trailing .* -- you're not interested and it slows down the match. Also you should lose the leading .* and use search() instead of match().</p> <p>The re.UNICODE flag is of no use to you in this case -- read the manual and see what it does.</p> <p>Why are you transcoding your data into UTF-8 and searching on that? Just leave in Unicode.</p> <p>Someone else pointed out that in general you need to decode <code>&amp;#1234;</code> etc thingies before doing any serious work on your data ... but didn't mention the <code>&amp;laquo;</code> etc thingies with which your data is peppered :-)</p>
0
2009-07-23T02:11:17Z
[ "python", "regex", "character-encoding" ]
Python Unicode Regular Expression
1,168,894
<p>I am using python 2.4 and I am having some problems with unicode regular expressions. I have tried to put together a very clear and concise example of my problem. It looks as though there is some problem with how Python is recognizing the different character encodings, or a problem with my understanding. Thank you very much for taking a look! </p> <pre><code>#!/usr/bin/python # # This is a simple python program designed to show my problems with regular expressions and character encoding in python # Written by Brian J. Stinar # Thanks for the help! import urllib # To get files off the Internet import chardet # To identify charactor encodings import re # Python Regular Expressions #import ponyguruma # Python Onyguruma Regular Expressions - this can be uncommented if you feel like messing with it, but I have the same issue no matter which RE's I'm using rawdata = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read() print (chardet.detect(rawdata)) #print (rawdata) ISO_8859_2_encoded = rawdata.decode('ISO-8859-2') # Let's grab this as text UTF_8_encoded = ISO_8859_2_encoded.encode('utf-8') # and encode the text as UTF-8 print(chardet.detect(UTF_8_encoded)) # Looks good # This totally doesn't work, even though you can see UNSUBSCRIBE in the HTML # Eventually, I want to recognize the entire physical address and UNSUBSCRIBE above it re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE) print (str(re_UNSUB_amsterdam.match(UTF_8_encoded)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on UTF-8") print (str(re_UNSUB_amsterdam.match(rawdata)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on raw data") re_amsterdam = re.compile(".*Adobe.*", re.UNICODE) print (str(re_amsterdam.match(rawdata)) + "\t--- RE for 'Adobe' on raw data") # However, this work?!? print (str(re_amsterdam.match(UTF_8_encoded)) + "\t--- RE for 'Adobe' on UTF-8") ''' # In additon, I tried this regular expression library much to the same unsatisfactory result new_re = ponyguruma.Regexp(".*UNSUBSCRIBE.*") if new_re.match(UTF_8_encoded) != None: print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on UTF-8") else: print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on UTF-8") if new_re.match(rawdata) != None: print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on raw data") else: print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on raw data") new_re = ponyguruma.Regexp(".*Adobe.*") if new_re.match(UTF_8_encoded) != None: print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on UTF-8") else: print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on UTF-8") new_re = ponyguruma.Regexp(".*Adobe.*") if new_re.match(rawdata) != None: print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on raw data") else: print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on raw data") ''' </code></pre> <p>I am working on a substitution project, and am having a difficult time with the non-ASCII encoded files. This problem is part of a bigger project - eventually I would like to substitute the text with other text (I got this working in ASCII, but I can't identify occurrences in other encodings yet.) Thanks again. </p> <p><a href="http://brian-stinar.blogspot.com" rel="nofollow">http://brian-stinar.blogspot.com</a></p> <p>-Brian J. Stinar-</p>
0
2009-07-22T23:57:26Z
1,169,542
<p>Your question is about regular expressions, but your problem can possibly be solved without them; instead use the standard string <code>replace</code> method.</p> <pre><code>import urllib raw = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read() decoded = raw.decode('iso-8859-2') type(decoded) # decoded is now &lt;type 'unicode'&gt; substituted = decoded.replace(u'UNSUBSCRIBE', u'whatever you prefer') </code></pre> <p>If nothing else, the above shows how to handle the encoding: simply decode into a unicode string and work with that. But note that this only works well for the case where you have only one or a very small number of substitutions to make (and those substitutions are not pattern based) because <code>replace()</code> can only handle one substitution at a time.</p> <p>For both string and pattern based substitutions you can do something like this to effect multiple replacements at once:</p> <pre><code>import re REPLACEMENTS = ((u'[aA]dobe', u'!twiddle!'), (u'UNS.*IBE', u'@wobble@'), (u'Dublin', u'Sydney')) def replacer(m): return REPLACEMENTS[list(m.groups()).index(m.group(0))][1] r = re.compile('|'.join('(%s)' % t[0] for t in REPLACEMENTS)) substituted = r.sub(replacer, decoded) </code></pre>
0
2009-07-23T04:01:02Z
[ "python", "regex", "character-encoding" ]
IronPython vs. Python .NET
1,168,914
<p>I want to access some .NET assemblies written in C# from Python code. </p> <p>A little research showed I have two choices:</p> <ul> <li><a href="http://www.codeplex.com/IronPython">IronPython</a> with .NET interface capability/support built-in</li> <li>Python with the <a href="http://pythonnet.sourceforge.net/">Python .NET</a> package</li> </ul> <p>What are the trade-offs between both solutions?</p>
56
2009-07-23T00:06:00Z
1,168,933
<p>If you want to mainly base your code on the .NET framework, I'd highly recommend IronPython vs Python.NET. IronPython is pretty much native .NET - so it just works great when integrating with other .NET langauges. </p> <p>Python.NET is good if you want to just integrate one or two components from .NET into a standard python application.</p> <p>There are notable differences when using IronPython - but most of them are fairly subtle. Python.NET uses the standard CPython runtime, so <a href="http://ironpython.codeplex.com/Wiki/View.aspx?title=IPy1.0.xCPyDifferences&amp;referringTitle=Home">this Wiki page</a> is a relevant discussion of the differences between the two implementations. The largest differences occur in the cost of exceptions - so some of the standard python libraries don't perform as well in IronPython due to their implementation.</p>
49
2009-07-23T00:12:09Z
[ ".net", "python", "ironpython", "python.net" ]
IronPython vs. Python .NET
1,168,914
<p>I want to access some .NET assemblies written in C# from Python code. </p> <p>A little research showed I have two choices:</p> <ul> <li><a href="http://www.codeplex.com/IronPython">IronPython</a> with .NET interface capability/support built-in</li> <li>Python with the <a href="http://pythonnet.sourceforge.net/">Python .NET</a> package</li> </ul> <p>What are the trade-offs between both solutions?</p>
56
2009-07-23T00:06:00Z
1,168,935
<p>IronPython is ".NET-native" -- so it will be preferable if you want to fully integrate your Python code with .NET all the way; Python.NET works with Classic Python, so it lets you keep your Python code's "arm's length" away from .NET proper. (Note that with <a href="http://www.voidspace.org.uk/ironpython/cpython%5Fextensions.shtml">this code</a> you can actually use extensions written for CPython from your IronPython code, so that's not a discriminating condition any more).</p>
7
2009-07-23T00:12:16Z
[ ".net", "python", "ironpython", "python.net" ]
IronPython vs. Python .NET
1,168,914
<p>I want to access some .NET assemblies written in C# from Python code. </p> <p>A little research showed I have two choices:</p> <ul> <li><a href="http://www.codeplex.com/IronPython">IronPython</a> with .NET interface capability/support built-in</li> <li>Python with the <a href="http://pythonnet.sourceforge.net/">Python .NET</a> package</li> </ul> <p>What are the trade-offs between both solutions?</p>
56
2009-07-23T00:06:00Z
1,168,939
<p>IronPython comes from Microsoft, so I would go with my gut and use that one first since you have to assume it will play nicer with other MSFT technologies. </p>
6
2009-07-23T00:13:49Z
[ ".net", "python", "ironpython", "python.net" ]
IronPython vs. Python .NET
1,168,914
<p>I want to access some .NET assemblies written in C# from Python code. </p> <p>A little research showed I have two choices:</p> <ul> <li><a href="http://www.codeplex.com/IronPython">IronPython</a> with .NET interface capability/support built-in</li> <li>Python with the <a href="http://pythonnet.sourceforge.net/">Python .NET</a> package</li> </ul> <p>What are the trade-offs between both solutions?</p>
56
2009-07-23T00:06:00Z
1,168,957
<p>While agreeing with the answers given by Reed Copsey and Alex Martelli, I'd like to point out one further difference - the Global Interpreter Lock (GIL). While IronPython doesn't have the limitations of the GIL, CPython does - so it would appear that for those applications where the GIL is a bottleneck, say in certain multicore scenarios, IronPython has an advantage over Python.NET.</p> <p>From the Python.NET documentation:</p> <blockquote> <p><strong>Important Note for embedders:</strong> Python is not free-threaded and uses a global interpreter lock to allow multi-threaded applications to interact safely with the Python interpreter. Much more information about this is available in the Python C API documentation on the <code>www.python.org</code> Website.</p> <p>When embedding Python in a managed application, you have to manage the GIL in just the same way you would when embedding Python in a C or C++ application.</p> <p>Before interacting with any of the objects or APIs provided by the <code>Python.Runtime</code> namespace, calling code must have acquired the Python global interpreter lock by calling the <code>PythonEngine.AcquireLock</code> method. The only exception to this rule is the <code>PythonEngine.Initialize</code> method, which may be called at startup without having acquired the GIL.</p> <p>When finished using Python APIs, managed code must call a corresponding <code>PythonEngine.ReleaseLock</code> to release the GIL and allow other threads to use Python.</p> <p>The <code>AcquireLock</code> and <code>ReleaseLock</code> methods are thin wrappers over the unmanaged <code>PyGILState_Ensure</code> and <code>PyGILState_Release</code> functions from the Python API, and the documentation for those APIs applies to the managed versions.</p> </blockquote> <p>Another issue is IDE support. CPython probably has better IDE support at present than IronPython - so this may be a factor in the choosing of one over the other.</p>
23
2009-07-23T00:20:06Z
[ ".net", "python", "ironpython", "python.net" ]
IronPython vs. Python .NET
1,168,914
<p>I want to access some .NET assemblies written in C# from Python code. </p> <p>A little research showed I have two choices:</p> <ul> <li><a href="http://www.codeplex.com/IronPython">IronPython</a> with .NET interface capability/support built-in</li> <li>Python with the <a href="http://pythonnet.sourceforge.net/">Python .NET</a> package</li> </ul> <p>What are the trade-offs between both solutions?</p>
56
2009-07-23T00:06:00Z
8,981,895
<ol> <li><p>Ironpython is like C# in turn it relies on static prebuilt libraries while unlike C# is a dynamic language.</p></li> <li><p>Cpython is like C++ like Ironpython is a dynamic language and has access to dynamic libraries which in turn translates to being forced to write everything.</p></li> <li><p>Ironpython is faster than C# in certain areas but not faster than Cpython, however you can link Ironpython to any language thus over coming problems but then again you can do the same with Cpython.</p></li> </ol> <p>A funny, simple and powerful language regardless what you choose!</p>
0
2012-01-24T04:09:19Z
[ ".net", "python", "ironpython", "python.net" ]
IronPython vs. Python .NET
1,168,914
<p>I want to access some .NET assemblies written in C# from Python code. </p> <p>A little research showed I have two choices:</p> <ul> <li><a href="http://www.codeplex.com/IronPython">IronPython</a> with .NET interface capability/support built-in</li> <li>Python with the <a href="http://pythonnet.sourceforge.net/">Python .NET</a> package</li> </ul> <p>What are the trade-offs between both solutions?</p>
56
2009-07-23T00:06:00Z
26,218,197
<p>Most of scientific and numerical Python libaries that rely on C-API (numpy, scipy, matplotlib, pandas, cython, etc.) are working mostly under CPython, so in that case your best bet is pythonnet (other names - Python.NET and Python for .NET). The same is true for CPython GUI bindings such as WxWidgets, PyQt/PySide, GTK, Kivy, etc., although both pythonnet and IronPython can use WPF and WinForms.</p> <p>And finally IronPython does not work with Python 3 yet.</p>
6
2014-10-06T14:14:17Z
[ ".net", "python", "ironpython", "python.net" ]
IronPython vs. Python .NET
1,168,914
<p>I want to access some .NET assemblies written in C# from Python code. </p> <p>A little research showed I have two choices:</p> <ul> <li><a href="http://www.codeplex.com/IronPython">IronPython</a> with .NET interface capability/support built-in</li> <li>Python with the <a href="http://pythonnet.sourceforge.net/">Python .NET</a> package</li> </ul> <p>What are the trade-offs between both solutions?</p>
56
2009-07-23T00:06:00Z
36,650,789
<p>As for 2016. </p> <p>In my company we used IronPython, but we were not satisfied with performances (mostly memory use - garbage collector was too slow) so we decided to switch to standard Python and integrate it with .Net using Zeroce-s ICE. </p>
0
2016-04-15T15:09:08Z
[ ".net", "python", "ironpython", "python.net" ]
Smart date interpretation
1,169,000
<p>I can't remember which application I was using, but I do recall it having really neat date parsing/interpretation.</p> <p>For example, you could type in 'two days ago' or 'tomorrow' and it would understand.</p> <p>Any libraries to suggest? Bonus points if usable from Python.</p>
6
2009-07-23T00:36:47Z
1,169,014
<p>Perhaps you are thinking of PHP's <code>strtotime()</code> function, the <a href="http://brian.moonspot.net/2008/09/20/strtotime-the-php-date-swiss-army-knife/">Swiss Army Knife of date parsing</a>:</p> <blockquote> <p>Man, what did I do before <code>strtotime()</code>. Oh, I know, I had a 482 line function to parse date formats and return timestamps. And I still could not do really cool stuff. Like tonight I needed to figure out when Thanksgiving was in the US. I knew it was the 4th Thursday in November. So, I started with some math stuff and checking what day of the week Nov. 1 would fall on. All that was making my head hurt. So, I just tried this for fun.</p> <pre><code>strtotime("thursday, november ".date("Y")." + 3 weeks") </code></pre> <p>That gives me Thanksgiving. Awesome.</p> </blockquote> <p>Would you believe it even has its own dedicated web site, <a href="http://www.strtotime.net/">www.strtotime.net</a>?</p> <p>Sadly, there does not appear to be a Python equivalent. The closest thing I could find is the <a href="http://labix.org/python-dateutil"><code>dateutil.parser</code></a> module.</p>
8
2009-07-23T00:41:44Z
[ "python", "date-parsing" ]
Smart date interpretation
1,169,000
<p>I can't remember which application I was using, but I do recall it having really neat date parsing/interpretation.</p> <p>For example, you could type in 'two days ago' or 'tomorrow' and it would understand.</p> <p>Any libraries to suggest? Bonus points if usable from Python.</p>
6
2009-07-23T00:36:47Z
1,169,027
<p>The simple one I have seen for python is <a href="http://pyparsing.wikispaces.com/UnderDevelopment#toc0" rel="nofollow">here</a>.</p> <p>It uses pyparsing and is only a small script, but it does what you ask. However, the advantage being it would be pretty easy to extend and improve on if needed. Pyparsing is relatively easy to learn as parsing goes.</p>
2
2009-07-23T00:46:41Z
[ "python", "date-parsing" ]
Smart date interpretation
1,169,000
<p>I can't remember which application I was using, but I do recall it having really neat date parsing/interpretation.</p> <p>For example, you could type in 'two days ago' or 'tomorrow' and it would understand.</p> <p>Any libraries to suggest? Bonus points if usable from Python.</p>
6
2009-07-23T00:36:47Z
1,169,085
<p>See my <a href="http://stackoverflow.com/questions/552073/whats-the-best-way-to-make-a-time-from-today-or-yesterday-and-a-time-in-pyth/552229#552229">SO answer</a> for links to three Python date parsing libraries. The one of these most commonly used is <a href="http://labix.org/python-dateutil">python-dateutils</a> but unfortunately it can't handle all formats.</p>
6
2009-07-23T01:09:40Z
[ "python", "date-parsing" ]
Python OS X 10.5 development environment
1,169,025
<p>I would like to try out the Google App Engine Python environment, which the docs say runs 2.5.2. As I use OS X Leopard, I have Python 2.5.1 installed, but would like the latest 2.5.x version installed (not 2.6 or 3.0). It seems the latest version is <a href="http://www.python.org/download/releases/2.5.4/" rel="nofollow" title="2.5.4">2.5.4</a></p> <p>So, I went to here:</p> <p><a href="http://wiki.python.org/moin/MacPython/Leopard" rel="nofollow">http://wiki.python.org/moin/MacPython/Leopard</a></p> <p>and stopped because I am worried installing the latest version might mess with the standard install. I really just want one version installed.</p> <p>So my questions are how do I safely install the latest 2.5.x? Is it possible to fully replace the built in version, and if so would that hurt any Mac tools?</p> <p>Cheers, Shane</p>
4
2009-07-23T00:45:23Z
1,169,058
<p>Your current python is in <code>/System/Library/Frameworks/Python.framework/</code>.</p> <p>If you install MacPython, it will go into <code>/Library/Frameworks/Python.framework/</code>. The installer will modify your $PATH (environment variable) so that typing <code>python</code> at the command line will run the version it installs.</p> <p>You can easily get back the old version by modifying the path again.</p> <p>You will have to reinstall any third-party modules you are using. This is because third-party modules go into <code>Python.framework/Versions/Current/lib/python2.5/site-packages/</code> for the version you're running.</p> <p>Since you're not modifying the system version, you aren't in danger of affecting any Apple system tools that rely on it.</p> <p>(in fact, arguably it is safer to install MacPython from the start, and never touch the Apple-supplied version. See <a href="http://developers.slashdot.org/article.pl?sid=09/02/18/1435227" rel="nofollow">here</a> for a similar situation involving Perl, where Apple updated the version of Perl in <code>/System</code> and broke a lot of people's setups)</p> <p>You may also be interested in <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow"><code>virtualenv</code></a>.</p>
3
2009-07-23T00:59:28Z
[ "python", "google-app-engine", "osx", "development-environment" ]
Python OS X 10.5 development environment
1,169,025
<p>I would like to try out the Google App Engine Python environment, which the docs say runs 2.5.2. As I use OS X Leopard, I have Python 2.5.1 installed, but would like the latest 2.5.x version installed (not 2.6 or 3.0). It seems the latest version is <a href="http://www.python.org/download/releases/2.5.4/" rel="nofollow" title="2.5.4">2.5.4</a></p> <p>So, I went to here:</p> <p><a href="http://wiki.python.org/moin/MacPython/Leopard" rel="nofollow">http://wiki.python.org/moin/MacPython/Leopard</a></p> <p>and stopped because I am worried installing the latest version might mess with the standard install. I really just want one version installed.</p> <p>So my questions are how do I safely install the latest 2.5.x? Is it possible to fully replace the built in version, and if so would that hurt any Mac tools?</p> <p>Cheers, Shane</p>
4
2009-07-23T00:45:23Z
1,169,279
<p>You can install python on your Mac, and it won't mess with the default installation. However, I strongly recommend that you use <a href="http://www.macports.org/">MacPorts</a> to install Python, since that will make it much easier for you to install Python libraries and packages further down the road. Additionally, if you try to install a program or library with MacPorts that depends on Python, MacPorts will download a copy of Python, even if you have MacPython installed, so you might end up with redundant copies of Python if you install MacPython but then choose to use MacPorts at a later date. To install Python with MacPorts, download and install MacPorts, then type:</p> <pre> sudo port install python25 python_select sudo python_select python25 </pre> <p>Run the following command to view all the MacPorts packages for Python:</p> <pre> port list | grep py25- </pre> <p>You can install any of the packages on the list by simply typing:</p> <pre> sudo port install <i>packagename</i> </pre> <p>In the above, replace <i>packagename</i> with the name of the package. On my first install I always run</p> <pre> sudo port install py25-setuptools </pre> <p>[ NOTE: These commands need to be run from the Terminal -- Applications > Utilities > Terminal.app ]</p>
7
2009-07-23T02:32:01Z
[ "python", "google-app-engine", "osx", "development-environment" ]