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 |
|---|---|---|---|---|---|---|---|---|---|
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pyth... | 21 | 2009-07-22T01:24:53Z | 1,162,636 | <p>Dunno about cleaner, but there's another alternative:</p>
<pre><code>for (op, code) in zip(s[0::2], s[1::2]):
print op, code
</code></pre>
<p>A no-copy version:</p>
<pre><code>from itertools import izip, islice
for (op, code) in izip(islice(s, 0, None, 2), islice(s, 1, None, 2)):
print op, code
</code></p... | 32 | 2009-07-22T01:39:53Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pyth... | 21 | 2009-07-22T01:24:53Z | 1,162,799 | <p>The other answers work well for n = 2, but for the general case you could try this:</p>
<pre><code>def slicen(s, n, truncate=False):
nslices = len(s) / n
if not truncate and (len(s) % n):
nslices += 1
return (s[i*n:n*(i+1)] for i in range(nslices))
>>> s = '+c-R+D-e'
>>> for o... | 2 | 2009-07-22T02:40:51Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pyth... | 21 | 2009-07-22T01:24:53Z | 1,162,864 | <p>Great opportunity for a generator. For larger lists, this will be much more efficient than zipping every other elemnent. Note that this version also handles strings with dangling <code>op</code>s</p>
<pre><code>def opcodes(s):
while True:
try:
op = s[0]
code = s[1]
... | 2 | 2009-07-22T02:59:36Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pyth... | 21 | 2009-07-22T01:24:53Z | 1,162,959 | <p><a href="http://stackoverflow.com/users/43089/triptych">Triptych</a> inspired this more general solution:</p>
<pre><code>def slicen(s, n, truncate=False):
assert n > 0
while len(s) >= n:
yield s[:n]
s = s[n:]
if len(s) and not truncate:
yield s
for op, code in slicen("+c-R... | 4 | 2009-07-22T03:43:59Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pyth... | 21 | 2009-07-22T01:24:53Z | 1,163,166 | <p>Maybe not the most efficient, but if you like regexes...</p>
<pre><code>import re
s = "+c-R+D-e"
for op, code in re.findall('(.)(.)', s):
print op, code
</code></pre>
| 0 | 2009-07-22T05:10:23Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pyth... | 21 | 2009-07-22T01:24:53Z | 19,699,417 | <p>This approach support an arbitrary number of elements per result, evaluates lazily, and the input iterable can be a generator (no indexing is attempted): </p>
<pre><code>import itertools
def groups_of_n(n, iterable):
c = itertools.count()
for _, gen in itertools.groupby(iterable, lambda x: c.next() / n):
... | 2 | 2013-10-31T06:00:27Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pyth... | 21 | 2009-07-22T01:24:53Z | 22,798,438 | <p>I ran into a similar problem. Ended doing something like this:</p>
<pre><code>ops = iter("+c-R+D-e")
for op in ops
code = ops.next()
print op, code
</code></pre>
<p>I felt it was the most readable.</p>
| 0 | 2014-04-01T22:53:01Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pyth... | 21 | 2009-07-22T01:24:53Z | 23,211,888 | <p>Here's my answer, a little bit cleaner to my eyes:</p>
<pre class="lang-py prettyprint-override"><code>for i in range(0, len(string) - 1):
if i % 2 == 0:
print string[i:i+2]
</code></pre>
| 0 | 2014-04-22T06:21:50Z | [
"python",
"iteration"
] |
GQL Query on date equality in Python | 1,162,644 | <p>Ok, you guys were quick and helpful last time so I'm going back to the well ;)</p>
<p>Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial.</p>
<p>I've got my date value being stored in my Memory class:</p>
<pre><code>c... | 0 | 2009-07-22T01:41:31Z | 1,162,879 | <pre><code>memories.filter("date=DATE(2007, 7, 20)")
</code></pre>
<p>Refer to <a href="http://code.google.com/appengine/docs/python/datastore/gqlreference.html" rel="nofollow">GQL Reference</a>.</p>
| 1 | 2009-07-22T03:06:46Z | [
"python",
"google-app-engine"
] |
GQL Query on date equality in Python | 1,162,644 | <p>Ok, you guys were quick and helpful last time so I'm going back to the well ;)</p>
<p>Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial.</p>
<p>I've got my date value being stored in my Memory class:</p>
<pre><code>c... | 0 | 2009-07-22T01:41:31Z | 1,163,586 | <pre><code>class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty(auto_now_add=True)
</code></pre>
<p>I think that you are either getting import errors for memory or your are getting an import error for datetime</p>
<p>if Memory is in another ... | 0 | 2009-07-22T07:18:48Z | [
"python",
"google-app-engine"
] |
GQL Query on date equality in Python | 1,162,644 | <p>Ok, you guys were quick and helpful last time so I'm going back to the well ;)</p>
<p>Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial.</p>
<p>I've got my date value being stored in my Memory class:</p>
<pre><code>c... | 0 | 2009-07-22T01:41:31Z | 1,165,432 | <p>You're trying to use GQL syntax with non-GQL Query objects. Your options are:</p>
<ol>
<li>Use the Query object and pass in a datetime.date object: <code>q = Memory.all().filter("date =", datetime.date.today())</code></li>
<li>Use a GqlQuery and use the DATE syntax: <code>q = db.GqlQuery("SELECT * FROM Memory WHERE... | 2 | 2009-07-22T13:53:42Z | [
"python",
"google-app-engine"
] |
How would you model this database relationship? | 1,162,877 | <p>I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients.</p>
<p>The application does need to know which one is whic... | 2 | 2009-07-22T03:05:08Z | 1,162,884 | <p>I agree with your conclusion. I would store the physician type in the many-to-many linking table.</p>
| 0 | 2009-07-22T03:08:40Z | [
"python",
"database",
"django",
"database-design"
] |
How would you model this database relationship? | 1,162,877 | <p>I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients.</p>
<p>The application does need to know which one is whic... | 2 | 2009-07-22T03:05:08Z | 1,162,892 | <p>Consider using a many-to-many join table. Use application logic to prevent more than two physicians per patient.</p>
<pre><code>Physician
Physician_ID
...
Patient
Patient_ID
...
Physician_Patient
Physician_ID int not null
Patient_ID int not null
Type ENUM ('Primary', 'Attending')
... | 1 | 2009-07-22T03:11:13Z | [
"python",
"database",
"django",
"database-design"
] |
How would you model this database relationship? | 1,162,877 | <p>I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients.</p>
<p>The application does need to know which one is whic... | 2 | 2009-07-22T03:05:08Z | 1,162,901 | <p>How about something like this:</p>
<pre><code>class Patient(models.Model):
primary_physician = models.ForeignKey('Physician', related_name='primary_patients')
attending_physicial = models.ForeignKey('Physician', related_name='attending_patients')
</code></pre>
<p>This allows you to have two foreign keys to... | 10 | 2009-07-22T03:14:48Z | [
"python",
"database",
"django",
"database-design"
] |
Cost of scaling Rails vs cost of scaling PHP vs Python frameworks | 1,163,012 | <p>I guess this question has been asked a lot around. I know <strong>Rails can scale</strong> because I have worked on it and it's awesome. And there is not much doubt about that as far as PHP frameworks are concerned.</p>
<p>I don't want to know which frameworks are better.</p>
<p>How much is difference in cost of ... | 7 | 2009-07-22T04:07:29Z | 1,163,208 | <p>One major factor in this is that isn't affected by choice of framework is database access. No matter what approach you take, you likely put data in a relational database. Then the question is how efficiently you can get the data out of the database. This primarily depends on the RDBMS (Oracle vs. Postgres vs. MySQL)... | 5 | 2009-07-22T05:27:53Z | [
"php",
"python",
"ruby-on-rails",
"scaling"
] |
Cost of scaling Rails vs cost of scaling PHP vs Python frameworks | 1,163,012 | <p>I guess this question has been asked a lot around. I know <strong>Rails can scale</strong> because I have worked on it and it's awesome. And there is not much doubt about that as far as PHP frameworks are concerned.</p>
<p>I don't want to know which frameworks are better.</p>
<p>How much is difference in cost of ... | 7 | 2009-07-22T04:07:29Z | 1,163,341 | <p>IMHO I don't think the cost of scaling is going to be any different between those three because none of them have "scalability batteries" included. I just don't see any huge architectural differences between those three choices that would cause a significant difference in scaling.</p>
<p>In other words, your appli... | 4 | 2009-07-22T06:16:17Z | [
"php",
"python",
"ruby-on-rails",
"scaling"
] |
Cost of scaling Rails vs cost of scaling PHP vs Python frameworks | 1,163,012 | <p>I guess this question has been asked a lot around. I know <strong>Rails can scale</strong> because I have worked on it and it's awesome. And there is not much doubt about that as far as PHP frameworks are concerned.</p>
<p>I don't want to know which frameworks are better.</p>
<p>How much is difference in cost of ... | 7 | 2009-07-22T04:07:29Z | 18,622,672 | <p>Unfortunately, I do not know any cost comparison of Rails, PHP and Django. But I do know a cost comparison of some Java Web Frameworks: Spring(9k$), Wicket(59k$) , GWT(6k$) and JSF(49k$). </p>
<p>You have the original conference here: </p>
<p><a href="http://www.devoxx.com/display/DV11/WWW++World+Wide+Wait++A+Perf... | 1 | 2013-09-04T19:55:08Z | [
"php",
"python",
"ruby-on-rails",
"scaling"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code>... | 6 | 2009-07-22T04:45:45Z | 1,163,165 | <p>Use a Profile model for extra account data besides user name and password. You can call user.get_profile() if you include this line in Profile:</p>
<pre><code>user = models.ForeignKey(User, unique=True)
</code></pre>
<p>and this line in settings.py:</p>
<pre><code>AUTH_PROFILE_MODULE = 'yourapp.Profile'
</code></... | 1 | 2009-07-22T05:10:07Z | [
"python",
"django",
"comments"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code>... | 6 | 2009-07-22T04:45:45Z | 1,163,803 | <p>According to the comment, it's either-or: the other fields are meant to be used when <code>user</code> <em>isn't</em> set. Have you checked that the relevant columns are definitely NOT NULL? They're marked as <code>blank=True</code> which normally means <code>required=False</code> at the field level. If you have act... | 0 | 2009-07-22T08:19:35Z | [
"python",
"django",
"comments"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code>... | 6 | 2009-07-22T04:45:45Z | 1,164,400 | <p>First off, the comments app already supports both authenticated and anonymous users, so I assume you want to accept comments from authenticated users only?</p>
<p>Thejaswi Puthraya had a <a href="http://thejaswi.info/blog/2008/11/19/part-1-django-comments-authenticated-users/" rel="nofollow">series</a> of <a href="... | 1 | 2009-07-22T10:37:25Z | [
"python",
"django",
"comments"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code>... | 6 | 2009-07-22T04:45:45Z | 1,193,040 | <p>I recommend that when you come up with a question about Django internals, you take a look at the source.</p>
<p>If we look at the <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/comments/views/comments.py#L32" rel="nofollow">start of post_comment view</a> we see that the POST querydict is... | 3 | 2009-07-28T09:45:07Z | [
"python",
"django",
"comments"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code>... | 6 | 2009-07-22T04:45:45Z | 1,229,332 | <p>Theju wrote an authenticated comments app â <a href="http://thejaswi.info/tech/blog/2009/08/04/reusable-app-authenticated-comments/" rel="nofollow">http://thejaswi.info/tech/blog/2009/08/04/reusable-app-authenticated-comments/</a></p>
| 1 | 2009-08-04T19:05:58Z | [
"python",
"django",
"comments"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code>... | 6 | 2009-07-22T04:45:45Z | 2,268,367 | <p>WordPress and other systems make this a no-brainer. If you're logged in, the comment form should just "do the right thing" and remove the name/email/url fields. Isn't this exactly the kind of heavy lifting a framework is supposed to do for you? </p>
<p>Rather than dancing around with subclassing models for somethin... | 4 | 2010-02-15T19:24:38Z | [
"python",
"django",
"comments"
] |
How to detect the country and city of a user accessing your site? | 1,163,136 | <p>How can you detect the country of origin of the users accessing your site? </p>
<p>I'm using Google Analytics on my site and can see that I have users coming from different regions of the world.</p>
<p>But within my application I would like to provide some additional customization based on the country and perhaps ... | 5 | 2009-07-22T05:01:11Z | 1,163,159 | <p>Get the visitor's IP and check it with a <a href="http://en.wikipedia.org/wiki/Geolocation" rel="nofollow">geolocation</a> web service (or purchase a geolocation database if you're keen to host that determination in-house).</p>
| 8 | 2009-07-22T05:07:50Z | [
"python",
"web-applications"
] |
How to detect the country and city of a user accessing your site? | 1,163,136 | <p>How can you detect the country of origin of the users accessing your site? </p>
<p>I'm using Google Analytics on my site and can see that I have users coming from different regions of the world.</p>
<p>But within my application I would like to provide some additional customization based on the country and perhaps ... | 5 | 2009-07-22T05:01:11Z | 1,163,695 | <p>Grab and gunzip <a href="http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz">http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz</a>, install the GeoIP-Python package (python-geoip package if you're in Debian or Ubuntu, otherwise install <a href="http://geolite.maxmind.com/downlo... | 12 | 2009-07-22T07:49:14Z | [
"python",
"web-applications"
] |
How to detect the country and city of a user accessing your site? | 1,163,136 | <p>How can you detect the country of origin of the users accessing your site? </p>
<p>I'm using Google Analytics on my site and can see that I have users coming from different regions of the world.</p>
<p>But within my application I would like to provide some additional customization based on the country and perhaps ... | 5 | 2009-07-22T05:01:11Z | 40,068,720 | <p>Max mind costs money.
For a free yet country code only solution you can try:
<a href="https://pypi.python.org/pypi/geoip2nation/" rel="nofollow">https://pypi.python.org/pypi/geoip2nation/</a></p>
<p>pip install geoip2nation</p>
<pre><code>from geoip import geoip
r = geoip.GeoIp()
r.load_memory()
r.resolve("12.12.1... | 0 | 2016-10-16T09:15:35Z | [
"python",
"web-applications"
] |
Non-recursive means of printing a list in Python | 1,163,429 | <p>Is there a way to perform the following in a non-recursive fashion:</p>
<pre><code>my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
... | 2 | 2009-07-22T06:42:56Z | 1,163,532 | <pre><code>def print_list(the_list, indent_level=0):
stack = [iter(the_list)]
while stack:
try:
item = stack[-1].next()
except StopIteration:
stack.pop()
indent_level -= 1
continue
if isinstance(item, list):
indent_level += 1
... | 2 | 2009-07-22T07:05:19Z | [
"python",
"recursion"
] |
Non-recursive means of printing a list in Python | 1,163,429 | <p>Is there a way to perform the following in a non-recursive fashion:</p>
<pre><code>my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
... | 2 | 2009-07-22T06:42:56Z | 1,163,533 | <p>Note that this depens on the input not containing tuples.</p>
<pre><code>l1 = my_list
done = False
# Repeatedly turn the list elements into tuples of the form
# (indent, item) until there are no more lists.
while not done:
done = True
l2 = []
for item in l1:
if isinstance(item,tuple):
... | 0 | 2009-07-22T07:05:31Z | [
"python",
"recursion"
] |
Non-recursive means of printing a list in Python | 1,163,429 | <p>Is there a way to perform the following in a non-recursive fashion:</p>
<pre><code>my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
... | 2 | 2009-07-22T06:42:56Z | 1,163,542 | <pre><code>stack = [(my_list, -1)]
while stack:
item, level = stack.pop()
if isinstance(item, list):
for i in reversed(item):
stack.append((i, level+1))
else:
print "\t" * level, item
</code></pre>
| 4 | 2009-07-22T07:07:21Z | [
"python",
"recursion"
] |
Non-recursive means of printing a list in Python | 1,163,429 | <p>Is there a way to perform the following in a non-recursive fashion:</p>
<pre><code>my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
... | 2 | 2009-07-22T06:42:56Z | 1,164,531 | <p>Everyone has given solutions which are</p>
<ul>
<li>production ready</li>
<li>use stack, so has same problem as recursion</li>
<li>or go thru list multiple time</li>
</ul>
<p>Here is a solution lateral solution :)</p>
<ul>
<li>not production ready but fun</li>
<li>no stack or anything like that, no lists in sight... | 0 | 2009-07-22T11:02:32Z | [
"python",
"recursion"
] |
Non-recursive means of printing a list in Python | 1,163,429 | <p>Is there a way to perform the following in a non-recursive fashion:</p>
<pre><code>my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
... | 2 | 2009-07-22T06:42:56Z | 1,164,783 | <p>Here's a variation of Martin Löwis' version that uses <code>for/else</code> instead of manually catching <code>StopIteration</code>, and <code>len(stack)</code> instead of keeping track of the indent level.</p>
<pre><code>def print_list(the_list):
stack = [iter(the_list)]
while stack:
for item in s... | 2 | 2009-07-22T11:58:11Z | [
"python",
"recursion"
] |
Reading integers from binary file in Python | 1,163,459 | <p>I'm trying to read a <a href="http://en.wikipedia.org/wiki/BMP_file_format">BMP</a> file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I excecute:</p>
<pre><code>fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
</code></pre>
<p>... | 40 | 2009-07-22T06:48:39Z | 1,163,508 | <p>The <code>read</code> method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in <code>struct</code> module: <a href="http://docs.python.org/library/struct.html">http://docs.python.org/library/struct.html</a>. </p>
<pre><code>import struct
print(struct.u... | 68 | 2009-07-22T06:59:55Z | [
"python",
"file",
"binary",
"integer"
] |
Reading integers from binary file in Python | 1,163,459 | <p>I'm trying to read a <a href="http://en.wikipedia.org/wiki/BMP_file_format">BMP</a> file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I excecute:</p>
<pre><code>fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
</code></pre>
<p>... | 40 | 2009-07-22T06:48:39Z | 1,163,525 | <p>As you are reading the binary file, you need to unpack it into a integer, so use struct module for that</p>
<pre><code>import struct
fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size, = struct.unpack("i",fin.read(4))
</code></pre>
| 4 | 2009-07-22T07:03:57Z | [
"python",
"file",
"binary",
"integer"
] |
Reading integers from binary file in Python | 1,163,459 | <p>I'm trying to read a <a href="http://en.wikipedia.org/wiki/BMP_file_format">BMP</a> file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I excecute:</p>
<pre><code>fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
</code></pre>
<p>... | 40 | 2009-07-22T06:48:39Z | 1,163,554 | <p>Except <code>struct</code> you can also use <code>array</code> module</p>
<pre><code>import array
values = array.array('l') # array of long integers
values.read(fin, 1) # read 1 integer
file_size = values[0]
</code></pre>
| 6 | 2009-07-22T07:10:16Z | [
"python",
"file",
"binary",
"integer"
] |
Reading integers from binary file in Python | 1,163,459 | <p>I'm trying to read a <a href="http://en.wikipedia.org/wiki/BMP_file_format">BMP</a> file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I excecute:</p>
<pre><code>fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
</code></pre>
<p>... | 40 | 2009-07-22T06:48:39Z | 11,713,266 | <p>An alternative method which does not make use of 'struct.unpack()' would be to use <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a>:</p>
<pre><code>import numpy as np
f = open("file.bin", "r")
a = np.fromfile(f, dtype=np.uint32)
</code></pre>
<p>'dtype' represents the datatype and can be int#, uint#, float#... | 22 | 2012-07-29T21:51:48Z | [
"python",
"file",
"binary",
"integer"
] |
Python plugin in netbeans manually | 1,163,531 | <p>Can install python plugin in netbeans 6.7 manually (without Tools/Plugin) ?
if yes (with .nbi package ) which url can use ?</p>
| 1 | 2009-07-22T07:04:38Z | 1,776,811 | <p>find one Netbeans that downloaded python plug-in and go to Netbeans folder and copy python folder. In computer that need to install python plug-in copy that folder in Netbeans root folder and go to Tools/Plugin and activate python . </p>
| 0 | 2009-11-21T21:15:06Z | [
"python",
"netbeans",
"netbeans6.7",
"netbeans-plugins"
] |
fast-ish python/jython IPC? | 1,163,574 | <p>All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.</p>
<p>The list of things I've tried:</p>
<ul>
<li... | 14 | 2009-07-22T07:14:36Z | 1,163,737 | <p>Have you considered <a href="http://hessian.caucho.com/" rel="nofollow">Hessian</a>? From the blurb:</p>
<blockquote>
<p>The Hessian binary web service
protocol makes web services usable
without requiring a large framework,
and without learning yet another
alphabet soup of protocols. Because it
is a bin... | 6 | 2009-07-22T08:00:13Z | [
"python",
"ipc",
"jython",
"twisted",
"rpc"
] |
fast-ish python/jython IPC? | 1,163,574 | <p>All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.</p>
<p>The list of things I've tried:</p>
<ul>
<li... | 14 | 2009-07-22T07:14:36Z | 1,163,852 | <p>Have you thought about using CORBA? It's fast, portable and object oriented...</p>
<p>I have only used it on the Java side (I think you could use a pure java broker with no problems from Jython), and with IIOP you should be able to interoperate with the CPython client.</p>
| 0 | 2009-07-22T08:27:26Z | [
"python",
"ipc",
"jython",
"twisted",
"rpc"
] |
fast-ish python/jython IPC? | 1,163,574 | <p>All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.</p>
<p>The list of things I've tried:</p>
<ul>
<li... | 14 | 2009-07-22T07:14:36Z | 1,163,968 | <p>How about using sockets, but with the help of <code>asyncore</code> and <code>asynchat</code>?</p>
<p>Some links:</p>
<ul>
<li><a href="http://effbot.org/librarybook/asynchat.htm">An example</a></li>
<li><a href="http://docs.python.org/library/asyncore.html">http://docs.python.org/library/asyncore.html</a></li>
<l... | 5 | 2009-07-22T08:56:45Z | [
"python",
"ipc",
"jython",
"twisted",
"rpc"
] |
fast-ish python/jython IPC? | 1,163,574 | <p>All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.</p>
<p>The list of things I've tried:</p>
<ul>
<li... | 14 | 2009-07-22T07:14:36Z | 1,164,219 | <p>Two that look the most interesting to me:</p>
<ul>
<li><p><a href="http://gearman.org/" rel="nofollow">Gearman</a> and <a href="http://github.com/samuel/python-gearman/tree/master" rel="nofollow">Python bindings</a>. It's quite a bit faster now that it's been re-written in C (originally perl). It's used in produc... | 2 | 2009-07-22T09:57:04Z | [
"python",
"ipc",
"jython",
"twisted",
"rpc"
] |
fast-ish python/jython IPC? | 1,163,574 | <p>All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.</p>
<p>The list of things I've tried:</p>
<ul>
<li... | 14 | 2009-07-22T07:14:36Z | 1,165,579 | <p>My favorite..
<a href="http://www.zeroc.com" rel="nofollow">zeroc's ice</a></p>
| 2 | 2009-07-22T14:14:53Z | [
"python",
"ipc",
"jython",
"twisted",
"rpc"
] |
python mysql connection problem | 1,164,033 | <p>This code works fine:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect("localhost", "root", "","bullsorbit")
cursor = db.cursor()
cursor.execute("Select * from table where conditions'")
numrows = int(cursor.rowcount)
print 'Total number of Pages : %d ' % numrows
</code></pre>
<p>but if I give my IP addre... | 1 | 2009-07-22T09:12:14Z | 1,164,071 | <p>with localhost you connect via loopback-interface.</p>
<p>with ip-addr you connect - as you connect from extern.</p>
<p>if your server allows only the local (loopback) connection
your ip-addr connection fails. (security!)</p>
<p>look at your mysql config, maybe only local-connections are allowed.</p>
<p>is the s... | 3 | 2009-07-22T09:18:48Z | [
"python",
"mysql"
] |
python mysql connection problem | 1,164,033 | <p>This code works fine:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect("localhost", "root", "","bullsorbit")
cursor = db.cursor()
cursor.execute("Select * from table where conditions'")
numrows = int(cursor.rowcount)
print 'Total number of Pages : %d ' % numrows
</code></pre>
<p>but if I give my IP addre... | 1 | 2009-07-22T09:12:14Z | 1,164,077 | <p>Instead of:</p>
<p><code>db = MySQLdb.connect("192.168..", "root", "","bullsorbit")</code></p>
<p>try:</p>
<p><code>db = MySQLdb.connect(user="root", host="192.168..", db="bullsorbit")</code></p>
<p>Password will default to empty string and try the usual identity methods. Host will also default to localhost on ... | 0 | 2009-07-22T09:19:52Z | [
"python",
"mysql"
] |
python mysql connection problem | 1,164,033 | <p>This code works fine:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect("localhost", "root", "","bullsorbit")
cursor = db.cursor()
cursor.execute("Select * from table where conditions'")
numrows = int(cursor.rowcount)
print 'Total number of Pages : %d ' % numrows
</code></pre>
<p>but if I give my IP addre... | 1 | 2009-07-22T09:12:14Z | 1,164,297 | <p>Code 2003 is a <a href="http://dev.mysql.com/doc/refman/5.1/en/error-messages-client.html">standard MySQL client error</a>:</p>
<blockquote>
<p>Error: 2003 (CR_CONN_HOST_ERROR) Message: Can't connect to MySQL server on '%s' (%d)</p>
</blockquote>
<p>I'd guess that your user is not allowed to connect to the MySQL... | 5 | 2009-07-22T10:17:09Z | [
"python",
"mysql"
] |
python mysql connection problem | 1,164,033 | <p>This code works fine:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect("localhost", "root", "","bullsorbit")
cursor = db.cursor()
cursor.execute("Select * from table where conditions'")
numrows = int(cursor.rowcount)
print 'Total number of Pages : %d ' % numrows
</code></pre>
<p>but if I give my IP addre... | 1 | 2009-07-22T09:12:14Z | 14,125,203 | <p>For the <code>2003</code> error, another possibility is that too many connections are being attempted in too short of time. I noticed this same behavior when I had <code>127.0.0.1</code> as my connect string. First I replaced it with <code>localhost</code> which got me further but still the same <code>2003</code> ... | 0 | 2013-01-02T16:06:39Z | [
"python",
"mysql"
] |
Python object creation | 1,164,309 | <p>I am pretty new to Python world and trying to learn it.</p>
<p>This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)</p>
<pre><code>class Car():
carName = "" ... | 5 | 2009-07-22T10:19:34Z | 1,164,319 | <p>derived from object for <a href="http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes">new-style class</a><br />
use <code>__init__</code> to initialize the new instance, not <code>__self__</code><br />
<code>__main__</code> is <a href="http://docs.python.org/library/%5F%5Fmain%5F%5F.html">h... | 13 | 2009-07-22T10:21:37Z | [
"python",
"class",
"object"
] |
Python object creation | 1,164,309 | <p>I am pretty new to Python world and trying to learn it.</p>
<p>This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)</p>
<pre><code>class Car():
carName = "" ... | 5 | 2009-07-22T10:19:34Z | 1,164,328 | <p>You don't define a variable, and you use <strong>init</strong> and self.
Like this:</p>
<pre><code>class Car(Object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
a = Car("bmw")
a.showName()
</code></pre>
| 1 | 2009-07-22T10:22:38Z | [
"python",
"class",
"object"
] |
Python object creation | 1,164,309 | <p>I am pretty new to Python world and trying to learn it.</p>
<p>This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)</p>
<pre><code>class Car():
carName = "" ... | 5 | 2009-07-22T10:19:34Z | 1,164,409 | <p>this is not correct!</p>
<pre><code>class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
</code></pre>
<p>the first carName is a <strong>class Variable</strong> like static member in c++</p>
<p>the ... | 1 | 2009-07-22T10:40:00Z | [
"python",
"class",
"object"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I ... | 11 | 2009-07-22T12:32:54Z | 1,164,988 | <p>If it's OK for you, there is a Django application ready, doing exactly what you want:
<a href="https://github.com/sorl/sorl-thumbnail" rel="nofollow">https://github.com/sorl/sorl-thumbnail</a></p>
| 7 | 2009-07-22T12:43:47Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I ... | 11 | 2009-07-22T12:32:54Z | 1,164,993 | <p>Not sure about the code you sent, because I never use Models as such, but there is another method.</p>
<p>You can implement your own <code>FileUploadHandler</code> for handling image file uploads. Example is
<a href="http://www.djangosnippets.org/snippets/1036/" rel="nofollow">here</a>.
Just after line 37 (<code>de... | 2 | 2009-07-22T12:44:10Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I ... | 11 | 2009-07-22T12:32:54Z | 1,165,042 | <p>A key question is: <strong>when</strong> should the thumbnail be generated?</p>
<ol>
<li>Dynamically when the user requests a thumbnail image?</li>
<li>Or do you want to create a physical disk file whenever a country is INSERTed/UPDATEd in the database.</li>
</ol>
<p>If (1) I suggest you create a view that maps to... | 2 | 2009-07-22T12:51:25Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I ... | 11 | 2009-07-22T12:32:54Z | 1,165,097 | <p>I guess it depends on how and when your using your thumbnails.</p>
<p>If you want to create some thumbnails every time the Country is saved, you could do it like so:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class C... | 2 | 2009-07-22T13:00:26Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I ... | 11 | 2009-07-22T12:32:54Z | 1,165,324 | <p>This is what I use in my models to save a new thumbnail if the uploaded image has changed. It's based of another DjangoSnippet but it I can't remember who wrote the orginal - if you know please add a comment so that I can credit them.</p>
<pre><code>from PIL import Image
from django.db import models
from django.con... | 4 | 2009-07-22T13:39:22Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I ... | 11 | 2009-07-22T12:32:54Z | 1,165,504 | <p>Overriding the save method is a good option, but I'd be more tempted to use a <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow">signal</a> in this case. Django signals allow you to "listen" to a given model type's various events; in this case, you'd be interested in the <code>post_save</... | 2 | 2009-07-22T14:03:32Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I ... | 11 | 2009-07-22T12:32:54Z | 1,165,940 | <p>Ryan is correct signals are a better way to go however the advantage of the overriden save is that we can get the old and new image paths, see if the image has changed (and if it has create a new thumbnail), save the model instance and then delete the old image and thumbnail.</p>
<p><em>Remember django does not cle... | 2 | 2009-07-22T15:01:54Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I ... | 11 | 2009-07-22T12:32:54Z | 1,335,728 | <p>I also swear by Justin Driscoll's <a href="http://code.google.com/p/django-photologue/" rel="nofollow">django-photologue</a> is also great for resizing. It:</p>
<ol>
<li><strong>Resizes</strong> (that is can be scaled to a height or width proportionately)</li>
<li><strong>Crops</strong> (kind-of intelligently: from... | 0 | 2009-08-26T15:51:36Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I ... | 11 | 2009-07-22T12:32:54Z | 6,321,526 | <p>You can give a try to:</p>
<p><a href="https://github.com/francescortiz/image" rel="nofollow">image headcut</a></p>
<p>features:</p>
<ul>
<li>Allows you to set the center of attention of an image... heads won't get cut anymore.</li>
<li>Video thumbnailing</li>
<li>Prevents cross-site image linking</li>
<li>Simple... | 2 | 2011-06-12T10:49:44Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I ... | 11 | 2009-07-22T12:32:54Z | 36,697,496 | <p>Another alternative is to use Imagemagick directly, if you want to avoid several difficulties with Pillow and Python 3 such as <a href="http://stackoverflow.com/questions/23970006/using-pillow-with-python-3">this one</a>.</p>
<pre><code>from subprocess import call
call(['convert', img_path_file_name, '-thumbnail', ... | 0 | 2016-04-18T14:54:54Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
SQLAlchemy - Models - using dynamic fields - ActiveRecord | 1,165,002 | <p>How close can I get to defining a model in SQLAlchemy like:</p>
<pre><code>class Person(Base):
pass
</code></pre>
<p>And just have it dynamically pick up the field names? anyway to get naming conventions to control the relationships between tables? I guess I'm looking for something similar to RoR's ActiveRec... | 1 | 2009-07-22T12:45:32Z | 1,165,050 | <p>It is very simple to automatically pick up the field names:</p>
<pre><code>from sqlalchemy import Table
from sqlalchemy.orm import MetaData, mapper
metadata = MetaData()
metadata.bind = engine
person_table = Table(metadata, "tablename", autoload=True)
class Person(object):
pass
mapper(Person, person_table)
... | 4 | 2009-07-22T12:53:21Z | [
"python",
"activerecord",
"ironpython",
"sqlalchemy"
] |
SQLAlchemy - Models - using dynamic fields - ActiveRecord | 1,165,002 | <p>How close can I get to defining a model in SQLAlchemy like:</p>
<pre><code>class Person(Base):
pass
</code></pre>
<p>And just have it dynamically pick up the field names? anyway to get naming conventions to control the relationships between tables? I guess I'm looking for something similar to RoR's ActiveRec... | 1 | 2009-07-22T12:45:32Z | 1,165,100 | <p>AFAIK sqlalchemy intentionally decouples database metadata and class layout. </p>
<p>You may should investigate Elixir (<a href="http://elixir.ematia.de/trac/wiki" rel="nofollow">http://elixir.ematia.de/trac/wiki</a>): Active Record Pattern for sqlalchemy, but you have to define the classes, not the database tables... | 2 | 2009-07-22T13:00:43Z | [
"python",
"activerecord",
"ironpython",
"sqlalchemy"
] |
Python: cannot read / write in another commandline application by using subprocess module | 1,165,064 | <p>I am using Python 3.0 in Windows and trying to automate the testing of a commandline application. The user can type commands in Application Under Test and it returns the output as 2 XML packets. One is a packet and the other one is an packet. By analyzing these packets I can verifyt he result. I ahev the code as b... | 1 | 2009-07-22T12:55:08Z | 1,165,126 | <p>Try sending your input using <code>communicate</code> instead of using <code>write</code>:</p>
<pre><code>result = p.communicate((command + '\r\n').encode())[0]
</code></pre>
| 0 | 2009-07-22T13:04:56Z | [
"python",
"subprocess",
"readline"
] |
Python: cannot read / write in another commandline application by using subprocess module | 1,165,064 | <p>I am using Python 3.0 in Windows and trying to automate the testing of a commandline application. The user can type commands in Application Under Test and it returns the output as 2 XML packets. One is a packet and the other one is an packet. By analyzing these packets I can verifyt he result. I ahev the code as b... | 1 | 2009-07-22T12:55:08Z | 1,165,421 | <p>This is a popular problem, e.g. see:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/1124884/interact-with-a-windows-console-application-via-python">http://stackoverflow.com/questions/1124884/interact-with-a-windows-console-application-via-python</a></li>
<li><a href="http://stackoverflow.com/questions/874... | 1 | 2009-07-22T13:52:50Z | [
"python",
"subprocess",
"readline"
] |
Python: cannot read / write in another commandline application by using subprocess module | 1,165,064 | <p>I am using Python 3.0 in Windows and trying to automate the testing of a commandline application. The user can type commands in Application Under Test and it returns the output as 2 XML packets. One is a packet and the other one is an packet. By analyzing these packets I can verifyt he result. I ahev the code as b... | 1 | 2009-07-22T12:55:08Z | 1,377,143 | <p>Have you considered using pexpect instead of subprocess? It handles the details which are probably preventing your code from working (like flushing buffers, etc). It may not be available for Py3k yet, but it works well in 2.x.</p>
<p>See: <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">http://p... | 0 | 2009-09-04T03:49:19Z | [
"python",
"subprocess",
"readline"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 1,165,398 | <p>not sure whether its "fast" or not, but normally, one can do this</p>
<pre><code>dicta = {"a":1,"b":2,"c":3,"d":4}
dictb = {"a":1,"d":2}
for key in dicta.keys():
if not key in dictb:
print key
</code></pre>
| 14 | 2009-07-22T13:48:39Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 1,165,429 | <p>As Alex Martelli wrote, if you simply want to check if any key in B is not in A, <code>any(True for k in dictB if k not in dictA)</code> would be the way to go.</p>
<p>To find the keys that are missing:</p>
<pre><code>diff = set(dictB)-set(dictA) #sets
C:\Dokumente und Einstellungen\thc>python -m timeit -s "d... | 14 | 2009-07-22T13:53:29Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 1,165,552 | <p>You can use set operations on the keys:</p>
<pre><code>diff = set(dictb.keys()) - set(dicta.keys())
</code></pre>
<p>Here is a class to find all the possibilities: what was added, what was removed, which key-value pairs are the same, and which key-value pairs are changed.</p>
<pre><code>class DictDiffer(object):
... | 176 | 2009-07-22T14:11:51Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 1,166,569 | <p>If you really mean exactly what you say (that you only need to find out IF "there are any keys" in B and not in A, not WHICH ONES might those be if any), the fastest way should be:</p>
<pre><code>if any(True for k in dictB if k not in dictA): ...
</code></pre>
<p>If you actually need to find out WHICH KEYS, if any... | 12 | 2009-07-22T16:39:16Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 1,166,667 | <p>Here's a way that will work, allows for keys that evaluate to <code>False</code>, and still uses a generator expression to fall out early if possible. It's not exceptionally pretty though.</p>
<pre><code>any(map(lambda x: True, (k for k in b if k not in a)))
</code></pre>
<p><strong>EDIT:</strong></p>
<p>THC4k po... | 2 | 2009-07-22T16:56:13Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 7,724,964 | <p>If on Python ⥠2.7:</p>
<pre><code># update different values in dictB
# I would assume only dictA should be updated,
# but the question specifies otherwise
for k in dictA.viewkeys() & dictB.viewkeys():
if dictA[k] != dictB[k]:
dictB[k]= dictA[k]
# add missing keys to dictA
dictA.update( (k,dict... | 2 | 2011-10-11T11:01:05Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 9,024,729 | <p>what about standart (compare FULL Object)</p>
<p>PyDev->new PyDev Module->Module: unittest</p>
<pre><code>import unittest
class Test(unittest.TestCase):
def testName(self):
obj1 = {1:1, 2:2}
obj2 = {1:1, 2:2}
self.maxDiff = None # sometimes is usefull
self.assertDictEqual(d1... | 0 | 2012-01-26T20:19:12Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 16,451,938 | <p>Not sure if it is still relevant but I came across this problem, my situation i just needed to return a dictionary of the changes for all nested dictionaries etc etc. Could not find a good solution out there but I did end up <a href="https://github.com/jmickle/jmickle/blob/master/recurse_dicts.py" rel="nofollow">wri... | 0 | 2013-05-08T23:33:07Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 19,634,030 | <p>There is an other <a href="http://stackoverflow.com/questions/6632244/difference-in-a-dict">question in stackoverflow about this argument</a> and i have to admit that there is a simple solution explained: the <a href="https://pypi.python.org/pypi/datadiff" rel="nofollow">datadiff library</a> of python helps printing... | 4 | 2013-10-28T11:47:32Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 23,134,762 | <p>This is an old question and asks a little bit less than what I needed so this answer actually solves more than this question asks. The answers in this question helped me solve the following:</p>
<ol>
<li>(asked) Record differences between two dictionaries</li>
<li>Merge differences from #1 into base dictionary</li>... | 1 | 2014-04-17T13:40:38Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 26,079,022 | <p>In case you want the difference recursively, I have written a package for python:
<a href="https://github.com/seperman/deepdiff">https://github.com/seperman/deepdiff</a></p>
<h2>Installation</h2>
<p>Install from PyPi:</p>
<pre><code>pip install deepdiff
</code></pre>
<h2>Example usage</h2>
<p>Importing</p>
<pr... | 23 | 2014-09-27T20:41:27Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 26,776,247 | <p>Here is a solution for deep comparing 2 dictionaries keys:</p>
<pre><code>def compareDictKeys(dict1, dict2):
if type(dict1) != dict or type(dict2) != dict:
return False
keys1, keys2 = dict1.keys(), dict2.keys()
diff = set(keys1) - set(keys2) or set(keys2) - set(keys1)
if not diff:
for key in k... | 1 | 2014-11-06T09:49:39Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 27,717,113 | <p>If you want a built-in solution for a full comparison with arbitrary dict structures, @Maxx's answer is a good start.</p>
<pre><code>import unittest
test = unittest.TestCase()
test.assertEqual(dictA, dictB)
</code></pre>
| 0 | 2014-12-31T06:26:57Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 28,974,718 | <p>here's a solution that can compare more than two dicts:</p>
<pre><code>def diff_dict(dicts, default=None):
diff_dict = {}
# add 'list()' around 'd.keys()' for python 3 compatibility
for k in set(sum([d.keys() for d in dicts], [])):
# we can just use "values = [d.get(k, default) ..." below if
... | 0 | 2015-03-10T21:47:16Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 30,861,178 | <p>Based on ghostdog74's answer,</p>
<pre><code>dicta = {"a":1,"d":2}
dictb = {"a":5,"d":2}
for value in dicta.values():
if not value in dictb.values():
print value
</code></pre>
<p>will print differ value of dicta</p>
| 0 | 2015-06-16T07:20:51Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 35,925,928 | <p>Below i created two dictionaries. I need to return the key and value differences between them. I am stuck here. I am not sure which way is correct. I need to know how to get the key value difference. I want to first check if they are the same and if they are not to print key -value differences. I dont want to use de... | 0 | 2016-03-10T19:50:56Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 37,835,849 | <p>My recipe of symmetric difference between two dictionaries:</p>
<pre><code>def find_dict_diffs(dict1, dict2):
unequal_keys = []
unequal_keys.extend(set(dict1.keys()).symmetric_difference(set(dict2.keys())))
for k in dict1.keys():
if dict1.get(k, 'N\A') != dict2.get(k, 'N\A'):
unequal... | 0 | 2016-06-15T12:44:04Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 38,405,539 | <p>As mentioned in other answers, unittest produces some nice output for comparing dicts, but in this example we don't want to have to build a whole test first.</p>
<p>Scraping the unittest source, it looks like you can get a fair solution with just this:</p>
<pre><code>import difflib
import pprint
def diff_dicts(a,... | 0 | 2016-07-15T21:55:48Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 38,516,027 | <p>Try this to find de intersection, the keys that is in both dictionarie, if you want the keys not found on second dictionarie, just use the <strong>not in</strong>...</p>
<pre><code>intersect = filter(lambda x, dictB=dictB.keys(): x in dictB, dictA.keys())
</code></pre>
| 0 | 2016-07-21T23:40:03Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<... | 112 | 2009-07-22T13:43:13Z | 38,645,967 | <p>use set(), documentation in <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">https://docs.python.org/2/library/sets.html</a></p>
<p>Example:</p>
<p>set(dictA.keys()).intersection(dictB.keys())</p>
| 2 | 2016-07-28T20:16:35Z | [
"python",
"dictionary"
] |
Using select/poll/kqueue/kevent to watch a directory for new files | 1,165,571 | <p>In my app I need to watch a directory for new files. The amount of traffic is very large and there are going to be a minimum of hundreds of new files per second appearing. Currently I'm using a busy loop with this kind of idea:</p>
<pre><code>while True:
time.sleep(0.2)
if len(os.listdir('.')) > 0:
# do ... | 5 | 2009-07-22T14:13:56Z | 1,178,398 | <p>Why not use a Python wrapper for one of the libraries for monitoring file changes, like <a href="http://www.gnome.org/~veillard/gamin/python.html" rel="nofollow">gamin</a> or inotify (search for pyinotify, I'm only allowed to post one hyperlink as a new user...) - that's sure to be faster and the low-level stuff is ... | 3 | 2009-07-24T15:24:38Z | [
"python",
"asynchronous",
"freebsd",
"polling"
] |
Using select/poll/kqueue/kevent to watch a directory for new files | 1,165,571 | <p>In my app I need to watch a directory for new files. The amount of traffic is very large and there are going to be a minimum of hundreds of new files per second appearing. Currently I'm using a busy loop with this kind of idea:</p>
<pre><code>while True:
time.sleep(0.2)
if len(os.listdir('.')) > 0:
# do ... | 5 | 2009-07-22T14:13:56Z | 1,180,643 | <blockquote>
<p>After running profiling I'm seeing a lot of time spent in the sleep, and I'm wondering if I should change this to use polling instead. </p>
</blockquote>
<p>Looks like you already <em>do</em> synchronous polling, by checking the state at regular intervals. Don't worry about the time "spent" in <code>... | 1 | 2009-07-24T23:24:14Z | [
"python",
"asynchronous",
"freebsd",
"polling"
] |
Using select/poll/kqueue/kevent to watch a directory for new files | 1,165,571 | <p>In my app I need to watch a directory for new files. The amount of traffic is very large and there are going to be a minimum of hundreds of new files per second appearing. Currently I'm using a busy loop with this kind of idea:</p>
<pre><code>while True:
time.sleep(0.2)
if len(os.listdir('.')) > 0:
# do ... | 5 | 2009-07-22T14:13:56Z | 1,458,591 | <p>FreeBSD and thus Mac OS X provide an analog of inotify called kqueue. Type man 2 kqueue on a FreeBSD machine for more information. For kqueue on Freebsd you have PyKQueue available at <a href="http://people.freebsd.org/~dwhite/PyKQueue/">http://people.freebsd.org/~dwhite/PyKQueue/</a>, unfortunately is not actively ... | 6 | 2009-09-22T07:24:01Z | [
"python",
"asynchronous",
"freebsd",
"polling"
] |
Using select/poll/kqueue/kevent to watch a directory for new files | 1,165,571 | <p>In my app I need to watch a directory for new files. The amount of traffic is very large and there are going to be a minimum of hundreds of new files per second appearing. Currently I'm using a busy loop with this kind of idea:</p>
<pre><code>while True:
time.sleep(0.2)
if len(os.listdir('.')) > 0:
# do ... | 5 | 2009-07-22T14:13:56Z | 1,459,945 | <p>You might want to have a look at <a href="http://docs.python.org/library/select.html#kqueue-objects" rel="nofollow">select.kqueue</a> - I've not used it but kqueue is the right interface for this under BSD I believe so you can monitor files / directories and be called back when and only when they change</p>
| 0 | 2009-09-22T12:58:52Z | [
"python",
"asynchronous",
"freebsd",
"polling"
] |
Using select/poll/kqueue/kevent to watch a directory for new files | 1,165,571 | <p>In my app I need to watch a directory for new files. The amount of traffic is very large and there are going to be a minimum of hundreds of new files per second appearing. Currently I'm using a busy loop with this kind of idea:</p>
<pre><code>while True:
time.sleep(0.2)
if len(os.listdir('.')) > 0:
# do ... | 5 | 2009-07-22T14:13:56Z | 4,448,422 | <p>I've written a library and a shell tool that should handle this for you.</p>
<p><a href="http://github.com/gorakhargosh/watchdog" rel="nofollow">http://github.com/gorakhargosh/watchdog</a></p>
<p>Although, kqueue is a very heavyweight way to monitor directories
I'd appreciate if you can test and checkout any perfo... | 0 | 2010-12-15T09:26:56Z | [
"python",
"asynchronous",
"freebsd",
"polling"
] |
Is it safe to track trunk in Django? | 1,165,631 | <p>I'm currently using <code>Django 1.1 beta</code> for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if <code>trunk</code> is stable enough for using in production, or I should stick... | 2 | 2009-07-22T14:22:12Z | 1,165,715 | <p>As with the trunk of any software project, it's only as stable as the people commiting things test for. Typically this is probably pretty stable, but you need to be aware that if you get caught with a 'bad' version (which can happen), your site/s just might come down over it temporarily.</p>
| 0 | 2009-07-22T14:32:01Z | [
"python",
"django"
] |
Is it safe to track trunk in Django? | 1,165,631 | <p>I'm currently using <code>Django 1.1 beta</code> for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if <code>trunk</code> is stable enough for using in production, or I should stick... | 2 | 2009-07-22T14:22:12Z | 1,165,718 | <p>You probably shouldn't pull Django trunk <em>every</em> day, sometimes there are big commits that might break some things on your site. Also it depends what features you use, the new ones will of cause be a bit more buggy than older features. But all in all there shouldn't be a problem using trunk for production. Yo... | 2 | 2009-07-22T14:32:41Z | [
"python",
"django"
] |
Is it safe to track trunk in Django? | 1,165,631 | <p>I'm currently using <code>Django 1.1 beta</code> for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if <code>trunk</code> is stable enough for using in production, or I should stick... | 2 | 2009-07-22T14:22:12Z | 1,185,666 | <p>I think you've done a good job of gathering the right links in the question. The only links I would add are:</p>
<ul>
<li><a href="http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges" rel="nofollow">http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges</a></li>
<li><a href="http://code.django... | 1 | 2009-07-26T21:55:39Z | [
"python",
"django"
] |
Is it safe to track trunk in Django? | 1,165,631 | <p>I'm currently using <code>Django 1.1 beta</code> for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if <code>trunk</code> is stable enough for using in production, or I should stick... | 2 | 2009-07-22T14:22:12Z | 1,249,054 | <p>First, <a href="http://docs.djangoproject.com/en/dev/releases/1.1-rc-1/" rel="nofollow">Django 1.1</a> is <a href="http://www.djangoproject.com/weblog/2009/jul/21/rc/" rel="nofollow">one step closer to being released</a>, as <a href="http://www.djangoproject.com/download/" rel="nofollow">RC1 is available for downloa... | 0 | 2009-08-08T14:39:57Z | [
"python",
"django"
] |
Is it safe to track trunk in Django? | 1,165,631 | <p>I'm currently using <code>Django 1.1 beta</code> for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if <code>trunk</code> is stable enough for using in production, or I should stick... | 2 | 2009-07-22T14:22:12Z | 1,249,509 | <p>For what it's worth, I've read in multiple places (in the documentation here: <a href="http://www.djangoproject.com/download/" rel="nofollow">http://www.djangoproject.com/download/</a> (see the side bar) and from the project's lead developers in a book of theirs) that it's fine to use the trunk. Many of their own de... | 0 | 2009-08-08T18:02:30Z | [
"python",
"django"
] |
Including current date in python logging file | 1,165,856 | <p>I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name?</p>
<p>Because I restart the process every morning the TimedRotatingFileHandler won't work. The project is larger, so I would be interest... | 2 | 2009-07-22T14:50:32Z | 1,165,912 | <p>You may be interested in the TimedRotatingFileHandler see <a href="http://docs.python.org/library/logging.html#logging.handlers.TimedRotatingFileHandler" rel="nofollow">http://docs.python.org/library/logging.html#logging.handlers.TimedRotatingFileHandler</a></p>
| 0 | 2009-07-22T14:56:06Z | [
"python",
"logging"
] |
Including current date in python logging file | 1,165,856 | <p>I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name?</p>
<p>Because I restart the process every morning the TimedRotatingFileHandler won't work. The project is larger, so I would be interest... | 2 | 2009-07-22T14:50:32Z | 1,165,931 | <p>You can use the <a href="http://docs.python.org/2/library/logging.handlers.html#timedrotatingfilehandler" rel="nofollow">TimedRotatingFileHandler</a>. For example:</p>
<pre><code>import logging
import logging.handlers
LOG_FILENAME = '/tmp/log'
# Set up a specific logger with our desired output level
log = logging... | 8 | 2009-07-22T14:59:47Z | [
"python",
"logging"
] |
How to strip decorators from a function in python | 1,166,118 | <p>Let's say I have the following:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
</code></pre>
<p>I want to test the <code>spam</code> function without going thr... | 34 | 2009-07-22T15:29:41Z | 1,166,200 | <p>In the general case, you can't, because</p>
<pre><code>@with_connection
def spam(connection):
# Do something
</code></pre>
<p>is equivalent to</p>
<pre><code>def spam(connection):
# Do something
spam = with_connection(spam)
</code></pre>
<p>which means that the "original" spam might not even exist anymo... | 23 | 2009-07-22T15:42:28Z | [
"python",
"decorator"
] |
How to strip decorators from a function in python | 1,166,118 | <p>Let's say I have the following:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
</code></pre>
<p>I want to test the <code>spam</code> function without going thr... | 34 | 2009-07-22T15:29:41Z | 1,166,227 | <p>Behold, FuglyHackThatWillWorkForYourExampleButICantPromiseAnythingElse:</p>
<pre><code> orig_spam = spam.func_closure[0].cell_contents
</code></pre>
<p><strong>Edit</strong>: For functions/methods decorated more than once and with more complicated decorators you can try using the following code. It relies on the f... | 12 | 2009-07-22T15:45:22Z | [
"python",
"decorator"
] |
How to strip decorators from a function in python | 1,166,118 | <p>Let's say I have the following:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
</code></pre>
<p>I want to test the <code>spam</code> function without going thr... | 34 | 2009-07-22T15:29:41Z | 1,167,248 | <p>balpha's solution can be made more generalizable with this meta-decorator:</p>
<pre><code>def include_original(dec):
def meta_decorator(f):
decorated = dec(f)
decorated._original = f
return decorated
return meta_decorator
</code></pre>
<p>Then you can decorate your decorators with @... | 22 | 2009-07-22T18:31:07Z | [
"python",
"decorator"
] |
How to strip decorators from a function in python | 1,166,118 | <p>Let's say I have the following:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
</code></pre>
<p>I want to test the <code>spam</code> function without going thr... | 34 | 2009-07-22T15:29:41Z | 1,168,448 | <p>The usual approach to testing such functions is to make any dependencies, such as get_connection, configurable. Then you can override it with a mock while testing. Basically the same as dependency injection in the Java world but a lot simpler thanks to Pythons dynamic nature.</p>
<p>Code for it might look something... | 2 | 2009-07-22T21:43:04Z | [
"python",
"decorator"
] |
How to strip decorators from a function in python | 1,166,118 | <p>Let's say I have the following:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
</code></pre>
<p>I want to test the <code>spam</code> function without going thr... | 34 | 2009-07-22T15:29:41Z | 1,169,178 | <p>Instead of doing..</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
orig_spam = magic_hack_of_a_function(spam)
</code></pre>
<p>You could just do..</p>
<pre><c... | 5 | 2009-07-23T01:51:05Z | [
"python",
"decorator"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.