title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
simple update in sqlalchemy
1,017,388
<p>UserTable is:</p> <ul> <li><p>id (INT)</p></li> <li><p>name (STR)</p></li> <li><p>last_login (DATETIME)</p></li> </ul> <p>Serving a web page request i have a <strong>user id</strong> in hand and I only wish to update the <strong>last_login</strong> field to 'now'.</p> <p>It seems to me that there are 2 ways:</p> <ol> <li><p>issue a direct SQL using db_engine (losing the mapper)</p></li> <li><p>OR query the user first and then update the object</p></li> </ol> <p>Both work fine but look quite disgusting in code.</p> <p><strong>Is anyone aware of a more elegant way of doing an update-with-no-query using sqlalchemy? Is there another ORM who has got this right?</strong></p> <p>Thanks</p>
7
2009-06-19T10:58:46Z
1,017,420
<p>Assuming you have a mapper UserTable in place:</p> <pre><code>DBSession.query(UserTable).filter_by(id = user_id).\ update({"last_login":datetime.datetime.now()}, synchronize_session=False) </code></pre> <p>Additional parameters in the <a href="http://www.sqlalchemy.org/docs/05/reference/orm/query.html#sqlalchemy.orm.query.Query.update">docs</a>.</p>
23
2009-06-19T11:10:50Z
[ "python", "sqlalchemy" ]
backend for python
1,017,399
<p>which is the best back end for python applications and what is the advantage of using sqlite ,how it can be connected to python applications</p>
0
2009-06-19T11:01:48Z
1,017,414
<p>What do you mean with back end? Python apps connect to SQLite just like any other database, you just have to import the correct module and check how to use it.</p> <p>The advantages of using SQLite are:</p> <ul> <li>You don't need to setup a database server, it's just a file</li> <li>No configurations needed</li> <li>Cross platform</li> </ul> <p>Mainly, desktops applications are the ones that take real advantage of this. For web apps, SQLite is not recommended, since the file containing the data, is easily readable (lacks any kind of encryption), and when the web server lacks special configuration, the file is downloadable by anyone.</p>
3
2009-06-19T11:07:53Z
[ "python" ]
backend for python
1,017,399
<p>which is the best back end for python applications and what is the advantage of using sqlite ,how it can be connected to python applications</p>
0
2009-06-19T11:01:48Z
1,017,523
<p>The language you are using at the application layer has little to do with your database choice underneath. You need to examine the advantages of other DB packages to get an idea of what you want.</p> <p>Here are some popular database packages for cheap or free:</p> <p>ms sql server express, pg/sql, mysql</p>
0
2009-06-19T11:45:43Z
[ "python" ]
backend for python
1,017,399
<p>which is the best back end for python applications and what is the advantage of using sqlite ,how it can be connected to python applications</p>
0
2009-06-19T11:01:48Z
1,017,603
<p>If you mean "what is the best database?" then there's simply no way to answer this question. If you just want a small database that won't be used by more than a handful of people at a time, SQLite is what you're looking for. If you're running a database for a giant corporation serving thousands, you're probably looking for Oracle. In between those, you have MySQL, PostgreSQL, SQL Server, db2, and probably more.</p> <p>If you're familiar with one of those, that may be the best to go with from a practical standpoint. If you're doing a typical webapp, my advice would be to go with MySQL or PostgreSQL as they're free and well supported by just about any ORM you could think of (my personal preference is towards PostgreSQL, but I'm not experienced enough with either of these to make a good argument one way or another). If you <em>do</em> go with one of those two, my recommendation is to use <a href="https://storm.canonical.com/" rel="nofollow">storm</a> as the ORM.</p> <p>(And yes, there are free versions of SQL Server and Oracle. You won't have as many choices as far as ORMs go though)</p>
0
2009-06-19T12:07:48Z
[ "python" ]
backend for python
1,017,399
<p>which is the best back end for python applications and what is the advantage of using sqlite ,how it can be connected to python applications</p>
0
2009-06-19T11:01:48Z
1,017,671
<p>Django, Twisted, and CherryPy are popular Python "Back-Ends" as far as web applications go, with Twisted likely being the most flexible as far as networking is concerned.</p> <p>SQLite can, as has been previously posted, be directly interfaced with using SQL commands as it has native bindings for Python, or it can be accessed with an Object Relational Manager such as SQLObject (another Python library).</p> <p>As far as performance is concered, SQLite is fairly scalable and should be able to handle most use cases that don't require a seperate database server (nothing enterprise level). An additional benefit of SQLite is that the database is self-contained in a single file allowing for easy backup while remained a common enough format that multiple applications can access the data. A word of advice on using SQLite with Python, however, is that you may run into issues with threading (in the past most of the bindings for SQLite were <em>not</em> thread-safe, although this may have changed over time).</p>
0
2009-06-19T12:22:19Z
[ "python" ]
Is there any Ruby or Python interpreter for Lego Mindstorm?
1,017,429
<p>I want to start coding in Python or Ruby. Since I own a <a href="http://en.wikipedia.org/wiki/Lego%5FRobotics">Lego Midstorms</a> kit I thought it would be nice to program against it. Are there any good translators / interpeters for the Mindstorms brick?</p>
21
2009-06-19T11:15:31Z
1,017,443
<p>Here's an <a href="http://rubyforge.org/projects/lego-mindstorms/" rel="nofollow">open source project for Ruby</a></p>
1
2009-06-19T11:19:48Z
[ "python", "ruby", "interpreter", "robotics", "lego" ]
Is there any Ruby or Python interpreter for Lego Mindstorm?
1,017,429
<p>I want to start coding in Python or Ruby. Since I own a <a href="http://en.wikipedia.org/wiki/Lego%5FRobotics">Lego Midstorms</a> kit I thought it would be nice to program against it. Are there any good translators / interpeters for the Mindstorms brick?</p>
21
2009-06-19T11:15:31Z
1,017,532
<p>With python you can use <a href="http://pypi.python.org/pypi/jaraco.nxt" rel="nofollow">jaraco.nxt</a> or <a href="http://code.google.com/p/nxt-python/" rel="nofollow">nxt-python</a> to control the NXT robot. I don't own one so I've never used any of those.</p> <p>Found this example using nxt-python:</p> <pre><code>#!/usr/bin/env python import nxt.locator from nxt.motor import Motor, PORT_B, PORT_C def spin_around(b): m_left = Motor(b, PORT_B) m_left.update(100, 360) m_right = Motor(b, PORT_C) m_right.update(-100, 360) sock = nxt.locator.find_one_brick() if sock: spin_around(sock.connect()) sock.close() else: print 'No NXT bricks found' </code></pre> <p>Seems nice.</p>
3
2009-06-19T11:48:10Z
[ "python", "ruby", "interpreter", "robotics", "lego" ]
Is there any Ruby or Python interpreter for Lego Mindstorm?
1,017,429
<p>I want to start coding in Python or Ruby. Since I own a <a href="http://en.wikipedia.org/wiki/Lego%5FRobotics">Lego Midstorms</a> kit I thought it would be nice to program against it. Are there any good translators / interpeters for the Mindstorms brick?</p>
21
2009-06-19T11:15:31Z
1,020,503
<p>The nxt-python and ruby-nxt projects are remote control interfaces to the NXT. They both run on a PC and remotely control the NXT via Bluetooth or USB. If you are looking for running alternative firmware on the NXT, there are several different alternatives. </p> <p>Steve Hassenplug has a webpage with a comprehensive list of all of the known alternative firmware and remote control options.<br /> <a href="http://www.teamhassenplug.org/NXT/NXTSoftware.html">NXT Software</a></p>
7
2009-06-19T23:43:24Z
[ "python", "ruby", "interpreter", "robotics", "lego" ]
Is there any Ruby or Python interpreter for Lego Mindstorm?
1,017,429
<p>I want to start coding in Python or Ruby. Since I own a <a href="http://en.wikipedia.org/wiki/Lego%5FRobotics">Lego Midstorms</a> kit I thought it would be nice to program against it. Are there any good translators / interpeters for the Mindstorms brick?</p>
21
2009-06-19T11:15:31Z
7,380,969
<p>Try pynxc <a href="http://code.google.com/p/pynxc/" rel="nofollow">http://code.google.com/p/pynxc/</a></p>
1
2011-09-11T20:18:54Z
[ "python", "ruby", "interpreter", "robotics", "lego" ]
PostgreSQL - how to run VACUUM from code outside transaction block?
1,017,463
<p>I am using Python with psycopg2 and I'm trying to run a full <code>VACUUM</code> after a daily operation which inserts several thousand rows. The problem is that when I try to run the <code>VACUUM</code> command within my code I get the following error:</p> <pre><code>psycopg2.InternalError: VACUUM cannot run inside a transaction block </code></pre> <p>How do I run this from the code outside a transaction block?</p> <p>If it makes a difference, I have a simple DB abstraction class, a subset of which is displayed below for context (not runnable, exception-handling and docstrings omitted and line spanning adjustments made):</p> <pre><code>class db(object): def __init__(dbname, host, port, user, password): self.conn = psycopg2.connect("dbname=%s host=%s port=%s \ user=%s password=%s" \ % (dbname, host, port, user, password)) self.cursor = self.conn.cursor() def _doQuery(self, query): self.cursor.execute(query) self.conn.commit() def vacuum(self): query = "VACUUM FULL" self._doQuery(query) </code></pre>
20
2009-06-19T11:26:33Z
1,017,569
<p>I don't know psycopg2 and PostgreSQL, but only apsw and SQLite, so I think I can not give a "psycopg2" help.</p> <p>But it seams to me, that PostgreSQL might work similar as SQLite does, it has two modes of operation:</p> <ul> <li>Outside a transaction block: This is semantically equivalent to have a transaction block around every single SQL operation</li> <li>Inside a transaction block, that is marked by "BEGIN TRANSACTION" and ended by "END TRANSACTION"</li> </ul> <p>When this is the case, the problem could be inside the access layer psycopg2. When it does normally operate in a way that transactions are implicitely inserted until a commit is made, there could be no "standard way" to make a vacuum.</p> <p>Of course it could be possible, that "psycopg2" has its special "vacuum" method, or a special operation mode, where no implicit transactions are started.</p> <p>When no such possibilities exists, there stays one single option (without changing the access layer ;-) ):</p> <p>Most databases have a shell programm to access the database. The program could run this shell program with a pipe (entering the vacuum-command into the shell), thus using the shell programm to make the vacuum. Since vacuum is a slow operation as such, the start of an external programm will be neglectible. Of course, the actual program should commit all uncommited work before, else there could be a dead-lock situation - the vacuum must wait until end of your last transaction.</p>
1
2009-06-19T11:59:33Z
[ "python", "sql", "postgresql", "psycopg2", "vacuum" ]
PostgreSQL - how to run VACUUM from code outside transaction block?
1,017,463
<p>I am using Python with psycopg2 and I'm trying to run a full <code>VACUUM</code> after a daily operation which inserts several thousand rows. The problem is that when I try to run the <code>VACUUM</code> command within my code I get the following error:</p> <pre><code>psycopg2.InternalError: VACUUM cannot run inside a transaction block </code></pre> <p>How do I run this from the code outside a transaction block?</p> <p>If it makes a difference, I have a simple DB abstraction class, a subset of which is displayed below for context (not runnable, exception-handling and docstrings omitted and line spanning adjustments made):</p> <pre><code>class db(object): def __init__(dbname, host, port, user, password): self.conn = psycopg2.connect("dbname=%s host=%s port=%s \ user=%s password=%s" \ % (dbname, host, port, user, password)) self.cursor = self.conn.cursor() def _doQuery(self, query): self.cursor.execute(query) self.conn.commit() def vacuum(self): query = "VACUUM FULL" self._doQuery(query) </code></pre>
20
2009-06-19T11:26:33Z
1,017,655
<p>After more searching I have discovered the isolation_level property of the psycopg2 connection object. It turns out that changing this to <code>0</code> will move you out of a transaction block. Changing the vacuum method of the above class to the following solves it. Note that I also set the isolation level back to what it previously was just in case (seems to be <code>1</code> by default).</p> <pre><code>def vacuum(self): old_isolation_level = self.conn.isolation_level self.conn.set_isolation_level(0) query = "VACUUM FULL" self._doQuery(query) self.conn.set_isolation_level(old_isolation_level) </code></pre> <p><a href="http://www.devx.com/opensource/Article/29071">This article</a> (near the end on that page) provides a brief explanation of isolation levels in this context.</p>
39
2009-06-19T12:18:49Z
[ "python", "sql", "postgresql", "psycopg2", "vacuum" ]
PostgreSQL - how to run VACUUM from code outside transaction block?
1,017,463
<p>I am using Python with psycopg2 and I'm trying to run a full <code>VACUUM</code> after a daily operation which inserts several thousand rows. The problem is that when I try to run the <code>VACUUM</code> command within my code I get the following error:</p> <pre><code>psycopg2.InternalError: VACUUM cannot run inside a transaction block </code></pre> <p>How do I run this from the code outside a transaction block?</p> <p>If it makes a difference, I have a simple DB abstraction class, a subset of which is displayed below for context (not runnable, exception-handling and docstrings omitted and line spanning adjustments made):</p> <pre><code>class db(object): def __init__(dbname, host, port, user, password): self.conn = psycopg2.connect("dbname=%s host=%s port=%s \ user=%s password=%s" \ % (dbname, host, port, user, password)) self.cursor = self.conn.cursor() def _doQuery(self, query): self.cursor.execute(query) self.conn.commit() def vacuum(self): query = "VACUUM FULL" self._doQuery(query) </code></pre>
20
2009-06-19T11:26:33Z
1,017,674
<p>Don't do it - you don't need VACUUM FULL. Actually if you run somewhat recent version of Postgres (let's say > 8.1) you don't even need to run plain VACUUM manually.</p>
-1
2009-06-19T12:22:50Z
[ "python", "sql", "postgresql", "psycopg2", "vacuum" ]
PostgreSQL - how to run VACUUM from code outside transaction block?
1,017,463
<p>I am using Python with psycopg2 and I'm trying to run a full <code>VACUUM</code> after a daily operation which inserts several thousand rows. The problem is that when I try to run the <code>VACUUM</code> command within my code I get the following error:</p> <pre><code>psycopg2.InternalError: VACUUM cannot run inside a transaction block </code></pre> <p>How do I run this from the code outside a transaction block?</p> <p>If it makes a difference, I have a simple DB abstraction class, a subset of which is displayed below for context (not runnable, exception-handling and docstrings omitted and line spanning adjustments made):</p> <pre><code>class db(object): def __init__(dbname, host, port, user, password): self.conn = psycopg2.connect("dbname=%s host=%s port=%s \ user=%s password=%s" \ % (dbname, host, port, user, password)) self.cursor = self.conn.cursor() def _doQuery(self, query): self.cursor.execute(query) self.conn.commit() def vacuum(self): query = "VACUUM FULL" self._doQuery(query) </code></pre>
20
2009-06-19T11:26:33Z
4,636,190
<p>Additionally, you can also get the messages given by the Vacuum or Analyse using:</p> <pre><code>&gt;&gt; print conn.notices #conn is the connection object </code></pre> <p>this command print a list with the log message of queries like Vacuum and Analyse:</p> <pre><code>INFO: "usuario": processados 1 de 1 páginas, contendo 7 registros vigentes e 0 registros não vigentes; 7 registros amostrados, 7 registros totais estimados INFO: analisando "public.usuario" </code></pre> <p>This can be useful to the DBAs ^^</p>
3
2011-01-08T21:15:48Z
[ "python", "sql", "postgresql", "psycopg2", "vacuum" ]
PostgreSQL - how to run VACUUM from code outside transaction block?
1,017,463
<p>I am using Python with psycopg2 and I'm trying to run a full <code>VACUUM</code> after a daily operation which inserts several thousand rows. The problem is that when I try to run the <code>VACUUM</code> command within my code I get the following error:</p> <pre><code>psycopg2.InternalError: VACUUM cannot run inside a transaction block </code></pre> <p>How do I run this from the code outside a transaction block?</p> <p>If it makes a difference, I have a simple DB abstraction class, a subset of which is displayed below for context (not runnable, exception-handling and docstrings omitted and line spanning adjustments made):</p> <pre><code>class db(object): def __init__(dbname, host, port, user, password): self.conn = psycopg2.connect("dbname=%s host=%s port=%s \ user=%s password=%s" \ % (dbname, host, port, user, password)) self.cursor = self.conn.cursor() def _doQuery(self, query): self.cursor.execute(query) self.conn.commit() def vacuum(self): query = "VACUUM FULL" self._doQuery(query) </code></pre>
20
2009-06-19T11:26:33Z
13,955,271
<p>While vacuum full is questionable in current versions of postgresql, forcing a 'vacuum analyze' or 'reindex' after certain massive actions can improve performance, or clean up disk usage. This is postgresql specific, and needs to be cleaned up to do the right thing for other databases.</p> <pre><code>from django.db import connection # Much of the proxy is not defined until this is done force_proxy = connection.cursor() realconn=connection.connection old_isolation_level = realconn.isolation_level realconn.set_isolation_level(0) cursor = realconn.cursor() cursor.execute('VACUUM ANALYZE') realconn.set_isolation_level(old_isolation_level) </code></pre> <p>Unfortunately the connection proxy provided by django doesn't provide access to set_isolation_level.</p>
3
2012-12-19T15:09:25Z
[ "python", "sql", "postgresql", "psycopg2", "vacuum" ]
PostgreSQL - how to run VACUUM from code outside transaction block?
1,017,463
<p>I am using Python with psycopg2 and I'm trying to run a full <code>VACUUM</code> after a daily operation which inserts several thousand rows. The problem is that when I try to run the <code>VACUUM</code> command within my code I get the following error:</p> <pre><code>psycopg2.InternalError: VACUUM cannot run inside a transaction block </code></pre> <p>How do I run this from the code outside a transaction block?</p> <p>If it makes a difference, I have a simple DB abstraction class, a subset of which is displayed below for context (not runnable, exception-handling and docstrings omitted and line spanning adjustments made):</p> <pre><code>class db(object): def __init__(dbname, host, port, user, password): self.conn = psycopg2.connect("dbname=%s host=%s port=%s \ user=%s password=%s" \ % (dbname, host, port, user, password)) self.cursor = self.conn.cursor() def _doQuery(self, query): self.cursor.execute(query) self.conn.commit() def vacuum(self): query = "VACUUM FULL" self._doQuery(query) </code></pre>
20
2009-06-19T11:26:33Z
23,684,825
<p>Note if you're using Django with South to perform a migration you can use the following code to execute a <code>VACUUM ANALYZE</code>. </p> <pre><code>def forwards(self, orm): db.commit_transaction() db.execute("VACUUM ANALYZE &lt;table&gt;") #Optionally start another transaction to do some more work... db.start_transaction() </code></pre>
2
2014-05-15T17:18:53Z
[ "python", "sql", "postgresql", "psycopg2", "vacuum" ]
NameError: global name 'has_no_changeset' is not defined
1,017,467
<p>OK - Python newbie here - I assume I am doing something really stupid, could you please tell me what it is so we can all get on with our lives?</p> <p>I get the error <code>NameError: global name 'has_no_changeset' is not defined</code> in the line 55 (where I try calling the function <code>has_no_changeset</code>).</p> <pre><code>from genshi.builder import tag from trac.core import implements,Component from trac.ticket.api import ITicketManipulator from trac.ticket.default_workflow import ConfigurableTicketWorkflow from trac.perm import IPermissionRequestor from trac.config import Option, ListOption import re revision = "$Rev$" url = "$URL$" class CloseActionController(Component): """Support for close checking. If a ticket is closed, it is NOT allowed if ALL the following conditions apply: a) ticket is 'bug' ticket b) resolution status is 'fixed' c) none of the ticket's changes include a comment containing a changeset, i.e. regex "\[\d+\]" d) the ticket does not have the keyword 'web' """ implements(ITicketManipulator) # ITicketManipulator methods def prepare_ticket(req, ticket, fields, actions): """Not currently called, but should be provided for future compatibility.""" return def has_no_changeset(ticket): db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT newvalue FROM ticket_change WHERE ticket=%s AND field='comment'", (str(ticket.id).encode('ascii','replace'),)) for newvalue, in cursor: if re.search("\[\d{5,}\]", newvalue): return False return True def validate_ticket(me, req, ticket): """Validate a ticket after it's been populated from user input. Must return a list of `(field, message)` tuples, one for each problem detected. `field` can be `None` to indicate an overall problem with the ticket. Therefore, a return value of `[]` means everything is OK.""" if ticket['type'] == 'bug' and ticket['resolution'] == 'fixed': if ticket['keywords'] == None or ticket['keywords'].find('web') == -1: if has_no_changeset(ticket): return [(None, 'You can only close a bug ticket as "fixed" if you refer to a changeset somewhere within the ticket, e.g. with [12345]!')] return[] </code></pre>
1
2009-06-19T11:28:17Z
1,017,473
<p>You need to explicitly specify <code>self</code> (or in your case, <code>me</code>) when referring to a method of the current class:</p> <pre><code>if me.has_no_changeset(ticket): </code></pre> <p>You're using <code>me</code> instead of <code>self</code> - that's legal but strongly discouraged. The first parameter of member functions should be called <code>self</code>:</p> <pre><code>def validate_ticket(self, req, ticket): # [...] if self.has_no_changeset(ticket): </code></pre>
4
2009-06-19T11:31:00Z
[ "python", "syntax" ]
Why isn't Python very good for functional programming?
1,017,621
<p>I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in <a href="http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming">this</a> question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)</p>
216
2009-06-19T12:12:06Z
1,017,663
<p>Guido has a good explanation of this <a href="http://python-history.blogspot.com/2009/04/origins-of-pythons-functional-features.html">here</a>. Here's the most relevant part:</p> <blockquote> <p>I have never considered Python to be heavily influenced by functional languages, no matter what people say or think. I was much more familiar with imperative languages such as C and Algol 68 and although I had made functions first-class objects, I didn't view Python as a functional programming language. However, earlier on, it was clear that users wanted to do much more with lists and functions.</p> <p>...</p> <p>It is also worth noting that even though I didn't envision Python as a functional language, the introduction of closures has been useful in the development of many other advanced programming features. For example, certain aspects of new-style classes, decorators, and other modern features rely upon this capability.</p> <p>Lastly, even though a number of functional programming features have been introduced over the years, Python still lacks certain features found in “real” functional programming languages. For instance, Python does not perform certain kinds of optimizations (e.g., tail recursion). In general, because Python's extremely dynamic nature, it is impossible to do the kind of compile-time optimization known from functional languages like Haskell or ML. And that's fine.</p> </blockquote> <p>I pull two things out of this:</p> <ol> <li>The language's creator doesn't really consider Python to be a functional language. Therefore, it's possible to see "functional-esque" features, but you're unlikely to see anything that is definitively functional.</li> <li>Python's dynamic nature inhibits some of the optimizations you see in other functional languages. Granted, Lisp is just as dynamic (if not more dynamic) as Python, so this is only a partial explanation.</li> </ol>
75
2009-06-19T12:20:18Z
[ "python", "functional-programming" ]
Why isn't Python very good for functional programming?
1,017,621
<p>I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in <a href="http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming">this</a> question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)</p>
216
2009-06-19T12:12:06Z
1,017,673
<p>Python is almost a functional language. It's "functional lite". </p> <p>It has extra features, so it isn't pure enough for some. </p> <p>It also lacks some features, so it isn't complete enough for some. </p> <p>The missing features are relatively easy to write. Check out posts like <a href="http://blog.sigfpe.com/2008/02/purely-functional-recursive-types-in.html" rel="nofollow">this</a> on FP in Python.</p>
9
2009-06-19T12:22:40Z
[ "python", "functional-programming" ]
Why isn't Python very good for functional programming?
1,017,621
<p>I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in <a href="http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming">this</a> question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)</p>
216
2009-06-19T12:12:06Z
1,017,682
<p>Scheme doesn't have algebraic data types or pattern matching but it's certainly a functional language. Annoying things about Python from a functional programming perspective:</p> <ol> <li><p>Crippled Lambdas. Since Lambdas can only contain an expression, and you can't do everything as easily in an expression context, this means that the functions you can define "on the fly" are limited.</p></li> <li><p>Ifs are statements, not expressions. This means, among other things, you can't have a lambda with an If inside it. (This is fixed by ternaries in Python 2.5, but it looks ugly.)</p></li> <li><p>Guido threatens to <a href="http://xahlee.org/perl-python/python_3000.html">remove map, filter, and reduce</a> every once in awhile</p></li> </ol> <p>On the other hand, python has lexical closures, Lambdas, and list comprehensions (which are really a "functional" concept whether or not Guido admits it). I do plenty of "functional-style" programming in Python, but I'd hardly say it's ideal.</p>
37
2009-06-19T12:24:44Z
[ "python", "functional-programming" ]
Why isn't Python very good for functional programming?
1,017,621
<p>I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in <a href="http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming">this</a> question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)</p>
216
2009-06-19T12:12:06Z
1,017,937
<p>The question you reference asks which languages promote both OO and functional programming. Python does not <em>promote</em> functional programming even though it <em>works</em> fairly well.</p> <p>The best argument <em>against</em> functional programming in Python is that imperative/OO use cases are carefully considered by Guido, while functional programming use cases are not. When I write imperative Python, it's one of the prettiest languages I know. When I write functional Python, it becomes as ugly and unpleasant as your average language that doesn't have a <a href="http://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life">BDFL</a>.</p> <p>Which is not to say that it's bad, just that you have to work harder than you would if you switched to a language that promotes functional programming or switched to writing OO Python.</p> <p>Here are the functional things I miss in Python:</p> <ul> <li><a href="http://learnyouahaskell.com/syntax-in-functions#pattern-matching">Pattern matching</a></li> <li><a href="http://book.realworldhaskell.org/read/functional-programming.html#fp.loop">Tail recursion</a></li> <li><a href="https://hackage.haskell.org/package/base/docs/Data-List.html">Large library of list functions</a></li> <li><a href="https://hackage.haskell.org/package/containers/docs/Data-Map.html">Functional dictionary class</a></li> <li><a href="http://learnyouahaskell.com/higher-order-functions#curried-functions">Automatic currying</a></li> <li><a href="http://learnyouahaskell.com/higher-order-functions#composition">Concise way to compose functions</a></li> <li>Lazy lists</li> <li>Simple, powerful expression syntax (Python's simple block syntax prevents Guido from adding it)</li> </ul> <hr> <ul> <li>No pattern matching and no tail recursion mean your basic algorithms have to be written imperatively. Recursion is ugly and slow in Python.</li> <li>A small list library and no functional dictionaries mean that you have to write a lot of stuff yourself. </li> <li>No syntax for currying or composition means that point-free style is about as full of punctuation as explicitly passing arguments.</li> <li>Iterators instead of lazy lists means that you have to know whether you want efficiency or persistence, and to scatter calls to <code>list</code> around if you want persistence. (Iterators are use-once)</li> <li>Python's simple imperative syntax, along with its simple LL1 parser, mean that a better syntax for if-expressions and lambda-expressions is basically impossible. Guido likes it this way, and I think he's right.</li> </ul>
264
2009-06-19T13:22:56Z
[ "python", "functional-programming" ]
Why isn't Python very good for functional programming?
1,017,621
<p>I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in <a href="http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming">this</a> question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)</p>
216
2009-06-19T12:12:06Z
1,017,986
<p>I would never call Python “functional” but whenever I program in Python the code invariably ends up being almost purely functional.</p> <p>Admittedly, that's mainly due to the extremely nice list comprehension. So I wouldn't necessarily suggest Python as a functional programming language but I would suggest functional programming for anyone using Python.</p>
14
2009-06-19T13:35:43Z
[ "python", "functional-programming" ]
Why isn't Python very good for functional programming?
1,017,621
<p>I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in <a href="http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming">this</a> question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)</p>
216
2009-06-19T12:12:06Z
1,018,393
<p>Let me demonstrate with a piece of code taken from an answer to a "functional" <a href="http://stackoverflow.com/questions/1016997/generate-from-generators/1017105#1017105">Python question</a> on SO</p> <p>Python:</p> <pre><code>def grandKids(generation, kidsFunc, val): layer = [val] for i in xrange(generation): layer = itertools.chain.from_iterable(itertools.imap(kidsFunc, layer)) return layer </code></pre> <p>Haskell:</p> <pre><code>grandKids generation kidsFunc val = iterate (concatMap kidsFunc) [val] !! generation </code></pre> <p>The main difference here is that Haskell's standard library has useful functions for functional programming: in this case <code>iterate</code>, <code>concat</code>, and <code>(!!)</code></p>
14
2009-06-19T14:50:09Z
[ "python", "functional-programming" ]
Why isn't Python very good for functional programming?
1,017,621
<p>I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in <a href="http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming">this</a> question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)</p>
216
2009-06-19T12:12:06Z
24,661,572
<p>One thing that is really important for this question (and the answers) is the following: What the hell is functional programming, and what are the most important properties of it. I'll try to give my view of it:</p> <p>Functional programming is a lot like writing math on a whiteboard. When you write equations on a whiteboard, you do not think about an execution order. There is (typically) no mutation. You don't come back the day after and look at it, and when you make the calculations again, you get a different result (or you may, if you've had some fresh coffee :)). Basically, what is on the board is there, and the answer was already there when you started writing things down, you just haven't realized what it is yet.</p> <p>Functional programming is a lot like that; you don't change things, you just evaluate the equation (or in this case, "program") and figure out what the answer is. The program is still there, unmodified. The same with the data.</p> <p>I would rank the following as the most important features of functional programming: a) referential transparency - if you evaluate the same statement at some other time and place, but with the same variable values, it will still mean the same. b) no side effect - no matter how long you stare at the whiteboard, the equation another guy is looking at at another whiteboard won't accidentally change. c) functions are values too. which can be passed around and applied with, or to, other variables. d) function composition, you can do h=g·f and thus define a new function h(..) which is equivalent to calling g(f(..)).</p> <p>This list is in my prioritized order, so referential transparency is the most important, followed by no side effects.</p> <p>Now, if you go through python and check how well the language and libraries supports, and guarantees, these aspects - then you are well on the way to answer your own question.</p>
7
2014-07-09T18:48:46Z
[ "python", "functional-programming" ]
Why isn't Python very good for functional programming?
1,017,621
<p>I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in <a href="http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming">this</a> question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)</p>
216
2009-06-19T12:12:06Z
35,236,180
<p>In addition to other answers, one reason Python and most other multi-paradigm languages are not well suited for true functional programming is because their compilers / virtual machines / run-times do not support functional optimization. This sort of optimization is achieved by the compiler understanding mathematical rules. For example, many programming languages support a <code>map</code> function or method. This is a fairly standard function that takes a function as one argument and a iterable as the second argument then applies that function to each element in the iterable. </p> <p>Anyways it turns out that <code>map( foo() , x ) * map( foo(), y )</code> is the same as <code>map( foo(), x * y )</code>. The latter case is actually faster than the former because the former performs two copies where the latter performs one.</p> <p>Better functional languages recognize these mathematically based relationships and automatically perform the optimization. Languages that aren't dedicated to the functional paradigm will likely not optimize.</p>
3
2016-02-06T01:16:27Z
[ "python", "functional-programming" ]
Why isn't Python very good for functional programming?
1,017,621
<p>I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in <a href="http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming">this</a> question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)</p>
216
2009-06-19T12:12:06Z
37,756,221
<p>Another reason not mentioned above is that many built-in functions and methods of built-in types modify and object but do not return the modified object. Functional code would be cleaner and more concise, for example, if some_list.append(some_object) returned some_list with some_object appended.</p>
2
2016-06-10T19:56:05Z
[ "python", "functional-programming" ]
Why isn't Python very good for functional programming?
1,017,621
<p>I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in <a href="http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming">this</a> question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)</p>
216
2009-06-19T12:12:06Z
39,640,685
<p>Another problem with languages that support operator overloading (like Python) is that even simple expressions, like <code>x + y</code>, can potentially cause side effects. In that example, <code>x.__add__</code> could be impure, and may even change over time. </p>
0
2016-09-22T13:38:24Z
[ "python", "functional-programming" ]
Is there an API to access a Google Group data?
1,017,794
<p>I'm trying to build some statistics for an email group I participate. Is there any Python API to access the email data on a GoogleGroup?</p> <p>Also, I know some statistics are available on the group's main page. I'm looking for something more complex than what is shown there.</p>
5
2009-06-19T12:48:08Z
1,017,810
<p>There isn't an API that I know of, however you can access the XML feed and manipulate it as required.</p>
4
2009-06-19T12:50:43Z
[ "python", "google-groups" ]
Formatting csv file data with html template
1,017,898
<p>I have an csv file, <strong>the data</strong>, and an HTML file, <strong>the template</strong>.</p> <p>I want a script that will create an individual html file per record from the csv file, using the html file as a template.</p> <p>Which is the best way to do this in Ruby? Python? Is there a tool/library I can use for this in either language?</p>
3
2009-06-19T13:12:25Z
1,017,907
<p>Ruby has built in CSV handling which should make it fairly trivial to output static HTML files.<br /> See:</p> <ul> <li><a href="http://www.rubytips.org/2008/01/06/csv-processing-in-ruby/" rel="nofollow">http://www.rubytips.org/2008/01/06/csv-processing-in-ruby/</a></li> <li><a href="http://www.ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html" rel="nofollow">http://www.ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html</a></li> </ul> <p>Actually, so does Python, so it's really a matter of personal preference (or of whichever you already have configured).</p>
3
2009-06-19T13:14:40Z
[ "python", "html", "ruby", "formatting", "csv" ]
Formatting csv file data with html template
1,017,898
<p>I have an csv file, <strong>the data</strong>, and an HTML file, <strong>the template</strong>.</p> <p>I want a script that will create an individual html file per record from the csv file, using the html file as a template.</p> <p>Which is the best way to do this in Ruby? Python? Is there a tool/library I can use for this in either language?</p>
3
2009-06-19T13:12:25Z
1,018,417
<p>Python with <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a>.</p> <pre><code>import jinja import csv env= jinja.Environment() env.loader= jinja.FileSystemLoader("some/directory") template= env.get_template( "name" ) rdr= csv.reader( open("some.csv", "r" ) ) csv_data = [ row for row in rdr ] print template.render( data=csv_data ) </code></pre> <p>It turns out that you might be able to get away with simply passing the <code>rdr</code> directly to Jinja for rending. </p> <p>If the template looks like this, it will work with a wide variety of Python structures, including an iterator.</p> <pre><code>&lt;table&gt; {% for row in data %} &lt;tr&gt; &lt;td&gt;{{ row.0 }}&lt;/td&gt;&lt;td&gt;{{ row.1 }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre>
3
2009-06-19T14:54:49Z
[ "python", "html", "ruby", "formatting", "csv" ]
Python sys.path modification not working
1,017,909
<p>I'm trying to modify the sys.path in one of my Python files in order to have some specific libraries dirs in the modules search path (it might not be the best way but ...). If I insert several paths in the front of sys.path my script is not taking into account those paths for future imports. If i make a whole new list containing those libraries dirs i need and assign that list to sys.path then those imports are taken into account. Is this the correct behavior? I'm using python 2.5.4. Could it be something from my environment that could lead to such behavior?</p> <p>Some code snippets: If I do <code></p> <pre> pathtoInsert1 = " .... " pathtoInsert2 = " .... " sys.path.insert(0, pathToInsert1) sys.path.insert(0, pathToInsert2) </pre> <p></code> it does not work. It does not take into account the paths.</p> <p>If I do <code></p> <pre> pathList = [pathToInsert1, pathToInsert2] sys.path = pathList </pre> <p></code> it works.</p> <p>Thanks</p>
7
2009-06-19T13:14:52Z
1,017,938
<p>How are you "inserting" the additional paths?</p> <p>Modifying the path is done the same way any other list in Python is modified - although it sounds like you're simply clobbering it by re-assigning it.</p> <p>Example of updating sys.path: <a href="http://www.johnny-lin.com/cdat_tips/tips_pylang/path.html" rel="nofollow">http://www.johnny-lin.com/cdat_tips/tips_pylang/path.html</a></p>
2
2009-06-19T13:23:05Z
[ "python", "path" ]
Python sys.path modification not working
1,017,909
<p>I'm trying to modify the sys.path in one of my Python files in order to have some specific libraries dirs in the modules search path (it might not be the best way but ...). If I insert several paths in the front of sys.path my script is not taking into account those paths for future imports. If i make a whole new list containing those libraries dirs i need and assign that list to sys.path then those imports are taken into account. Is this the correct behavior? I'm using python 2.5.4. Could it be something from my environment that could lead to such behavior?</p> <p>Some code snippets: If I do <code></p> <pre> pathtoInsert1 = " .... " pathtoInsert2 = " .... " sys.path.insert(0, pathToInsert1) sys.path.insert(0, pathToInsert2) </pre> <p></code> it does not work. It does not take into account the paths.</p> <p>If I do <code></p> <pre> pathList = [pathToInsert1, pathToInsert2] sys.path = pathList </pre> <p></code> it works.</p> <p>Thanks</p>
7
2009-06-19T13:14:52Z
1,017,948
<p>You really need to post some code for us to be able to help you. However, I can make an educated guess. You say that if you make a whole new list and assign it to sys.path then it works. I assume you mean that you're doing something like this</p> <pre><code>sys.path = ["dir1", "dir2", ...] </code></pre> <p>But that if you insert the paths at the beginning then it doesn't work. My guess is that you're using the insert method, like so</p> <pre><code>sys.path.insert(0, ["dir1", "dir2"]) </code></pre> <p>If so then this is incorrect. This would create a list that looks like</p> <pre><code>[["dir1", "dir2"], "dir3", ...] </code></pre> <p>You should instead say</p> <pre><code>sys.path[:0] = ["dir1", "dir2"] </code></pre> <p>which will give you</p> <pre><code>["dir1", "dir2", "dir3", ...] </code></pre> <p>But this is all guesswork until you post your code.</p>
17
2009-06-19T13:26:14Z
[ "python", "path" ]
Python sys.path modification not working
1,017,909
<p>I'm trying to modify the sys.path in one of my Python files in order to have some specific libraries dirs in the modules search path (it might not be the best way but ...). If I insert several paths in the front of sys.path my script is not taking into account those paths for future imports. If i make a whole new list containing those libraries dirs i need and assign that list to sys.path then those imports are taken into account. Is this the correct behavior? I'm using python 2.5.4. Could it be something from my environment that could lead to such behavior?</p> <p>Some code snippets: If I do <code></p> <pre> pathtoInsert1 = " .... " pathtoInsert2 = " .... " sys.path.insert(0, pathToInsert1) sys.path.insert(0, pathToInsert2) </pre> <p></code> it does not work. It does not take into account the paths.</p> <p>If I do <code></p> <pre> pathList = [pathToInsert1, pathToInsert2] sys.path = pathList </pre> <p></code> it works.</p> <p>Thanks</p>
7
2009-06-19T13:14:52Z
1,333,396
<p>Example of updating sys.path taken from <a href="http://www.johnny-lin.com/cdat%5Ftips/tips%5Fpylang/path.html" rel="nofollow">here</a></p> <pre><code>import sys sys.path.append("/home/me/mypy") </code></pre> <p>This worked for me.</p>
4
2009-08-26T09:15:12Z
[ "python", "path" ]
Python sys.path modification not working
1,017,909
<p>I'm trying to modify the sys.path in one of my Python files in order to have some specific libraries dirs in the modules search path (it might not be the best way but ...). If I insert several paths in the front of sys.path my script is not taking into account those paths for future imports. If i make a whole new list containing those libraries dirs i need and assign that list to sys.path then those imports are taken into account. Is this the correct behavior? I'm using python 2.5.4. Could it be something from my environment that could lead to such behavior?</p> <p>Some code snippets: If I do <code></p> <pre> pathtoInsert1 = " .... " pathtoInsert2 = " .... " sys.path.insert(0, pathToInsert1) sys.path.insert(0, pathToInsert2) </pre> <p></code> it does not work. It does not take into account the paths.</p> <p>If I do <code></p> <pre> pathList = [pathToInsert1, pathToInsert2] sys.path = pathList </pre> <p></code> it works.</p> <p>Thanks</p>
7
2009-06-19T13:14:52Z
15,163,787
<p>I just had a similar problem while working in iPython with modules that are distributed over several directories. In that case, to get import to work, one must make sure the <code>module.__path__</code> of modules with distributed <code>__init__.py</code> includes all directories where one of the module's <code>__init__.py</code> are, as well as making sure the correct directory is in the sys.path list.</p> <p>For example, I have a module called foo, which contains a module called bar which is spread over several directories:</p> <pre><code>aerith/foo/bar/__init__.py aerith/foo/bar/baz/__init__.py bob/foo/bar/__init__.py bob/foo/bar/baf/__init__.py carol/foo/bar/__init__.py carol/foo/bar/quux/__init__.py </code></pre> <p>In iPython, I had already imported baz and baf, and wanted to import quux.</p> <p><code>from foo.bar import quux</code></p> <p>This gave an ImportError, because <code>carol</code> was not in <code>sys.path</code>, but <code>sys.path.append('carol')</code> did not fix the ImportError.</p> <p>What was required was informing the <code>bar</code> module that one of its <code>__init__.py</code> could be found in 'carol/foo/bar'.</p> <pre><code>foo.bar.__path__.append('carol/foo/bar') from foo.bar import quux </code></pre>
1
2013-03-01T17:46:02Z
[ "python", "path" ]
How do I know which contract failed with Python's contract.py?
1,017,985
<p>I'm playing with <a href="http://www.wayforward.net/pycontract/" rel="nofollow">contract.py</a>, Terrence Way's reference implementation of design-by-contract for Python. The implementation throws an exception when a contract (precondition/postcondition/invariant) is violated, but it doesn't provide you a quick way of identifying which specific contract has failed if there are multiple ones associated with a method. </p> <p>For example, if I take the <a href="http://www.wayforward.net/pycontract/examples/circbuf.py" rel="nofollow">circbuf.py</a> example, and violate the precondition by passing in a negative argument, like so: </p> <pre><code>circbuf(-5) </code></pre> <p>Then I get a traceback that looks like this:</p> <pre><code>Traceback (most recent call last): File "circbuf.py", line 115, in &lt;module&gt; circbuf(-5) File "&lt;string&gt;", line 3, in __assert_circbuf___init___chk File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1204, in call_constructor_all File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1293, in _method_call_all File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1332, in _call_all File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1371, in _check_preconditions contract.PreconditionViolationError: ('__main__.circbuf.__init__', 4) </code></pre> <p>My hunch is that the second argument in the PreconditionViolationError (4) refers to the line number in the circbuf.<strong>init</strong> docstring that contains the assertion:</p> <pre><code>def __init__(self, leng): """Construct an empty circular buffer. pre:: leng &gt; 0 post[self]:: self.is_empty() and len(self.buf) == leng """ </code></pre> <p>However, it's a pain to have to open the file and count the docstring line numbers. Does anybody have a quicker solution for identifying which contract has failed? </p> <p>(Note that in this example, there's a single precondition, so it's obvious, but multiple preconditions are possible).</p>
1
2009-06-19T13:35:32Z
1,020,981
<p>Without modifying his code, I don't think you can, but since this is python...</p> <p>If you look for where he raises the exception to the user, it I think is possible to push the info you're looking for into it... I wouldn't expect you to be able to get the trace-back to be any better though because the code is actually contained in a comment block and then processed.</p> <p>The code is pretty complicated, but this might be a block to look at - maybe if you dump out some of the args you can figure out whats going on...</p> <pre><code>def _check_preconditions(a, func, va, ka): # ttw006: correctly weaken pre-conditions... # ab002: Avoid generating AttributeError exceptions... if hasattr(func, '__assert_pre'): try: func.__assert_pre(*va, **ka) except PreconditionViolationError, args: # if the pre-conditions fail, *all* super-preconditions # must fail too, otherwise for f in a: if f is not func and hasattr(f, '__assert_pre'): f.__assert_pre(*va, **ka) raise InvalidPreconditionError(args) # rr001: raise original PreconditionViolationError, not # inner AttributeError... # raise raise args # ...rr001 # ...ab002 # ...ttw006 </code></pre>
1
2009-06-20T05:01:22Z
[ "python", "design-by-contract" ]
How do I know which contract failed with Python's contract.py?
1,017,985
<p>I'm playing with <a href="http://www.wayforward.net/pycontract/" rel="nofollow">contract.py</a>, Terrence Way's reference implementation of design-by-contract for Python. The implementation throws an exception when a contract (precondition/postcondition/invariant) is violated, but it doesn't provide you a quick way of identifying which specific contract has failed if there are multiple ones associated with a method. </p> <p>For example, if I take the <a href="http://www.wayforward.net/pycontract/examples/circbuf.py" rel="nofollow">circbuf.py</a> example, and violate the precondition by passing in a negative argument, like so: </p> <pre><code>circbuf(-5) </code></pre> <p>Then I get a traceback that looks like this:</p> <pre><code>Traceback (most recent call last): File "circbuf.py", line 115, in &lt;module&gt; circbuf(-5) File "&lt;string&gt;", line 3, in __assert_circbuf___init___chk File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1204, in call_constructor_all File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1293, in _method_call_all File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1332, in _call_all File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1371, in _check_preconditions contract.PreconditionViolationError: ('__main__.circbuf.__init__', 4) </code></pre> <p>My hunch is that the second argument in the PreconditionViolationError (4) refers to the line number in the circbuf.<strong>init</strong> docstring that contains the assertion:</p> <pre><code>def __init__(self, leng): """Construct an empty circular buffer. pre:: leng &gt; 0 post[self]:: self.is_empty() and len(self.buf) == leng """ </code></pre> <p>However, it's a pain to have to open the file and count the docstring line numbers. Does anybody have a quicker solution for identifying which contract has failed? </p> <p>(Note that in this example, there's a single precondition, so it's obvious, but multiple preconditions are possible).</p>
1
2009-06-19T13:35:32Z
11,017,292
<p>This is an old question but I may as well answer it. I added some output, you'll see it at the comment # jlr001. Add the line below to your contract.py and when it raises an exception it will show the doc line number and the statement that triggered it. Nothing more than that, but it will at least stop you from needing to guess which condition triggered it.</p> <pre><code>def _define_checker(name, args, contract, path): """Define a function that does contract assertion checking. args is a string argument declaration (ex: 'a, b, c = 1, *va, **ka') contract is an element of the contracts list returned by parse_docstring module is the containing module (not parent class) Returns the newly-defined function. pre:: isstring(name) isstring(args) contract[0] in _CONTRACTS len(contract[2]) &gt; 0 post:: isinstance(__return__, FunctionType) __return__.__name__ == name """ output = StringIO() output.write('def %s(%s):\n' % (name, args)) # ttw001... raise new exception classes ex = _EXCEPTIONS.get(contract[0], 'ContractViolationError') output.write('\tfrom %s import forall, exists, implies, %s\n' % \ (MODULE, ex)) loc = '.'.join([x.__name__ for x in path]) for c in contract[2]: output.write('\tif not (') output.write(c[0]) # jlr001: adding conidition statement to output message, easier debugging output.write('): raise %s("%s", %u, "%s")\n' % (ex, loc, c[1], c[0])) # ...ttw001 # ttw016: return True for superclasses to use in preconditions output.write('\treturn True') # ...ttw016 return _define(name, output.getvalue(), path[0]) </code></pre>
1
2012-06-13T14:39:08Z
[ "python", "design-by-contract" ]
Help me understand the difference between CLOBs and BLOBs in Oracle
1,018,073
<p>This is mainly just a "check my understanding" type of question. Here's my understanding of CLOBs and BLOBs as they work in Oracle:</p> <ul> <li>CLOBs are for text like XML, JSON, etc. You should not assume what encoding the database will store it as (at least in an application) as it will be converted to whatever encoding the database was configured to use.</li> <li>BLOBs are for binary data. You can be reasonably assured that they will be stored how you send them and that you will get them back with exactly the same data as they were sent as.</li> </ul> <p>So in other words, say I have some binary data (in this case a pickled python object). I need to be assured that when I send it, it will be stored exactly how I sent it and that when I get it back it will be exactly the same. A BLOB is what I want, correct?</p> <p>Is it really feasible to use a CLOB for this? Or will character encoding cause enough problems that it's not worth it?</p>
33
2009-06-19T13:51:38Z
1,018,096
<p><code>CLOB</code> is encoding and collation sensitive, <code>BLOB</code> is not.</p> <p>When you write into a <code>CLOB</code> using, say, <code>CL8WIN1251</code>, you write a <code>0xC0</code> (which is Cyrillic letter А).</p> <p>When you read data back using <code>AL16UTF16</code>, you get back <code>0x0410</code>, which is a <code>UTF16</code> represenation of this letter.</p> <p>If you were reading from a <code>BLOB</code>, you would get same <code>0xC0</code> back.</p>
46
2009-06-19T13:56:25Z
[ "python", "oracle" ]
Help me understand the difference between CLOBs and BLOBs in Oracle
1,018,073
<p>This is mainly just a "check my understanding" type of question. Here's my understanding of CLOBs and BLOBs as they work in Oracle:</p> <ul> <li>CLOBs are for text like XML, JSON, etc. You should not assume what encoding the database will store it as (at least in an application) as it will be converted to whatever encoding the database was configured to use.</li> <li>BLOBs are for binary data. You can be reasonably assured that they will be stored how you send them and that you will get them back with exactly the same data as they were sent as.</li> </ul> <p>So in other words, say I have some binary data (in this case a pickled python object). I need to be assured that when I send it, it will be stored exactly how I sent it and that when I get it back it will be exactly the same. A BLOB is what I want, correct?</p> <p>Is it really feasible to use a CLOB for this? Or will character encoding cause enough problems that it's not worth it?</p>
33
2009-06-19T13:51:38Z
1,018,102
<p>Your understanding is correct. Since you mention Python, think of the Python 3 distinction between strings and bytes: CLOBs and BLOBs are quite analogous, with the extra issue that the encoding of CLOBs is not under your app's control.</p>
9
2009-06-19T13:57:36Z
[ "python", "oracle" ]
One django installation different users per site
1,018,111
<p>How can I have different users for different sites with django. My application should look like this:</p> <pre><code>a.mydomain.com b.otherdomain.com </code></pre> <p>Users should be bound to the domain, so that a.mydomain.com and b.otherdomain.com have different users.</p>
0
2009-06-19T13:59:32Z
1,018,202
<p>In the <a href="http://docs.djangoproject.com/en/dev/topics/auth/" rel="nofollow">auth</a> setup, you could create separate custom permissions, one per domain, and check if the current user has the permission for the current domain -- see the "custom permissions" section in the auth doc in question.</p>
1
2009-06-19T14:20:43Z
[ "python", "django", "authentication", "django-models" ]
Pass-through keyword arguments
1,018,359
<p>I've got a class function that needs to "pass through" a particular keyword argument:</p> <pre><code>def createOrOpenTable(self, tableName, schema, asType=Table): if self.tableExists(tableName): return self.openTable(tableName, asType=asType) else: return self.createTable(self, tableName, schema, asType=asType) </code></pre> <p>When I call it, I get an error like this:</p> <pre><code>TypeError: createTable() got multiple values for keyword argument 'asType' </code></pre> <p>Is there any way to "pass through" such a keyword argument?</p> <p>I've thought of several answers, but none of them are optimal. From worst to best:</p> <ul> <li><p>I could change the keyword name on one or more of the functions, but I want to use the same keyword for all three functions, since the parameter carries the same meaning.</p></li> <li><p>I could pass the <code>asType</code> parameter by position instead of by keyword, but if I add other keyword parameters to <code>openTable</code> or <code>createTable</code>, I'd have to remember to change the calls. I'd rather it automatically adapt, as it would if I could use the keyword form.</p></li> <li><p>I could use the <code>**args</code> form here instead, to get a dictionary of keyword parameters rather than using a default parameter, but that seems like using a sledgehammer to swat a fly (because of the extra lines of code needed to properly parse it).</p></li> </ul> <p>Is there a better solution?</p>
4
2009-06-19T14:44:33Z
1,018,372
<p>You're doing it right... Just take out the <code>self</code> in the second function call :)</p> <pre><code> return self.createTable(self, tableName, schema, asType=asType) </code></pre> <p>should be:</p> <pre><code> return self.createTable(tableName, schema, asType=asType) </code></pre>
9
2009-06-19T14:46:01Z
[ "python" ]
Pass-through keyword arguments
1,018,359
<p>I've got a class function that needs to "pass through" a particular keyword argument:</p> <pre><code>def createOrOpenTable(self, tableName, schema, asType=Table): if self.tableExists(tableName): return self.openTable(tableName, asType=asType) else: return self.createTable(self, tableName, schema, asType=asType) </code></pre> <p>When I call it, I get an error like this:</p> <pre><code>TypeError: createTable() got multiple values for keyword argument 'asType' </code></pre> <p>Is there any way to "pass through" such a keyword argument?</p> <p>I've thought of several answers, but none of them are optimal. From worst to best:</p> <ul> <li><p>I could change the keyword name on one or more of the functions, but I want to use the same keyword for all three functions, since the parameter carries the same meaning.</p></li> <li><p>I could pass the <code>asType</code> parameter by position instead of by keyword, but if I add other keyword parameters to <code>openTable</code> or <code>createTable</code>, I'd have to remember to change the calls. I'd rather it automatically adapt, as it would if I could use the keyword form.</p></li> <li><p>I could use the <code>**args</code> form here instead, to get a dictionary of keyword parameters rather than using a default parameter, but that seems like using a sledgehammer to swat a fly (because of the extra lines of code needed to properly parse it).</p></li> </ul> <p>Is there a better solution?</p>
4
2009-06-19T14:44:33Z
1,018,431
<p>I have to say, that I first thought of a more complicated problem. But the answer of David Wolever is absolutely correct. It is just the duplicate self here, that creates the problem. This way, the positional parameters get out of line and asType is given a value as possitional parameter (once) and as keyword-parameter (second time!).</p> <p>A much more interesting problem is, what to do, when you want to enhance the called routine (createTable in the example) without everytime enhancing the intermediate function. Here, the **args solution makes the trick:</p> <p>For example:</p> <pre><code>def createOrOpenTable(self, tableName, schema, **args): if self.tableExists(tableName): return self.openTable(tableName, **args) else: return self.createTable(tableName, schema, **args) </code></pre> <p>By this way, it is possible to enhance the signature of createTable and openTable without having to change createOrOpenTable any more.</p> <p>When create and openTable can have different keyword-parameters, then of course both routines must be defined as follows:</p> <pre><code>def createTable(self, tableName, schema, asType=None, **others): ... </code></pre> <p>The others parameter eats up any keyword parameters unknown to the method -- it is also not needed to evaluate it.</p>
5
2009-06-19T14:57:58Z
[ "python" ]
Pass-through keyword arguments
1,018,359
<p>I've got a class function that needs to "pass through" a particular keyword argument:</p> <pre><code>def createOrOpenTable(self, tableName, schema, asType=Table): if self.tableExists(tableName): return self.openTable(tableName, asType=asType) else: return self.createTable(self, tableName, schema, asType=asType) </code></pre> <p>When I call it, I get an error like this:</p> <pre><code>TypeError: createTable() got multiple values for keyword argument 'asType' </code></pre> <p>Is there any way to "pass through" such a keyword argument?</p> <p>I've thought of several answers, but none of them are optimal. From worst to best:</p> <ul> <li><p>I could change the keyword name on one or more of the functions, but I want to use the same keyword for all three functions, since the parameter carries the same meaning.</p></li> <li><p>I could pass the <code>asType</code> parameter by position instead of by keyword, but if I add other keyword parameters to <code>openTable</code> or <code>createTable</code>, I'd have to remember to change the calls. I'd rather it automatically adapt, as it would if I could use the keyword form.</p></li> <li><p>I could use the <code>**args</code> form here instead, to get a dictionary of keyword parameters rather than using a default parameter, but that seems like using a sledgehammer to swat a fly (because of the extra lines of code needed to properly parse it).</p></li> </ul> <p>Is there a better solution?</p>
4
2009-06-19T14:44:33Z
1,018,487
<p>I would have posted a comment to Juergen's post, but I need to write a code example. Here's a little bit more generic version:</p> <pre><code>def createOrOpenTable(self, tableName, schema, *args, **argd): if self.tableExists(tableName): return self.openTable(tableName, *args, **argd) else: return self.createTable(tableName, schema, *args, **argd) </code></pre> <p>This will allow positional arguments to also be effective (which is important if you truly want this to be a "pass-through."</p>
5
2009-06-19T15:07:34Z
[ "python" ]
Python and if statement
1,018,415
<p>I'm running a script to feed an exe file a statement like below:</p> <pre><code>for j in ('90.','52.62263.','26.5651.','10.8123.'): if j == '90.': z = ('0.') elif j == '52.62263.': z = ('0.', '72.', '144.', '216.', '288.') elif j == '26.5651': z = ('324.', '36.', '108.', '180.', '252.') else: z = ('288.', '0.', '72.', '144.', '216.') for k in z: exepath = os.path.join('\Program Files' , 'BRL-CAD' , 'bin' , 'rtarea.exe') exepath = '"' + os.path.normpath(exepath) + '"' cmd = exepath + '-j' + str(el) + '-k' + str(z) process=Popen('echo ' + cmd, shell=True, stderr=STDOUT ) print process </code></pre> <p>I'm using the command prompt and when I run the exe with these numbers there are times when It doesn't seem to be in order. Like sometimes it will print out 3 statements of the 52.62263 but then before they all are printed it will print out a single 26.5651 and then go back to 52.62263. It's not just those numbers that act like this. Different runs it may be different numbers (A 52.62263 between "two" 90 statements) . All in all, I want it to print it in order top to bottom. Any suggestions and using my code any helpful solutions? thanks!</p>
2
2009-06-19T14:54:30Z
1,018,426
<p><code>z = ('0.')</code> is not a tuple, therefore your <code>for k in z</code> loop will iterate over the characters "0" and ".". Add a comma to tell python you want it to be a tuple:</p> <pre><code>z = ('0.',) </code></pre>
8
2009-06-19T14:57:07Z
[ "python", "if-statement" ]
Python and if statement
1,018,415
<p>I'm running a script to feed an exe file a statement like below:</p> <pre><code>for j in ('90.','52.62263.','26.5651.','10.8123.'): if j == '90.': z = ('0.') elif j == '52.62263.': z = ('0.', '72.', '144.', '216.', '288.') elif j == '26.5651': z = ('324.', '36.', '108.', '180.', '252.') else: z = ('288.', '0.', '72.', '144.', '216.') for k in z: exepath = os.path.join('\Program Files' , 'BRL-CAD' , 'bin' , 'rtarea.exe') exepath = '"' + os.path.normpath(exepath) + '"' cmd = exepath + '-j' + str(el) + '-k' + str(z) process=Popen('echo ' + cmd, shell=True, stderr=STDOUT ) print process </code></pre> <p>I'm using the command prompt and when I run the exe with these numbers there are times when It doesn't seem to be in order. Like sometimes it will print out 3 statements of the 52.62263 but then before they all are printed it will print out a single 26.5651 and then go back to 52.62263. It's not just those numbers that act like this. Different runs it may be different numbers (A 52.62263 between "two" 90 statements) . All in all, I want it to print it in order top to bottom. Any suggestions and using my code any helpful solutions? thanks!</p>
2
2009-06-19T14:54:30Z
1,018,480
<p>I think what's happening right now is that you are not waiting for those processes to finish before they're printed. Try something like this in your last 2 lines:</p> <pre><code>from subprocess import Popen, STDOUT stdout, stderr = Popen('echo ' + cmd, shell=True, stderr=STDOUT).communicate() print stdout </code></pre>
6
2009-06-19T15:06:14Z
[ "python", "if-statement" ]
Python and if statement
1,018,415
<p>I'm running a script to feed an exe file a statement like below:</p> <pre><code>for j in ('90.','52.62263.','26.5651.','10.8123.'): if j == '90.': z = ('0.') elif j == '52.62263.': z = ('0.', '72.', '144.', '216.', '288.') elif j == '26.5651': z = ('324.', '36.', '108.', '180.', '252.') else: z = ('288.', '0.', '72.', '144.', '216.') for k in z: exepath = os.path.join('\Program Files' , 'BRL-CAD' , 'bin' , 'rtarea.exe') exepath = '"' + os.path.normpath(exepath) + '"' cmd = exepath + '-j' + str(el) + '-k' + str(z) process=Popen('echo ' + cmd, shell=True, stderr=STDOUT ) print process </code></pre> <p>I'm using the command prompt and when I run the exe with these numbers there are times when It doesn't seem to be in order. Like sometimes it will print out 3 statements of the 52.62263 but then before they all are printed it will print out a single 26.5651 and then go back to 52.62263. It's not just those numbers that act like this. Different runs it may be different numbers (A 52.62263 between "two" 90 statements) . All in all, I want it to print it in order top to bottom. Any suggestions and using my code any helpful solutions? thanks!</p>
2
2009-06-19T14:54:30Z
1,018,511
<p>What eduffy said. And this is a little cleaner; just prints, but you get the idea:</p> <pre><code>import os data = { '90.': ('0.',), '52.62263.': ('0.', '72.', '144.', '216.', '288.'), '26.5651.': ('324.', '36.', '108.', '180.', '252.'), '10.8123.': ('288.', '0.', '72.', '144.', '216.'), } for tag in data: for k in data[tag]: exepath = os.path.join('\Program Files', 'BRL-CAD', 'bin', 'rtarea.exe') exepath = '"' + os.path.normpath(exepath) + '"' cmd = exepath + ' -el ' + str(tag) + ' -az ' + str(data[tag]) process = 'echo ' + cmd print process </code></pre>
5
2009-06-19T15:10:57Z
[ "python", "if-statement" ]
Python and if statement
1,018,415
<p>I'm running a script to feed an exe file a statement like below:</p> <pre><code>for j in ('90.','52.62263.','26.5651.','10.8123.'): if j == '90.': z = ('0.') elif j == '52.62263.': z = ('0.', '72.', '144.', '216.', '288.') elif j == '26.5651': z = ('324.', '36.', '108.', '180.', '252.') else: z = ('288.', '0.', '72.', '144.', '216.') for k in z: exepath = os.path.join('\Program Files' , 'BRL-CAD' , 'bin' , 'rtarea.exe') exepath = '"' + os.path.normpath(exepath) + '"' cmd = exepath + '-j' + str(el) + '-k' + str(z) process=Popen('echo ' + cmd, shell=True, stderr=STDOUT ) print process </code></pre> <p>I'm using the command prompt and when I run the exe with these numbers there are times when It doesn't seem to be in order. Like sometimes it will print out 3 statements of the 52.62263 but then before they all are printed it will print out a single 26.5651 and then go back to 52.62263. It's not just those numbers that act like this. Different runs it may be different numbers (A 52.62263 between "two" 90 statements) . All in all, I want it to print it in order top to bottom. Any suggestions and using my code any helpful solutions? thanks!</p>
2
2009-06-19T14:54:30Z
1,018,513
<p>Since you've made a few posts about this bit of code, allow me to just correct/pythonify/beautify the whole thing:</p> <pre><code>for j,z in { '90.' : ('0.',) , '52.62263.' : ('0.', '72.', '144.', '216.', '288.') , '26.5651.' : ('324.', '36.', '108.', '180.', '252.') , '10.8123.' : ('288.', '0.', '72.', '144.', '216.') }.iteritems(): for k in z: exepath = os.path.join('\Program Files' , 'BRL-CAD', 'bin' , 'rtarea.exe') exepath = '"%s"' % os.path.normpath(exepath) cmd = exepath + '-j' + str(el) + '-k' + z process = Popen('echo ' + cmd, shell=True, stderr=STDOUT ) print process </code></pre>
2
2009-06-19T15:11:09Z
[ "python", "if-statement" ]
Python logging incompatibilty between 2.5 and 2.6
1,018,527
<p>Could you help me solve the following incompatibility issue between Python 2.5 and 2.6?</p> <p>logger.conf:</p> <pre><code>[loggers] keys=root,aLogger,bLogger [handlers] keys=consoleHandler [formatters] keys= [logger_root] level=NOTSET handlers=consoleHandler [logger_aLogger] level=DEBUG handlers=consoleHandler propagate=0 qualname=a [logger_bLogger] level=INFO handlers=consoleHandler propagate=0 qualname=b [handler_consoleHandler] class=StreamHandler args=(sys.stderr,) </code></pre> <p>module_one.py:</p> <pre><code>import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') def function_one(): b_log.info("function_one() called.") </code></pre> <p>module_two.py:</p> <pre><code>import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') def function_two(): a_log.info("function_two() called.") </code></pre> <p>logger.py:</p> <pre><code>from module_one import function_one from module_two import function_two function_one() function_two() </code></pre> <p>Output of calling logger.py under Ubuntu 9.04:</p> <pre><code>$ python2.5 logger.py $ $ python2.6 logger.py function_one() called. function_two() called. $ </code></pre>
6
2009-06-19T15:14:14Z
1,018,694
<p>I don't understand the reasons of this behavior myself but as you well stated in 2.6 it works differently. We can assume this is a bug affecting 2.5</p> <p>As a workaround I suggest the following:</p> <p>extra_module.py:</p> <pre><code>import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') </code></pre> <p>module_one.py:</p> <pre><code>from extra_module import a_log def function_one(): a_log.info("function_one() called.") </code></pre> <p>module_two.py:</p> <pre><code>from extra_module import b_log def function_two(): b_log.info("function_two() called.") </code></pre> <p>by using this scheme I was able to run logger.py on python2.5.4 with the same behavior as of 2.6</p>
1
2009-06-19T15:46:30Z
[ "python", "logging", "incompatibility" ]
Python logging incompatibilty between 2.5 and 2.6
1,018,527
<p>Could you help me solve the following incompatibility issue between Python 2.5 and 2.6?</p> <p>logger.conf:</p> <pre><code>[loggers] keys=root,aLogger,bLogger [handlers] keys=consoleHandler [formatters] keys= [logger_root] level=NOTSET handlers=consoleHandler [logger_aLogger] level=DEBUG handlers=consoleHandler propagate=0 qualname=a [logger_bLogger] level=INFO handlers=consoleHandler propagate=0 qualname=b [handler_consoleHandler] class=StreamHandler args=(sys.stderr,) </code></pre> <p>module_one.py:</p> <pre><code>import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') def function_one(): b_log.info("function_one() called.") </code></pre> <p>module_two.py:</p> <pre><code>import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') def function_two(): a_log.info("function_two() called.") </code></pre> <p>logger.py:</p> <pre><code>from module_one import function_one from module_two import function_two function_one() function_two() </code></pre> <p>Output of calling logger.py under Ubuntu 9.04:</p> <pre><code>$ python2.5 logger.py $ $ python2.6 logger.py function_one() called. function_two() called. $ </code></pre>
6
2009-06-19T15:14:14Z
1,018,696
<p>Interesting... I played a little in the console and it looks like the second call to <code>logging.config.fileConfig</code> is mucking things up. Not sure why this is though... Here's a transcript that shows the problem:</p> <pre><code>lorien$ python2.5 Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import logging &gt;&gt;&gt; import logging.config &gt;&gt;&gt; logging.config.fileConfig('logger.conf') &gt;&gt;&gt; alog = logging.getLogger('a.submod') &gt;&gt;&gt; alog.info('foo') foo &gt;&gt;&gt; import logging &gt;&gt;&gt; import logging.config &gt;&gt;&gt; alog.info('foo') foo &gt;&gt;&gt; logging.config.fileConfig('logger.conf') &gt;&gt;&gt; alog.info('foo') &gt;&gt;&gt; alog = logging.getLogger('a.submod') &gt;&gt;&gt; alog.info('foo') &gt;&gt;&gt; &gt;&gt;&gt; blog = logging.getLogger('b.submod') &gt;&gt;&gt; blog.info('foo') foo &gt;&gt;&gt; </code></pre> <p>As soon as I call <code>logging.config.fileConfig</code> the second time, my logger instance stops logging. Grabbing a new logging instance doesn't help since it's the same object. If I wait until after configuring both times to fetch the logger instances, then things work - this is why the <code>blog</code> instance works.</p> <p>My suggestion is to delay grabbing the logger instances until you are in the functions. If you move the calls to <code>logging.getLogger()</code> into <code>function_one</code> and <code>function_two</code>, then everything works well.</p>
0
2009-06-19T15:47:03Z
[ "python", "logging", "incompatibility" ]
Python logging incompatibilty between 2.5 and 2.6
1,018,527
<p>Could you help me solve the following incompatibility issue between Python 2.5 and 2.6?</p> <p>logger.conf:</p> <pre><code>[loggers] keys=root,aLogger,bLogger [handlers] keys=consoleHandler [formatters] keys= [logger_root] level=NOTSET handlers=consoleHandler [logger_aLogger] level=DEBUG handlers=consoleHandler propagate=0 qualname=a [logger_bLogger] level=INFO handlers=consoleHandler propagate=0 qualname=b [handler_consoleHandler] class=StreamHandler args=(sys.stderr,) </code></pre> <p>module_one.py:</p> <pre><code>import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') def function_one(): b_log.info("function_one() called.") </code></pre> <p>module_two.py:</p> <pre><code>import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') def function_two(): a_log.info("function_two() called.") </code></pre> <p>logger.py:</p> <pre><code>from module_one import function_one from module_two import function_two function_one() function_two() </code></pre> <p>Output of calling logger.py under Ubuntu 9.04:</p> <pre><code>$ python2.5 logger.py $ $ python2.6 logger.py function_one() called. function_two() called. $ </code></pre>
6
2009-06-19T15:14:14Z
1,019,022
<p>This is a bug which was fixed between 2.5 and 2.6. The fileConfig() function is intended for one-off configuration and so should not be called more than once - however you choose to arrange this. The intended behaviour of fileConfig is to disable any loggers which are not explicitly mentioned in the configuration, and leave enabled the mentioned loggers and their children; the bug was causing the children to be disabled when they shouldn't have been. The example logger configuration mentions loggers 'a' and 'b'; after calling getLogger('a.submod') a child logger is created. The second fileConfig call wrongly disables this in Python 2.5 - in Python 2.6 the logger is not disabled as it is a child of a logger explicitly mentioned in the configuration.</p>
8
2009-06-19T17:03:53Z
[ "python", "logging", "incompatibility" ]
Python logging incompatibilty between 2.5 and 2.6
1,018,527
<p>Could you help me solve the following incompatibility issue between Python 2.5 and 2.6?</p> <p>logger.conf:</p> <pre><code>[loggers] keys=root,aLogger,bLogger [handlers] keys=consoleHandler [formatters] keys= [logger_root] level=NOTSET handlers=consoleHandler [logger_aLogger] level=DEBUG handlers=consoleHandler propagate=0 qualname=a [logger_bLogger] level=INFO handlers=consoleHandler propagate=0 qualname=b [handler_consoleHandler] class=StreamHandler args=(sys.stderr,) </code></pre> <p>module_one.py:</p> <pre><code>import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') def function_one(): b_log.info("function_one() called.") </code></pre> <p>module_two.py:</p> <pre><code>import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') def function_two(): a_log.info("function_two() called.") </code></pre> <p>logger.py:</p> <pre><code>from module_one import function_one from module_two import function_two function_one() function_two() </code></pre> <p>Output of calling logger.py under Ubuntu 9.04:</p> <pre><code>$ python2.5 logger.py $ $ python2.6 logger.py function_one() called. function_two() called. $ </code></pre>
6
2009-06-19T15:14:14Z
1,019,090
<p>I was able to fix this by changing the names of the loggers like so, in both files:</p> <pre><code>logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a') b_log = logging.getLogger('b') </code></pre> <p>I'm not sure of the exact error, but the v2.5 logger module seems to have trouble matching names passed to <code>getLogger()</code> with names in the config file.</p>
0
2009-06-19T17:23:15Z
[ "python", "logging", "incompatibility" ]
'Unstarring' posts using Google Reader API
1,018,626
<p>Does anybody know how to remove stars for articles starred in Google Reader using its unofficial API? </p> <p>I found this one but it doesn't work:</p> <p><a href="http://www.niallkennedy.com/blog/2005/12/google-reader-api.html" rel="nofollow">http://www.niallkennedy.com/blog/2005/12/google-reader-api.html</a></p> <p>Neither does the pyrfeed module in Python, I get the IOError exception every time.</p>
3
2009-06-19T15:35:20Z
1,018,666
<p>Try using:</p> <pre><code>r=user%2F[user ID]%2Fstate%2Fcom.google%2Fstarred </code></pre> <p>instead of</p> <pre><code>a=user%2F[user ID]%2Fstate%2Fcom.google%2Fstarred </code></pre> <p>when invoking edit-tag.</p>
1
2009-06-19T15:42:17Z
[ "python", "google-reader" ]
'Unstarring' posts using Google Reader API
1,018,626
<p>Does anybody know how to remove stars for articles starred in Google Reader using its unofficial API? </p> <p>I found this one but it doesn't work:</p> <p><a href="http://www.niallkennedy.com/blog/2005/12/google-reader-api.html" rel="nofollow">http://www.niallkennedy.com/blog/2005/12/google-reader-api.html</a></p> <p>Neither does the pyrfeed module in Python, I get the IOError exception every time.</p>
3
2009-06-19T15:35:20Z
6,300,705
<p>I don't have Python code for this (I have Java), but the problem you're stumbling with is pretty much independent from the language you use, and it is always good to be able to see some code where you need to have all the details. You just need to do the requests I do, and verify some of the details I highlight and check if it might be your problem.</p> <p>You can use this to remove the star for a given post (note that this service supports more than one item at the same time if you need that):</p> <pre><code> String authToken = getGoogleAuthKey(); // I use Jsoup for the requests, but you can use anything you // like - for jsoup you usually just need to include a jar // into your java project Document doc = Jsoup.connect("http://www.google.com/reader/api/0/edit-tag") // this is important for permission - more details on how to get this ahead in the text .header("Authorization", _AUTHPARAMS + authToken) .data( // you don't need the userid, the '-' will suffice // "r" means remove. you can also use "a" to add // you have lots of other options besides starred. e.g: read "r", "user/-/state/com.google/starred", "async", "true", // the feed, but don't forget the beginning: feed/ "s", "feed/http://www.gizmodo.com/index.xml", // there are 2 id formats, easy to convert - more info ahead in the text "i", "tag:google.com,2005:reader/item/1a68fb395bcb6947", // another token - this one for allow editing - more details on how to get this ahead in the text "T", "//wF1kyvFPIe6JiyITNnMWdA" ) // I also send my API key, but I don't think this is mandatory .userAgent("[YOUR_APP_ID_GOES_HERE].apps.googleusercontent.com") .timeout(10000) // VERY IMPORTANT - don't forget the post! (using get() will not work) .post(); </code></pre> <p>You can check my answer in this <a href="http://stackoverflow.com/questions/1434146/how-to-mark-items-read-with-google-reader-api">other question</a> for some more implementation details (the ones referred to on the comments).</p> <p>To list all the starred items inside a feed, you can use <a href="http://www.google.com/reader/api/0/stream/items/ids" rel="nofollow">http://www.google.com/reader/api/0/stream/items/ids</a> or <a href="http://www.google.com/reader/atom/user/-/state/com.google/starred" rel="nofollow">http://www.google.com/reader/atom/user/-/state/com.google/starred</a> . You can use these ids to call the above mentioned API for removing the star.</p> <p>These last 2 are a lot easier to use. You can check details on the API on these unoffical (but nicely structured) resources: <a href="http://www.chrisdadswell.co.uk/android-coding-example-authenticating-clientlogin-google-reader-api/" rel="nofollow">http://www.chrisdadswell.co.uk/android-coding-example-authenticating-clientlogin-google-reader-api/</a> , <a href="http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI" rel="nofollow">http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI</a> , <a href="http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2" rel="nofollow">http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2</a></p> <p>Hope it helps!</p>
0
2011-06-10T00:16:38Z
[ "python", "google-reader" ]
Python tkInter text entry validation
1,018,729
<p>I'm trying to validate the entry of text using Python/tkInter</p> <pre><code>def validate_text(): return False text = Entry(textframe, validate="focusout", validatecommand=validate_text) </code></pre> <p>where validate_text is the function - I've tried always returning False and always returning True and there's no difference in the outcome..? Is there a set of arguments in the function that I need to include?</p> <p>Edit - changed from NONE to focusout...still not working</p>
1
2009-06-19T15:54:36Z
1,018,742
<p>"Note that this option [validatecommand] is only used if the validate option is not NONE"</p> <p>From <a href="http://effbot.org/tkinterbook/entry.htm#entry.Entry.config-method" rel="nofollow">http://effbot.org/tkinterbook/entry.htm#entry.Entry.config-method</a></p>
0
2009-06-19T15:58:21Z
[ "python", "tkinter" ]
Python tkInter text entry validation
1,018,729
<p>I'm trying to validate the entry of text using Python/tkInter</p> <pre><code>def validate_text(): return False text = Entry(textframe, validate="focusout", validatecommand=validate_text) </code></pre> <p>where validate_text is the function - I've tried always returning False and always returning True and there's no difference in the outcome..? Is there a set of arguments in the function that I need to include?</p> <p>Edit - changed from NONE to focusout...still not working</p>
1
2009-06-19T15:54:36Z
9,246,129
<p><code>focusout</code> means validatecommand will be only be invoked when you take the focus out from the entrywidget.</p> <p>You could try 'key' for validating while typing.</p> <p>Tcl manual:<br> Validation works by setting the validateCommand option to a script which will be evaluated according to the validate option as follows:</p> <ul> <li><p>none<br> Default. This means no validation will occur.</p></li> <li><p>focus<br> validateCommand will be called when the entry receives or loses focus.</p></li> <li><p>focusin<br> validateCommand will be called when the entry receives focus.</p></li> <li><p>focusout<br> validateCommand will be called when the entry loses focus.</p></li> <li><p>key<br> validateCommand will be called when the entry is edited.</p></li> <li><p>all<br> validateCommand will be called for all above conditions. </p></li> </ul>
0
2012-02-12T03:13:48Z
[ "python", "tkinter" ]
Python tkInter text entry validation
1,018,729
<p>I'm trying to validate the entry of text using Python/tkInter</p> <pre><code>def validate_text(): return False text = Entry(textframe, validate="focusout", validatecommand=validate_text) </code></pre> <p>where validate_text is the function - I've tried always returning False and always returning True and there's no difference in the outcome..? Is there a set of arguments in the function that I need to include?</p> <p>Edit - changed from NONE to focusout...still not working</p>
1
2009-06-19T15:54:36Z
11,786,588
<p>I think the only thing your missing is an <strong>invalidcommand (or invcmd)</strong>. What are you expecting validatecommand (or vcmd) to do if it returns false? According to the Tk Manual (see below), if vcmd returns False and validate is <em>not</em> set to none then invcmd will be called. The typical command for invcmd is Tkinter.bell, which makes a ding sound. Also note that vcmd and invcmd are very <em>touchy</em>, and will turn validate to 'none' if they encounter an exception, if the widget is changed in anyway inside the vcmd or invcmd functions or if vcmd does not return a valid Tcl boolean. In particular textvariable is notorious for causing issues, and <a href="http://www.tcl.tk/man/tcl/TkCmd/entry.htm#M7" rel="nofollow">a section in Entry called valdation</a> specifically deals with that.</p> <p>Here are the relevant portions from Tk Command Entry (same for Spinbox). See below for more references. </p> <blockquote> <p>Command-Line Name: <strong>-validatecommand or -vcmd</strong><br> Database Name: <strong>validateCommand</strong><br> Database Class: <strong>ValidateCommand</strong><br> Specifies a script to eval when you want to validate the input into the entry widget. Setting it to {} disables this feature (the default). This command must return a valid Tcl boolean value. If it returns 0 (or the valid Tcl boolean equivalent) then it means you reject the new edition and it will not occur and the invalidCommand will be evaluated if it is set. If it returns 1, then the new edition occurs. See Validation below for more information. </p> <p>Command-Line Name: <strong>-invalidcommand or -invcmd</strong><br> Database Name: <strong>invalidCommand</strong><br> Database Class: <strong>InvalidCommand</strong><br> Specifies a script to eval when validateCommand returns 0. Setting it to {} disables this feature (the default). The best use of this option is to set it to bell. See Validation below for more information. </p> </blockquote> <p>Have a look at <a href="http://stackoverflow.com/a/4140988/1020470">this SO answer</a>, the <a href="http://www.tcl.tk/man/tcl/" rel="nofollow">Tk commands</a> and <a href="http://epydoc.sourceforge.net/stdlib/Tkinter-module.html" rel="nofollow">epydoc-Tkinter</a> for more references.</p> <p>There are so many duplicates to this question. <a href="http://stackoverflow.com/a/4372831/1020470">Python tkInter Entry fun</a><br> <a href="http://stackoverflow.com/a/8960839/1020470">Restricting the value in Tkinter Entry widget</a></p>
2
2012-08-02T22:13:34Z
[ "python", "tkinter" ]
Difference between using __init__ and setting a class variable
1,018,977
<p>I'm trying to learn descriptors, and I'm confused by objects behaviour - in the two examples below, as I understood <code>__init__</code> they should work the same. Can someone unconfuse me, or point me to a resource that explains this?</p> <pre><code>import math class poweroftwo(object): """any time this is set with an int, turns it's value to a tuple of the int and the int^2""" def __init__(self, value=None, name="var"): self.val = (value, math.pow(value, 2)) self.name = name def __set__(self, obj, val): print "SET" self.val = (val, math.pow(val, 2)) def __get__(self, obj, objecttype): print "GET" return self.val class powoftwotest(object): def __init__(self, value): self.x = poweroftwo(value) class powoftwotest_two(object): x = poweroftwo(10) &gt;&gt;&gt; a = powoftwotest_two() &gt;&gt;&gt; b = powoftwotest(10) &gt;&gt;&gt; a.x == b.x &gt;&gt;&gt; GET &gt;&gt;&gt; False #Why not true? shouldn't both a.x and b.x be instances of poweroftwo with the same values? </code></pre>
3
2009-06-19T16:54:44Z
1,019,059
<p>First, please name all classes with LeadingUpperCaseNames.</p> <pre><code>&gt;&gt;&gt; a.x GET (10, 100.0) &gt;&gt;&gt; b.x &lt;__main__.poweroftwo object at 0x00C57D10&gt; &gt;&gt;&gt; type(a.x) GET &lt;type 'tuple'&gt; &gt;&gt;&gt; type(b.x) &lt;class '__main__.poweroftwo'&gt; </code></pre> <p><code>a.x</code> is instance-level access, which supports descriptors. This is what is meant in section 3.4.2.2 by "(a so-called descriptor class) appears in the class dictionary of another new-style class". The class dictionary must be accessed by an instance to use the <code>__get__</code> and <code>__set__</code> methods.</p> <p><code>b.x</code> is class-level access, which does not support descriptors.</p>
3
2009-06-19T17:15:01Z
[ "python", "descriptor" ]
How to replace a column using Python's built-in .csv writer module?
1,019,200
<p>I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python.</p> <p>I'm having trouble with the "replace" part of the solution. I've read the <a href="http://docs.python.org/library/csv.html" rel="nofollow">official csv module documentation</a> about how to use the writer, but there isn't really a clear enough example for me (yes, I'm slow). So, now for the question: how does one iterate through the rows of a csv file with a writer object?</p> <p>p.s. apologies in advance for the clumsy code, I'm still learning :)</p> <pre><code>import csv csvfile = open("PALTemplateData.csv") csvout = open("PALTemplateDataOUT.csv") dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) writer = csv.writer(csvout, dialect) total=0; needchange=0; changed = 0; temp = '' changeList = [] for row in reader: total=total+1 temp = row[len(row)-1] if '/?' in temp: needchange=needchange+1; changeList.append(row.index) for row in writer: #this doesn't compile, hence the question if row.index in changeList: changed=changed+1 temp = row[len(row)-1] temp.replace('/?', '?') row[len(row)-1] = temp writer.writerow(row) print('Total URLs:', total) print('Total URLs to change:', needchange) print('Total URLs changed:', changed) </code></pre>
1
2009-06-19T17:47:56Z
1,019,265
<p>The reason you're getting an error is that the writer doesn't have data to iterate over. You're supposed to give it the data - presumably, you'd have some sort of list or generator that produces the rows to write out.</p> <p>I'd suggest just combining the two loops, like so:</p> <pre><code>for row in reader: row[-1] = row[-1].replace('/?', '?') writer.writerow(row) </code></pre> <p>And with that, you don't even need <code>total</code>, <code>needchange</code>, and <code>changeList</code>. (There are a bunch of optimizations in there that I unfortunately don't have time to explain, but I'll see if I can edit that info in later)</p>
6
2009-06-19T18:01:33Z
[ "python", "file-io", "csv" ]
How to replace a column using Python's built-in .csv writer module?
1,019,200
<p>I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python.</p> <p>I'm having trouble with the "replace" part of the solution. I've read the <a href="http://docs.python.org/library/csv.html" rel="nofollow">official csv module documentation</a> about how to use the writer, but there isn't really a clear enough example for me (yes, I'm slow). So, now for the question: how does one iterate through the rows of a csv file with a writer object?</p> <p>p.s. apologies in advance for the clumsy code, I'm still learning :)</p> <pre><code>import csv csvfile = open("PALTemplateData.csv") csvout = open("PALTemplateDataOUT.csv") dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) writer = csv.writer(csvout, dialect) total=0; needchange=0; changed = 0; temp = '' changeList = [] for row in reader: total=total+1 temp = row[len(row)-1] if '/?' in temp: needchange=needchange+1; changeList.append(row.index) for row in writer: #this doesn't compile, hence the question if row.index in changeList: changed=changed+1 temp = row[len(row)-1] temp.replace('/?', '?') row[len(row)-1] = temp writer.writerow(row) print('Total URLs:', total) print('Total URLs to change:', needchange) print('Total URLs changed:', changed) </code></pre>
1
2009-06-19T17:47:56Z
1,019,269
<p>You should only have one loop and read and write at the same time - if your replacements only affect one line at a time, you don't need to loop over the data twice.</p> <pre><code>for row in reader: total=total+1 temp = row[len(row)-1] if '/?' in temp: temp = row[len(row)-1] temp.replace('/?', '?') row[len(row)-1] = temp writer.writerow(row) </code></pre> <p>This is just to illustrate the loop, not sure if the replacement code will work like this.</p>
1
2009-06-19T18:02:16Z
[ "python", "file-io", "csv" ]
How to replace a column using Python's built-in .csv writer module?
1,019,200
<p>I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python.</p> <p>I'm having trouble with the "replace" part of the solution. I've read the <a href="http://docs.python.org/library/csv.html" rel="nofollow">official csv module documentation</a> about how to use the writer, but there isn't really a clear enough example for me (yes, I'm slow). So, now for the question: how does one iterate through the rows of a csv file with a writer object?</p> <p>p.s. apologies in advance for the clumsy code, I'm still learning :)</p> <pre><code>import csv csvfile = open("PALTemplateData.csv") csvout = open("PALTemplateDataOUT.csv") dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) writer = csv.writer(csvout, dialect) total=0; needchange=0; changed = 0; temp = '' changeList = [] for row in reader: total=total+1 temp = row[len(row)-1] if '/?' in temp: needchange=needchange+1; changeList.append(row.index) for row in writer: #this doesn't compile, hence the question if row.index in changeList: changed=changed+1 temp = row[len(row)-1] temp.replace('/?', '?') row[len(row)-1] = temp writer.writerow(row) print('Total URLs:', total) print('Total URLs to change:', needchange) print('Total URLs changed:', changed) </code></pre>
1
2009-06-19T17:47:56Z
1,159,816
<p>Once you have your csv in a big list, one easy way to replace a column in a list would be to transpose your matrix, replace the row, and then transpose it back:</p> <pre><code>mydata = [[1, 'a', 10], [2, 'b', 20], [3, 'c', 30]] def transpose(matrix): return [[matrix[x][y] for x in range(len(matrix))] for y in range(len(matrix[0]))] transposedData = transpose(mydata) print transposedData &gt;&gt;&gt; [[1, 2, 3], ['a', 'b', 'c'], [10, 20, 30]] editedData = transposedData[:2] + [50,70,90] print editedData &gt;&gt;&gt; [[1, 2, 3], ['a', 'b', 'c'], [50, 70, 90]] mydata = transpose(editedData) print mydata &gt;&gt;&gt; [[1, 'a', 50], [2, 'b', 70], [3, 'c', 90]] </code></pre>
0
2009-07-21T15:10:01Z
[ "python", "file-io", "csv" ]
Algorithm for updating a list from a list
1,019,302
<p>I've got a data source that provides a list of objects and their properties (a CSV file, but that doesn't matter). Each time my program runs, it needs to pull a new copy of the list of objects, compare it to the list of objects (and their properties) stored in the database, and update the database as needed.</p> <p>Dealing with new objects is easy - the data source gives each object a sequential ID number, check the top ID number in the new information against the database, and you're done. I'm looking for suggestions for the other cases - when some of an object's properties have changed, or when an object has been deleted.</p> <p>A naive solution would be to pull all the objects from the database and get the complement of the intersection of the two sets (old and new) and then examine those results, but that seems like it wouldn't be very efficient if the sets get large. Any ideas?</p>
0
2009-06-19T18:09:22Z
1,019,395
<p>Is there no way to maintain a "last time modified" field? That's what it sounds like you're really looking for: an incremental backup, based on last time backup was run, compared to last time an object was changed/deleted(/added).</p>
1
2009-06-19T18:25:21Z
[ "python", "google-app-engine", "set" ]
Algorithm for updating a list from a list
1,019,302
<p>I've got a data source that provides a list of objects and their properties (a CSV file, but that doesn't matter). Each time my program runs, it needs to pull a new copy of the list of objects, compare it to the list of objects (and their properties) stored in the database, and update the database as needed.</p> <p>Dealing with new objects is easy - the data source gives each object a sequential ID number, check the top ID number in the new information against the database, and you're done. I'm looking for suggestions for the other cases - when some of an object's properties have changed, or when an object has been deleted.</p> <p>A naive solution would be to pull all the objects from the database and get the complement of the intersection of the two sets (old and new) and then examine those results, but that seems like it wouldn't be very efficient if the sets get large. Any ideas?</p>
0
2009-06-19T18:09:22Z
1,019,401
<p>When you pull the list into your program, iterate over the list doing a query based on a column property in the database table that maps to the same property of the object from list like ObjectName. Or you could load the whole table into a list and compare the list that way. I assuming that you have something unique about the object that exists besides the ID the database assigns.</p> <p>If that object is not found in the table via the query, create a new entry. If it is found like FogleBird mentioned, have a computed hash or CRC stored for that object in the table that you can compare with the object in the list(run computation on the object). If the hashes don't match, update that object with the one on the list.</p>
0
2009-06-19T18:26:18Z
[ "python", "google-app-engine", "set" ]
Algorithm for updating a list from a list
1,019,302
<p>I've got a data source that provides a list of objects and their properties (a CSV file, but that doesn't matter). Each time my program runs, it needs to pull a new copy of the list of objects, compare it to the list of objects (and their properties) stored in the database, and update the database as needed.</p> <p>Dealing with new objects is easy - the data source gives each object a sequential ID number, check the top ID number in the new information against the database, and you're done. I'm looking for suggestions for the other cases - when some of an object's properties have changed, or when an object has been deleted.</p> <p>A naive solution would be to pull all the objects from the database and get the complement of the intersection of the two sets (old and new) and then examine those results, but that seems like it wouldn't be very efficient if the sets get large. Any ideas?</p>
0
2009-06-19T18:09:22Z
1,019,428
<p>You need to have timestamps in both your database and your CSV file. Timestamp should show the data when the record was updated and you should compare timestamps of the record with same IDs to decide if you need updating it or not</p> <p>As to your idea about intersection... It should be done vise versa! You have to import all data from CSV to the temporary table and do intersection between 2 SQL database tables. If you use Oracle or MS SQL 2008 (not sure for 2005) you will found a very usefull MERGE keyword, so you can write SQL with less efforts then you will spend for merging data in other programming language.</p>
1
2009-06-19T18:33:05Z
[ "python", "google-app-engine", "set" ]
Algorithm for updating a list from a list
1,019,302
<p>I've got a data source that provides a list of objects and their properties (a CSV file, but that doesn't matter). Each time my program runs, it needs to pull a new copy of the list of objects, compare it to the list of objects (and their properties) stored in the database, and update the database as needed.</p> <p>Dealing with new objects is easy - the data source gives each object a sequential ID number, check the top ID number in the new information against the database, and you're done. I'm looking for suggestions for the other cases - when some of an object's properties have changed, or when an object has been deleted.</p> <p>A naive solution would be to pull all the objects from the database and get the complement of the intersection of the two sets (old and new) and then examine those results, but that seems like it wouldn't be very efficient if the sets get large. Any ideas?</p>
0
2009-06-19T18:09:22Z
1,019,596
<p>The standard approach for huge piles of data amounts to this. </p> <p>We'll assume that list_1 is the "master" (without duplicates) and list_2 is the "updates" which may have duplicates.</p> <pre><code>iter_1 = iter( sorted(list_1) ) # Essentially SELECT...ORDER BY iter_2 = iter( sorted(list_2) ) eof_1 = False eof_2 = False try: item_1 = iter_1.next() except StopIteration: eof_1= True try: item_2 = iter_2.next() except StopIteration: eof_2= True while not eof_1 and not eof_2: if item_1 == item_2: # do your update to create the new master list. try: item_2 = iter_2.next() except StopIteration: eof_2= True elif item_1 &lt; item_2: try: item_1 = iter_1.next() except StopIteration: eof_1= True elif item_2 &lt; item_1: # Do your insert to create the new master list. try: item_2 = iter_2.next() except StopIteration: eof_2= True assert eof_1 or eof_2 if eof_1: # item_2 and the rest of list_2 are inserts. elif eof_2: pass else: raise Error("What!?!?") </code></pre> <p>Yes, it involves a potential sort. If list_1 is kept in sorted order when you write it back to the file system, that saves considerable time. If list_2 can be accumulated in a structure that keeps it sorted, then that saves considerable time.</p> <p>Sorry about the wordiness, but you need to know which iterator raised the <code>StopIteration</code>, so you can't (trivially) wrap the whole while loop in a big-old-try block.</p>
1
2009-06-19T19:11:13Z
[ "python", "google-app-engine", "set" ]
Is there an easy way to convert an std::list<double> to a Python list?
1,019,457
<p>I'm writing a little Python extension in C/C++, and I've got a function like this:</p> <pre><code>void set_parameters(int first_param, std::list&lt;double&gt; param_list) { //do stuff } </code></pre> <p>I'd like to be able to call it from Python like this:</p> <pre><code>set_parameters(f_param, [1.0, 0.5, 2.1]) </code></pre> <p>Is there a reasonably easy way to make that conversion? Ideally, I'd like a way that doesn't need a whole lot of extra dependencies, but some things just aren't possible without extra stuff, so that's not as big a deal.</p>
2
2009-06-19T18:39:23Z
1,019,574
<p>Take a look at <a href="http://www.boost.org/doc/libs/1%5F39%5F0/libs/python/doc/index.html" rel="nofollow">Boost.Python</a>. Question you've asked is covered in <a href="http://www.boost.org/doc/libs/1%5F39%5F0/libs/python/doc/tutorial/doc/html/python/iterators.html" rel="nofollow">Iterators</a> chapter of the tutorial</p> <p>The point is, Boost.Python provides stl_input_iterator template that converts Python's iterable to stl's input_iterator, which can be used to fill your std::list.</p>
0
2009-06-19T19:07:21Z
[ "python", "c", "stl" ]
Is there an easy way to convert an std::list<double> to a Python list?
1,019,457
<p>I'm writing a little Python extension in C/C++, and I've got a function like this:</p> <pre><code>void set_parameters(int first_param, std::list&lt;double&gt; param_list) { //do stuff } </code></pre> <p>I'd like to be able to call it from Python like this:</p> <pre><code>set_parameters(f_param, [1.0, 0.5, 2.1]) </code></pre> <p>Is there a reasonably easy way to make that conversion? Ideally, I'd like a way that doesn't need a whole lot of extra dependencies, but some things just aren't possible without extra stuff, so that's not as big a deal.</p>
2
2009-06-19T18:39:23Z
1,020,113
<p>It turned out to be less pain than I thought, once I found the docs that I probably should have read before I asked the question. I was able to get a PyList object in my wrapper function, then just iterate over it and push the values onto the vector I needed. The code looks like this:</p> <pre><code>static PyObject* py_set_perlin_parameters(PyObject* self, PyObject* args) { int octaves; double persistence; PyObject* zoom_list; int zoom_count = 0; std::vector&lt;double&gt; zoom_vector; if(!PyArg_ParseTuple(args, "idO!:set_perlin_parameters", &amp;octaves, &amp;persistence, &amp;PyList_Type, &amp;zoom_list)) { return NULL; } if(!PyList_Check(zoom_list)) { PyErr_SetString(PyExc_TypeError, "set_perlin_parameters: third parameter must be a list"); return NULL; } zoom_count = PyList_Size(zoom_list); for(int i = 0; i &lt; zoom_count; i++) { PyObject* list_val; double val; list_val = PyList_GetItem(zoom_list, i); if(list_val == NULL) { return NULL; } val = PyFloat_AsDouble(list_val); zoom_vector.push_back(val); } set_perlin_parameters(octaves, persistence, zoom_vector); return Py_None; } </code></pre>
0
2009-06-19T21:29:57Z
[ "python", "c", "stl" ]
What's a good data model for cross-tabulation?
1,019,643
<p>I'm implementing a cross-tabulation library in Python as a programming exercise for my new job, and I've got an implementation of the requirements that <em>works</em> but is inelegant and redundant. I'd like a better model for it, something that allows a nice, clean movement of data between the base model, stored as tabular data in flat files, and all of the statistical analysis results that might be asked of this.</p> <p>Right now, I have a progression from a set of tuples for each row in the table, to a histogram counting the frequencies of the appearances of the tuples of interest, to a serializer that -- somewhat clumsily -- compiles the output into a set of table cells for display. However, I end up having to go back up to the table or to the histogram more often than I want to because there's never enough information in place.</p> <p>So, any ideas?</p> <p>Edit: Here's an example of some data, and what I want to be able to build from it. Note that "." denotes a bit of 'missing' data, that is only conditionally counted.</p> <pre><code>1 . 1 1 0 3 1 0 3 1 2 3 2 . 1 2 0 . 2 2 2 2 2 4 2 2 . </code></pre> <p>If I were looking at the correlation between columns 0 and 2 above, this is the table I'd have:</p> <pre><code> . 1 2 3 4 1 0 1 0 3 0 2 2 1 1 0 1 </code></pre> <p>In addition, I'd want to be able to calculate ratio of frequency/total, frequency/subtotal, &amp;c.</p>
6
2009-06-19T19:22:33Z
1,019,679
<p>Why not store it using HTML Tables? It might not be the best, but you could then, very easily, view it in a browser.</p> <p>Edit:</p> <p>I just re-read the question and you're asking for data model, not a storage model. To answer that question...</p> <p>It all depends on how you're going to be reporting on the data. For example if you're going to be doing a lot of pivoting or aggregation it might make more sense to store it in column major order, this way you can just sum a column to get counts, for example.</p> <p>It'll help a lot if you explain what kind of information you're trying to extract.</p>
-1
2009-06-19T19:29:09Z
[ "python", "algorithm", "data-structures", "statistics", "crosstab" ]
What's a good data model for cross-tabulation?
1,019,643
<p>I'm implementing a cross-tabulation library in Python as a programming exercise for my new job, and I've got an implementation of the requirements that <em>works</em> but is inelegant and redundant. I'd like a better model for it, something that allows a nice, clean movement of data between the base model, stored as tabular data in flat files, and all of the statistical analysis results that might be asked of this.</p> <p>Right now, I have a progression from a set of tuples for each row in the table, to a histogram counting the frequencies of the appearances of the tuples of interest, to a serializer that -- somewhat clumsily -- compiles the output into a set of table cells for display. However, I end up having to go back up to the table or to the histogram more often than I want to because there's never enough information in place.</p> <p>So, any ideas?</p> <p>Edit: Here's an example of some data, and what I want to be able to build from it. Note that "." denotes a bit of 'missing' data, that is only conditionally counted.</p> <pre><code>1 . 1 1 0 3 1 0 3 1 2 3 2 . 1 2 0 . 2 2 2 2 2 4 2 2 . </code></pre> <p>If I were looking at the correlation between columns 0 and 2 above, this is the table I'd have:</p> <pre><code> . 1 2 3 4 1 0 1 0 3 0 2 2 1 1 0 1 </code></pre> <p>In addition, I'd want to be able to calculate ratio of frequency/total, frequency/subtotal, &amp;c.</p>
6
2009-06-19T19:22:33Z
1,019,777
<p>Since this is an early programming exercise for Python, they probably want you to see what Python built-in mechanisms would be appropriate for the initial version of the problem. The dictionary structure seems a good candidate. The first column value from your tab-sep file can be the key into a dictionary. The entry found by that key can itself be a dictionary, whose key is the second column value. The entries of the subdictionary would be a count, initialized to 1 when you add a new subdictionary when a pair is first encountered.</p>
0
2009-06-19T19:57:22Z
[ "python", "algorithm", "data-structures", "statistics", "crosstab" ]
What's a good data model for cross-tabulation?
1,019,643
<p>I'm implementing a cross-tabulation library in Python as a programming exercise for my new job, and I've got an implementation of the requirements that <em>works</em> but is inelegant and redundant. I'd like a better model for it, something that allows a nice, clean movement of data between the base model, stored as tabular data in flat files, and all of the statistical analysis results that might be asked of this.</p> <p>Right now, I have a progression from a set of tuples for each row in the table, to a histogram counting the frequencies of the appearances of the tuples of interest, to a serializer that -- somewhat clumsily -- compiles the output into a set of table cells for display. However, I end up having to go back up to the table or to the histogram more often than I want to because there's never enough information in place.</p> <p>So, any ideas?</p> <p>Edit: Here's an example of some data, and what I want to be able to build from it. Note that "." denotes a bit of 'missing' data, that is only conditionally counted.</p> <pre><code>1 . 1 1 0 3 1 0 3 1 2 3 2 . 1 2 0 . 2 2 2 2 2 4 2 2 . </code></pre> <p>If I were looking at the correlation between columns 0 and 2 above, this is the table I'd have:</p> <pre><code> . 1 2 3 4 1 0 1 0 3 0 2 2 1 1 0 1 </code></pre> <p>In addition, I'd want to be able to calculate ratio of frequency/total, frequency/subtotal, &amp;c.</p>
6
2009-06-19T19:22:33Z
1,022,761
<p>You could use an in-memory <code>sqlite</code> database as a data structure, and define the desired operations as SQL queries.</p> <pre><code>import sqlite3 c = sqlite3.Connection(':memory:') c.execute('CREATE TABLE data (a, b, c)') c.executemany('INSERT INTO data VALUES (?, ?, ?)', [ (1, None, 1), (1, 0, 3), (1, 0, 3), (1, 2, 3), (2, None, 1), (2, 0, None), (2, 2, 2), (2, 2, 4), (2, 2, None), ]) # queries # ... </code></pre>
1
2009-06-20T23:03:24Z
[ "python", "algorithm", "data-structures", "statistics", "crosstab" ]
What's a good data model for cross-tabulation?
1,019,643
<p>I'm implementing a cross-tabulation library in Python as a programming exercise for my new job, and I've got an implementation of the requirements that <em>works</em> but is inelegant and redundant. I'd like a better model for it, something that allows a nice, clean movement of data between the base model, stored as tabular data in flat files, and all of the statistical analysis results that might be asked of this.</p> <p>Right now, I have a progression from a set of tuples for each row in the table, to a histogram counting the frequencies of the appearances of the tuples of interest, to a serializer that -- somewhat clumsily -- compiles the output into a set of table cells for display. However, I end up having to go back up to the table or to the histogram more often than I want to because there's never enough information in place.</p> <p>So, any ideas?</p> <p>Edit: Here's an example of some data, and what I want to be able to build from it. Note that "." denotes a bit of 'missing' data, that is only conditionally counted.</p> <pre><code>1 . 1 1 0 3 1 0 3 1 2 3 2 . 1 2 0 . 2 2 2 2 2 4 2 2 . </code></pre> <p>If I were looking at the correlation between columns 0 and 2 above, this is the table I'd have:</p> <pre><code> . 1 2 3 4 1 0 1 0 3 0 2 2 1 1 0 1 </code></pre> <p>In addition, I'd want to be able to calculate ratio of frequency/total, frequency/subtotal, &amp;c.</p>
6
2009-06-19T19:22:33Z
6,702,011
<p>S W has posted <a href="http://code.activestate.com/recipes/334695-pivotcrosstabdenormalization-of-a-normalized-list/" rel="nofollow">a good basic recipe for this on activestate.com</a>.</p> <p>The essence seems to be...</p> <ol> <li>Define xsort=[] and ysort=[] as arrays of your axes. Populate them by iterating through your data, or some other way.</li> <li>Define rs={} as a dict of dicts of your tabulated data, by iterating through your data and incrementing rs[yvalue][xvalue]. Create missing keys if/when needed.</li> </ol> <p>Then for example the total for row y would be <code>sum([rs[y][x] for x in xsort])</code></p>
1
2011-07-15T02:11:19Z
[ "python", "algorithm", "data-structures", "statistics", "crosstab" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
1,019,720
<p>There's a tool called <a href="http://sourceforge.net/projects/strace/" rel="nofollow">strace</a> - it monitors system calls made by a given process. You just need to watch out for specific calls suggesting 'illegal' function access. AFAIK, it's the method used in programming competitions to sandbox contestants' programs.</p>
1
2009-06-19T19:39:42Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
1,019,727
<p>I'd say this is extremely dangerous on many levels. You're essentially opening yourself up to any exploit that can be found on your system (whereas you're normally limited to the ones people can exploit remotely). I'd say don't do it if you can avoid it.</p> <p>If you do want to do it, you might want to use some kind of virtual machine to run the user's code. Using something like <a href="http://www.linux-kvm.org" rel="nofollow">KVM</a> it's possible to set up a number of virtual machines using the same base image (you can even store a snapshot in an already-booted state, though I'm not sure how it will handle being cloned). You can then create the VMs on demand, run the user's code, return the results, and then kill off the VM. If you keep the VMs isolated from each other and the network, the users can wreak any havoc they want and it won't hurt your physical server. The only danger you're exposing yourself to under these conditions would be some kind of exploit that allows them to escape from the VM... those are extremely rare, and will be more rare as hardware virtualization improves.</p>
3
2009-06-19T19:40:48Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
1,019,986
<p>About the only chance you have is running a VirtualMachine and those can have vulnerabilities. If you want your machine hacked in the short term just use permissions and make a special user with access to maybe one directory. If you want to postpone the hacking to some point in the future then run a webserver inside a virtual machine and port forward to that. You'll want to keep a backup of that because you'll probably have that hacked in under an hour and want to restart a fresh copy every few hours. You'll also want to keep an image of the whole machine to just reimage the whole thing once a week or so in order to overcome the weekly hackings. Don't let that machine talk to any other machine on your network. Blacklist it everywhere. I'm talking about the virtual machine and the physical machine IP addresses. Do regular security audits on any other machines on your other machines on the network. Please rename the machines IHaveBeenHacked1 and IHaveBeenHacked2 and prevent access to those in your hosts lists and firewalls.</p> <p>This way you might stave off your level of hackage for a while.</p>
-2
2009-06-19T20:53:23Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
1,020,006
<p>Although it is still in development, and not yet considered secure, you might check out the technology behind <a href="http://code.google.com/p/nativeclient/" rel="nofollow">Google Native Client</a>. It is designed to allow untrusted native code to be run in a web browser, but could probably be adapted for use on a web server. You might use something like this on top of other techniques such as a virtual machine, for additional security.</p>
3
2009-06-19T21:00:31Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
1,020,010
<p>On <a href="http://fedoraproject.org/" rel="nofollow">Fedora 11</a>, there is the <a href="http://danwalsh.livejournal.com/28545.html" rel="nofollow">SELinux Sandbox</a> which seems to do exactly what you want (except perhaps limiting spawning new processes; the linked blog post does not mention that).</p> <p>Of course, there is always the risk of kernel bugs; even with SELinux, parts of the kernel are still exposed to all processes.</p>
2
2009-06-19T21:01:57Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
1,020,081
<p>The few details you provide imply that you have administrative control over the server itself, so my suggestion makes this assumption.</p> <p>I'd tackle this as a batch system. The web server accepts an upload of the source file, a process polls the submission directory, processes the file, and then submits the result to another directory which the web application polls until it finds the result and displays it.</p> <p>The fun part is how to safely handle the execution.</p> <p>My OS of choice is FreeBSD, so I'd set up a pre-configured jail (not to be confused with a vanilla chroot jail) that would compile, run, and save the output. Then, for each source file submission, launch a pristine copy of the jail for each execution, with a copy of the source file inside.</p> <p>Provided that the jail's /dev is pruned down to almost nothing, system resource limits are set safely, and that the traffic can't route out of the jail (bound to unroutable address or simply firewalled), I would personally be comfortable running this on a server under my care.</p> <p>Since you use Linux, I'd investigate User Mode Linux or Linux-VServer, which are very similar in concept to FreeBSD jails (I've never used them myself, but have read about them). There are several other such systems listed <a href="http://en.wikipedia.org/wiki/Operating_system-level_virtualization" rel="nofollow">here</a>.</p> <p>This method is much more secure than a vanilla chroot jail, and it is much more light-weight than using full virtualization such as qemu/kvm or VMware.</p> <p>I'm not a programmer, so I don't what kind of AJAX-y thing you could use to poll for the results, but I'm sure it could be done. As an admin, I would find this a fun project to partake in. Have fun. :)</p>
4
2009-06-19T21:24:28Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
1,020,272
<p>Along with the other sugestions you might find this useful.</p> <p><a href="http://www.eelis.net/geordi/" rel="nofollow">http://www.eelis.net/geordi/</a></p> <p>This is from <a href="http://codepad.org/about" rel="nofollow">http://codepad.org/about</a>, <a href="http://codepad.org" rel="nofollow">codepad.org</a>'s about page. </p>
4
2009-06-19T22:12:13Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
1,020,287
<p>See <a href="http://code.google.com/p/chromium/wiki/LinuxSandboxing" rel="nofollow">this page on Google Chrome's sandboxing methods for Linux</a>. As you can see, there are plenty of methods, but none of them are great for a distributable application like Chrome because some distros might not include them. This is not really a problem for a web application though, because you can control what is installed on your server.</p> <p>Personally, my favorite is <a href="http://en.wikipedia.org/wiki/Seccomp" rel="nofollow">Seccomp</a>, because it has a <em>very</em> low overhead compared to other tools like ptrace (switch address spaces on <em>every</em> syscall!) or KVM (big memory hungry virtual machine), and it is incredibly simple compared to tools like SELinux (and therefore more likely to be secure).</p>
1
2009-06-19T22:17:47Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
1,029,301
<p>I think your solutions must concentrate on analyzing the source code. I don't know any tools, and I think this would be pretty hard with <code>C</code>, but, for example, a <code>Pascal</code> program which doesn't include any modules would be pretty harmless in my opinion.</p>
0
2009-06-22T20:45:42Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
15,609,095
<p>Spawning a new VM under KVM or qemu to compile and run the code looks like the way to go. Running the code under jail/LXC can compromise the machine if it exploits the unsecured parts of the OS like networking code. Advantage of running under a VM are obvious. One can only hack the VM but not the machine itself. But the side effect is you need lots of resources (CPU and Memory) to spawn a VM for each request.</p>
0
2013-03-25T06:42:47Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
16,050,403
<p>ptrace-based confinement for untrusted programs can be used like the one described in <a href="http://www.cs.vu.nl/~rutger/publications/jailer.pdf" rel="nofollow">http://www.cs.vu.nl/~rutger/publications/jailer.pdf</a>, <a href="http://www.cs.vu.nl/~guido/mansion/publications/ps/secrypt07.pdf" rel="nofollow">http://www.cs.vu.nl/~guido/mansion/publications/ps/secrypt07.pdf</a>.</p> <p>They have a change-root-ing policy rule, CHRDIR, whose effect is similar to chroot. (Section "The jailing policy")</p> <p>However, they might have not published their source code (partially based on a modified strace <a href="http://www.liacs.nl/~wichert/strace/" rel="nofollow">http://www.liacs.nl/~wichert/strace/</a> -- Section "Implementation")...</p> <p>See also other available ptrace-based approaches to chroot-in-userpace: <a href="http://unix.stackexchange.com/a/72697/4319">http://unix.stackexchange.com/a/72697/4319</a></p>
0
2013-04-17T02:27:37Z
[ "python", "c", "linux", "security", "sandbox" ]
Sandboxing in Linux
1,019,707
<p>I want to create a Web app which would allow the user to upload some C code, and see the results of its execution (the code would be compiled on the server). The users are untrusted, which obviously has some huge security implications.</p> <p>So I need to create some kind of sandbox for the apps. At the most basic level, I'd like to restrict access to the file system to some specified directories. I cannot use chroot jails directly, since the web app is not running as a privileged user. I guess a suid executable which sets up the jail would be an option.</p> <p>The uploaded programs would be rather small, so they should execute quickly (a couple of seconds at most). Hence, I can kill the process after a preset timeout, but how do I ensure that it doesn't spawn new processes? Or if I can't, is killing the entire pgid a reliable method?</p> <p>What would be the best way to go about this - other than "don't do it at all"? :) What other glaring security problems have I missed?</p> <p>FWIW, the web app will be written in Python.</p>
15
2009-06-19T19:35:07Z
17,868,112
<p>I guess <a href="https://openjudge.net/~liuyu/Project/LibSandbox" rel="nofollow">libsandbox</a> serves your purpose. Its core library is written for C/C++, but it also has a wrapper for Python programs. It provides options to customize which system calls can be allowed, how much memory can be used, how long can the guest program be run, etc. It is already being used in a couple of online judges such as <a href="http://acm.hit.edu.cn/judge/" rel="nofollow">HOJ</a>. </p>
2
2013-07-25T20:26:19Z
[ "python", "c", "linux", "security", "sandbox" ]
Speed of calculating powers (in python)
1,019,740
<p>I'm curious as to why it's so much faster to multiply than to take powers in python (though from what I've read this may well be true in many other languages too). For example it's much faster to do</p> <pre><code>x*x </code></pre> <p>than</p> <pre><code>x**2 </code></pre> <p>I suppose the ** operator is more general and can also deal with fractional powers. But if that's why it's so much slower, why doesn't it perform a check for an int exponent and then just do the multiplication? <br/></p> <p><strong>Edit:</strong> Here's some example code I tried...</p> <pre><code>def pow1(r, n): for i in range(r): p = i**n def pow2(r, n): for i in range(r): p = 1 for j in range(n): p *= i </code></pre> <p>Now, pow2 is just a quick example and is clearly not optimised!<br/> But even so I find that using n = 2 and r = 1,000,000, then pow1 takes ~ 2500ms and pow2 takes ~ 1700ms.<br/> I admit that for large values of n, then pow1 does get much quicker than pow2. But that's not too surprising.<br/></p>
16
2009-06-19T19:46:44Z
1,019,808
<p>how about x*x*x*x*x? is it still faster than x**5?</p> <p>as int exponents gets larger, taking powers might be faster than multiplication. but the number where actual crossover occurs depends on various conditions, so in my opinion, that's why the optimization was not done(or couldn't be done) in language/library level. But users can still optimize for some special cases :)</p>
0
2009-06-19T20:06:00Z
[ "python", "algorithm", "performance" ]
Speed of calculating powers (in python)
1,019,740
<p>I'm curious as to why it's so much faster to multiply than to take powers in python (though from what I've read this may well be true in many other languages too). For example it's much faster to do</p> <pre><code>x*x </code></pre> <p>than</p> <pre><code>x**2 </code></pre> <p>I suppose the ** operator is more general and can also deal with fractional powers. But if that's why it's so much slower, why doesn't it perform a check for an int exponent and then just do the multiplication? <br/></p> <p><strong>Edit:</strong> Here's some example code I tried...</p> <pre><code>def pow1(r, n): for i in range(r): p = i**n def pow2(r, n): for i in range(r): p = 1 for j in range(n): p *= i </code></pre> <p>Now, pow2 is just a quick example and is clearly not optimised!<br/> But even so I find that using n = 2 and r = 1,000,000, then pow1 takes ~ 2500ms and pow2 takes ~ 1700ms.<br/> I admit that for large values of n, then pow1 does get much quicker than pow2. But that's not too surprising.<br/></p>
16
2009-06-19T19:46:44Z
1,019,815
<p>Adding a check is an expense, too. Do you always want that check there? A compiled language could make the check for a constant exponent to see if it's a relatively small integer because there's no run-time cost, just a compile-time cost. An interpreted language might not make that check.</p> <p>It's up to the particular implementation unless that kind of detail is specified by the language.</p> <p>Python doesn't know what distribution of exponents you're going to feed it. If it's going to be 99% non-integer values, do you want the code to check for an integer every time, making runtime even slower?</p>
6
2009-06-19T20:07:50Z
[ "python", "algorithm", "performance" ]
Speed of calculating powers (in python)
1,019,740
<p>I'm curious as to why it's so much faster to multiply than to take powers in python (though from what I've read this may well be true in many other languages too). For example it's much faster to do</p> <pre><code>x*x </code></pre> <p>than</p> <pre><code>x**2 </code></pre> <p>I suppose the ** operator is more general and can also deal with fractional powers. But if that's why it's so much slower, why doesn't it perform a check for an int exponent and then just do the multiplication? <br/></p> <p><strong>Edit:</strong> Here's some example code I tried...</p> <pre><code>def pow1(r, n): for i in range(r): p = i**n def pow2(r, n): for i in range(r): p = 1 for j in range(n): p *= i </code></pre> <p>Now, pow2 is just a quick example and is clearly not optimised!<br/> But even so I find that using n = 2 and r = 1,000,000, then pow1 takes ~ 2500ms and pow2 takes ~ 1700ms.<br/> I admit that for large values of n, then pow1 does get much quicker than pow2. But that's not too surprising.<br/></p>
16
2009-06-19T19:46:44Z
1,019,868
<p>I'd suspect that nobody was expecting this to be all that important. Typically, if you want to do serious calculations, you do them in Fortran or C or C++ or something like that (and perhaps call them from Python).</p> <p>Treating everything as exp(n * log(x)) works well in cases where n isn't integral or is pretty large, but is relatively inefficient for small integers. Checking to see if n is a small enough integer does take time, and adds complication.</p> <p>Whether the check is worth it depends on the expected exponents, how important it is to get best performance here, and the cost of the extra complexity. Apparently, Guido and the rest of the Python gang decided the check wasn't worth doing.</p> <p>If you like, you could write your own repeated-multiplication function.</p>
1
2009-06-19T20:20:10Z
[ "python", "algorithm", "performance" ]
Speed of calculating powers (in python)
1,019,740
<p>I'm curious as to why it's so much faster to multiply than to take powers in python (though from what I've read this may well be true in many other languages too). For example it's much faster to do</p> <pre><code>x*x </code></pre> <p>than</p> <pre><code>x**2 </code></pre> <p>I suppose the ** operator is more general and can also deal with fractional powers. But if that's why it's so much slower, why doesn't it perform a check for an int exponent and then just do the multiplication? <br/></p> <p><strong>Edit:</strong> Here's some example code I tried...</p> <pre><code>def pow1(r, n): for i in range(r): p = i**n def pow2(r, n): for i in range(r): p = 1 for j in range(n): p *= i </code></pre> <p>Now, pow2 is just a quick example and is clearly not optimised!<br/> But even so I find that using n = 2 and r = 1,000,000, then pow1 takes ~ 2500ms and pow2 takes ~ 1700ms.<br/> I admit that for large values of n, then pow1 does get much quicker than pow2. But that's not too surprising.<br/></p>
16
2009-06-19T19:46:44Z
1,019,932
<p>Basically naive multiplication is O(n) with a very low constant factor. Taking the power is O(log n) with a higher constant factor (There are special cases that need to be tested... fractional exponents, negative exponents, etc) . Edit: just to be clear, that's O(n) where n is the exponent.</p> <p>Of course the naive approach will be faster for small n, you're only really implementing a small subset of exponential math so your constant factor is negligible. </p>
17
2009-06-19T20:33:46Z
[ "python", "algorithm", "performance" ]
Speed of calculating powers (in python)
1,019,740
<p>I'm curious as to why it's so much faster to multiply than to take powers in python (though from what I've read this may well be true in many other languages too). For example it's much faster to do</p> <pre><code>x*x </code></pre> <p>than</p> <pre><code>x**2 </code></pre> <p>I suppose the ** operator is more general and can also deal with fractional powers. But if that's why it's so much slower, why doesn't it perform a check for an int exponent and then just do the multiplication? <br/></p> <p><strong>Edit:</strong> Here's some example code I tried...</p> <pre><code>def pow1(r, n): for i in range(r): p = i**n def pow2(r, n): for i in range(r): p = 1 for j in range(n): p *= i </code></pre> <p>Now, pow2 is just a quick example and is clearly not optimised!<br/> But even so I find that using n = 2 and r = 1,000,000, then pow1 takes ~ 2500ms and pow2 takes ~ 1700ms.<br/> I admit that for large values of n, then pow1 does get much quicker than pow2. But that's not too surprising.<br/></p>
16
2009-06-19T19:46:44Z
1,020,252
<p>Doing this in the exponent check will slow down the cases where it isn't a simple power of two very slightly, so isn't necessarily a win. However, in cases where the exponent is known in advance( eg. literal 2 is used), the bytecode generated could be optimised with a simple peephole optimisation. Presumably this simply hasn't been considered worth doing (it's a fairly specific case). </p> <p>Here's a quick proof of concept that does such an optimisation (usable as a decorator). Note: you'll need the <a href="http://code.google.com/p/byteplay/" rel="nofollow">byteplay</a> module to run it.</p> <pre><code>import byteplay, timeit def optimise(func): c = byteplay.Code.from_code(func.func_code) prev=None for i, (op, arg) in enumerate(c.code): if op == byteplay.BINARY_POWER: if c.code[i-1] == (byteplay.LOAD_CONST, 2): c.code[i-1] = (byteplay.DUP_TOP, None) c.code[i] = (byteplay.BINARY_MULTIPLY, None) func.func_code = c.to_code() return func def square(x): return x**2 print "Unoptimised :", timeit.Timer('square(10)','from __main__ import square').timeit(10000000) square = optimise(square) print "Optimised :", timeit.Timer('square(10)','from __main__ import square').timeit(10000000) </code></pre> <p>Which gives the timings:</p> <pre><code>Unoptimised : 6.42024898529 Optimised : 4.52667593956 </code></pre> <p><strong>[Edit]</strong> Actually, thinking about it a bit more, there's a very good reason why this optimisaton isn't done. There's no guarantee that someone won't create a user defined class that overrides the <code>__mul__</code> and <code>__pow__</code> methods and do something different for each. The only way to do it safely is if you can guarantee that the object on the top of the stack is one that has the same result "x<code>**2</code>" and "<code>x*x</code>", but working that out is much harder. Eg. in my example it's impossible, as any object could be passed to the square function.</p>
3
2009-06-19T22:05:31Z
[ "python", "algorithm", "performance" ]
Speed of calculating powers (in python)
1,019,740
<p>I'm curious as to why it's so much faster to multiply than to take powers in python (though from what I've read this may well be true in many other languages too). For example it's much faster to do</p> <pre><code>x*x </code></pre> <p>than</p> <pre><code>x**2 </code></pre> <p>I suppose the ** operator is more general and can also deal with fractional powers. But if that's why it's so much slower, why doesn't it perform a check for an int exponent and then just do the multiplication? <br/></p> <p><strong>Edit:</strong> Here's some example code I tried...</p> <pre><code>def pow1(r, n): for i in range(r): p = i**n def pow2(r, n): for i in range(r): p = 1 for j in range(n): p *= i </code></pre> <p>Now, pow2 is just a quick example and is clearly not optimised!<br/> But even so I find that using n = 2 and r = 1,000,000, then pow1 takes ~ 2500ms and pow2 takes ~ 1700ms.<br/> I admit that for large values of n, then pow1 does get much quicker than pow2. But that's not too surprising.<br/></p>
16
2009-06-19T19:46:44Z
24,951,249
<p>An implementation of b^p with binary exponentiation</p> <pre><code>def power(b, p): """ Calculates b^p Complexity O(log p) b -&gt; double p -&gt; integer res -&gt; double """ res = 1 while p: if p &amp; 0x1: res *= b b *= b p &gt;&gt;= 1 return res </code></pre>
1
2014-07-25T08:25:08Z
[ "python", "algorithm", "performance" ]
split a string by a delimiter in a context sensitive way
1,019,756
<p>For example, I want to split</p> <pre><code>str = '"a,b,c",d,e,f' </code></pre> <p>into </p> <pre><code>["a,b,c",'d','e','f'] </code></pre> <p>(i.e. don't split the quoted part) In this case, this can be done with </p> <pre><code>re.findall('".*?"|[^,]+',str) </code></pre> <p>However, if</p> <pre><code>str = '"a,,b,c",d,,f' </code></pre> <p>I want </p> <pre><code>["a,,b,c",'d','','f'] </code></pre> <p>i.e. I want a behavior that is like python's split function. Is there any way I can do this in one (small) line, possibly using Python's re library? </p> <p>Actually, I just realized (on this site) that the csv module is perfect for what I want to do, but I am curious whether there is a regular expression that re can use to do it as well.</p>
2
2009-06-19T19:51:33Z
1,019,826
<p>Use the csv module as it is a real parser. Regular expressions are nonoptimal (or completely unsuited) for most things involving matching delimiters in which the rules change (I'm unsure as to whether this particular grammar is regular or not). You might be able to create a regex that would work in this case, but it would be rather complex (especially dealing with cases like "He said, \"How are you\"").</p>
2
2009-06-19T20:09:50Z
[ "python", "regex", "split" ]
split a string by a delimiter in a context sensitive way
1,019,756
<p>For example, I want to split</p> <pre><code>str = '"a,b,c",d,e,f' </code></pre> <p>into </p> <pre><code>["a,b,c",'d','e','f'] </code></pre> <p>(i.e. don't split the quoted part) In this case, this can be done with </p> <pre><code>re.findall('".*?"|[^,]+',str) </code></pre> <p>However, if</p> <pre><code>str = '"a,,b,c",d,,f' </code></pre> <p>I want </p> <pre><code>["a,,b,c",'d','','f'] </code></pre> <p>i.e. I want a behavior that is like python's split function. Is there any way I can do this in one (small) line, possibly using Python's re library? </p> <p>Actually, I just realized (on this site) that the csv module is perfect for what I want to do, but I am curious whether there is a regular expression that re can use to do it as well.</p>
2
2009-06-19T19:51:33Z
1,019,902
<p>Writing a state machine for this would, on the other hand, seem to be quite straightforward. DFAs and regexes have the same power, but usually one of them is better suited to the problem at hand, and is usually very dependent on the additional logic you might need to implement.</p>
1
2009-06-19T20:26:55Z
[ "python", "regex", "split" ]
split a string by a delimiter in a context sensitive way
1,019,756
<p>For example, I want to split</p> <pre><code>str = '"a,b,c",d,e,f' </code></pre> <p>into </p> <pre><code>["a,b,c",'d','e','f'] </code></pre> <p>(i.e. don't split the quoted part) In this case, this can be done with </p> <pre><code>re.findall('".*?"|[^,]+',str) </code></pre> <p>However, if</p> <pre><code>str = '"a,,b,c",d,,f' </code></pre> <p>I want </p> <pre><code>["a,,b,c",'d','','f'] </code></pre> <p>i.e. I want a behavior that is like python's split function. Is there any way I can do this in one (small) line, possibly using Python's re library? </p> <p>Actually, I just realized (on this site) that the csv module is perfect for what I want to do, but I am curious whether there is a regular expression that re can use to do it as well.</p>
2
2009-06-19T19:51:33Z
1,020,007
<p>You can get close using non-greedy specifiers. The closest I've got is:</p> <pre><code>&gt;&gt;&gt; re.findall('(".*?"|.*?)(?:,|$)', '"a,b,c",d,e,f') ['"a,,b,c"', 'd', '', 'f', ''] </code></pre> <p>But as you see, you end up with a redundant empty string at the end, which is indistinguishable from the result you get when the string ends with a comma:</p> <pre><code>&gt;&gt;&gt; re.findall('(".*?"|.*?)(?:,|$)', '"a,b,c",d,e,f,') ['"a,,b,c"', 'd', '', 'f', ''] </code></pre> <p>so you'd need to do some manual tweaking at the end - something like:</p> <pre><code>matches = regex,findall(s) if not s.endswith(","): matches.pop() </code></pre> <p>or</p> <pre><code>matches = regex.findall(s+",")[:-1] </code></pre> <p>There's probably a better way.</p>
0
2009-06-19T21:00:49Z
[ "python", "regex", "split" ]
split a string by a delimiter in a context sensitive way
1,019,756
<p>For example, I want to split</p> <pre><code>str = '"a,b,c",d,e,f' </code></pre> <p>into </p> <pre><code>["a,b,c",'d','e','f'] </code></pre> <p>(i.e. don't split the quoted part) In this case, this can be done with </p> <pre><code>re.findall('".*?"|[^,]+',str) </code></pre> <p>However, if</p> <pre><code>str = '"a,,b,c",d,,f' </code></pre> <p>I want </p> <pre><code>["a,,b,c",'d','','f'] </code></pre> <p>i.e. I want a behavior that is like python's split function. Is there any way I can do this in one (small) line, possibly using Python's re library? </p> <p>Actually, I just realized (on this site) that the csv module is perfect for what I want to do, but I am curious whether there is a regular expression that re can use to do it as well.</p>
2
2009-06-19T19:51:33Z
1,020,098
<p><strong>Here's a function that'll accomplish the task:</strong></p> <pre><code>def smart_split(data, delimiter=","): """ Performs splitting with string preservation. This reads both single and double quoted strings. """ result = [] quote_type = None buffer = "" position = 0 while position &lt; len(data): if data[position] in ["\"", "'"]: quote_type = data[position] while quote_type is not None: position += 1 if data[position] == quote_type: quote_type = None position += 1 else: buffer += data[position] if data[position] == delimiter: result.append(buffer) buffer = "" else: buffer += data[position] position += 1 result.append(buffer) return result </code></pre> <p><strong>Example of use:</strong></p> <pre><code>str = '"a,b,c",d,e,f' print smart_split(str) # Prints: ['a,b,c', 'd', 'e', 'f'] </code></pre>
0
2009-06-19T21:26:25Z
[ "python", "regex", "split" ]
split a string by a delimiter in a context sensitive way
1,019,756
<p>For example, I want to split</p> <pre><code>str = '"a,b,c",d,e,f' </code></pre> <p>into </p> <pre><code>["a,b,c",'d','e','f'] </code></pre> <p>(i.e. don't split the quoted part) In this case, this can be done with </p> <pre><code>re.findall('".*?"|[^,]+',str) </code></pre> <p>However, if</p> <pre><code>str = '"a,,b,c",d,,f' </code></pre> <p>I want </p> <pre><code>["a,,b,c",'d','','f'] </code></pre> <p>i.e. I want a behavior that is like python's split function. Is there any way I can do this in one (small) line, possibly using Python's re library? </p> <p>Actually, I just realized (on this site) that the csv module is perfect for what I want to do, but I am curious whether there is a regular expression that re can use to do it as well.</p>
2
2009-06-19T19:51:33Z
1,021,506
<pre><code>re.split(',(?=(?:[^"]*"[^"]*")*[^"]*$)', str) </code></pre> <p>After matching a comma, if there's an odd number of quotation marks up ahead ahead, the comma must be inside a pair of quotation marks, so it doesn't count as a delimiter. Obviously this doesn't take the possibility of escaped quotation marks into account, but that can handled if need be--it just makes the regex about twice as ugly as it already is. :D</p>
2
2009-06-20T12:14:01Z
[ "python", "regex", "split" ]
split a string by a delimiter in a context sensitive way
1,019,756
<p>For example, I want to split</p> <pre><code>str = '"a,b,c",d,e,f' </code></pre> <p>into </p> <pre><code>["a,b,c",'d','e','f'] </code></pre> <p>(i.e. don't split the quoted part) In this case, this can be done with </p> <pre><code>re.findall('".*?"|[^,]+',str) </code></pre> <p>However, if</p> <pre><code>str = '"a,,b,c",d,,f' </code></pre> <p>I want </p> <pre><code>["a,,b,c",'d','','f'] </code></pre> <p>i.e. I want a behavior that is like python's split function. Is there any way I can do this in one (small) line, possibly using Python's re library? </p> <p>Actually, I just realized (on this site) that the csv module is perfect for what I want to do, but I am curious whether there is a regular expression that re can use to do it as well.</p>
2
2009-06-19T19:51:33Z
1,021,866
<p>Here's a really short function that will do the same thing:</p> <pre><code>def split (aString): splitByQuotes = (",%s,"%aString).split('"') splitByQuotes[0::2] = [x.split(",")[1:-1] for x in splitByQuotes[0::2]] return [a.strip() \ for b in splitByQuotes \ for a in (b if type(b)==list else [b])] </code></pre> <p>It splits the string where the quotes are, creating a list where every even element is the stuff outside the quotes and every odd element is the stuff that was encapsulated within quotes. The stuff in quotes it leaves alone, the stuff outside it splits where the commas are. Now we have a list of alternating lists and strings, which we then unwrap with the last line. The reason for wrapping the string in commas at the beginning and removing commas in the middle is to prevent spare empty elements in the list. It should be able to handle whitespace - I added a strip() function at the end to make it produce clean output, but that's not necessary.</p> <p>usage:</p> <pre><code>&gt;&gt;&gt; print split('c, , "a,,b,c",d,"moo","f"') ['c', '', 'a,,b,c', 'd', 'moo', 'f'] </code></pre>
0
2009-06-20T15:38:27Z
[ "python", "regex", "split" ]
split a string by a delimiter in a context sensitive way
1,019,756
<p>For example, I want to split</p> <pre><code>str = '"a,b,c",d,e,f' </code></pre> <p>into </p> <pre><code>["a,b,c",'d','e','f'] </code></pre> <p>(i.e. don't split the quoted part) In this case, this can be done with </p> <pre><code>re.findall('".*?"|[^,]+',str) </code></pre> <p>However, if</p> <pre><code>str = '"a,,b,c",d,,f' </code></pre> <p>I want </p> <pre><code>["a,,b,c",'d','','f'] </code></pre> <p>i.e. I want a behavior that is like python's split function. Is there any way I can do this in one (small) line, possibly using Python's re library? </p> <p>Actually, I just realized (on this site) that the csv module is perfect for what I want to do, but I am curious whether there is a regular expression that re can use to do it as well.</p>
2
2009-06-19T19:51:33Z
1,021,945
<p><a href="http://books.google.com/books?id=GX3w%5F18-JegC&amp;lpg=PA401&amp;ots=PHojQnfpRY&amp;dq=comma-separated%20%22mastering%20regular%20expressions%22&amp;pg=PA271" rel="nofollow">Page 271</a> of Friedl's <em>Mastering Regular Expressions</em> has a regular expression for extracting possibly quoted CSV fields, but it requires a bit of postprocessing:</p> <pre><code>&gt;&gt;&gt; re.findall('(?:^|,)(?:"((?:[^"]|"")*)"|([^",]*))',str) [('a,b,c', ''), ('', 'd'), ('', 'e'), ('', 'f')] &gt;&gt;&gt; re.findall('(?:^|,)(?:"((?:[^"]|"")*)"|([^",]*))','"a,b,c",d,,f') [('a,b,c', ''), ('', 'd'), ('', ''), ('', 'f')] </code></pre> <p>Same pattern with the verbose flag:</p> <pre><code>csv = re.compile(r""" (?:^|,) (?: # now match either a double-quoted field # (inside, paired double quotes are allowed)... " # (double-quoted field's opening quote) ( (?: [^"] | "" )* ) " # (double-quoted field's closing quote) | # ...or some non-quote/non-comma text... ( [^",]* ) )""", re.X) </code></pre>
1
2009-06-20T16:21:35Z
[ "python", "regex", "split" ]
Python tkInter Entry fun
1,019,782
<p>Playing around with Python - tkInter - Entry widget - when I use validatecommand (below), the check happens the first time the string > Max, but when I continue to enter text the check steps - there's no delete or insert after the first time? Any advice? (outside of not building a desktop app via python)</p> <p><hr /></p> <pre><code>#!/usr/bin/env python from Tkinter import * class MyEntry(Entry): def __init__(self, master, maxchars): Entry.__init__(self, master, validate = "key", validatecommand=self.validatecommand) self.MAX = maxchars def validatecommand(self, *args): if len(self.get()) &gt;= self.MAX: self.delete(0,3) self.insert(0, "no") return True if __name__ == '__main__': tkmain = Tk() e = MyEntry(tkmain, 5) e.grid() tkmain.mainloop() </code></pre>
1
2009-06-19T19:58:15Z
1,020,087
<p>I'm sure exactly what the reason is, but I have a hunch. The validation check is done every time the entry is edited. I did some testing and found that it does indeed execute, and can do all sorts of things during the validation every time. What causes it to stop working correctly is when you edit it from within the validatecommand function. This causes it to stop calling the validate function any further. I guess it no longer recognizes further edits to the entry value or something.</p> <p>lgal Serban seems to have the behind the scenes info on why this occurs.</p>
1
2009-06-19T21:25:00Z
[ "python", "tkinter" ]
Python tkInter Entry fun
1,019,782
<p>Playing around with Python - tkInter - Entry widget - when I use validatecommand (below), the check happens the first time the string > Max, but when I continue to enter text the check steps - there's no delete or insert after the first time? Any advice? (outside of not building a desktop app via python)</p> <p><hr /></p> <pre><code>#!/usr/bin/env python from Tkinter import * class MyEntry(Entry): def __init__(self, master, maxchars): Entry.__init__(self, master, validate = "key", validatecommand=self.validatecommand) self.MAX = maxchars def validatecommand(self, *args): if len(self.get()) &gt;= self.MAX: self.delete(0,3) self.insert(0, "no") return True if __name__ == '__main__': tkmain = Tk() e = MyEntry(tkmain, 5) e.grid() tkmain.mainloop() </code></pre>
1
2009-06-19T19:58:15Z
1,020,123
<p><a href="http://www.tcl.tk/man/tcl8.4/TkCmd/entry.htm#M30" rel="nofollow">From the Tk man</a>:</p> <blockquote> <p>The validate option will also set itself to none when you edit the entry widget from within either the validateCommand or the invalidCommand. Such editions will override the one that was being validated. If you wish to edit the entry widget (for example set it to {}) during validation and still have the validate option set, you should include the command</p> <p>after idle {%W config -validate %v}</p> </blockquote> <p>don't know how to translate that to python.</p>
3
2009-06-19T21:32:54Z
[ "python", "tkinter" ]
Python tkInter Entry fun
1,019,782
<p>Playing around with Python - tkInter - Entry widget - when I use validatecommand (below), the check happens the first time the string > Max, but when I continue to enter text the check steps - there's no delete or insert after the first time? Any advice? (outside of not building a desktop app via python)</p> <p><hr /></p> <pre><code>#!/usr/bin/env python from Tkinter import * class MyEntry(Entry): def __init__(self, master, maxchars): Entry.__init__(self, master, validate = "key", validatecommand=self.validatecommand) self.MAX = maxchars def validatecommand(self, *args): if len(self.get()) &gt;= self.MAX: self.delete(0,3) self.insert(0, "no") return True if __name__ == '__main__': tkmain = Tk() e = MyEntry(tkmain, 5) e.grid() tkmain.mainloop() </code></pre>
1
2009-06-19T19:58:15Z
4,372,831
<p>Here is a code sample that will limit the input to 5 characters:</p> <pre><code>import Tkinter as tk master = tk.Tk() def callback(): print e.get() def val(i): print "validating" print i if int(i) &gt; 4: print "False" return False return True vcmd = (master.register(val), '%i') e = tk.Entry(master, validate="key", validatecommand=vcmd) e.pack() b = tk.Button(master, text="OK", command=lambda: callback()) b.pack() tk.mainloop() </code></pre> <p>I threw in a bunch of print statements so you can sort of see what it's doing in the console.</p> <p>Here are the other substitutions you can pass:</p> <pre><code> %d Type of action: 1 for insert, 0 for delete, or -1 for focus, forced or textvariable validation. %i Index of char string to be inserted/deleted, if any, otherwise -1. %P The value of the entry if the edit is allowed. If you are config- uring the entry widget to have a new textvariable, this will be the value of that textvariable. %s The current value of entry prior to editing. %S The text string being inserted/deleted, if any, {} otherwise. %v The type of validation currently set. %V The type of validation that triggered the callback (key, focusin, focusout, forced). %W The name of the entry widget. </code></pre>
2
2010-12-07T02:21:21Z
[ "python", "tkinter" ]
Subclassing in Python
1,019,834
<p>Is it possible to subclass dynamically? I know there's <strong>_<em>bases</em>_</strong> but I don't want to effect all instances of the class. I want the object cf to polymorph into a mixin of the DrvCrystalfontz class. Further into the hierarchy is a subclass of gobject that needs to be available at this level for connecting signals, and the solution below isn't sufficient.</p> <pre><code>class DrvCrystalfontz: def __init__(self, model, visitor, obj=None, config=None): if model not in Models.keys(): error("Unknown Crystalfontz model %s" % model) return self.model = Models[model] if self.model.protocol == 1: cf = Protocol1(self, visitor, obj, config) elif self.model.protocol == 2: cf = Protocol2(self, visitor, obj, config) elif self.model.protocol == 3: cf = Protocol3(self, visitor, obj, config) for key in cf.__dict__.keys(): self.__dict__[key] = cf.__dict__[key] </code></pre>
-3
2009-06-19T20:11:03Z
1,019,915
<p>I'm not sure I'm clear on your desired use here, but it is possible to subclass dynamically. You can use the <code>type</code> object to dynamically construct a class given a name, tuple of base classes and dict of methods / class attributes, eg:</p> <pre><code>&gt;&gt;&gt; MySub = type("MySub", (DrvCrystalfontz, some_other_class), {'some_extra method' : lamba self: do_something() }) </code></pre> <p>MySub is now a subclass of <code>DrvCrystalfontz</code> and<code> some_other_class</code>, inherits their methods, and adds a new one ("<code>some_extra_method</code>").</p>
2
2009-06-19T20:29:59Z
[ "python", "subclassing" ]
Python - configuration options, how to input/handle?
1,019,850
<p>When your application takes a few (~ 5) configuration parameters, and the application is going to be used by non-technology users (i.e. <a href="http://en.wiktionary.org/wiki/KISS" rel="nofollow">KISS</a>), how do you usually handle reading configuration options, and then passing around the parameters between objects/functions (multiple modules)?</p> <p>Options examples: input and output directories/file names, verbosity level.</p> <p>I generally use <code>optparse</code> (Python) and pass around the options/parameters as arguments; but I'm wondering if it's more common to use a configuration text file that is read directly by all modules' objects (but then, isn't this like having 'global' variables?, and without anyone 'owning' the state?).</p> <p>Another typical issue is unit testing; if I want to unit test each single module independently, a particular module may only require 1 out of the 5 configuration options; how do you usually decouple individual modules/objects from the rest of the application, and yet still allow it to accept 1 or 2 required parameters (does the unit test framework somehow invoke or take over the configuration functionality)?</p> <p>My guess is that there is not a unique correct way to do this, but it'd be interesting to read about various approaches, or well-known patterns.</p>
3
2009-06-19T20:16:15Z
1,019,852
<pre><code>"Counts answer" Please update these counts and feel free to add/modify. Do you usually read config options via: - command-line/gui options : 1 - a config text file : 0 How do multiple modules/objects have access to these options? - they receive them from the caller as an argument: 1 - read them directly from the config text file: 0 When doing unit-testing of a single module (NOT the "main" module) and the module uses one option, e.g. input filename: - unit-test framework provides own "simplified" config functionality: 0 - unit-test framework invokes main app's config functionality: 1 Do you use: - optparse: 1 - getopt: 0 - others? Please list any config management "design pattern" (usable in Python) and add a count if you use it - thanks. - - </code></pre>
0
2009-06-19T20:17:00Z
[ "python", "options", "optional-parameters" ]
Python - configuration options, how to input/handle?
1,019,850
<p>When your application takes a few (~ 5) configuration parameters, and the application is going to be used by non-technology users (i.e. <a href="http://en.wiktionary.org/wiki/KISS" rel="nofollow">KISS</a>), how do you usually handle reading configuration options, and then passing around the parameters between objects/functions (multiple modules)?</p> <p>Options examples: input and output directories/file names, verbosity level.</p> <p>I generally use <code>optparse</code> (Python) and pass around the options/parameters as arguments; but I'm wondering if it's more common to use a configuration text file that is read directly by all modules' objects (but then, isn't this like having 'global' variables?, and without anyone 'owning' the state?).</p> <p>Another typical issue is unit testing; if I want to unit test each single module independently, a particular module may only require 1 out of the 5 configuration options; how do you usually decouple individual modules/objects from the rest of the application, and yet still allow it to accept 1 or 2 required parameters (does the unit test framework somehow invoke or take over the configuration functionality)?</p> <p>My guess is that there is not a unique correct way to do this, but it'd be interesting to read about various approaches, or well-known patterns.</p>
3
2009-06-19T20:16:15Z
1,019,883
<p>Do you usually read config options via: - command-line/gui options - a config text file </p> <p>Both. We use Django's settings.py and logging.ini. We also use command-line options and arguments for the options that change most frequently.</p> <p>How do multiple modules/objects have access to these options?</p> <ul> <li>settings.py; logging.ini -- can't say.</li> <li>Our options are private to the main program, and used to build<br /> arguments to functions or object initializers. </li> </ul> <p>[Sharing the optparse options is a big pain in the neck and needless binds a lot of things into an untestable mess.]</p> <p>When doing unit-testing of a single module (NOT the "main" module): (e.g. read option specifying input filename)</p> <p>[I can't parse the question. I assume this is "how do you test when there are options?"]</p> <p>The answer is -- we don't. Since only the main method parses command-line options, no other module, function or class has any idea of command-line options. There's no this module "require 1 out of the 5 config options" The module's classes (or functions) have ordinary arguments and that's that.</p> <p>We only use <code>optparse</code>.</p>
2
2009-06-19T20:23:47Z
[ "python", "options", "optional-parameters" ]
How to walk up a linked-list using a list comprehension?
1,020,037
<p>I've been trying to think of a way to traverse a hierarchical structure, like a linked list, using a list expression, but haven't come up with anything that seems to work.</p> <p>Basically, I want to convert this code:</p> <pre><code>p = self.parent names = [] while p: names.append(p.name) p = p.parent print ".".join(names) </code></pre> <p>into a one-liner like:</p> <pre><code>print ".".join( [o.name for o in &lt;???&gt;] ) </code></pre> <p>I'm not sure how to do the traversal in the <code>???</code> part, though, <em>in a generic way</em> (if its even possible). I have several structures with similar <code>.parent</code> type attributes, and don't want to have write a yielding function for each.</p> <p>Edit:</p> <p>I can't use the <code>__iter__</code> methods of the object itself because its already used for iterating over the values contained within the object itself. Most other answers, except for liori's, hardcode the attribute name, which is what I want to avoid.</p> <p>Here's my adaptation based upon liori's answer:</p> <pre><code>import operator def walk(attr, start): if callable(attr): getter = attr else: getter = operator.attrgetter(attr) o = getter(start) while o: yield o o = getter(o) </code></pre>
1
2009-06-19T21:12:29Z
1,020,055
<p>List comprehension works with objects that are iterators (have the next() method). You need to define an iterator for your structure in order to be able to iterate it this way.</p>
1
2009-06-19T21:17:15Z
[ "python", "list-comprehension" ]