title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
BytesIO with python v2.5 | 1,279,244 | <p><strong>Question:</strong></p>
<p>How do I get a byte stream that works like StringIO for Python 2.5?</p>
<p><strong>Application:</strong></p>
<p>I'm converting a PDF to text, but don't want to save a file to the hard disk.</p>
<p><strong>Other Thoughts:</strong></p>
<p>I figured I could use StringIO, but there's no mode parameter (I guess "String" implies text mode). </p>
<p>Apparently the io.BytesIO class is new in v2.6, so that doesn't work for me either.</p>
<p>I've got a solution with the tempfile module, but I'd like to avoid any reads/writes to/from the hard disk.</p>
| 1 | 2009-08-14T17:54:01Z | 1,279,265 | <p>If you're working with PDF, then <code>StringIO</code> should be fine as long as you pay heed to the docs:</p>
<blockquote>
<p>The StringIO object can accept either Unicode or 8-bit strings, but mixing the two may take some care. If both are used, 8-bit strings that cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause a UnicodeError to be raised when getvalue() is called.</p>
</blockquote>
<p>Note this is <strong>not</strong> true for <code>cStringIO</code>:</p>
<blockquote>
<p>Unlike the memory files implemented by the StringIO module, those provided by this module are not able to accept Unicode strings that cannot be encoded as plain ASCII strings.</p>
</blockquote>
<p>See the full documentation at:</p>
<ul>
<li><a href="http://docs.python.org/library/stringio.html" rel="nofollow">http://docs.python.org/library/stringio.html</a></li>
</ul>
| 2 | 2009-08-14T17:58:23Z | [
"python",
"stringio",
"bytesio"
] |
How do I use extended characters in Python's curses library? | 1,279,341 | <p>I've been reading tutorials about Curses programming in Python, and many refer to an ability to use extended characters, such as line-drawing symbols. They're characters > 255, and the curses library knows how to display them in the current terminal font.</p>
<p>Some of the tutorials say you use it like this:</p>
<pre><code>c = ACS_ULCORNER
</code></pre>
<p>...and some say you use it like this:</p>
<pre><code>c = curses.ACS_ULCORNER
</code></pre>
<p>(That's supposed to be the upper-left corner of a box, like an L flipped vertically)</p>
<p>Anyway, regardless of which method I use, the name is not defined and the program thus fails. I tried "import curses" and "from curses import *", and neither works.</p>
<p>Curses' window() function makes use of these characters, so I even tried poking around on my box for the source to see how <em>it</em> does it, but I can't find it anywhere.</p>
| 4 | 2009-08-14T18:15:17Z | 1,279,422 | <p>From <code>curses/__init__.py</code>:</p>
<blockquote>
<p>Some constants, most notably the <code>ACS_*</code>
ones, are only added to the C
<code>_curses</code> module's dictionary after <code>initscr()</code> is called. (Some versions
of SGI's curses don't define values
for those constants until <code>initscr()</code>
has been called.) This wrapper
function calls the underlying C
<code>initscr()</code>, and then copies the
constants from the
<code>_curses</code> module to the curses package's dictionary. Don't do '<code>from curses
import *</code>' if you'll be needing the
<code>ACS_*</code> constants.</p>
</blockquote>
<p>In other words:</p>
<pre><code>>>> import curses
>>> curses.ACS_ULCORNER
exception
>>> curses.initscr()
>>> curses.ACS_ULCORNER
>>> 4194412
</code></pre>
| 2 | 2009-08-14T18:30:59Z | [
"python",
"curses"
] |
How do I use extended characters in Python's curses library? | 1,279,341 | <p>I've been reading tutorials about Curses programming in Python, and many refer to an ability to use extended characters, such as line-drawing symbols. They're characters > 255, and the curses library knows how to display them in the current terminal font.</p>
<p>Some of the tutorials say you use it like this:</p>
<pre><code>c = ACS_ULCORNER
</code></pre>
<p>...and some say you use it like this:</p>
<pre><code>c = curses.ACS_ULCORNER
</code></pre>
<p>(That's supposed to be the upper-left corner of a box, like an L flipped vertically)</p>
<p>Anyway, regardless of which method I use, the name is not defined and the program thus fails. I tried "import curses" and "from curses import *", and neither works.</p>
<p>Curses' window() function makes use of these characters, so I even tried poking around on my box for the source to see how <em>it</em> does it, but I can't find it anywhere.</p>
| 4 | 2009-08-14T18:15:17Z | 16,564,494 | <p>I believe the below is appropriately related, to be posted under this question. Here I'll be using <a href="http://sdaaubckp.svn.sourceforge.net/viewvc/sdaaubckp/single-scripts/utfinfo.pl" rel="nofollow">utfinfo.pl</a> (see also on <a href="http://superuser.com/questions/581523/program-to-check-look-up-utf-8-unicode-characters-in-string-on-command-line/581529#581529">Super User</a>). </p>
<p>First of all, for standard ASCII character set, the Unicode code point and the byte encoding is the same:</p>
<pre><code>$ echo 'a' | perl utfinfo.pl
Char: 'a' u: 97 [0x0061] b: 97 [0x61] n: LATIN SMALL LETTER A [Basic Latin]
</code></pre>
<p>So we can do in Python's <code>curses</code>:</p>
<pre><code>window.addch('a')
window.border('a')
</code></pre>
<p>... and it works as intended </p>
<p>However, if a character is above basic ASCII, then there are differences, which <a href="http://docs.python.org/2/library/curses.html#curses.window.addch" rel="nofollow"><code>addch</code> docs</a> don't necessarily make explicit. First, I can do:</p>
<pre><code>window.addch(curses.ACS_PI)
window.border(curses.ACS_PI)
</code></pre>
<p>... in which case, in my <code>gnome-terminal</code>, the Unicode character 'Ï' is rendered. However, if you inspect <code>ACS_PI</code>, you'll see it's an integer number, with a value of 4194427 (0x40007b); so the following will also render the same character (or rater, glyph?) 'Ï':</p>
<pre><code>window.addch(0x40007b)
window.border(0x40007b)
</code></pre>
<p>To see what's going on, I grepped through the <code>ncurses</code> source, and found the following:</p>
<pre><code>#define ACS_PI NCURSES_ACS('{') /* Pi */
#define NCURSES_ACS(c) (acs_map[NCURSES_CAST(unsigned char,c)])
#define NCURSES_CAST(type,value) static_cast<type>(value)
#lib_acs.c: NCURSES_EXPORT_VAR(chtype *) _nc_acs_map(void): MyBuffer = typeCalloc(chtype, ACS_LEN);
#define typeCalloc(type,elts) (type *)calloc((elts),sizeof(type))
#./widechar/lib_wacs.c: { '{', { '*', 0x03c0 }}, /* greek pi */
</code></pre>
<p>Note here:</p>
<pre><code>$ echo '{Ï' | perl utfinfo.pl
Got 2 uchars
Char: '{' u: 123 [0x007B] b: 123 [0x7B] n: LEFT CURLY BRACKET [Basic Latin]
Char: 'Ï' u: 960 [0x03C0] b: 207,128 [0xCF,0x80] n: GREEK SMALL LETTER PI [Greek and Coptic]
</code></pre>
<p>... neither of which relates to the value of 4194427 (0x40007b) for <code>ACS_PI</code>. </p>
<p>Thus, when <code>addch</code> and/or <code>border</code> see a character above ASCII (basically an <code>unsigned int</code>, as opposed to <code>unsigned char</code>), they (at least in this instance) use that number <strong>not</strong> as Unicode code point, or as UTF-8 encoded bytes representation - but instead, they use it as a look-up index for <code>acs_map</code>-ping function (which ultimately, however, <em>would</em> return the Unicode code point, even if it emulates VT-100). That is why the following specification:</p>
<pre><code>window.addch('Ï')
window.border('Ï')
</code></pre>
<p>will fail in Python 2.7 with <code>argument 1 or 3 must be a ch or an int</code>; and in Python 3.2 would render simply a space instead of a character. When we specify <code>'Ï'</code>. we've actually specified the UTF-8 encoding [0xCF,0x80] - but even if we specify the Unicode code point:</p>
<pre><code>window.addch(0x03C0)
window.border0x03C0)
</code></pre>
<p>... it simply renders nothing (space) in both Python 2.7 and 3.2. </p>
<p>That being said - the function <code>addstr</code> <em>does</em> accept UTF-8 encoded strings, and works fine:</p>
<pre><code>window.addstr('Ï')
</code></pre>
<p>... but for borders - since <code>border()</code> apparently handles characters in the same way <code>addch()</code> does - we're apparently out of luck, for anything not explicitly specified as an <code>ACS</code> constant (and there's not that many of them, either). </p>
<p>Hope this helps someone,<br>
Cheers!</p>
| 3 | 2013-05-15T12:02:49Z | [
"python",
"curses"
] |
How do I use extended characters in Python's curses library? | 1,279,341 | <p>I've been reading tutorials about Curses programming in Python, and many refer to an ability to use extended characters, such as line-drawing symbols. They're characters > 255, and the curses library knows how to display them in the current terminal font.</p>
<p>Some of the tutorials say you use it like this:</p>
<pre><code>c = ACS_ULCORNER
</code></pre>
<p>...and some say you use it like this:</p>
<pre><code>c = curses.ACS_ULCORNER
</code></pre>
<p>(That's supposed to be the upper-left corner of a box, like an L flipped vertically)</p>
<p>Anyway, regardless of which method I use, the name is not defined and the program thus fails. I tried "import curses" and "from curses import *", and neither works.</p>
<p>Curses' window() function makes use of these characters, so I even tried poking around on my box for the source to see how <em>it</em> does it, but I can't find it anywhere.</p>
| 4 | 2009-08-14T18:15:17Z | 28,426,471 | <p>you have to set your local to all, then encode your output as utf-8 as follows:</p>
<pre><code>import curses
import locale
locale.setlocale(locale.LC_ALL, '') # set your locale
scr = curses.initscr()
scr.clear()
scr.addstr(0, 0, u'\u3042'.encode('utf-8'))
scr.refresh()
# here implement simple code to wait for user input to quit
scr.endwin()
</code></pre>
<p>output:
ã</p>
| 2 | 2015-02-10T07:43:07Z | [
"python",
"curses"
] |
sqlalchemy - grouping items and iterating over the sub-lists | 1,279,356 | <p>Consider a table like this:</p>
<pre><code>| Name | Version | Other |
| ---------------------|-------|
| Foo | 1 | 'a' |
| Foo | 2 | 'b' |
| Bar | 5 | 'c' |
| Baz | 3 | 'd' |
| Baz | 4 | 'e' |
| Baz | 5 | 'f' |
--------------------------------
</code></pre>
<p>I would like to write a sqlalchemy query statement to list all items (as mapper objects, not just the Name column) with max version: <code>Foo-2-b, Bar-5-c, Baz-5-f</code>. I understand that I would have to use the <code>group_by</code> method, but beyond that I am puzzled as to how to retrieve the sub-lists (and then find the max element). SQLAlchemy documentation is apparently not very clear on this.</p>
<p>In the real scenario, there are many other columns (like 'Other') - which is why I need the actual row object (mapper class) to be returned rather than just the 'Name' value.</p>
| 2 | 2009-08-14T18:18:30Z | 1,279,433 | <p>Here's the SQL you can call with the <code>engine.execute</code> command:</p>
<pre><code>select
t1.*
from
table t1
inner join
(select
Name,
max(version) as Version
from
table
group by
name) s on
s.name = t1.name
and s.version = t1.version
</code></pre>
| -1 | 2009-08-14T18:32:49Z | [
"python",
"sql",
"sqlalchemy"
] |
sqlalchemy - grouping items and iterating over the sub-lists | 1,279,356 | <p>Consider a table like this:</p>
<pre><code>| Name | Version | Other |
| ---------------------|-------|
| Foo | 1 | 'a' |
| Foo | 2 | 'b' |
| Bar | 5 | 'c' |
| Baz | 3 | 'd' |
| Baz | 4 | 'e' |
| Baz | 5 | 'f' |
--------------------------------
</code></pre>
<p>I would like to write a sqlalchemy query statement to list all items (as mapper objects, not just the Name column) with max version: <code>Foo-2-b, Bar-5-c, Baz-5-f</code>. I understand that I would have to use the <code>group_by</code> method, but beyond that I am puzzled as to how to retrieve the sub-lists (and then find the max element). SQLAlchemy documentation is apparently not very clear on this.</p>
<p>In the real scenario, there are many other columns (like 'Other') - which is why I need the actual row object (mapper class) to be returned rather than just the 'Name' value.</p>
| 2 | 2009-08-14T18:18:30Z | 1,279,554 | <p>If you need full objects you'll need to select maximum versions by name in a subquery and join to that:</p>
<pre><code>max_versions = session.query(Cls.name, func.max(Cls.version).label('max_version'))\
.group_by(Cls.name).subquery()
objs = session.query(Cls).join((max_versions,
and_(Cls.name == max_versions.c.name,
Cls.version == max_versions.c.max_version)
)).all()
</code></pre>
<p>This will result in something like this:</p>
<pre><code>SELECT tbl.id AS tbl_id, tbl.name AS tbl_name, tbl.version AS tbl_version
FROM tbl JOIN (SELECT tbl.name AS name, max(tbl.version) AS max_version
FROM tbl GROUP BY tbl.name) AS anon_1 ON tbl.name = anon_1.name AND tbl.version = anon_1.max_version
</code></pre>
<p>Be aware that you'll get multiple rows with the same name if there are multiple rows with the max version.</p>
| 4 | 2009-08-14T18:53:40Z | [
"python",
"sql",
"sqlalchemy"
] |
Default route doesn't work | 1,279,403 | <p>I'm using the standard routing module with pylons to try and setup a default route for the home page of my website. </p>
<p>I've followed the instructions in the docs and here <a href="http://routes.groovie.org/recipes.html" rel="nofollow">http://routes.groovie.org/recipes.html</a> but when I try <code>http://127.0.0.1:5000/</code> I just get the 'Welcome to Pylons' default page. </p>
<p>My config/routing.py file looks like this</p>
<p>from pylons import config
from routes import Mapper</p>
<pre><code>def make_map():
"""Create, configure and return the routes Mapper"""
map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
map.minimization = False
map.connect('/error/{action}', controller='error')
map.connect('/error/{action}/{id}', controller='error')
# CUSTOM ROUTES HERE
map.connect( '', controller='main', action='index' )
map.connect('/{controller}/{action}')
map.connect('/{controller}/{action}/{id}')
return map
</code></pre>
<p>I've also tried
map.connect( '/', controller='main', action='index' )</p>
<p>and (using <code>http://127.0.0.1:5000/homepage/</code>)</p>
<pre><code>map.connect( 'homepage', controller='main', action='index' )
</code></pre>
<p>But nothing works at all. I know its reloading my config file as I used
paster serve --reload development.ini
to start the server</p>
<p>system info </p>
<pre><code>$ paster --version
PasteScript 1.7.3 from /Library/Python/2.5/site-packages/PasteScript-1.7.3-py2.5.egg (python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12))
</code></pre>
| 4 | 2009-08-14T18:27:52Z | 1,280,099 | <p>You have to delete the static page (myapp/public/index.html). Static
files take priority due to the Cascade configuration at the end of
middleware.py. </p>
| 9 | 2009-08-14T20:40:39Z | [
"python",
"routes",
"pylons"
] |
Django - SQL Query - Timestamp | 1,279,490 | <p>Can anyone turn me to a tutorial, code or some kind of resource that will help me out with the following problem.</p>
<p>I have a table in a mySQL database. It contains an ID, Timestamp, another ID and a value. I'm passing it the 'main' ID which can uniquely identify a piece of data. However, I want to do a time search on this piece of data(therefore using the timestamp field). Therefore what would be ideal is to say: between the hours of 12 and 1, show me all the values logged for ID = 1987. </p>
<p>How would I go about querying this in Django? I know in mySQL it'd be something like less than/greater than etc... but how would I go about doing this in Django? i've been using Object.Filter for most of database handling so far. Finally, I'd like to stress that I'm new to Django and I'm genuinely stumped!</p>
| 0 | 2009-08-14T18:41:26Z | 1,279,577 | <p>If the table in question maps to a Django model <code>MyModel</code>, e.g.</p>
<pre><code>class MyModel(models.Model):
...
primaryid = ...
timestamp = ...
secondaryid = ...
valuefield = ...
</code></pre>
<p>then you can use</p>
<pre><code>MyModel.objects.filter(
primaryid=1987
).exclude(
timestamp__lt=<min_timestamp>
).exclude(
timestamp__gt=<max_timestamp>
).values_list('valuefield', flat=True)
</code></pre>
<p>This selects entries with the primaryid 1987, with timestamp values between <code><min_timestamp></code> and <code><max_timestamp></code>, and returns the corresponding values in a list.</p>
<p><strong>Update:</strong> Corrected bug in query (<code>filter</code> -> <code>exclude</code>).</p>
| 3 | 2009-08-14T18:58:46Z | [
"python",
"mysql",
"django"
] |
Django - SQL Query - Timestamp | 1,279,490 | <p>Can anyone turn me to a tutorial, code or some kind of resource that will help me out with the following problem.</p>
<p>I have a table in a mySQL database. It contains an ID, Timestamp, another ID and a value. I'm passing it the 'main' ID which can uniquely identify a piece of data. However, I want to do a time search on this piece of data(therefore using the timestamp field). Therefore what would be ideal is to say: between the hours of 12 and 1, show me all the values logged for ID = 1987. </p>
<p>How would I go about querying this in Django? I know in mySQL it'd be something like less than/greater than etc... but how would I go about doing this in Django? i've been using Object.Filter for most of database handling so far. Finally, I'd like to stress that I'm new to Django and I'm genuinely stumped!</p>
| 0 | 2009-08-14T18:41:26Z | 1,284,454 | <p>I don't think Vinay Sajip's answer is correct. The closest correct variant based on his code is:</p>
<pre><code>MyModel.objects.filter(
primaryid=1987
).exclude(
timestamp__lt=min_timestamp
).exclude(
timestamp__gt=max_timestamp
).values_list('valuefield', flat=True)
</code></pre>
<p>That's "exclude the ones less than the minimum timestamp and exclude the ones greater than the maximum timestamp." Alternatively, you can do this:</p>
<pre><code>MyModel.objects.filter(
primaryid=1987
).filter(
timestamp__gte=min_timestamp
).exclude(
timestamp__gte=max_timestamp
).values_list('valuefield', flat=True)
</code></pre>
<p>exclude() and filter() are opposites: exclude() omits the identified rows and filter() includes them. You can use a combination of them to include/exclude whichever you prefer. In your case, you want to exclude() those below your minimum time stamp and to exclude() those above your maximum time stamp.</p>
<p>Here is the documentation on <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#chaining-filters" rel="nofollow">chaining QuerySet filters</a>.</p>
| 2 | 2009-08-16T14:44:12Z | [
"python",
"mysql",
"django"
] |
SQLAlchemy - Trying Eager loading.. Attribute Error | 1,279,583 | <p>I access a a postgres table using SQLAlchemy. I want a query to have eagerloading.</p>
<pre><code>from sqlalchemy.orm import sessionmaker, scoped_session, eagerload
from settings import DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, Boolean, MetaData, ForeignKey
from sqlalchemy.orm import mapper
from sqlalchemy.ext.declarative import declarative_base
def create_session():
engine = create_engine('postgres://%s:%s@%s:%s/%s' % (DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME), echo=True)
Session = scoped_session(sessionmaker(bind=engine))
return Session()
Base = declarative_base()
class Zipcode(Base):
__tablename__ = 'zipcode'
zipcode = Column(String(6), primary_key = True, nullable=False)
city = Column(String(30), nullable=False)
state = Column(String(30), nullable=False)
session = create_session()
query = session.query(Zipcode).options(eagerload('zipcode')).filter(Zipcode.state.in_(['NH', 'ME']))
#query = session.query(Zipcode.zipcode).filter(Zipcode.state.in_(['NH', 'ME']))
print query.count()
</code></pre>
<p>This fails with
AttributeError: 'ColumnProperty' object has no attribute 'mapper'</p>
<p>One without eagerloading returns the records correctly.</p>
<p>I am new to SQLAlchemy. I am not sure what the problem is. Any pointers?</p>
| 1 | 2009-08-14T18:59:49Z | 1,279,980 | <p>You can only eager load on a relation property. Not on the table itself. Eager loading is meant for loading objects from other tables at the same time as getting a particular object. The way you load all the objects for a query will be simply adding all().</p>
<pre><code>query = session.query(Zipcode).options(eagerload('zipcode')).filter(Zipcode.state.in_(['NH', 'ME'])).all()
</code></pre>
<p>The query will now be a list of all objects (rows) in the table and len(query) will give you the count.</p>
| 2 | 2009-08-14T20:19:18Z | [
"python",
"postgresql",
"sqlalchemy"
] |
What is an ORM and where can I learn more about it? | 1,279,613 | <p>Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?</p>
| 64 | 2009-08-14T19:03:59Z | 1,279,636 | <p>This is a huge topic. Pick up a good hibernate book and it should explain ORM in detail before getting to the nitty gritty hibernate material.</p>
<p><a href="https://www.hibernate.org/" rel="nofollow">https://www.hibernate.org/</a></p>
| 0 | 2009-08-14T19:08:17Z | [
"python",
"orm"
] |
What is an ORM and where can I learn more about it? | 1,279,613 | <p>Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?</p>
| 64 | 2009-08-14T19:03:59Z | 1,279,638 | <p>An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database.</p>
<p>Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders.</p>
<p>Here's a brief clip from Martin Fowler (Data Mapper):</p>
<p><a href="http://martinfowler.com/eaaCatalog/dataMapper.html">Patterns of Enterprise Application Architecture Data Mappers</a></p>
| 8 | 2009-08-14T19:08:40Z | [
"python",
"orm"
] |
What is an ORM and where can I learn more about it? | 1,279,613 | <p>Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?</p>
| 64 | 2009-08-14T19:03:59Z | 1,279,641 | <p>Like all acronyms it's ambiguous, but I assume they mean <a href="http://en.wikipedia.org/wiki/Object-relational%5Fmapping" rel="nofollow">object-relational mapper</a> -- a way to cover your eyes and make believe there's no SQL underneath, but rather it's all objects;-). Not really true, of course, and not without problems -- the always colorful Jeff Atwood has described ORM as <a href="http://www.codinghorror.com/blog/archives/000621.html" rel="nofollow">the Vietnam of CS</a>;-). But, if you know little or no SQL, and have a pretty simple / small-scale problem, they can save you time!-)</p>
| 1 | 2009-08-14T19:09:41Z | [
"python",
"orm"
] |
What is an ORM and where can I learn more about it? | 1,279,613 | <p>Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?</p>
| 64 | 2009-08-14T19:03:59Z | 1,279,678 | <h2>Introduction</h2>
<p><a href="http://en.wikipedia.org/wiki/Object-relational_mapping">Object-Relational Mapping</a> (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a <em>library</em> that implements the Object-Relational Mapping technique, hence the phrase "an ORM".</p>
<p>An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same language you're using.</p>
<p>For example, here is a completely imaginary case with a pseudo language:</p>
<p>You have a book class, you want to retrieve all the books of which the author is "Linus". Manually, you would do something like that:</p>
<pre><code>book_list = new List();
sql = "SELECT book FROM library WHERE author = 'Linus'";
data = query(sql); // I over simplify ...
while (row = data.next())
{
book = new Book();
book.setAuthor(row.get('author');
book_list.add(book);
}
</code></pre>
<p>With an ORM library, it would look like this:</p>
<pre><code>book_list = BookTable.query(author="Linus");
</code></pre>
<p>The mechanical part is taken care of automatically via the ORM library.</p>
<h2>Pros and Cons</h2>
<p><strong>Using ORM saves a lot of time because:</strong></p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>: You write your data model in only one place, and it's easier to update, maintain, and reuse the code.</li>
<li>A lot of stuff is done automatically, from database handling to I18N.</li>
<li>It forces you to write <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> code, which, in the end, makes your code a little cleaner.</li>
<li>You don't have to write poorly-formed SQL (most Web programmers really suck at it, because SQL is treated like a "sub" language, when in reality it's a very powerful and complex one).</li>
<li>Sanitizing; using prepared statements or transactions are as easy as calling a method.</li>
</ul>
<p><strong>Using an ORM library is more flexible because:</strong></p>
<ul>
<li>It fits in your natural way of coding (it's your language!).</li>
<li>It abstracts the DB system, so you can change it whenever you want.</li>
<li>The model is weakly bound to the rest of the application, so you can change it or use it anywhere else.</li>
<li>It lets you use OOP goodness like data inheritance without a headache.</li>
</ul>
<p><strong>But ORM can be a pain:</strong></p>
<ul>
<li>You have to learn it, and ORM libraries are not lightweight tools;</li>
<li>You have to set it up. Same problem.</li>
<li>Performance is OK for usual queries, but a SQL master will always do better with his own SQL for big projects.</li>
<li>It abstracts the DB. While it's OK if you know what's happening behind the scene, it's a trap for new programmers that can write very greedy statements, like a heavy hit in a <code>for</code> loop.</li>
</ul>
<h2>How to learn about ORM?</h2>
<p>Well, use one. Whichever ORM library you choose, they all use the same principles. There are a lot of ORM libraries around here:</p>
<ul>
<li>Java: <a href="http://en.wikipedia.org/wiki/Hibernate_(Java)">Hibernate</a>.</li>
<li>PHP: <a href="http://en.wikipedia.org/wiki/Propel_(PHP)">Propel</a> or <a href="http://en.wikipedia.org/wiki/Doctrine_(PHP)">Doctrine</a> (I prefer the last one).</li>
<li>Python: the Django ORM or <a href="http://en.wikipedia.org/wiki/SQLAlchemy">SQLAlchemy</a> (My favorite ORM library ever).</li>
</ul>
<p>If you want to try an ORM library in Web programming, you'd be better off using an entire framework stack like:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Symfony">Symfony</a> (PHP, using Propel or Doctrine).</li>
<li><a href="http://en.wikipedia.org/wiki/Django_(web_framework)">Django</a> (Python, using a internal ORM).</li>
</ul>
<p>Do not try to write your own ORM, unless you are trying to learn something. This is a gigantic piece of work, and the old ones took a lot of time and work before they became reliable.</p>
| 166 | 2009-08-14T19:17:15Z | [
"python",
"orm"
] |
What is an ORM and where can I learn more about it? | 1,279,613 | <p>Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?</p>
| 64 | 2009-08-14T19:03:59Z | 1,279,769 | <p>The first chapter of the Hibernate book <a href="http://rads.stackoverflow.com/amzn/click/1932394885" rel="nofollow">Java Persistence with Hibernate (3rd ed.)</a> has an excellent overview of general ORM concepts and discusses motivation and design of ORMs. Highly recommended, even if you don't work with Java.</p>
| 3 | 2009-08-14T19:35:48Z | [
"python",
"orm"
] |
What is an ORM and where can I learn more about it? | 1,279,613 | <p>Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?</p>
| 64 | 2009-08-14T19:03:59Z | 1,280,345 | <blockquote>
<p><em>Can anyone give me a brief explanation...</em></p>
</blockquote>
<p>Sure.</p>
<p>ORM stands for "Object to Relational Mapping" where </p>
<ul>
<li><p>The <strong>Object</strong> part is the one you use with your programming language ( python in this case ) </p></li>
<li><p>The <strong>Relational</strong> part is a Relational Database Manager System ( A database that is ) there are other types of databases but the most popular is relational ( you know tables, columns, pk fk etc eg Oracle MySQL, MS-SQL ) </p></li>
<li><p>And finally the <strong>Mapping</strong> part is where you do a bridge between your objects and your tables. </p></li>
</ul>
<p>In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.</p>
<p>So let's say you have this object.</p>
<pre><code> class Employee:
def __init__( self, name ):
self.__name = name
def getName( self ):
return self.__name
#etc.
</code></pre>
<p>and the table</p>
<pre><code> create table employee(
name varcar(10),
-- etc
)
</code></pre>
<p>Using an ORM framework would allow you to map that object with a db record automagically and write something like:</p>
<pre><code> emp = Employee("Ryan")
orm.save( emp )
</code></pre>
<p>And have the employee inserted into the DB.</p>
<p><sub> Oops it was not that brief but I hope it is simple enough to catch other articles you read.</sub></p>
| 17 | 2009-08-14T21:34:45Z | [
"python",
"orm"
] |
What is an ORM and where can I learn more about it? | 1,279,613 | <p>Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?</p>
| 64 | 2009-08-14T19:03:59Z | 1,687,149 | <p><a href="https://storm.canonical.com/" rel="nofollow">Storm</a> is a great option for those using python.</p>
| 2 | 2009-11-06T11:59:53Z | [
"python",
"orm"
] |
What is an ORM and where can I learn more about it? | 1,279,613 | <p>Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?</p>
| 64 | 2009-08-14T19:03:59Z | 4,028,003 | <p>DALMP <a href="http://code.google.com/p/dalmp/" rel="nofollow">http://code.google.com/p/dalmp/</a> could be a good one for php/mysql currently supporting many caches backends like redis/memcache/apc</p>
| 0 | 2010-10-26T21:02:32Z | [
"python",
"orm"
] |
OCR Playing Cards | 1,279,768 | <p>I decided to do a project for fun where I want to take as input the image of a playing card and return its rank and suit. I figure that I only need look at the upper-left corner, since that has all the information. It should be robust - if I have a large image of an Ace of Diamonds, I should be able to scale it anywhere from 20 to 200% and still get the right answer.</p>
<p>First question - is there anything already written that does this? If so I'll find something else to OCR so I don't duplicate the efforts.</p>
<p>Second - what's the best way to go about doing this? Neural network? Something hand-coded? Can anyone give any pointers? (0xCAAF9452 is not an acceptable answer).</p>
| 12 | 2009-08-14T19:35:47Z | 1,280,040 | <p>Check out <a href="http://d-touch.org/" rel="nofollow">http://d-touch.org/</a>, you would have to design your own playing cards though.</p>
<p>You might also be interested in <a href="http://code.google.com/p/ocropus/" rel="nofollow">ocropus</a>.</p>
| 1 | 2009-08-14T20:31:55Z | [
"python",
"artificial-intelligence",
"ocr",
"computer-vision"
] |
OCR Playing Cards | 1,279,768 | <p>I decided to do a project for fun where I want to take as input the image of a playing card and return its rank and suit. I figure that I only need look at the upper-left corner, since that has all the information. It should be robust - if I have a large image of an Ace of Diamonds, I should be able to scale it anywhere from 20 to 200% and still get the right answer.</p>
<p>First question - is there anything already written that does this? If so I'll find something else to OCR so I don't duplicate the efforts.</p>
<p>Second - what's the best way to go about doing this? Neural network? Something hand-coded? Can anyone give any pointers? (0xCAAF9452 is not an acceptable answer).</p>
| 12 | 2009-08-14T19:35:47Z | 1,280,314 | <p>I don't think there's something already written for what you are trying to accomplish (at least open source and in Python).</p>
<p>As for your second question, it depends on what you are trying to recognize. If the inputs can come from different sources -- e.g., different brands of playing cards with distinctive styles --, then you should probably use a <strong>machine learning</strong>-based algorithm (such as neural network or support vector machine [SVM]), in order to let it learn how to recognize unknown inputs. However, if the input is always the same in shape or style, then a simple <strong>image comparison algorithm</strong> will suffice (e.g., compare the pixels of the sliced upper-left corner with the pixels of each rank).</p>
<p>If you do decide to use a machine learning-based algorithm, I also think you don't need very complex features, as the suits and ranks don't really vary that much in shape or style, and you should be fine with using just the pixels of the upper left corner as features.</p>
<p>There's a toy OCR example <strong><a href="http://code.google.com/p/svm-ocr-demo/" rel="nofollow">here</a></strong> that you may find interesting. The lib that is used (LibSVM) also has a Python version, which I have used, and found very simple to work with.</p>
<p>Hope it helps.</p>
| 2 | 2009-08-14T21:28:24Z | [
"python",
"artificial-intelligence",
"ocr",
"computer-vision"
] |
OCR Playing Cards | 1,279,768 | <p>I decided to do a project for fun where I want to take as input the image of a playing card and return its rank and suit. I figure that I only need look at the upper-left corner, since that has all the information. It should be robust - if I have a large image of an Ace of Diamonds, I should be able to scale it anywhere from 20 to 200% and still get the right answer.</p>
<p>First question - is there anything already written that does this? If so I'll find something else to OCR so I don't duplicate the efforts.</p>
<p>Second - what's the best way to go about doing this? Neural network? Something hand-coded? Can anyone give any pointers? (0xCAAF9452 is not an acceptable answer).</p>
| 12 | 2009-08-14T19:35:47Z | 1,280,833 | <p>It's not as robust, but you can look at the colours of 3 or 4 locations on the card so that if they are white or if they are a color, you can determine which card and suit it is. Obviously this won't work if you don't always have the same cards.</p>
| 1 | 2009-08-15T00:38:49Z | [
"python",
"artificial-intelligence",
"ocr",
"computer-vision"
] |
OCR Playing Cards | 1,279,768 | <p>I decided to do a project for fun where I want to take as input the image of a playing card and return its rank and suit. I figure that I only need look at the upper-left corner, since that has all the information. It should be robust - if I have a large image of an Ace of Diamonds, I should be able to scale it anywhere from 20 to 200% and still get the right answer.</p>
<p>First question - is there anything already written that does this? If so I'll find something else to OCR so I don't duplicate the efforts.</p>
<p>Second - what's the best way to go about doing this? Neural network? Something hand-coded? Can anyone give any pointers? (0xCAAF9452 is not an acceptable answer).</p>
| 12 | 2009-08-14T19:35:47Z | 1,280,850 | <p>Personally I would go the machine learning route with this one.</p>
| 1 | 2009-08-15T00:48:00Z | [
"python",
"artificial-intelligence",
"ocr",
"computer-vision"
] |
OCR Playing Cards | 1,279,768 | <p>I decided to do a project for fun where I want to take as input the image of a playing card and return its rank and suit. I figure that I only need look at the upper-left corner, since that has all the information. It should be robust - if I have a large image of an Ace of Diamonds, I should be able to scale it anywhere from 20 to 200% and still get the right answer.</p>
<p>First question - is there anything already written that does this? If so I'll find something else to OCR so I don't duplicate the efforts.</p>
<p>Second - what's the best way to go about doing this? Neural network? Something hand-coded? Can anyone give any pointers? (0xCAAF9452 is not an acceptable answer).</p>
| 12 | 2009-08-14T19:35:47Z | 1,280,852 | <p>There is a bunch of material online about this in the context of building online poker bots. See, for example: <a href="http://www.codingthewheel.com/archives/ocr-online-poker-optical-character-recognition" rel="nofollow">http://www.codingthewheel.com/archives/ocr-online-poker-optical-character-recognition</a></p>
| 4 | 2009-08-15T00:48:59Z | [
"python",
"artificial-intelligence",
"ocr",
"computer-vision"
] |
OCR Playing Cards | 1,279,768 | <p>I decided to do a project for fun where I want to take as input the image of a playing card and return its rank and suit. I figure that I only need look at the upper-left corner, since that has all the information. It should be robust - if I have a large image of an Ace of Diamonds, I should be able to scale it anywhere from 20 to 200% and still get the right answer.</p>
<p>First question - is there anything already written that does this? If so I'll find something else to OCR so I don't duplicate the efforts.</p>
<p>Second - what's the best way to go about doing this? Neural network? Something hand-coded? Can anyone give any pointers? (0xCAAF9452 is not an acceptable answer).</p>
| 12 | 2009-08-14T19:35:47Z | 1,288,332 | <p>Given the limited sample size (4 suits, 13 different values) I'd just try to match a reference image of the suit and value with a new input image. First find the bounding box of the incoming suit / value (the smallest box enclosing all non-white pixels), scale your reference pictures to match the size of that bounding box, and find the best "match" through pixel-wise absolute difference. The colour of the picture (i.e. red or black) will make this even easier.</p>
| 1 | 2009-08-17T14:41:17Z | [
"python",
"artificial-intelligence",
"ocr",
"computer-vision"
] |
OCR Playing Cards | 1,279,768 | <p>I decided to do a project for fun where I want to take as input the image of a playing card and return its rank and suit. I figure that I only need look at the upper-left corner, since that has all the information. It should be robust - if I have a large image of an Ace of Diamonds, I should be able to scale it anywhere from 20 to 200% and still get the right answer.</p>
<p>First question - is there anything already written that does this? If so I'll find something else to OCR so I don't duplicate the efforts.</p>
<p>Second - what's the best way to go about doing this? Neural network? Something hand-coded? Can anyone give any pointers? (0xCAAF9452 is not an acceptable answer).</p>
| 12 | 2009-08-14T19:35:47Z | 1,288,359 | <p>Use <a href="http://sourceforge.net/projects/opencvlibrary/" rel="nofollow">OpenCV</a></p>
| 3 | 2009-08-17T14:45:10Z | [
"python",
"artificial-intelligence",
"ocr",
"computer-vision"
] |
remove duplicates from nested dictionaries in list | 1,279,805 | <p>quick and very basic newbie question.</p>
<p>If i have list of dictionaries looking like this:</p>
<pre><code>L = []
L.append({"value1": value1, "value2": value2, "value3": value3, "value4": value4})
</code></pre>
<p>Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and remove those duplicate dictionaries.</p>
<p>Preserving order is of no importance.</p>
<p>Thanks.</p>
<p>EDIT:</p>
<p>If there are five inputs, like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": sdfsf, "value2": sdfsdf, "value3": abcd, "value4": gk},
{"value1": asddas, "value2": asdsa, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}]
</code></pre>
<p>The output shoud look like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}
</code></pre>
| 4 | 2009-08-14T19:41:26Z | 1,279,865 | <pre><code>for dic in list:
for anotherdic in list:
if dic != anotherdic:
if dic["value3"] == anotherdic["value3"] or dic["value4"] == anotherdic["value4"]:
list.remove(anotherdic)
</code></pre>
<p>Tested with</p>
<pre><code>list = [{"value1": 'fssd', "value2": 'dsfds', "value3": 'abcd', "value4": 'gk'},
{"value1": 'asdasd', "value2": 'asdas', "value3": 'dafdd', "value4": 'sdfsdf'},
{"value1": 'sdfsf', "value2": 'sdfsdf', "value3": 'abcd', "value4": 'gk'},
{"value1": 'asddas', "value2": 'asdsa', "value3": 'abcd', "value4": 'gk'},
{"value1": 'asdasd', "value2": 'dskksks', "value3": 'ldlsld', "value4": 'sdlsld'}]
</code></pre>
<p>worked fine for me :)</p>
| 1 | 2009-08-14T19:55:18Z | [
"python",
"dictionary"
] |
remove duplicates from nested dictionaries in list | 1,279,805 | <p>quick and very basic newbie question.</p>
<p>If i have list of dictionaries looking like this:</p>
<pre><code>L = []
L.append({"value1": value1, "value2": value2, "value3": value3, "value4": value4})
</code></pre>
<p>Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and remove those duplicate dictionaries.</p>
<p>Preserving order is of no importance.</p>
<p>Thanks.</p>
<p>EDIT:</p>
<p>If there are five inputs, like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": sdfsf, "value2": sdfsdf, "value3": abcd, "value4": gk},
{"value1": asddas, "value2": asdsa, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}]
</code></pre>
<p>The output shoud look like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}
</code></pre>
| 4 | 2009-08-14T19:41:26Z | 1,279,914 | <p>That's a list of one dictionary and but, assuming there are more dictionaries in the list <code>l</code>:</p>
<pre><code>l = [ldict for ldict in l if ldict.get("value3") != value3 or ldict.get("value4") != value4]
</code></pre>
<p>But is that what you really want to do? Perhaps you need to refine your description.</p>
<p>BTW, don't use <code>list</code> as a name since it is the name of a Python built-in.</p>
<p>EDIT: Assuming you started with a list of dictionaries, rather than a list of lists of 1 dictionary each that should work with your example. It wouldn't work if either of the values were None, so better something like:</p>
<pre><code>l = [ldict for ldict in l if not ( ("value3" in ldict and ldict["value3"] == value3) and ("value4" in ldict and ldict["value4"] == value4) )]
</code></pre>
<p>But it still seems like an unusual data structure.</p>
<p>EDIT: no need to use explicit <code>get</code>s.</p>
<p>Also, there are always tradeoffs in solutions. Without more info and without actually measuring, it's hard to know which performance tradeoffs are most important for the problem. But, as the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">Zen</a> sez: "Simple is better than complex".</p>
| 1 | 2009-08-14T20:05:27Z | [
"python",
"dictionary"
] |
remove duplicates from nested dictionaries in list | 1,279,805 | <p>quick and very basic newbie question.</p>
<p>If i have list of dictionaries looking like this:</p>
<pre><code>L = []
L.append({"value1": value1, "value2": value2, "value3": value3, "value4": value4})
</code></pre>
<p>Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and remove those duplicate dictionaries.</p>
<p>Preserving order is of no importance.</p>
<p>Thanks.</p>
<p>EDIT:</p>
<p>If there are five inputs, like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": sdfsf, "value2": sdfsdf, "value3": abcd, "value4": gk},
{"value1": asddas, "value2": asdsa, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}]
</code></pre>
<p>The output shoud look like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}
</code></pre>
| 4 | 2009-08-14T19:41:26Z | 1,279,921 | <p>You can use a temporary array to store an items dict. The previous code was bugged for removing items in the for loop.</p>
<pre><code>(v,r) = ([],[])
for i in l:
if ('value4', i['value4']) not in v and ('value3', i['value3']) not in v:
r.append(i)
v.extend(i.items())
l = r
</code></pre>
<p>Your test:</p>
<pre><code>l = [{"value1": 'fssd', "value2": 'dsfds', "value3": 'abcd', "value4": 'gk'},
{"value1": 'asdasd', "value2": 'asdas', "value3": 'dafdd', "value4": 'sdfsdf'},
{"value1": 'sdfsf', "value2": 'sdfsdf', "value3": 'abcd', "value4": 'gk'},
{"value1": 'asddas', "value2": 'asdsa', "value3": 'abcd', "value4": 'gk'},
{"value1": 'asdasd', "value2": 'dskksks', "value3": 'ldlsld', "value4": 'sdlsld'}]
</code></pre>
<p>ouputs</p>
<pre><code>{'value4': 'gk', 'value3': 'abcd', 'value2': 'dsfds', 'value1': 'fssd'}
{'value4': 'sdfsdf', 'value3': 'dafdd', 'value2': 'asdas', 'value1': 'asdasd'}
{'value4': 'sdlsld', 'value3': 'ldlsld', 'value2': 'dskksks', 'value1': 'asdasd'}
</code></pre>
| 2 | 2009-08-14T20:06:33Z | [
"python",
"dictionary"
] |
remove duplicates from nested dictionaries in list | 1,279,805 | <p>quick and very basic newbie question.</p>
<p>If i have list of dictionaries looking like this:</p>
<pre><code>L = []
L.append({"value1": value1, "value2": value2, "value3": value3, "value4": value4})
</code></pre>
<p>Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and remove those duplicate dictionaries.</p>
<p>Preserving order is of no importance.</p>
<p>Thanks.</p>
<p>EDIT:</p>
<p>If there are five inputs, like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": sdfsf, "value2": sdfsdf, "value3": abcd, "value4": gk},
{"value1": asddas, "value2": asdsa, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}]
</code></pre>
<p>The output shoud look like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}
</code></pre>
| 4 | 2009-08-14T19:41:26Z | 1,280,217 | <p>Here's one way:</p>
<pre><code>keyfunc = lambda d: (d['value3'], d['value4'])
from itertools import groupby
giter = groupby(sorted(L, key=keyfunc), keyfunc)
L2 = [g[1].next() for g in giter]
print L2
</code></pre>
| 7 | 2009-08-14T21:03:26Z | [
"python",
"dictionary"
] |
remove duplicates from nested dictionaries in list | 1,279,805 | <p>quick and very basic newbie question.</p>
<p>If i have list of dictionaries looking like this:</p>
<pre><code>L = []
L.append({"value1": value1, "value2": value2, "value3": value3, "value4": value4})
</code></pre>
<p>Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and remove those duplicate dictionaries.</p>
<p>Preserving order is of no importance.</p>
<p>Thanks.</p>
<p>EDIT:</p>
<p>If there are five inputs, like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": sdfsf, "value2": sdfsdf, "value3": abcd, "value4": gk},
{"value1": asddas, "value2": asdsa, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}]
</code></pre>
<p>The output shoud look like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}
</code></pre>
| 4 | 2009-08-14T19:41:26Z | 1,280,364 | <p>If I understand correctly, you want to discard matches that come later in the original list but do not care about the order of the resulting list, so:</p>
<p>(Tested with 2.5.2)</p>
<pre><code>tempDict = {}
for d in L[::-1]:
tempDict[(d["value3"],d["value4"])] = d
L[:] = tempDict.itervalues()
tempDict = None
</code></pre>
| 0 | 2009-08-14T21:40:29Z | [
"python",
"dictionary"
] |
remove duplicates from nested dictionaries in list | 1,279,805 | <p>quick and very basic newbie question.</p>
<p>If i have list of dictionaries looking like this:</p>
<pre><code>L = []
L.append({"value1": value1, "value2": value2, "value3": value3, "value4": value4})
</code></pre>
<p>Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and remove those duplicate dictionaries.</p>
<p>Preserving order is of no importance.</p>
<p>Thanks.</p>
<p>EDIT:</p>
<p>If there are five inputs, like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": sdfsf, "value2": sdfsdf, "value3": abcd, "value4": gk},
{"value1": asddas, "value2": asdsa, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}]
</code></pre>
<p>The output shoud look like this:</p>
<pre><code>L = [{"value1": fssd, "value2": dsfds, "value3": abcd, "value4": gk},
{"value1": asdasd, "value2": asdas, "value3": dafdd, "value4": sdfsdf},
{"value1": asdasd, "value2": dskksks, "value3": ldlsld, "value4": sdlsld}
</code></pre>
| 4 | 2009-08-14T19:41:26Z | 1,280,464 | <p>In Python 2.6 or 3.*:</p>
<pre><code>import itertools
import pprint
L = [{"value1": "fssd", "value2": "dsfds", "value3": "abcd", "value4": "gk"},
{"value1": "asdasd", "value2": "asdas", "value3": "dafdd", "value4": "sdfsdf"},
{"value1": "sdfsf", "value2": "sdfsdf", "value3": "abcd", "value4": "gk"},
{"value1": "asddas", "value2": "asdsa", "value3": "abcd", "value4": "gk"},
{"value1": "asdasd", "value2": "dskksks", "value3": "ldlsld", "value4": "sdlsld"}]
getvals = operator.itemgetter('value3', 'value4')
L.sort(key=getvals)
result = []
for k, g in itertools.groupby(L, getvals):
result.append(g.next())
L[:] = result
pprint.pprint(L)
</code></pre>
<p>Almost the same in Python 2.5, except you have to use g.next() instead of next(g) in the append.</p>
| 6 | 2009-08-14T22:15:18Z | [
"python",
"dictionary"
] |
exec() bytecode with arbitrary locals? | 1,280,100 | <p>Suppose I want to execute code, for example</p>
<pre><code> value += 5
</code></pre>
<p>inside a namespace of my own (so the result is essentially <code>mydict['value'] += 5</code>). There's a function <code>exec()</code>, but I have to pass a string there:</p>
<pre><code> exec('value += 5', mydict)
</code></pre>
<p>and passing statements as strings seems strange (e.g. it's not colorized that way).
Can it be done like:</p>
<pre><code> def block():
value += 5
???(block, mydict)
</code></pre>
<p>? The obvious candidate for last line was <code>exec(block.__code__, mydict)</code>, but no luck: it raises <code>UnboundLocalError</code> about <code>value</code>. I believe it basically executes <code>block()</code>, not <em>the code inside block</em>, so assignments aren't easy â is that correct?</p>
<p>Of course, another possible solution would be to disassembly <code>block.__code__</code>...</p>
<p>FYI, I got the question because of <a href="http://mail.python.org/pipermail/python-ideas/2009-August/005552.html" rel="nofollow">this thread</a>. Also, this is why some (me undecided) call for new syntax </p>
<pre><code> using mydict:
value += 5
</code></pre>
<p><hr /></p>
<p>Note how this doesn't throw error but doesn't change <code>mydict</code> either:</p>
<pre><code> def block(value = 0):
value += 5
block(**mydict)
</code></pre>
| 2 | 2009-08-14T20:41:10Z | 1,280,493 | <p>You can pass bytecode instead of a string to <code>exec</code>, you just need to make the right bytecode for the purpose:</p>
<pre><code>>>> bytecode = compile('value += 5', '<string>', 'exec')
>>> mydict = {'value': 23}
>>> exec(bytecode, mydict)
>>> mydict['value']
28
</code></pre>
<p>Specifically, ...:</p>
<pre><code>>>> import dis
>>> dis.dis(bytecode)
1 0 LOAD_NAME 0 (value)
3 LOAD_CONST 0 (5)
6 INPLACE_ADD
7 STORE_NAME 0 (value)
10 LOAD_CONST 1 (None)
13 RETURN_VALUE
</code></pre>
<p>the load and store instructions must be of the _NAME persuasion, and this <code>compile</code> makes them so, while...:</p>
<pre><code>>>> def f(): value += 5
...
>>> dis.dis(f.func_code)
1 0 LOAD_FAST 0 (value)
3 LOAD_CONST 1 (5)
6 INPLACE_ADD
7 STORE_FAST 0 (value)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
</code></pre>
<p>...code in a function is optimized to use the _FAST versions, and those don't work on a dict passed to <code>exec</code>. If you started somehow with a bytecode using the _FAST instructions, you could patch it to use the _NAME kind instead, e.g. with <a href="http://mail.python.org/pipermail/python-announce-list/2004-July/003280.html" rel="nofollow">bytecodehacks</a> or some similar approach.</p>
| 6 | 2009-08-14T22:25:28Z | [
"python",
"python-3.x",
"bytecode",
"codeblocks"
] |
exec() bytecode with arbitrary locals? | 1,280,100 | <p>Suppose I want to execute code, for example</p>
<pre><code> value += 5
</code></pre>
<p>inside a namespace of my own (so the result is essentially <code>mydict['value'] += 5</code>). There's a function <code>exec()</code>, but I have to pass a string there:</p>
<pre><code> exec('value += 5', mydict)
</code></pre>
<p>and passing statements as strings seems strange (e.g. it's not colorized that way).
Can it be done like:</p>
<pre><code> def block():
value += 5
???(block, mydict)
</code></pre>
<p>? The obvious candidate for last line was <code>exec(block.__code__, mydict)</code>, but no luck: it raises <code>UnboundLocalError</code> about <code>value</code>. I believe it basically executes <code>block()</code>, not <em>the code inside block</em>, so assignments aren't easy â is that correct?</p>
<p>Of course, another possible solution would be to disassembly <code>block.__code__</code>...</p>
<p>FYI, I got the question because of <a href="http://mail.python.org/pipermail/python-ideas/2009-August/005552.html" rel="nofollow">this thread</a>. Also, this is why some (me undecided) call for new syntax </p>
<pre><code> using mydict:
value += 5
</code></pre>
<p><hr /></p>
<p>Note how this doesn't throw error but doesn't change <code>mydict</code> either:</p>
<pre><code> def block(value = 0):
value += 5
block(**mydict)
</code></pre>
| 2 | 2009-08-14T20:41:10Z | 1,280,876 | <p>Use the <code>global</code> keyword to force dynamic scoping on any variables you want to modify from within the block:</p>
<pre><code>def block():
global value
value += 5
mydict = {"value": 42}
exec(block.__code__, mydict)
print(mydict["value"])
</code></pre>
| 3 | 2009-08-15T00:59:58Z | [
"python",
"python-3.x",
"bytecode",
"codeblocks"
] |
exec() bytecode with arbitrary locals? | 1,280,100 | <p>Suppose I want to execute code, for example</p>
<pre><code> value += 5
</code></pre>
<p>inside a namespace of my own (so the result is essentially <code>mydict['value'] += 5</code>). There's a function <code>exec()</code>, but I have to pass a string there:</p>
<pre><code> exec('value += 5', mydict)
</code></pre>
<p>and passing statements as strings seems strange (e.g. it's not colorized that way).
Can it be done like:</p>
<pre><code> def block():
value += 5
???(block, mydict)
</code></pre>
<p>? The obvious candidate for last line was <code>exec(block.__code__, mydict)</code>, but no luck: it raises <code>UnboundLocalError</code> about <code>value</code>. I believe it basically executes <code>block()</code>, not <em>the code inside block</em>, so assignments aren't easy â is that correct?</p>
<p>Of course, another possible solution would be to disassembly <code>block.__code__</code>...</p>
<p>FYI, I got the question because of <a href="http://mail.python.org/pipermail/python-ideas/2009-August/005552.html" rel="nofollow">this thread</a>. Also, this is why some (me undecided) call for new syntax </p>
<pre><code> using mydict:
value += 5
</code></pre>
<p><hr /></p>
<p>Note how this doesn't throw error but doesn't change <code>mydict</code> either:</p>
<pre><code> def block(value = 0):
value += 5
block(**mydict)
</code></pre>
| 2 | 2009-08-14T20:41:10Z | 1,314,536 | <p>From S.Lott's comment above I think I get the idea for an answer using creation of new class. </p>
<pre><code>class _(__metaclass__ = change(mydict)):
value += 1
...
</code></pre>
<p>where <code>change</code> is a metaclass whose <code>__prepare__</code> reads dictionary and whose <code>__new__</code> updates dictionary. </p>
<p>For reuse, the snippet below would work, but it's kind of ugly:</p>
<pre><code>def increase_value(d):
class _(__metaclass__ = change(d)):
value += 1
...
increase_value(mydict)
</code></pre>
| 0 | 2009-08-21T22:54:06Z | [
"python",
"python-3.x",
"bytecode",
"codeblocks"
] |
exec() bytecode with arbitrary locals? | 1,280,100 | <p>Suppose I want to execute code, for example</p>
<pre><code> value += 5
</code></pre>
<p>inside a namespace of my own (so the result is essentially <code>mydict['value'] += 5</code>). There's a function <code>exec()</code>, but I have to pass a string there:</p>
<pre><code> exec('value += 5', mydict)
</code></pre>
<p>and passing statements as strings seems strange (e.g. it's not colorized that way).
Can it be done like:</p>
<pre><code> def block():
value += 5
???(block, mydict)
</code></pre>
<p>? The obvious candidate for last line was <code>exec(block.__code__, mydict)</code>, but no luck: it raises <code>UnboundLocalError</code> about <code>value</code>. I believe it basically executes <code>block()</code>, not <em>the code inside block</em>, so assignments aren't easy â is that correct?</p>
<p>Of course, another possible solution would be to disassembly <code>block.__code__</code>...</p>
<p>FYI, I got the question because of <a href="http://mail.python.org/pipermail/python-ideas/2009-August/005552.html" rel="nofollow">this thread</a>. Also, this is why some (me undecided) call for new syntax </p>
<pre><code> using mydict:
value += 5
</code></pre>
<p><hr /></p>
<p>Note how this doesn't throw error but doesn't change <code>mydict</code> either:</p>
<pre><code> def block(value = 0):
value += 5
block(**mydict)
</code></pre>
| 2 | 2009-08-14T20:41:10Z | 1,844,933 | <p>Here is a crazy decorator to create such a block that uses "custom locals". In reality it is a quick hack to turn all variable access inside the function to global access, and evaluate the result with the custom locals dictionary as environment.</p>
<pre><code>import dis
import functools
import types
import string
def withlocals(func):
"""Decorator for executing a block with custom "local" variables.
The decorated function takes one argument: its scope dictionary.
>>> @withlocals
... def block():
... counter += 1
... luckynumber = 88
>>> d = {"counter": 1}
>>> block(d)
>>> d["counter"]
2
>>> d["luckynumber"]
88
"""
def opstr(*opnames):
return "".join([chr(dis.opmap[N]) for N in opnames])
translation_table = string.maketrans(
opstr("LOAD_FAST", "STORE_FAST"),
opstr("LOAD_GLOBAL", "STORE_GLOBAL"))
c = func.func_code
newcode = types.CodeType(c.co_argcount,
0, # co_nlocals
c.co_stacksize,
c.co_flags,
c.co_code.translate(translation_table),
c.co_consts,
c.co_varnames, # co_names, name of global vars
(), # co_varnames
c.co_filename,
c.co_name,
c.co_firstlineno,
c.co_lnotab)
@functools.wraps(func)
def wrapper(mylocals):
return eval(newcode, mylocals)
return wrapper
if __name__ == '__main__':
import doctest
doctest.testmod()
</code></pre>
<p>This is just a monkey-patching adaption of someone's brilliant recipe for a <a href="http://code.activestate.com/recipes/576944/" rel="nofollow">goto decorator</a></p>
| 3 | 2009-12-04T04:52:37Z | [
"python",
"python-3.x",
"bytecode",
"codeblocks"
] |
How to classify users into different countries, based on the Location field | 1,280,266 | <p>Most web applications have a Location field, in which uses may enter a Location of their choice.</p>
<p>How would you classify users into different countries, based on the location entered.</p>
<p>For eg, I used the Stack Overflow dump of <code>users.xml</code> and extracted users' names, reputation and location:</p>
<pre><code>['Jeff Atwood', '12853', 'El Cerrito, CA']
['Jarrod Dixon', '1114', 'Morganton, NC']
['Sneakers OToole', '200', 'Unknown']
['Greg Hurlman', '5327', 'Halfway between the boardwalk and Six Flags, NJ']
['Power-coder', '812', 'Burlington, Ontario, Canada']
['Chris Jester-Young', '16509', 'Durham, NC']
['Teifion', '7024', 'Wales']
['Grant', '3333', 'Georgia']
['TimM', '133', 'Alabama']
['Leon Bambrick', '2450', 'Australia']
['Coincoin', '3801', 'Montreal']
['Tom Grochowicz', '125', 'NJ']
['Rex M', '12822', 'US']
['Dillie-O', '7109', 'Prescott, AZ']
['Pete', '653', 'Reynoldsburg, OH']
['Nick Berardi', '9762', 'Phoenixville, PA']
['Kandis', '39', '']
['Shawn', '4248', 'philadelphia']
['Yaakov Ellis', '3651', 'Israel']
['redwards', '21', 'US']
['Dave Ward', '4831', 'Atlanta']
['Liron Yahdav', '527', 'San Rafael, CA']
['Geoff Dalgas', '648', 'Corvallis, OR']
['Kevin Dente', '1619', 'Oakland, CA']
['Tom', '3316', '']
['denny', '573', 'Winchester, VA']
['Karl Seguin', '4195', 'Ottawa']
['Bob', '4652', 'US']
['saniul', '2352', 'London, UK']
['saint_groceon', '1087', 'Houston, TX']
['Tim Boland', '192', 'Cincinnati Ohio']
['Darren Kopp', '5807', 'Woods Cross, UT']
</code></pre>
<p>using the following Python script:</p>
<pre><code>from xml.etree import ElementTree
root = ElementTree.parse('SO Export/so-export-2009-05/users.xml').getroot()
items = ['DisplayName','Reputation','Location']
def loop1():
for count,i in enumerate(root):
det = [i.get(x) for x in items]
print det
if count>30: break
loop1()
</code></pre>
<p>What is the simplest way to classify people into different countries? Are there any ready lookup tables available that provide me an output saying <code>X</code> location belongs to <code>Y</code> country?</p>
<p>The lookup table need not be totally accurate. Reasonably accurate answers are obtained by querying the location string on Google, or better still, Wolfram Alpha.</p>
| 1 | 2009-08-14T21:15:13Z | 1,280,300 | <p>Force users to specify country, because you'll have to deal with ambiguities. This would be the right way.</p>
<p>If that's not possible, at least make your best-guess in conjunction with their IP address.</p>
<p>For example, ['Grant', '3333', 'Georgia']</p>
<p>Is this Georgia, USA?
Or is this the Republic of Georgia?</p>
<p>If their IP address suggests somewhere in Central Asia or Eastern Europe, then chances are it's the Republic of Georgia. If it's North America, chances are pretty good they mean Georgia, USA.</p>
<p>Note that mappings for IP address to country isn't 100% accurate, and the database needs to be updated regularly. In my opinion, far too much trouble.</p>
| 1 | 2009-08-14T21:24:03Z | [
"python",
"xml",
"geolocation",
"elementtree"
] |
How to classify users into different countries, based on the Location field | 1,280,266 | <p>Most web applications have a Location field, in which uses may enter a Location of their choice.</p>
<p>How would you classify users into different countries, based on the location entered.</p>
<p>For eg, I used the Stack Overflow dump of <code>users.xml</code> and extracted users' names, reputation and location:</p>
<pre><code>['Jeff Atwood', '12853', 'El Cerrito, CA']
['Jarrod Dixon', '1114', 'Morganton, NC']
['Sneakers OToole', '200', 'Unknown']
['Greg Hurlman', '5327', 'Halfway between the boardwalk and Six Flags, NJ']
['Power-coder', '812', 'Burlington, Ontario, Canada']
['Chris Jester-Young', '16509', 'Durham, NC']
['Teifion', '7024', 'Wales']
['Grant', '3333', 'Georgia']
['TimM', '133', 'Alabama']
['Leon Bambrick', '2450', 'Australia']
['Coincoin', '3801', 'Montreal']
['Tom Grochowicz', '125', 'NJ']
['Rex M', '12822', 'US']
['Dillie-O', '7109', 'Prescott, AZ']
['Pete', '653', 'Reynoldsburg, OH']
['Nick Berardi', '9762', 'Phoenixville, PA']
['Kandis', '39', '']
['Shawn', '4248', 'philadelphia']
['Yaakov Ellis', '3651', 'Israel']
['redwards', '21', 'US']
['Dave Ward', '4831', 'Atlanta']
['Liron Yahdav', '527', 'San Rafael, CA']
['Geoff Dalgas', '648', 'Corvallis, OR']
['Kevin Dente', '1619', 'Oakland, CA']
['Tom', '3316', '']
['denny', '573', 'Winchester, VA']
['Karl Seguin', '4195', 'Ottawa']
['Bob', '4652', 'US']
['saniul', '2352', 'London, UK']
['saint_groceon', '1087', 'Houston, TX']
['Tim Boland', '192', 'Cincinnati Ohio']
['Darren Kopp', '5807', 'Woods Cross, UT']
</code></pre>
<p>using the following Python script:</p>
<pre><code>from xml.etree import ElementTree
root = ElementTree.parse('SO Export/so-export-2009-05/users.xml').getroot()
items = ['DisplayName','Reputation','Location']
def loop1():
for count,i in enumerate(root):
det = [i.get(x) for x in items]
print det
if count>30: break
loop1()
</code></pre>
<p>What is the simplest way to classify people into different countries? Are there any ready lookup tables available that provide me an output saying <code>X</code> location belongs to <code>Y</code> country?</p>
<p>The lookup table need not be totally accurate. Reasonably accurate answers are obtained by querying the location string on Google, or better still, Wolfram Alpha.</p>
| 1 | 2009-08-14T21:15:13Z | 1,280,334 | <p>You best bet is to use a Geocoding API like <a href="http://code.google.com/p/geopy/" rel="nofollow">geopy</a> (<a href="http://code.google.com/p/geopy/wiki/GettingStarted" rel="nofollow">some Examples</a>).</p>
<p>The <a href="http://code.google.com/apis/maps/documentation/geocoding/#GeocodingResponses" rel="nofollow">Google Geocoding API</a>, for example, will return the country in the <code>CountryNameCode</code>-field of the response.</p>
<p>With just this one location field the number of false matches will probably be relatively high, but maybe it is good enough.</p>
<p>If you had server logs, you could try to also look up the users IP address with an IP geocoder (more information and pointers on <a href="http://en.wikipedia.org/wiki/Geolocation%5Fsoftware" rel="nofollow">Wikipedia</a></p>
| 2 | 2009-08-14T21:33:06Z | [
"python",
"xml",
"geolocation",
"elementtree"
] |
Ruby to python one-liner conversion | 1,280,379 | <p>I have a little one-liner in my Rails app that returns a range of copyright dates with an optional parameter, e.g.:</p>
<pre><code>def copyright_dates(start_year = Date.today().year)
[start_year, Date.today().year].sort.uniq.join(" - ")
end
</code></pre>
<p>I'm moving the app over to Django, and while I love it, I miss a bit of the conciseness. The same method in Python looks like:</p>
<pre><code>def copyright_dates(start_year = datetime.datetime.today().year):
years = list(set([start_year, datetime.datetime.today().year]))
years.sort()
return " - ".join(map(str, years))
</code></pre>
<p>It's been years since I've touched Python, so I'm betting there's an easier way to do it. Any ideas?</p>
<p><strong>EDIT</strong>: I know lists and sets are a bit of overkill, but I want the following output assuming the code is run in 2009:</p>
<pre><code>copyright_dates() # '2009'
copyright_dates(2007) # '2007 - 2009'
copyright_dates(2012) # '2009 - 2012'
</code></pre>
| 0 | 2009-08-14T21:46:01Z | 1,280,415 | <pre><code>from datetime import datetime
def copyright_dates(start_year = datetime.now().year):
return " - ".join(str(y) for y in sorted(set([start_year, datetime.now().year])))
</code></pre>
| 5 | 2009-08-14T21:54:45Z | [
"python",
"ruby-on-rails",
"ruby",
"django"
] |
Ruby to python one-liner conversion | 1,280,379 | <p>I have a little one-liner in my Rails app that returns a range of copyright dates with an optional parameter, e.g.:</p>
<pre><code>def copyright_dates(start_year = Date.today().year)
[start_year, Date.today().year].sort.uniq.join(" - ")
end
</code></pre>
<p>I'm moving the app over to Django, and while I love it, I miss a bit of the conciseness. The same method in Python looks like:</p>
<pre><code>def copyright_dates(start_year = datetime.datetime.today().year):
years = list(set([start_year, datetime.datetime.today().year]))
years.sort()
return " - ".join(map(str, years))
</code></pre>
<p>It's been years since I've touched Python, so I'm betting there's an easier way to do it. Any ideas?</p>
<p><strong>EDIT</strong>: I know lists and sets are a bit of overkill, but I want the following output assuming the code is run in 2009:</p>
<pre><code>copyright_dates() # '2009'
copyright_dates(2007) # '2007 - 2009'
copyright_dates(2012) # '2009 - 2012'
</code></pre>
| 0 | 2009-08-14T21:46:01Z | 1,280,439 | <p>Lists and sets seem to be overkill to me.</p>
<p>How about this:</p>
<pre><code>def copyright_dates(start=datetime.datetime.today().year):
now = datetime.datetime.today().year
return (start==now and str(now) or "%d - %d" % (min(start, now), max(start, now)))
</code></pre>
| 2 | 2009-08-14T22:03:20Z | [
"python",
"ruby-on-rails",
"ruby",
"django"
] |
Ruby to python one-liner conversion | 1,280,379 | <p>I have a little one-liner in my Rails app that returns a range of copyright dates with an optional parameter, e.g.:</p>
<pre><code>def copyright_dates(start_year = Date.today().year)
[start_year, Date.today().year].sort.uniq.join(" - ")
end
</code></pre>
<p>I'm moving the app over to Django, and while I love it, I miss a bit of the conciseness. The same method in Python looks like:</p>
<pre><code>def copyright_dates(start_year = datetime.datetime.today().year):
years = list(set([start_year, datetime.datetime.today().year]))
years.sort()
return " - ".join(map(str, years))
</code></pre>
<p>It's been years since I've touched Python, so I'm betting there's an easier way to do it. Any ideas?</p>
<p><strong>EDIT</strong>: I know lists and sets are a bit of overkill, but I want the following output assuming the code is run in 2009:</p>
<pre><code>copyright_dates() # '2009'
copyright_dates(2007) # '2007 - 2009'
copyright_dates(2012) # '2009 - 2012'
</code></pre>
| 0 | 2009-08-14T21:46:01Z | 1,280,601 | <p>Watch out for the default parameter which is evaluated once. So if your web application runs over 12/31/09 without a restart, you won't get the expected output.</p>
<p>Try:</p>
<pre><code>def copy(start=None):
start, curr = start if start else datetime.today().year, datetime.today().year
return str(start) if start == curr else '%d - %d' % tuple(sorted([start, curr]))
</code></pre>
| 5 | 2009-08-14T23:02:32Z | [
"python",
"ruby-on-rails",
"ruby",
"django"
] |
wxPython: Items in BoxSizer don't expand horizontally, only vertically | 1,280,600 | <p>I have several buttons in various sizers and they expand in the way that I want them to. However, when I add the parent to a new wx.BoxSizer that is used to add a border around all the elements in the frame, the sizer that has been added functions correctly vertically, but not horizontally.</p>
<p>The following code demonstrates the problem:</p>
<pre><code>#! /usr/bin/env python
import wx
import webbrowser
class App(wx.App):
def OnInit(self):
frame = MainFrame()
frame.Show()
self.SetTopWindow(frame)
return True
class MainFrame(wx.Frame):
title = 'Title'
def __init__(self):
wx.Frame.__init__(self, None, -1, self.title)
panel = wx.Panel(self)
#icon = wx.Icon('icon.png', wx.BITMAP_TYPE_PNG)
#self.SetIcon(icon)
sizer = wx.FlexGridSizer(rows=2, cols=1, vgap=10, hgap=10)
button1 = wx.Button(panel, -1, 'BUTTON')
sizer.Add(button1, 0, wx.EXPAND)
buttonSizer = wx.FlexGridSizer(rows=1, cols=4, vgap=10, hgap=5)
buttonDelete = wx.Button(panel, -1, 'Delete')
buttonSizer.Add(buttonDelete, 0, 0)
buttonEdit = wx.Button(panel, -1, 'Edit')
buttonSizer.Add(buttonEdit, 0, 0)
buttonNew = wx.Button(panel, -1, 'New')
buttonSizer.Add(buttonNew, 0, 0)
buttonSizer.AddGrowableCol(0, 0)
sizer.Add(buttonSizer, 0, wx.EXPAND|wx.HORIZONTAL)
sizer.AddGrowableCol(0, 0)
sizer.AddGrowableRow(0, 0)
mainSizer = wx.BoxSizer(wx.EXPAND)
mainSizer.Add(sizer, 0, wx.EXPAND|wx.ALL, 10)
#panel.SetSizerAndFit(sizer)
#sizer.SetSizeHints(self)
panel.SetSizerAndFit(mainSizer)
mainSizer.SetSizeHints(self)
if __name__ == '__main__':
app = App(False)
app.MainLoop()
</code></pre>
<p>Commenting out lines <strong>57</strong> and <strong>58</strong> and uncommenting lines <strong>55</strong> and <strong>56</strong> removes the extra BoxSizer and shows how I expect everything to function (without the whitespace of course).</p>
<p>I am completely stuck with this problem and still have no clue as to how to fix it.</p>
| 9 | 2009-08-14T23:02:25Z | 1,281,041 | <p>First of all, you're passing some flags incorrectly. BoxSizer takes wx.HORIZONTAL or wx.VERTICAL, not wx.EXPAND. sizer.Add does not take wx.HORIZONTAL.</p>
<p>If you have a VERTICAL BoxSizer, wx.EXPAND will make the control fill horizontally, while a proportion of 1 or more (second argument to Add) will make the control fill vertically. It's the opposite for HORIZONTAL BoxSizers.</p>
<pre><code>sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(widget1, 0, wx.EXPAND)
sizer.Add(widget2, 1)
</code></pre>
<p>widget1 will expand horizontally. widget2 will expand vertically.</p>
<p>If you put a sizer in another sizer, you need to be sure to have its proportion and EXPAND flags set so that its insides will grow how you want them to.</p>
<p>I'll leave the rest to you.</p>
| 23 | 2009-08-15T03:12:03Z | [
"python",
"wxpython",
"wxwidgets"
] |
detecting two simultaneous keys in pyglet (python) | 1,280,616 | <p>I wanted to know how to detect when two keys are simultaneously pressed using pyglet.
I currently have </p>
<pre>
def on_text_motion(self, motion):
(dx,dy) = ARROW_KEY_TO_VERSOR[motion]
self.window.move_dx_dy((dx,dy))
</pre>
<p>But this only gets arrow keys one at a time...
I'd like to distinguish between the combination UP+LEFT
and UP, then LEFT...</p>
<p>Hope I made myself clear
Manu</p>
| 3 | 2009-08-14T23:10:48Z | 1,280,698 | <p>Try <a href="http://www.pyglet.org/doc/api/pyglet.window.key.KeyStateHandler-class.html" rel="nofollow">pyglet.window.key.KeyStateHandler</a>:</p>
<pre><code>import pyglet
key = pyglet.window.key
win = pyglet.window.Window()
keyboard = key.KeyStateHandler()
win.push_handlers(keyboard)
print keyboard[key.UP] and keyboard[key.LEFT]
</code></pre>
| 4 | 2009-08-14T23:42:41Z | [
"python",
"keyboard",
"pyglet"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,677 | <p>When faced with that sort of program logic, I would probably break up the sequence of loops into two or more separate functions.</p>
<p>Another technique in Python is to use <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehensions</a> where possible, instead of a loop.</p>
| 7 | 2009-08-14T23:36:03Z | [
"python",
"for-loop",
"nested-loops"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,678 | <p>My personal argument would be that you're likely doing something wrong if you have 6 nested loops...</p>
<p>That said, functional decomposition is what you're looking for. Refactor so some of the loops happen in seperate function calls, then call those functions.</p>
| 2 | 2009-08-14T23:36:32Z | [
"python",
"for-loop",
"nested-loops"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,679 | <p>Assuming each loop has some sort of independent meaning, break them out into named functions:</p>
<pre><code>def do_tigers():
for x in range(3):
print something
def do_lions():
do_lionesses()
for x in range(3):
do_tigers()
def do_penguins():
for x in range(3):
do_lions()
..etc.
</code></pre>
<p>I could perhaps have chosen better names. 8-)</p>
| 4 | 2009-08-14T23:36:59Z | [
"python",
"for-loop",
"nested-loops"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,680 | <p>Have you looked into <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">List Comprehensions?</a></p>
<p>Something like:</p>
<pre><code>[do_something() for x in range(3) for y in range(3)]
</code></pre>
| 0 | 2009-08-14T23:37:05Z | [
"python",
"for-loop",
"nested-loops"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,685 | <p>That way looks pretty straightforward and easy. Are you are saying you want to generalize to multiple layers of loops.... can you give a real-life example?</p>
<p>Another option I could think of would be to use a function to generate the parameters and then just apply them in a loop</p>
<pre><code>def generate_params(n):
return itertools.product(range(n), range(n))
for x,y in generate_params(3):
do_something()
</code></pre>
| 0 | 2009-08-14T23:37:45Z | [
"python",
"for-loop",
"nested-loops"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,712 | <p>you can also use the <a href="http://docs.python.org/tutorial/datastructures.html" rel="nofollow">map()</a> <a href="http://en.wikipedia.org/wiki/Map%5F%28higher-order%5Ffunction%29" rel="nofollow">function</a> </p>
| 0 | 2009-08-14T23:47:07Z | [
"python",
"for-loop",
"nested-loops"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,724 | <p>If you're frequently iterating over a Cartesian product like in your example, you might want to investigate <a href="http://docs.python.org/library/itertools.html#itertools.product">Python 2.6's itertools.product</a> -- or write your own if you're in an earlier Python.</p>
<pre><code>from itertools import product
for y, x in product(range(3), repeat=2):
do_something()
for y1, x1 in product(range(3), repeat=2):
do_something_else()
</code></pre>
| 49 | 2009-08-14T23:51:35Z | [
"python",
"for-loop",
"nested-loops"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,726 | <p>Technically, you could use <code>itertools.product</code> to get a cartesian product of N sequences, and iterate over that:</p>
<pre><code> for y, x, y1, x1 in itertools.product(range(3), repeat=4):
do_something_else()
</code></pre>
<p>But I don't think that actually wins you anything readability-wise.</p>
| 2 | 2009-08-14T23:51:54Z | [
"python",
"for-loop",
"nested-loops"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,730 | <p>This is fairly common when looping over multidimensional spaces. My solution is:</p>
<pre><code>xy_grid = [(x, y) for x in range(3) for y in range(3)]
for x, y in xy_grid:
# do something
for x1, y1 in xy_grid:
# do something else
</code></pre>
| 10 | 2009-08-14T23:53:34Z | [
"python",
"for-loop",
"nested-loops"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,745 | <p>From your code it looks like you want to perform an operation with every possible pair of points where x and y are in the range 0..2.</p>
<p>To do that:</p>
<pre><code>for x1,y1,x2,y2 in itertools.product(range(3), repeat=4):
do_something_with_two_points(x1,y1,2,y2)
</code></pre>
<p>The operation <code>do_something_with_two_points</code> will be called 81 times - once for every possible combination of points. </p>
| 1 | 2009-08-14T23:57:37Z | [
"python",
"for-loop",
"nested-loops"
] |
In python is there an easier way to write 6 nested for loops? | 1,280,667 | <p>This problem has been getting at me for a while now. Is there an easier way to write nested <code>for</code> loops in python? For example if my code went something like this:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
</code></pre>
<p>would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.</p>
<p>Oh in the example there were only 4 nested <code>for</code> loops to make things easier.</p>
| 30 | 2009-08-14T23:31:40Z | 1,280,875 | <p>Python iterators, and generators in particular, exist exactly to allow the nice refactoring of otherwise-complicated loops. Of course, it's hard to get an abstraction out from a simple example, but assuming the <code>3</code> needs to be a parameter (maybe the whole <code>range(3)</code> should be?), and the two functions you're calling need some parameters that are loop variables, you could refactor the code:</p>
<pre><code> for y in range(3):
for x in range(3):
do_something(x, y)
for y1 in range(3):
for x1 in range(3):
do_something_else(x, y, x1, y1)
</code></pre>
<p>into, e.g.:</p>
<pre><code>def nestloop(n, *funcs):
head = funcs[0]
tail = funcs[1:]
for y in range(n):
for x in range(n):
yield head, x, y
if tail:
for subtup in nestloop(n, *tail):
yield subtup[:1] + (x, y) + subtup[1:]
for funcandargs in nestloop(3, do_something, do_something_else):
funcandargs[0](*funcandargs[1:])
</code></pre>
<p>The exact kind of refactoring will no doubt need to be tweaked for your exact purposes, but the general point that iterators (and usually in fact just simple generators) afford very nice refactorings of loops remains -- all the looping logic goes inside the generator, and the application-level code is left with simple <code>for</code> loops and actual application-relevant processing of the items yielded in the for loops.</p>
| 2 | 2009-08-15T00:59:33Z | [
"python",
"for-loop",
"nested-loops"
] |
How can I list the methods in a Python 2.5 module? | 1,280,787 | <p>I'm trying to use a Python library written in C that has no documentation of any kind. I want to use introspection to at least see what methods and classes are in the modules. Does somebody have a function or library I can use to list the functions (with argument lists) and classes (with methods and member variables) within a module? </p>
<p>I found <a href="http://www.diveintopython.net/power_of_introspection/index.html">this article</a> about Python introspection, but I'm pretty sure it doesn't apply to Python 2.5. Thanks for the help.</p>
| 19 | 2009-08-15T00:13:02Z | 1,280,796 | <p>The dir() functions shows all members a module has.</p>
| 2 | 2009-08-15T00:17:30Z | [
"python",
"introspection",
"python-2.5"
] |
How can I list the methods in a Python 2.5 module? | 1,280,787 | <p>I'm trying to use a Python library written in C that has no documentation of any kind. I want to use introspection to at least see what methods and classes are in the modules. Does somebody have a function or library I can use to list the functions (with argument lists) and classes (with methods and member variables) within a module? </p>
<p>I found <a href="http://www.diveintopython.net/power_of_introspection/index.html">this article</a> about Python introspection, but I'm pretty sure it doesn't apply to Python 2.5. Thanks for the help.</p>
| 19 | 2009-08-15T00:13:02Z | 1,280,800 | <p>Here are some things you can do at least:</p>
<pre><code>import module
print dir(module) # Find functions of interest.
# For each function of interest:
help(module.interesting_function)
print module.interesting_function.func_defaults
</code></pre>
| 43 | 2009-08-15T00:17:51Z | [
"python",
"introspection",
"python-2.5"
] |
How can I list the methods in a Python 2.5 module? | 1,280,787 | <p>I'm trying to use a Python library written in C that has no documentation of any kind. I want to use introspection to at least see what methods and classes are in the modules. Does somebody have a function or library I can use to list the functions (with argument lists) and classes (with methods and member variables) within a module? </p>
<p>I found <a href="http://www.diveintopython.net/power_of_introspection/index.html">this article</a> about Python introspection, but I'm pretty sure it doesn't apply to Python 2.5. Thanks for the help.</p>
| 19 | 2009-08-15T00:13:02Z | 1,280,817 | <p>Just this is pretty good too:</p>
<pre><code>import module
help(module)
</code></pre>
<p>It will print the docstring for the module, then list the contents of the module, printing their docstrings too.</p>
| 3 | 2009-08-15T00:25:24Z | [
"python",
"introspection",
"python-2.5"
] |
How can I list the methods in a Python 2.5 module? | 1,280,787 | <p>I'm trying to use a Python library written in C that has no documentation of any kind. I want to use introspection to at least see what methods and classes are in the modules. Does somebody have a function or library I can use to list the functions (with argument lists) and classes (with methods and member variables) within a module? </p>
<p>I found <a href="http://www.diveintopython.net/power_of_introspection/index.html">this article</a> about Python introspection, but I'm pretty sure it doesn't apply to Python 2.5. Thanks for the help.</p>
| 19 | 2009-08-15T00:13:02Z | 1,280,846 | <p>Mark Pilgrim's <a href="http://diveintopython.net/power_of_introspection/index.html" rel="nofollow">chapter 4</a>, which you mention, does actually apply just fine to Python 2.5 (and any other recent <code>2.*</code> version, thanks to backwards compatibility). Mark doesn't mention <code>help</code>, but I see other answers do.</p>
<p>One key bit that nobody (including Mark;-) seems to have mentioned is <a href="https://docs.python.org/2/library/inspect.html" rel="nofollow">inspect</a>, an excellent module in Python's standard library that really helps with advanced introspection.</p>
| 12 | 2009-08-15T00:44:24Z | [
"python",
"introspection",
"python-2.5"
] |
Scraping Ajax - Using python | 1,281,075 | <p>I'm trying to scrap a page in youtube with python which has lot of ajax in it</p>
<p>I've to call the java script each time to get the info. But i'm not really sure how to go about it. I'm using the urllib2 module to open URLs. Any help would be appreciated.</p>
| 2 | 2009-08-15T03:34:05Z | 1,281,111 | <p>Youtube (and everything else Google makes) have EXTENSIVE APIs already in place for giving you access to just about any and all data you could possibly want.</p>
<p>Take a look at <a href="http://code.google.com/apis/youtube/overview.html">The Youtube Data API</a> for more information.</p>
<p>I use urllib to make the API requests and ElementTree to parse the returned XML.</p>
| 6 | 2009-08-15T03:59:05Z | [
"python",
"ajax",
"screen-scraping"
] |
Scraping Ajax - Using python | 1,281,075 | <p>I'm trying to scrap a page in youtube with python which has lot of ajax in it</p>
<p>I've to call the java script each time to get the info. But i'm not really sure how to go about it. I'm using the urllib2 module to open URLs. Any help would be appreciated.</p>
| 2 | 2009-08-15T03:34:05Z | 1,281,115 | <p>Main problem is, you're violating the TOS (terms of service) for the youtube site. Youtube engineers and lawyers will do their professional best to track you down and make an example of you if you persist. If you're happy with that prospect, then, on you head be it -- technically, your best bet are <a href="http://pypi.python.org/pypi/python-spidermonkey">python-spidermonkey</a> and <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html">selenium</a>. I wanted to put the technical hints on record in case anybody in the future has needs like the ones your question's title indicates, <em>without</em> the legal issues you clearly have if you continue in this particular endeavor.</p>
| 6 | 2009-08-15T04:01:10Z | [
"python",
"ajax",
"screen-scraping"
] |
Scraping Ajax - Using python | 1,281,075 | <p>I'm trying to scrap a page in youtube with python which has lot of ajax in it</p>
<p>I've to call the java script each time to get the info. But i'm not really sure how to go about it. I'm using the urllib2 module to open URLs. Any help would be appreciated.</p>
| 2 | 2009-08-15T03:34:05Z | 1,281,746 | <p>As suggested, you should use the YouTube API to access the data made available legitimately.</p>
<p>Regarding the general question of scraping AJAX, you might want to consider the <a href="http://scrapy.org" rel="nofollow">scrapy framework</a>. It provides extensive support for crawling and scraping web sites and uses python-spidermonkey under the hood to access javascript links. </p>
| 0 | 2009-08-15T11:57:00Z | [
"python",
"ajax",
"screen-scraping"
] |
Scraping Ajax - Using python | 1,281,075 | <p>I'm trying to scrap a page in youtube with python which has lot of ajax in it</p>
<p>I've to call the java script each time to get the info. But i'm not really sure how to go about it. I'm using the urllib2 module to open URLs. Any help would be appreciated.</p>
| 2 | 2009-08-15T03:34:05Z | 3,134,226 | <p>Here is how I would do it: Install Firebug on Firefox, then turn the NET on in firebug and click on the desired link on YouTube. Now see what happens and what pages are requested. Find the one that are responsible for the AJAX part of page. Now you can use urllib or Mechanize to fetch the link. If you CAN pull the same content this way, then you have what you are looking for, then just parse the content. If you CAN'T pull the content this way, then that would suggest that the requested page might be looking at user login credentials, sessions info or other header fields such as HTTP_REFERER ... etc. Then you might want to look at something more extensive like the scrapy ... etc. I would suggest that you always follow the simple path first. Good luck and happy <strong>"responsibly"</strong> scraping! :)</p>
| 2 | 2010-06-28T16:28:13Z | [
"python",
"ajax",
"screen-scraping"
] |
Scraping Ajax - Using python | 1,281,075 | <p>I'm trying to scrap a page in youtube with python which has lot of ajax in it</p>
<p>I've to call the java script each time to get the info. But i'm not really sure how to go about it. I'm using the urllib2 module to open URLs. Any help would be appreciated.</p>
| 2 | 2009-08-15T03:34:05Z | 3,162,794 | <p>You could sniff the network traffic with something like <a href="http://www.wireshark.org/" rel="nofollow">Wireshark</a> then replay the HTTP calls via a scraping framework that is robust enough to deal with AJAX, such as <a href="http://scrapy.org/" rel="nofollow">scraPY</a>.</p>
| 0 | 2010-07-02T01:45:05Z | [
"python",
"ajax",
"screen-scraping"
] |
What's the Ruby equivalent of Python's os.walk? | 1,281,090 | <p>Does anyone know if there's an existing module/function inside Ruby to traverse file system directories and files? I'm looking for something similar to Python's <code>os.walk</code>. The closest module I've found is <code>Find</code> but requires some extra work to do the traversal.</p>
<p>The Python code looks like the following:</p>
<pre><code>for root, dirs, files in os.walk('.'):
for name in files:
print name
for name in dirs:
print name
</code></pre>
| 20 | 2009-08-15T03:40:16Z | 1,281,103 | <p>The following will print all files recursively. Then you can use File.directory? to see if the it is a directory or a file.</p>
<pre><code>Dir['**/*'].each { |f| print f }
</code></pre>
| 20 | 2009-08-15T03:51:30Z | [
"python",
"ruby"
] |
What's the Ruby equivalent of Python's os.walk? | 1,281,090 | <p>Does anyone know if there's an existing module/function inside Ruby to traverse file system directories and files? I'm looking for something similar to Python's <code>os.walk</code>. The closest module I've found is <code>Find</code> but requires some extra work to do the traversal.</p>
<p>The Python code looks like the following:</p>
<pre><code>for root, dirs, files in os.walk('.'):
for name in files:
print name
for name in dirs:
print name
</code></pre>
| 20 | 2009-08-15T03:40:16Z | 1,281,222 | <p><a href="http://www.ruby-doc.org/stdlib-2.0/libdoc/find/rdoc/Find.html" rel="nofollow">Find</a> seems pretty simple to me:</p>
<pre><code>require "find"
Find.find('mydir'){|f| puts f}
</code></pre>
| 8 | 2009-08-15T05:17:15Z | [
"python",
"ruby"
] |
What's the Ruby equivalent of Python's os.walk? | 1,281,090 | <p>Does anyone know if there's an existing module/function inside Ruby to traverse file system directories and files? I'm looking for something similar to Python's <code>os.walk</code>. The closest module I've found is <code>Find</code> but requires some extra work to do the traversal.</p>
<p>The Python code looks like the following:</p>
<pre><code>for root, dirs, files in os.walk('.'):
for name in files:
print name
for name in dirs:
print name
</code></pre>
| 20 | 2009-08-15T03:40:16Z | 1,282,690 | <pre><code>require 'pathname'
def os_walk(dir)
root = Pathname(dir)
files, dirs = [], []
Pathname(root).find do |path|
unless path == root
dirs << path if path.directory?
files << path if path.file?
end
end
[root, files, dirs]
end
root, files, dirs = os_walk('.')
</code></pre>
| 3 | 2009-08-15T19:50:27Z | [
"python",
"ruby"
] |
Why can't I set a global variable in Python? | 1,281,184 | <p>How do global variables work in Python? I know global variables are evil, I'm just experimenting.</p>
<p>This does not work in python:</p>
<pre><code>G = None
def foo():
if G is None:
G = 1
foo()
</code></pre>
<p>I get an error:</p>
<pre><code>UnboundLocalError: local variable 'G' referenced before assignment
</code></pre>
<p>What am I doing wrong?</p>
| 17 | 2009-08-15T04:49:48Z | 1,281,186 | <p>You need the <a href="http://www.python.org/doc/ref/global.html"><code>global</code></a> statement:</p>
<pre><code>def foo():
global G
if G is None:
G = 1
</code></pre>
<p>In Python, variables <em>that you assign to</em> become local variables by default. You need to use <code>global</code> to declare them as global variables. On the other hand, variables that you <em>refer to but do not assign to</em> do not automatically become local variables. These variables refer to the closest variable in an enclosing scope.</p>
<p>Python 3.x introduces the <a href="http://docs.python.org/dev/3.0/reference/simple%5Fstmts.html#grammar-token-nonlocal%5Fstmt"><code>nonlocal</code></a> statement which is analogous to <code>global</code>, but binds the variable to its nearest enclosing scope. For example:</p>
<pre><code>def foo():
x = 5
def bar():
nonlocal x
x = x * 2
bar()
return x
</code></pre>
<p>This function returns 10 when called.</p>
| 43 | 2009-08-15T04:50:57Z | [
"python",
"global-variables"
] |
Why can't I set a global variable in Python? | 1,281,184 | <p>How do global variables work in Python? I know global variables are evil, I'm just experimenting.</p>
<p>This does not work in python:</p>
<pre><code>G = None
def foo():
if G is None:
G = 1
foo()
</code></pre>
<p>I get an error:</p>
<pre><code>UnboundLocalError: local variable 'G' referenced before assignment
</code></pre>
<p>What am I doing wrong?</p>
| 17 | 2009-08-15T04:49:48Z | 1,281,190 | <p>You still have to declare G as global, from within that function:</p>
<pre><code>G = None
def foo():
global G
if G is None:
G = 1
foo()
print G
</code></pre>
<p>which simply outputs</p>
<pre><code>1
</code></pre>
| 4 | 2009-08-15T04:51:33Z | [
"python",
"global-variables"
] |
Why can't I set a global variable in Python? | 1,281,184 | <p>How do global variables work in Python? I know global variables are evil, I'm just experimenting.</p>
<p>This does not work in python:</p>
<pre><code>G = None
def foo():
if G is None:
G = 1
foo()
</code></pre>
<p>I get an error:</p>
<pre><code>UnboundLocalError: local variable 'G' referenced before assignment
</code></pre>
<p>What am I doing wrong?</p>
| 17 | 2009-08-15T04:49:48Z | 1,281,193 | <p>Define G as global in the function like this:</p>
<pre><code>#!/usr/bin/python
G = None;
def foo():
global G
if G is None:
G = 1;
print G;
foo();
</code></pre>
<p>The above python prints <code>1</code>. </p>
<p>Using global variables like this is bad practice because: <a href="http://c2.com/cgi/wiki?GlobalVariablesAreBad" rel="nofollow">http://c2.com/cgi/wiki?GlobalVariablesAreBad</a></p>
| 1 | 2009-08-15T04:54:34Z | [
"python",
"global-variables"
] |
Why can't I set a global variable in Python? | 1,281,184 | <p>How do global variables work in Python? I know global variables are evil, I'm just experimenting.</p>
<p>This does not work in python:</p>
<pre><code>G = None
def foo():
if G is None:
G = 1
foo()
</code></pre>
<p>I get an error:</p>
<pre><code>UnboundLocalError: local variable 'G' referenced before assignment
</code></pre>
<p>What am I doing wrong?</p>
| 17 | 2009-08-15T04:49:48Z | 1,281,207 | <p>You need to declare <code>G</code> as <code>global</code>, but as for why: whenever you refer to a variable inside a function, if you <em>set</em> the variable anywhere in that function, Python assumes that it's a local variable. So if a local variable by that name doesn't exist at that point in the code, you'll get the <code>UnboundLocalError</code>. If you actually meant to refer to a global variable, as in your question, you need the <code>global</code> keyword to tell Python that's what you meant.</p>
<p>If you don't assign to the variable anywhere in the function, but only access its value, Python will use the global variable by that name if one exists. So you could do:</p>
<pre><code>G = None
def foo():
if G is None:
print G
foo()
</code></pre>
<p>This code prints <code>None</code> and does not throw the UnboundLocalError.</p>
| 6 | 2009-08-15T05:04:52Z | [
"python",
"global-variables"
] |
DOCTEST==argv[0] as a convention? | 1,281,385 | <p>In a bit of Python I'm writing (a command line and filter testing tool: <i><a href="http://bitbucket.org/jimd/claft/" rel="nofollow">claft</a></i>) I wanted a simple way to invoke the built-in test suite (<i>doctest</i>) and I decided on the following:</p>
<pre><code>if 'DOCTEST' in os.environ and os.environ['DOCTEST']==sys.argv[0]:
_runDocTests()
sys.exit()
</code></pre>
<p>Thus if the DOCTEST variable is set for some other program I'll just ignore it. In fact my test for this is just: DOCTEST=./claft ./claft or if I want to be verbose I can use: DOCTEST=./claft VERBOSE=1 ./claft So even if I leave DOCTEST=./claft in my environment the test code will only run when I invoke my program from within its own directory. If I switch to one of my test suites and invoke it using a relative PATH then I'm safe from inadvertently triggering this function.</p>
<p>Has anyone else used this sort of convention?</p>
<p>What are other suggestions or best practices for avoiding conflicts among environment variable names? For providing "hidden" access to test harness functionality?</p>
<p>(Also, if anyone wants to play with <i>claft</i> please feel free to give it a spin. It's pretty ugly code for now, and is barely a proof of concept. But it is minimally functional. It's also been a nice way to teach myself how to use Mercurial and bitbucket. The wiki and issue tracking are the best places to post feedback about <i>claft</i>).</p>
| 0 | 2009-08-15T07:25:54Z | 1,281,446 | <p>Since you're already doing command-line parsing, why not just add a <code>--selftest</code> option? You won't have to worry about any conflicts that way, and invocation will be easier.</p>
| 3 | 2009-08-15T08:10:32Z | [
"python",
"unit-testing",
"testing",
"doctest"
] |
DOCTEST==argv[0] as a convention? | 1,281,385 | <p>In a bit of Python I'm writing (a command line and filter testing tool: <i><a href="http://bitbucket.org/jimd/claft/" rel="nofollow">claft</a></i>) I wanted a simple way to invoke the built-in test suite (<i>doctest</i>) and I decided on the following:</p>
<pre><code>if 'DOCTEST' in os.environ and os.environ['DOCTEST']==sys.argv[0]:
_runDocTests()
sys.exit()
</code></pre>
<p>Thus if the DOCTEST variable is set for some other program I'll just ignore it. In fact my test for this is just: DOCTEST=./claft ./claft or if I want to be verbose I can use: DOCTEST=./claft VERBOSE=1 ./claft So even if I leave DOCTEST=./claft in my environment the test code will only run when I invoke my program from within its own directory. If I switch to one of my test suites and invoke it using a relative PATH then I'm safe from inadvertently triggering this function.</p>
<p>Has anyone else used this sort of convention?</p>
<p>What are other suggestions or best practices for avoiding conflicts among environment variable names? For providing "hidden" access to test harness functionality?</p>
<p>(Also, if anyone wants to play with <i>claft</i> please feel free to give it a spin. It's pretty ugly code for now, and is barely a proof of concept. But it is minimally functional. It's also been a nice way to teach myself how to use Mercurial and bitbucket. The wiki and issue tracking are the best places to post feedback about <i>claft</i>).</p>
| 0 | 2009-08-15T07:25:54Z | 1,285,309 | <p>Another <em>hackish</em> way to avoid namespace conflicts with the environment: looks for myprogname_DEBUG or the like. </p>
| 0 | 2009-08-16T20:46:09Z | [
"python",
"unit-testing",
"testing",
"doctest"
] |
How to get the desktop resolution in Mac via Python? | 1,281,397 | <p>Trying to write a python application that downloads images from an RSS feed, and makes a composite background. How do I get the current desktop resolution on Mac OS X (leopard?)</p>
| 5 | 2009-08-15T07:35:13Z | 1,281,568 | <p>As usual, using features that are binded to an OS is a very bad idea. There are hundred of portable libs in Python that give you access to that information. The first that comes to my mind is of course pygame :</p>
<pre><code>import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,480), FULLSCREEN)
x, y = screen.get_size()
</code></pre>
<p>But I guess cocoa do just as good, and therefor wxpython or qt is your friend. I suppose on Windows you did something like this :</p>
<pre><code>from win32api import GetSystemMetrics
width = GetSystemMetrics [0]
height = GetSystemMetrics [1]
</code></pre>
<p>Sure it's easier, but won't work on Mac, Linux, BSD, Solaris, and probably nor very later windows version.</p>
| 1 | 2009-08-15T10:01:06Z | [
"python",
"osx"
] |
How to get the desktop resolution in Mac via Python? | 1,281,397 | <p>Trying to write a python application that downloads images from an RSS feed, and makes a composite background. How do I get the current desktop resolution on Mac OS X (leopard?)</p>
| 5 | 2009-08-15T07:35:13Z | 1,281,659 | <p>With Pyobjc something like this should work. Pyobjc comes with Leopard.</p>
<pre><code>from AppKit import NSScreen
print NSScreen.mainScreen().frame()
</code></pre>
<p>With that, you can also grab the width and height.</p>
<pre><code>NSScreen.mainScreen().frame().width
NSScreen.mainScreen().frame().height
</code></pre>
| 10 | 2009-08-15T11:07:52Z | [
"python",
"osx"
] |
How to get the desktop resolution in Mac via Python? | 1,281,397 | <p>Trying to write a python application that downloads images from an RSS feed, and makes a composite background. How do I get the current desktop resolution on Mac OS X (leopard?)</p>
| 5 | 2009-08-15T07:35:13Z | 8,203,217 | <p>If you are doing this from a LaunchAgent script, you may need to drop down to CoreGraphics primitives rather than AppKit-level methods. Working on this today, my LaunchAgent-loaded script gets <code>None</code> back from <code>NSScreen.mainScreen()</code>, but works fine if I load it from a terminal in my session.</p>
<pre><code>from Quartz import CGDisplayBounds
from Quartz import CGMainDisplayID
def screen_size():
mainMonitor = CGDisplayBounds(CGMainDisplayID())
return (mainMonitor.size.width, mainMonitor.size.height)
</code></pre>
| 3 | 2011-11-20T17:19:54Z | [
"python",
"osx"
] |
Accessing elements with offsets in Python's for .. in loops | 1,281,752 | <p>I've been mucking around a bit with Python, and I've gathered that it's usually better (or 'pythonic') to use</p>
<pre><code>for x in SomeArray:
</code></pre>
<p>rather than the more C-style</p>
<pre><code>for i in range(0, len(SomeArray)):
</code></pre>
<p>I do see the benefits in this, mainly cleaner code, and the ability to use the nice <code>map()</code> and related functions. However, I am quite often faced with the situation where I would like to simultaneously access elements of varying offsets in the array. For example, I might want to add the current element to the element two steps behind it. Is there a way to do this without resorting to explicit indices?</p>
| 7 | 2009-08-15T12:00:36Z | 1,281,758 | <p>The way to do this in Python is:</p>
<pre><code>for i, x in enumerate(SomeArray):
print i, x
</code></pre>
<p>The <a href="http://docs.python.org/library/functions.html#enumerate"><code>enumerate</code></a> generator produces a sequence of 2-tuples, each containing the array index and the element.</p>
| 13 | 2009-08-15T12:03:33Z | [
"python",
"loops"
] |
Accessing elements with offsets in Python's for .. in loops | 1,281,752 | <p>I've been mucking around a bit with Python, and I've gathered that it's usually better (or 'pythonic') to use</p>
<pre><code>for x in SomeArray:
</code></pre>
<p>rather than the more C-style</p>
<pre><code>for i in range(0, len(SomeArray)):
</code></pre>
<p>I do see the benefits in this, mainly cleaner code, and the ability to use the nice <code>map()</code> and related functions. However, I am quite often faced with the situation where I would like to simultaneously access elements of varying offsets in the array. For example, I might want to add the current element to the element two steps behind it. Is there a way to do this without resorting to explicit indices?</p>
| 7 | 2009-08-15T12:00:36Z | 1,282,034 | <p>List indexing and zip() are your friends.</p>
<p>Here's my answer for your more specific question:</p>
<blockquote>
<p>I might want to add the current element to the element two steps behind it. Is there a way to do this without resorting to explicit indices?</p>
</blockquote>
<pre><code>arr = range(10)
[i+j for i,j in zip(arr[:-2], arr[2:])]
</code></pre>
<p>You can also use the module <a href="http://www.scipy.org/">numpy</a> if you intend to work on numerical arrays. For example, the above code can be more elegantly written as:</p>
<pre><code>import numpy
narr = numpy.arange(10)
narr[:-2] + narr[2:]
</code></pre>
<p>Adding the nth element to the (n-2)th element is equivalent to adding the mth element to the (m+2) element (for the mathematically inclined, we performed the substitution n->m+2). The range of n is [2, len(arr)) and the range of m is [0, len(arr)-2). Note the brackets and parenthesis. The elements from 0 to len(arr)-3 (you exclude the last two elements) is indexed as [:-2] while elements from 2 to len(arr)-1 (you exclude the first two elements) is indexed as [2:].</p>
<p>I assume that you already know list comprehensions.</p>
| 6 | 2009-08-15T14:43:54Z | [
"python",
"loops"
] |
Making sure that psycopg2 database connection alive | 1,281,875 | <p>I have a python application that opens a database connection that can hang online for an hours, but sometimes the database server reboots and while python still have the connection it won't work with <code>OperationalError</code> exception.</p>
<p>So I'm looking for any reliable method to "ping" the database and know that connection is alive. I've checked a psycopg2 documentation but can't find anything like that. Sure I can issue some simple SQL statement like <code>SELECT 1</code> and catch the exception, but I hope there is a native method, something like PHP <a href="http://us2.php.net/manual/en/function.pg-connection-status.php">pg_connection_status</a></p>
<p>Thanks.</p>
| 7 | 2009-08-15T13:17:09Z | 1,282,019 | <p><code>pg_connection_status</code> is implemented using PQstatus. psycopg doesn't expose that API, so the check is not available. The only two places psycopg calls PQstatus itself is when a new connection is made, and at the beginning of execute. So yes, you will need to issue a simple SQL statement to find out whether the connection is still there.</p>
| 8 | 2009-08-15T14:36:08Z | [
"python",
"database",
"connection",
"psycopg2"
] |
Making sure that psycopg2 database connection alive | 1,281,875 | <p>I have a python application that opens a database connection that can hang online for an hours, but sometimes the database server reboots and while python still have the connection it won't work with <code>OperationalError</code> exception.</p>
<p>So I'm looking for any reliable method to "ping" the database and know that connection is alive. I've checked a psycopg2 documentation but can't find anything like that. Sure I can issue some simple SQL statement like <code>SELECT 1</code> and catch the exception, but I hope there is a native method, something like PHP <a href="http://us2.php.net/manual/en/function.pg-connection-status.php">pg_connection_status</a></p>
<p>Thanks.</p>
| 7 | 2009-08-15T13:17:09Z | 18,708,605 | <p>This question is really old, but still pops up on Google searches so I think it's valuable to know that the <code>psycopg2.connection</code> instance now has a <a href="http://initd.org/psycopg/docs/connection.html#connection.closed"><code>closed</code> attribute</a> that will be <code>0</code> when the connection is open, and greater than zero when the connection is closed. The following example should demonstrate:</p>
<pre><code>import psycopg2
import subprocess
connection = psycopg2.connect(
database=database,
user=username,
password=password,
host=host,
port=port
)
print connection.closed # 0
# restart the db externally
subprocess.check_call("sudo /etc/init.d/postgresql restart", shell=True)
# this query will fail because the db is no longer connected
try:
cur = connection.cursor()
cur.execute('SELECT 1')
except psycopg2.OperationalError:
pass
print connection.closed # 2
</code></pre>
| 13 | 2013-09-09T23:29:24Z | [
"python",
"database",
"connection",
"psycopg2"
] |
Making sure that psycopg2 database connection alive | 1,281,875 | <p>I have a python application that opens a database connection that can hang online for an hours, but sometimes the database server reboots and while python still have the connection it won't work with <code>OperationalError</code> exception.</p>
<p>So I'm looking for any reliable method to "ping" the database and know that connection is alive. I've checked a psycopg2 documentation but can't find anything like that. Sure I can issue some simple SQL statement like <code>SELECT 1</code> and catch the exception, but I hope there is a native method, something like PHP <a href="http://us2.php.net/manual/en/function.pg-connection-status.php">pg_connection_status</a></p>
<p>Thanks.</p>
| 7 | 2009-08-15T13:17:09Z | 20,090,982 | <p><code>connection.closed</code> does not reflect a connection closed/severed by the server. It only indicates a connection closed by the client using <code>connection.close()</code></p>
<p>In order to make sure a connection is still valid, read the property <code>connection.isolation_level</code>. This will raise an OperationalError with pgcode == "57P01" in case the connection is dead. </p>
<p>This adds a bit of latency for a roundtrip to the database but should be preferable to a <code>SELECT 1</code> or similar.</p>
<pre><code>import psycopg2
dsn = "dbname=postgres"
conn = psycopg2.connect(dsn)
# ... some time elapses, e.g. connection within a connection pool
try:
connection.isolation_level
except OperationalError as oe:
conn = psycopg2.connect(dsn)
c = conn.cursor()
c.execute("SELECT 1")
</code></pre>
| 3 | 2013-11-20T08:39:32Z | [
"python",
"database",
"connection",
"psycopg2"
] |
Copying files to directories as specified in a file list with python | 1,281,944 | <p>I have a bunch of files in a single directory that I would like to organize in sub-directories.</p>
<p>This directory structure (which file would go in which directory) is specified in a file list that looks like this:</p>
<p><code>Directory: Music\</code></p>
<p><code> -> 01-some_song1.mp3</code></p>
<p><code> -> 02-some_song2.mp3</code></p>
<p><code> -> 03-some_song3.mp3</code></p>
<p><code>Directory: Images\</code></p>
<p><code> -> 01-some_image1.jpg</code></p>
<p><code> -> 02-some_image2.jpg</code></p>
<p><code>......................</code></p>
<p>I was thinking of extracting the data (directory name and file name) and store it in a dictionary that would look like this:</p>
<pre><code>dictionary = {'Music': (01-some_song1.mp3, 02-some_song2.mp3,
03-some_song3.mp3),
'Images': (01-some_image1.jpg, 02-some_image2.jpg),
......................................................
}
</code></pre>
<p>After that I would copy/move the files in their respective directories.</p>
<p>I already extracted the directory names and created the empty dirs.</p>
<p>For the dictionary values I tried to get a list of lists by doing the following:</p>
<pre><code>def get_values(file):
values = []
tmp = []
pattern = re.compile(r'^-> (.+?)$')
for line in file:
if line.strip().startswith('->'):
match = re.search(pattern, line.strip())
if match:
tmp.append(match.group(1))
elif line.strip().startswith('Directory'):
values.append(tmp)
del tmp[:]
return values
</code></pre>
<p>This doesn't seem to work. Each list from the <code>values</code> list contains the same 4 file names over and over again.</p>
<p>What am I doing wrong?</p>
<p>I would also like to know what are the other ways of doing this whole thing? I'm sure there's a better/simpler/cleaner way.</p>
| 1 | 2009-08-15T13:50:33Z | 1,281,966 | <p>I think that the cause is that you are reusing always the same list. </p>
<p><code>del tmp[:]</code> clears the list and doesn't create a new instance. In your case, you need to create a new list by calling <code>tmp = []</code></p>
<p>Following fix should work (I didn't test it)</p>
<pre>
def get_values(file):
values = []
tmp = []
pattern = re.compile(r'^-> (.+?)$')
for line in file:
if line.strip().startswith('->'):
match = re.search(pattern, line.strip())
if match:
tmp.append(match.group(1))
elif line.strip().startswith('Directory'):
values.append(tmp)
tmp = []
return values
</pre>
| 1 | 2009-08-15T14:01:13Z | [
"python",
"file",
"copy",
"directory"
] |
Copying files to directories as specified in a file list with python | 1,281,944 | <p>I have a bunch of files in a single directory that I would like to organize in sub-directories.</p>
<p>This directory structure (which file would go in which directory) is specified in a file list that looks like this:</p>
<p><code>Directory: Music\</code></p>
<p><code> -> 01-some_song1.mp3</code></p>
<p><code> -> 02-some_song2.mp3</code></p>
<p><code> -> 03-some_song3.mp3</code></p>
<p><code>Directory: Images\</code></p>
<p><code> -> 01-some_image1.jpg</code></p>
<p><code> -> 02-some_image2.jpg</code></p>
<p><code>......................</code></p>
<p>I was thinking of extracting the data (directory name and file name) and store it in a dictionary that would look like this:</p>
<pre><code>dictionary = {'Music': (01-some_song1.mp3, 02-some_song2.mp3,
03-some_song3.mp3),
'Images': (01-some_image1.jpg, 02-some_image2.jpg),
......................................................
}
</code></pre>
<p>After that I would copy/move the files in their respective directories.</p>
<p>I already extracted the directory names and created the empty dirs.</p>
<p>For the dictionary values I tried to get a list of lists by doing the following:</p>
<pre><code>def get_values(file):
values = []
tmp = []
pattern = re.compile(r'^-> (.+?)$')
for line in file:
if line.strip().startswith('->'):
match = re.search(pattern, line.strip())
if match:
tmp.append(match.group(1))
elif line.strip().startswith('Directory'):
values.append(tmp)
del tmp[:]
return values
</code></pre>
<p>This doesn't seem to work. Each list from the <code>values</code> list contains the same 4 file names over and over again.</p>
<p>What am I doing wrong?</p>
<p>I would also like to know what are the other ways of doing this whole thing? I'm sure there's a better/simpler/cleaner way.</p>
| 1 | 2009-08-15T13:50:33Z | 1,282,027 | <p>no need to use regular expression </p>
<pre><code>d = {}
for line in open("file"):
line=line.strip()
if line.endswith("\\"):
directory = line.split(":")[-1].strip().replace("\\","")
d.setdefault(directory,[])
if line.startswith("->"):
song=line.split(" ")[-1]
d[directory].append(song)
print d
</code></pre>
<p>output</p>
<pre><code># python python.py
{'Images': ['01-some_image1.jpg', '02-some_image2.jpg'], 'Music': ['01-some_song1.mp3', '02-some_song2.mp3', '03-some_song3.mp3']}
</code></pre>
| 1 | 2009-08-15T14:41:01Z | [
"python",
"file",
"copy",
"directory"
] |
Copying files to directories as specified in a file list with python | 1,281,944 | <p>I have a bunch of files in a single directory that I would like to organize in sub-directories.</p>
<p>This directory structure (which file would go in which directory) is specified in a file list that looks like this:</p>
<p><code>Directory: Music\</code></p>
<p><code> -> 01-some_song1.mp3</code></p>
<p><code> -> 02-some_song2.mp3</code></p>
<p><code> -> 03-some_song3.mp3</code></p>
<p><code>Directory: Images\</code></p>
<p><code> -> 01-some_image1.jpg</code></p>
<p><code> -> 02-some_image2.jpg</code></p>
<p><code>......................</code></p>
<p>I was thinking of extracting the data (directory name and file name) and store it in a dictionary that would look like this:</p>
<pre><code>dictionary = {'Music': (01-some_song1.mp3, 02-some_song2.mp3,
03-some_song3.mp3),
'Images': (01-some_image1.jpg, 02-some_image2.jpg),
......................................................
}
</code></pre>
<p>After that I would copy/move the files in their respective directories.</p>
<p>I already extracted the directory names and created the empty dirs.</p>
<p>For the dictionary values I tried to get a list of lists by doing the following:</p>
<pre><code>def get_values(file):
values = []
tmp = []
pattern = re.compile(r'^-> (.+?)$')
for line in file:
if line.strip().startswith('->'):
match = re.search(pattern, line.strip())
if match:
tmp.append(match.group(1))
elif line.strip().startswith('Directory'):
values.append(tmp)
del tmp[:]
return values
</code></pre>
<p>This doesn't seem to work. Each list from the <code>values</code> list contains the same 4 file names over and over again.</p>
<p>What am I doing wrong?</p>
<p>I would also like to know what are the other ways of doing this whole thing? I'm sure there's a better/simpler/cleaner way.</p>
| 1 | 2009-08-15T13:50:33Z | 1,282,076 | <p>If you use collections.defaultdict(list), you get a list that dictionary whose elements are lists. If the key is not found, it is added with a value of empty list, so you can start appending to the list immediately. That's what this line does:</p>
<pre><code>d[dir].append(match.group(1))
</code></pre>
<p>It creates the directory name as a key if it does not exist and appends the file name found to the list.</p>
<p>BTW, if you are having problems getting your regexes to work, try creating them with the debug flag. I can't remember the symbolic name, but the number is 128. So if you do this:</p>
<pre><code>file_regex = re.compile(r'^-> (.+?)$', 128)
</code></pre>
<p>You get this additional output:</p>
<pre><code>at at_beginning
literal 45
literal 62
literal 32
subpattern 1
min_repeat 1 65535
any None
at at_end
</code></pre>
<p>And you can see that there is a start line match plus '-> ' (for 45 62 32) and then a repeated any pattern and end of line match. Very useful for debugging.</p>
<p>Code:</p>
<pre><code>from __future__ import with_statement
import re
import collections
def get_values(file):
d = collections.defaultdict(list)
dir = ""
dir_regex = re.compile(r'^Directory: (.+?)\\$')
file_regex = re.compile(r'\-\> (.+?)$')
with open(file) as f:
for line in f:
line = line.strip()
match = dir_regex.search(line)
if match:
dir = match.group(1)
else:
match = file_regex.search(line)
if match:
d[dir].append(match.group(1))
return d
if __name__ == '__main__':
d = get_values('test_file')
for k, v in d.items():
print k, v
</code></pre>
<p>Result:</p>
<pre><code>Images ['01-some_image1.jpg', '02-some_image2.jpg']
Music ['01-some_song1.mp3', '02-some_song2.mp3', '03-some_song3.mp3']
</code></pre>
| 0 | 2009-08-15T15:02:56Z | [
"python",
"file",
"copy",
"directory"
] |
Program invoking: at least one command line parameter | 1,282,347 | <p>I'm trying to check that a user of this code runs this program from command line using only one command line parameter (the name of the file). When I run this code like this (I'm on windows)</p>
<pre><code>C:\>python program.py
Usage: program.py <file.txt>
C:\>
</code></pre>
<p>Right. But when I run this program using a file I want to manipulate, I get nothing printed:</p>
<pre><code>C:\>python program.py file.txt
C:\>
</code></pre>
<p>Where's the problem, my code is here</p>
<pre><code>#!/Python26/
# -*- coding: utf-8 -*-
import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <file.txt>" % (argv[0],))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
f = open(sys.argv[1])
lines = f.readlines()
f.close()
for line in lines:
line = line.strip()
etc...
</code></pre>
| 2 | 2009-08-15T17:07:29Z | 1,282,354 | <p>Here's your problem:</p>
<pre><code>def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <file.txt>" % (argv[0],))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
</code></pre>
<p>Your main function returns 1 if <code>len(argv) < 2</code>, otherwise it returns <code>None</code>. Nothing after <code>if __name__ == "__main__"</code> is evaluated.</p>
<p>As a minor aside, you don't need to make your string-formatting argument a tuple if it is only one item. This is equally valid, if not a little more clear:</p>
<pre><code>sys.stderr.write("Usage: %s <file.txt>" % argv[0])
</code></pre>
| 0 | 2009-08-15T17:12:04Z | [
"python"
] |
Program invoking: at least one command line parameter | 1,282,347 | <p>I'm trying to check that a user of this code runs this program from command line using only one command line parameter (the name of the file). When I run this code like this (I'm on windows)</p>
<pre><code>C:\>python program.py
Usage: program.py <file.txt>
C:\>
</code></pre>
<p>Right. But when I run this program using a file I want to manipulate, I get nothing printed:</p>
<pre><code>C:\>python program.py file.txt
C:\>
</code></pre>
<p>Where's the problem, my code is here</p>
<pre><code>#!/Python26/
# -*- coding: utf-8 -*-
import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <file.txt>" % (argv[0],))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
f = open(sys.argv[1])
lines = f.readlines()
f.close()
for line in lines:
line = line.strip()
etc...
</code></pre>
| 2 | 2009-08-15T17:07:29Z | 1,282,355 | <p>You need to move the <code>f = open...</code> and beyond into the main function. As it stands, it never gets executed because execution ends at the sys.exit call.</p>
<p>[EDIT] Structuring a module this way is a common Python idiom, BTW. In this way, a file may contain class and function definitions which can be imported by another module and it can also contain code, for example, tests, that is executed only when the file is run directly as a script.</p>
| 4 | 2009-08-15T17:12:30Z | [
"python"
] |
Program invoking: at least one command line parameter | 1,282,347 | <p>I'm trying to check that a user of this code runs this program from command line using only one command line parameter (the name of the file). When I run this code like this (I'm on windows)</p>
<pre><code>C:\>python program.py
Usage: program.py <file.txt>
C:\>
</code></pre>
<p>Right. But when I run this program using a file I want to manipulate, I get nothing printed:</p>
<pre><code>C:\>python program.py file.txt
C:\>
</code></pre>
<p>Where's the problem, my code is here</p>
<pre><code>#!/Python26/
# -*- coding: utf-8 -*-
import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <file.txt>" % (argv[0],))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
f = open(sys.argv[1])
lines = f.readlines()
f.close()
for line in lines:
line = line.strip()
etc...
</code></pre>
| 2 | 2009-08-15T17:07:29Z | 1,282,358 | <p>I guess you want:</p>
<pre><code>#!/Python26/
# -*- coding: utf-8 -*-
import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <file.txt>" % (argv[0],))
return 1
f = open(sys.argv[1])
lines = f.readlines()
f.close()
for line in lines:
line = line.strip()
etc...
if __name__ == "__main__":
sys.exit(main(sys.argv))
</code></pre>
| 3 | 2009-08-15T17:14:56Z | [
"python"
] |
Program invoking: at least one command line parameter | 1,282,347 | <p>I'm trying to check that a user of this code runs this program from command line using only one command line parameter (the name of the file). When I run this code like this (I'm on windows)</p>
<pre><code>C:\>python program.py
Usage: program.py <file.txt>
C:\>
</code></pre>
<p>Right. But when I run this program using a file I want to manipulate, I get nothing printed:</p>
<pre><code>C:\>python program.py file.txt
C:\>
</code></pre>
<p>Where's the problem, my code is here</p>
<pre><code>#!/Python26/
# -*- coding: utf-8 -*-
import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <file.txt>" % (argv[0],))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
f = open(sys.argv[1])
lines = f.readlines()
f.close()
for line in lines:
line = line.strip()
etc...
</code></pre>
| 2 | 2009-08-15T17:07:29Z | 1,282,362 | <pre><code>import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <file.txt>" % (argv[0],))
return 1
f = open(sys.argv[1])
lines = f.readlines()
f.close()
for line in lines:
line = line.strip()
etc...
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
</code></pre>
| 1 | 2009-08-15T17:16:10Z | [
"python"
] |
Program invoking: at least one command line parameter | 1,282,347 | <p>I'm trying to check that a user of this code runs this program from command line using only one command line parameter (the name of the file). When I run this code like this (I'm on windows)</p>
<pre><code>C:\>python program.py
Usage: program.py <file.txt>
C:\>
</code></pre>
<p>Right. But when I run this program using a file I want to manipulate, I get nothing printed:</p>
<pre><code>C:\>python program.py file.txt
C:\>
</code></pre>
<p>Where's the problem, my code is here</p>
<pre><code>#!/Python26/
# -*- coding: utf-8 -*-
import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <file.txt>" % (argv[0],))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
f = open(sys.argv[1])
lines = f.readlines()
f.close()
for line in lines:
line = line.strip()
etc...
</code></pre>
| 2 | 2009-08-15T17:07:29Z | 1,282,532 | <p>I notice the peculiar fact that everybody's code is suggesting that your <code>main</code> should ignore its arguments (except for checking it has enough) and reach back right into sys.argv instead. That's truly weird and I can't imagine any case where it would be reasonable -- makes main hard to reuse and surprising if this module ever gets imported, hard to test, and all without any advantage whatsoever with respect to the obvious, plain way to do it.</p>
<p>So, the way I recommend you to code this is, instead:</p>
<pre><code>import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <file.txt>" % argv[0])
return 1
with open(argv[1]) as f:
for line in f:
line = line.strip()
# etc, etc...
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
</code></pre>
<p>You'll notice a few more suggested changes in this variant -- for example, I'm assuming you're using the current production version of Python, 2.6, so that the <code>with</code> statement is available (in 2.5 it needed a <code>from __future__ import</code>), etc, etc. But the main point is, a function should use its arguments, not reach back into a different module to grab them all over again when they've already been passed to it!-)</p>
| 2 | 2009-08-15T18:39:12Z | [
"python"
] |
Program invoking: at least one command line parameter | 1,282,347 | <p>I'm trying to check that a user of this code runs this program from command line using only one command line parameter (the name of the file). When I run this code like this (I'm on windows)</p>
<pre><code>C:\>python program.py
Usage: program.py <file.txt>
C:\>
</code></pre>
<p>Right. But when I run this program using a file I want to manipulate, I get nothing printed:</p>
<pre><code>C:\>python program.py file.txt
C:\>
</code></pre>
<p>Where's the problem, my code is here</p>
<pre><code>#!/Python26/
# -*- coding: utf-8 -*-
import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <file.txt>" % (argv[0],))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
f = open(sys.argv[1])
lines = f.readlines()
f.close()
for line in lines:
line = line.strip()
etc...
</code></pre>
| 2 | 2009-08-15T17:07:29Z | 24,611,790 | <p>Please be aware that depending on your Python installation (you said initially you were on Windows), the numbering of command line arguments can be off by one. As it is good practice to write portable code (no matter whether you plan to run it somewhere else, sooner or later this <em>always</em> pays off), I'd recommend to use the <a href="https://docs.python.org/2.7/library/argparse.html" rel="nofollow"><code>argparse</code></a> module, which puts you on the safe side here. By using it, you don't have to care if <code>argv[0]</code> actually contains <code>python.exe</code> (which is the case for many Python installations on Windows) or the name of your script, for example. Plus, it also creates a proper help message for the caller, and much more.</p>
| 0 | 2014-07-07T13:31:11Z | [
"python"
] |
Handling both SSL and non-SSL connections when inheriting from httplib.HTTP(s)Connection | 1,282,368 | <p>I have a class that inherits from httplib.HTTPSConnection. </p>
<pre><code>class MyConnection(httplib.HTTPSConnection):
def __init__(self, *args, **kw):
httplib.HTTPSConnection.__init__(self,*args, **kw)
...
</code></pre>
<p>Is it possible to turn off the SSL layer when the class is instantiatied so I can also use it to communicate with non-secure servers?</p>
<p>I my case it is known before initialisation if SSL should be used so another solution would be to try to switch the inheritance from <em>httplib.HTTPSConnection</em> to <em>httplib.HTTPConnection</em>, but I am also not sure how to do this in a sensible way?</p>
| 1 | 2009-08-15T17:18:09Z | 1,282,386 | <p>Per your last paragraph, in Python you can use something like a factory pattern:</p>
<pre><code>class Foo:
def doit(self):
print "I'm a foo"
class Bar:
def doit(self):
print "I'm a bar"
def MakeClass(isSecure):
if isSecure:
base = Foo
else:
base = Bar
class Quux(base):
def __init__(self):
print "I am derived from", base
return Quux()
MakeClass(True).doit()
MakeClass(False).doit()
</code></pre>
<p>outputs:</p>
<pre><code>I am derived from __main__.Foo
I'm a foo
I am derived from __main__.Bar
I'm a bar
</code></pre>
| 2 | 2009-08-15T17:26:25Z | [
"python",
"http",
"https"
] |
Handling both SSL and non-SSL connections when inheriting from httplib.HTTP(s)Connection | 1,282,368 | <p>I have a class that inherits from httplib.HTTPSConnection. </p>
<pre><code>class MyConnection(httplib.HTTPSConnection):
def __init__(self, *args, **kw):
httplib.HTTPSConnection.__init__(self,*args, **kw)
...
</code></pre>
<p>Is it possible to turn off the SSL layer when the class is instantiatied so I can also use it to communicate with non-secure servers?</p>
<p>I my case it is known before initialisation if SSL should be used so another solution would be to try to switch the inheritance from <em>httplib.HTTPSConnection</em> to <em>httplib.HTTPConnection</em>, but I am also not sure how to do this in a sensible way?</p>
| 1 | 2009-08-15T17:18:09Z | 1,282,390 | <p>Apparently, you want to use MyConnection for multiple subsequent connections to different hosts. If so, you shouldn't be inheriting from HTTP(S)Connection at all - that class isn't really meant to be used for multiple connections. Instead, just make MyConnection <em>have</em> a HTTP(S)Connection.</p>
| 0 | 2009-08-15T17:27:11Z | [
"python",
"http",
"https"
] |
Handling both SSL and non-SSL connections when inheriting from httplib.HTTP(s)Connection | 1,282,368 | <p>I have a class that inherits from httplib.HTTPSConnection. </p>
<pre><code>class MyConnection(httplib.HTTPSConnection):
def __init__(self, *args, **kw):
httplib.HTTPSConnection.__init__(self,*args, **kw)
...
</code></pre>
<p>Is it possible to turn off the SSL layer when the class is instantiatied so I can also use it to communicate with non-secure servers?</p>
<p>I my case it is known before initialisation if SSL should be used so another solution would be to try to switch the inheritance from <em>httplib.HTTPSConnection</em> to <em>httplib.HTTPConnection</em>, but I am also not sure how to do this in a sensible way?</p>
| 1 | 2009-08-15T17:18:09Z | 1,282,550 | <p>As per my comment on @Mark's answer, I like the factory approach he's advocating. However, I wouldn't do it exactly his way, because he makes a new class afresh every time. Rather, this is a nice use case for mixin MI and <code>super</code>, as follows:</p>
<pre><code>class MyConnectionPlugin(object):
def __init__(self, *args, **kw):
super(MyConnectionPlugin, self).__init__(*args, **kw)
# etc etc -- rest of initiatizations, other methods
class SecureConnection(MyConnectionPlugin,
httplib.HTTPSConnection, object):
pass
class PlainConnection(MyConnectionPlugin,
httplib.HTTPConnection, object):
pass
def ConnectionClass(secure):
if secure:
return SecureConnection
else:
return PlainConnection
conn = ConnectionClass(whatever_expression())()
</code></pre>
<p>etc.</p>
<p>Now, alternatives ARE possible, since a Python object can change its own <code>__class__</code>, and so forth. However, like shooting flies with a rhino rifle, using excessive force (extremely powerful, deep, and near-magical language features) to solve problems that can be nicely solved with reasonable restraint (the equivalent of a flyswatter), is NOT recommended;-).</p>
<p><strong>Edit</strong>: the extra injection of <code>object</code> in the bases is needed only to compensate for the sad fact that in Python 2.* the HTTPConnection class is old-style and therefore doesn't play well with others -- witness...:</p>
<pre><code>>>> import httplib
>>> class Z(object): pass
...
>>> class Y(Z, httplib.HTTPConnection): pass
...
>>> Y.mro()
[<class '__main__.Y'>, <class '__main__.Z'>, <type 'object'>, <class httplib.HTTPConnection at 0x264ae0>]
>>> class X(Z, httplib.HTTPConnection, object): pass
...
>>> X.mro()
[<class '__main__.X'>, <class '__main__.Z'>, <class httplib.HTTPConnection at 0x264ae0>, <type 'object'>]
>>>
</code></pre>
<p>The method-resolution order (aka MRO) in class Y (without the further injection of an <code>object</code> base) has object before the class from httplib (so <code>super</code> doesn't do the right thing), but the extra injection jiggles the MRO to compensate. Alas, such care is needed in Python 2.* when dealing with bad old legacy-style classes; fortunately, in Python 3, the legacy style has disappeared and every class "plays well with others" as it should!-)</p>
| 1 | 2009-08-15T18:51:55Z | [
"python",
"http",
"https"
] |
Explain socket buffers please | 1,282,656 | <p>I was trying to find examples about socket programming and came upon this script:
<a href="http://stacklessexamples.googlecode.com/svn/trunk/examples/networking/mud.py" rel="nofollow">http://stacklessexamples.googlecode.com/svn/trunk/examples/networking/mud.py</a></p>
<p>When reading through this script i found this line:
listenSocket.listen(5)</p>
<p>As i understand it - it reads 5 bytes from the buffer and then does stuff with it... </p>
<p>but what happens if more than 5 bytes were sent by the other end? </p>
<p>in the other place of that script it checks input against 4 commands and sees if there is \r\n in the string. dont commands like "look" plus \r\n make up for more than 5 bytes?</p>
<p>Alan</p>
| 1 | 2009-08-15T19:38:37Z | 1,282,669 | <p>The following is applicable to sockets in general, but it should help answer your specific question about using sockets from Python.</p>
<p>socket.listen() is used on a <em>server</em> socket to listen for incoming connection requests.</p>
<p>The parameter passed to listen is called the <em>backlog</em> and it means how many connections should the socket accept and put in a pending buffer until you finish your call to accept(). That applies to connections that are waiting to connect to your server socket between the time you have called listen() and the time you have finished a matching call to accept().</p>
<p>So, in your example you're setting the backlog to 5 connections.</p>
<p><strong>Note</strong>.. if you set your backlog to 5 connections, the following connections (6th, 7th etc.) will be dropped and the connecting socket will receive an <em>error connecting</em> message (something like a "host actively refused the connection" message)</p>
| 12 | 2009-08-15T19:42:20Z | [
"python",
"sockets",
"stackless",
"python-stackless"
] |
Explain socket buffers please | 1,282,656 | <p>I was trying to find examples about socket programming and came upon this script:
<a href="http://stacklessexamples.googlecode.com/svn/trunk/examples/networking/mud.py" rel="nofollow">http://stacklessexamples.googlecode.com/svn/trunk/examples/networking/mud.py</a></p>
<p>When reading through this script i found this line:
listenSocket.listen(5)</p>
<p>As i understand it - it reads 5 bytes from the buffer and then does stuff with it... </p>
<p>but what happens if more than 5 bytes were sent by the other end? </p>
<p>in the other place of that script it checks input against 4 commands and sees if there is \r\n in the string. dont commands like "look" plus \r\n make up for more than 5 bytes?</p>
<p>Alan</p>
| 1 | 2009-08-15T19:38:37Z | 1,282,673 | <p>This might help you understand the code: <a href="http://www.amk.ca/python/howto/sockets/" rel="nofollow">http://www.amk.ca/python/howto/sockets/</a></p>
| 0 | 2009-08-15T19:43:31Z | [
"python",
"sockets",
"stackless",
"python-stackless"
] |
Explain socket buffers please | 1,282,656 | <p>I was trying to find examples about socket programming and came upon this script:
<a href="http://stacklessexamples.googlecode.com/svn/trunk/examples/networking/mud.py" rel="nofollow">http://stacklessexamples.googlecode.com/svn/trunk/examples/networking/mud.py</a></p>
<p>When reading through this script i found this line:
listenSocket.listen(5)</p>
<p>As i understand it - it reads 5 bytes from the buffer and then does stuff with it... </p>
<p>but what happens if more than 5 bytes were sent by the other end? </p>
<p>in the other place of that script it checks input against 4 commands and sees if there is \r\n in the string. dont commands like "look" plus \r\n make up for more than 5 bytes?</p>
<p>Alan</p>
| 1 | 2009-08-15T19:38:37Z | 1,282,677 | <p>The argument <code>5</code> to <code>listenSocket.listen</code> isn't the number of bytes to read or buffer, it's the <code>backlog</code>:</p>
<blockquote>
<p><a href="http://docs.python.org/library/socket.html#socket.socket.listen" rel="nofollow"><code>socket.listen(backlog)</code></a></p>
<p>Listen for connections made to the
socket. The backlog argument specifies
the maximum number of queued
connections and should be at least 1;
the maximum value is system-dependent
(usually 5).</p>
</blockquote>
| 0 | 2009-08-15T19:45:13Z | [
"python",
"sockets",
"stackless",
"python-stackless"
] |
aap - python trouble | 1,282,828 | <p>i'm trying to run aap-application. Version is 1.076 (tried higher). All commands send me an error like: </p>
<pre><code>> Traceback (most recent call last):
> File "/usr/bin/aap", line 10, in
> <module>
> import Main File "/usr/share/aap/Main.py", line 14, in
> <module>
> from DoAddDef import doadddef File "/usr/share/aap/DoAddDef.py",
> line 10, in <module>
> from Action import find_primary_action File
> "/usr/share/aap/Action.py", line 30,
> in <module>
> from Dictlist import listitem2str, str2dictlist, dictlist2str File
> "/usr/share/aap/Dictlist.py", line 18,
> in <module>
> from Process import recipe_error File "/usr/share/aap/Process.py", line
> 13, in <module>
> from Work import setrpstack File "/usr/share/aap/Work.py", line 25, in
> <module>
> from Node import Node File "/usr/share/aap/Node.py", line 10, in
> <module>
> import Filetype File "/usr/share/aap/Filetype.py", line
> 1417
> as = 0
> ^ SyntaxError: invalid syntax
</code></pre>
<p>What problem could it be?</p>
| 1 | 2009-08-15T21:00:29Z | 1,282,839 | <p><code>as</code> is a <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#keywords" rel="nofollow">reserved word</a> in Python.</p>
<p>Seems aap-application was written for Python 2.5 and bellow:</p>
<blockquote>
<p>Changed in version 2.5: Both <strong><code>as</code></strong> and <code>with</code> are only recognized when the <code>with_statement</code> future feature has been
enabled. <strong>It will always be enabled in
Python 2.6</strong>. See section The with
statement for details. Note that using
as and with as identifiers will always
issue a warning, even when the
<code>with_statement</code> future directive is not
in effect.</p>
</blockquote>
| 3 | 2009-08-15T21:07:05Z | [
"python",
"linux"
] |
aap - python trouble | 1,282,828 | <p>i'm trying to run aap-application. Version is 1.076 (tried higher). All commands send me an error like: </p>
<pre><code>> Traceback (most recent call last):
> File "/usr/bin/aap", line 10, in
> <module>
> import Main File "/usr/share/aap/Main.py", line 14, in
> <module>
> from DoAddDef import doadddef File "/usr/share/aap/DoAddDef.py",
> line 10, in <module>
> from Action import find_primary_action File
> "/usr/share/aap/Action.py", line 30,
> in <module>
> from Dictlist import listitem2str, str2dictlist, dictlist2str File
> "/usr/share/aap/Dictlist.py", line 18,
> in <module>
> from Process import recipe_error File "/usr/share/aap/Process.py", line
> 13, in <module>
> from Work import setrpstack File "/usr/share/aap/Work.py", line 25, in
> <module>
> from Node import Node File "/usr/share/aap/Node.py", line 10, in
> <module>
> import Filetype File "/usr/share/aap/Filetype.py", line
> 1417
> as = 0
> ^ SyntaxError: invalid syntax
</code></pre>
<p>What problem could it be?</p>
| 1 | 2009-08-15T21:00:29Z | 1,282,840 | <p>Well, <code>as</code> is a reserved word in Python. So, that can't be used in FileType.py as a variable name.</p>
<p>Try updating your installation of <code>aap</code> or writing in to the aap authors/forums.</p>
| 6 | 2009-08-15T21:07:16Z | [
"python",
"linux"
] |
Using Python to read the screen and controlling keyboard/mouse on OSX | 1,282,860 | <p>I'm looking for or trying to write a testing suite in Python which will control the mouse/keyboard and watch the screen for changes.</p>
<p>The obvious parts I need are (1) screen watcher, (2) keyboard/mouse control.</p>
<p>The latter is explained <a href="http://stackoverflow.com/questions/281133/controlling-the-mouse-from-python-in-os-x">here</a>, but what is the best way to go about doing the former on OSX?</p>
| 0 | 2009-08-15T21:13:45Z | 1,283,063 | <p>I can't think of a smart way to "watch the screen for changes" in any OS nor with any language. On MacOSX, you can take screenshots programmatically at any time, e.g. with code like the one Apple shows at <a href="http://developer.apple.com/samplecode/SonOfGrab/" rel="nofollow">this sample</a> (translating the Objective C into Python + PyObjC if you want), or more simply by executing the external command <code>screencapture -x -T 0 /tmp/zap.png</code> (e.g. via subprocess) and examining the resulting PNG image -- but locating the differences between two successive screenshot is anything but trivial, and the whole approach is time consuming (there's no way that I know to receive notification of generic screen changes, so you need to keep repeating this periodically -- eek!-).</p>
<p>Depending on what exactly you're trying to accomplish, maybe you can get away with something simpler than completely unconstrained "watching screen changes"...?</p>
| 2 | 2009-08-15T22:50:04Z | [
"python",
"user-interface",
"osx"
] |
How are nested dictionaries handled by DictWriter? | 1,282,920 | <p>Using the CSV module in python, I was experimenting with the DictWriter class to convert dictionaries to rows in a csv. Is there any way to handle nested dictionaries? Specifically, I'm exporting Disqus comments that have a structure like this:</p>
<pre><code>{
u'status': u'approved',
u'forum': {u'id': u'', u'': u'', u'shortname': u'', u'name': u'', u'description': u''},
u'thread': {u'allow_comments': True, u'forum': u'', u'title': u'', u'url': u'', u'created_at': u'', u'id': u'', u'hidden': False, u'identifier': [], u'slug': u''},
u'is_anonymous': False,
u'author': {u'username': u'', u'email_hash': u'', u'display_name': u'', u'has_avatar': True, u'url': u'', u'id': 1, u'avatar': {u'small': u'', u'large': u'', u'medium': u''}, u'email': u''},
u'created_at': u'2009-08-12T10:14',
u'points': 0,
u'message': u"",
u'has_been_moderated': False,
u'ip_address': u'',
u'id': u'',
u'parent_post': None
}
</code></pre>
<p>I wanted to specify fields from the author and thread properties and haven't found a way so far. Here's the code:</p>
<pre><code>f = open('export.csv', 'wb')
fieldnames = ('id','status','is_anonymous','created_at','ip_address','points','has_been_moderated','parent_post','thread')
try:
exportWriter = csv.DictWriter(f,
fieldnames,
restval=None,
extrasaction='ignore',
quoting=csv.QUOTE_NONNUMERIC
)
for c in comments:
exportWriter.writerow(c)
finally:
f.close()
</code></pre>
| 2 | 2009-08-15T21:39:49Z | 1,282,968 | <p>I think the main problem your going to have is how to represent a nested data structure in one flat row of csv data.</p>
<p>You could use some form of name mangeling to flatten the keys from the sub dict's into the top level dict.</p>
<p>eg thread': {u'allow_comments': </p>
<p>would become thread_allows_comments. </p>
| 1 | 2009-08-15T21:59:11Z | [
"python",
"csv"
] |
Python integer division yields float | 1,282,945 | <pre><code>Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/2
1.0
</code></pre>
<p>Is this intended? I strongly remember earlier versions returning <code>int/int=int</code>? What should I do, is there a new division operator or must I always cast?</p>
| 101 | 2009-08-15T21:48:39Z | 1,282,948 | <p>Oops, immediately found <code>2//2</code>.</p>
| 32 | 2009-08-15T21:50:14Z | [
"python",
"integer",
"python-3.x",
"division"
] |
Python integer division yields float | 1,282,945 | <pre><code>Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/2
1.0
</code></pre>
<p>Is this intended? I strongly remember earlier versions returning <code>int/int=int</code>? What should I do, is there a new division operator or must I always cast?</p>
| 101 | 2009-08-15T21:48:39Z | 1,282,954 | <p>Take a look at <a href="http://www.python.org/dev/peps/pep-0238/">PEP-238</a>: Changing the Division Operator</p>
<blockquote>
<p>The // operator will be available to request floor division unambiguously.</p>
</blockquote>
| 142 | 2009-08-15T21:51:44Z | [
"python",
"integer",
"python-3.x",
"division"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.