title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Print Tuple Index in Python | 2,464,808 | <p>This question falls into the "yes - this works, yes - this is ugly, yes - there is probably a better way" category. I want to use a regular expression to pull groups out of a match and then print the group number and the group value. It is to show someone how regular expressions work and to keep track of the values ... | 0 | 2010-03-17T18:22:59Z | 2,464,831 | <pre><code> for index, group in enumerate(FundTypeGroups):
print "%s: %s" % (index, group)
</code></pre>
<p>(and the variables should not start with a capital letter...)</p>
| 4 | 2010-03-17T18:25:52Z | [
"python",
"indexing",
"tuples"
] |
Rewriting An URL With Regular Expression Substitution in Routes | 2,464,844 | <p>In my Pylons app, some content is located at URLs that look like <a href="http://mysite/data/31415" rel="nofollow">http://mysite/data/31415</a>. Users can go to that URL directly, or search for "31415" via the search page. My constraints, however, mean that <a href="http://mysite/data/000031415" rel="nofollow">htt... | 1 | 2010-03-17T18:27:50Z | 2,465,788 | <p>I know I am cheating by introducing a different routing library, since I haven't used <code>Routes</code>, but here's how this is done with <code>Werkzeug</code>'s routing package. It lets you specify that a given fragment of the path is an integer. You can also implement a more specialized "converter" by inheriting... | 0 | 2010-03-17T20:49:28Z | [
"python",
"routes",
"pylons"
] |
Rewriting An URL With Regular Expression Substitution in Routes | 2,464,844 | <p>In my Pylons app, some content is located at URLs that look like <a href="http://mysite/data/31415" rel="nofollow">http://mysite/data/31415</a>. Users can go to that URL directly, or search for "31415" via the search page. My constraints, however, mean that <a href="http://mysite/data/000031415" rel="nofollow">htt... | 1 | 2010-03-17T18:27:50Z | 3,836,044 | <p>You can actually do that via <a href="http://routes.groovie.org/manual.html#conditions" rel="nofollow">conditional functions</a>, since they let you modify the variables from the URL in place. </p>
| 1 | 2010-10-01T01:57:41Z | [
"python",
"routes",
"pylons"
] |
Python or matplotlib limitation error | 2,464,863 | <p>I wrote an algorithm using python and matplotlib that generates histograms from some text input data. When the number of data input is approx. greater than 15000, I get in the (append) line of my code:</p>
<pre><code>mydata = []
for i in range(len(data)):
mydata.append(string.atof(data[i]))
</code></pre>
<p>th... | 1 | 2010-03-17T18:30:08Z | 2,464,931 | <p>That's a data parsing error:</p>
<pre><code>>>> float("-a")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): -a
</code></pre>
<p>Python data structure size if only limited by the available memory.</p>
| 1 | 2010-03-17T18:39:14Z | [
"python",
"matplotlib"
] |
Numpy histogram of large arrays | 2,464,871 | <p>I have a bunch of csv datasets, about 10Gb in size each. I'd like to generate histograms from their columns. But it seems like the only way to do this in numpy is to first load the entire column into a numpy array and then call <code>numpy.histogram</code> on that array. This consumes an unnecessary amount of memory... | 12 | 2010-03-17T18:31:09Z | 2,465,026 | <p>Here's a way to bin your values directly:</p>
<pre><code>import numpy as NP
column_of_values = NP.random.randint(10, 99, 10)
# set the bin values:
bins = NP.array([0.0, 20.0, 50.0, 75.0])
binned_values = NP.digitize(column_of_values, bins)
</code></pre>
<p>'binned_values' is an index array, containing the index... | 6 | 2010-03-17T18:53:27Z | [
"python",
"numpy",
"scipy",
"histogram"
] |
Numpy histogram of large arrays | 2,464,871 | <p>I have a bunch of csv datasets, about 10Gb in size each. I'd like to generate histograms from their columns. But it seems like the only way to do this in numpy is to first load the entire column into a numpy array and then call <code>numpy.histogram</code> on that array. This consumes an unnecessary amount of memory... | 12 | 2010-03-17T18:31:09Z | 2,465,323 | <p>As you said, it's not that hard to roll your own. You'll need to set up the bins yourself and reuse them as you iterate over the file. The following ought to be a decent starting point:</p>
<pre><code>import numpy as np
datamin = -5
datamax = 5
numbins = 20
mybins = np.linspace(datamin, datamax, numbins)
myhist =... | 8 | 2010-03-17T19:43:20Z | [
"python",
"numpy",
"scipy",
"histogram"
] |
Numpy histogram of large arrays | 2,464,871 | <p>I have a bunch of csv datasets, about 10Gb in size each. I'd like to generate histograms from their columns. But it seems like the only way to do this in numpy is to first load the entire column into a numpy array and then call <code>numpy.histogram</code> on that array. This consumes an unnecessary amount of memory... | 12 | 2010-03-17T18:31:09Z | 20,826,401 | <p><strong>Binning with Generators</strong> (<em>large dataset; fixed-width bins; float data</em>)</p>
<p>If you know the width of your desired bins ahead of time -- even if there are hundreds or thousands of buckets -- then I think rolling your own solution would be fast (both to write, and to run). Here's some Pyt... | 2 | 2013-12-29T14:55:13Z | [
"python",
"numpy",
"scipy",
"histogram"
] |
Numpy histogram of large arrays | 2,464,871 | <p>I have a bunch of csv datasets, about 10Gb in size each. I'd like to generate histograms from their columns. But it seems like the only way to do this in numpy is to first load the entire column into a numpy array and then call <code>numpy.histogram</code> on that array. This consumes an unnecessary amount of memory... | 12 | 2010-03-17T18:31:09Z | 20,826,889 | <p><strong>Binning with a Fenwick Tree</strong> <em>(very large dataset; percentile boundaries needed)</em></p>
<p><em>I'm posting a second answer to the same question since this approach is very different, and addresses different issues.</em></p>
<p>What if you have a VERY large dataset (billions of samples), and yo... | 3 | 2013-12-29T15:43:14Z | [
"python",
"numpy",
"scipy",
"histogram"
] |
What's the u prefix in a python string | 2,464,959 | <p>Like in: </p>
<pre><code>u'Hello'
</code></pre>
<p>My guess is that it indicates "unicode", is it correct?</p>
<p>If so, since when is it available?</p>
| 92 | 2010-03-17T18:43:20Z | 2,464,968 | <p>You're right.</p>
<p><a href="http://docs.python.org/2/tutorial/introduction.html#unicode-strings" rel="nofollow">http://docs.python.org/2/tutorial/introduction.html#unicode-strings</a></p>
<p>It's been syntax since 2.0.</p>
| 49 | 2010-03-17T18:45:05Z | [
"python",
"syntax"
] |
What's the u prefix in a python string | 2,464,959 | <p>Like in: </p>
<pre><code>u'Hello'
</code></pre>
<p>My guess is that it indicates "unicode", is it correct?</p>
<p>If so, since when is it available?</p>
| 92 | 2010-03-17T18:43:20Z | 2,464,974 | <blockquote>
<p>My guess is that it indicates "unicode", is it correct?</p>
</blockquote>
<p>Yes.</p>
<blockquote>
<p>If so, since when is it available?</p>
</blockquote>
<p>Python 2.x.</p>
<p>(In Python 3.x the strings use Unicode by default and there's no need for the <code>u</code> prefix.)</p>
| 24 | 2010-03-17T18:45:32Z | [
"python",
"syntax"
] |
What's the u prefix in a python string | 2,464,959 | <p>Like in: </p>
<pre><code>u'Hello'
</code></pre>
<p>My guess is that it indicates "unicode", is it correct?</p>
<p>If so, since when is it available?</p>
| 92 | 2010-03-17T18:43:20Z | 2,465,010 | <p>The following should help:</p>
<p><a href="http://docs.python.org/library/functions.html#unicode" rel="nofollow">http://docs.python.org/library/functions.html#unicode</a></p>
<p><a href="http://www.amk.ca/python/howto/unicode" rel="nofollow">http://www.amk.ca/python/howto/unicode</a> (skip down to "Python's Unicod... | 2 | 2010-03-17T18:50:52Z | [
"python",
"syntax"
] |
What's the u prefix in a python string | 2,464,959 | <p>Like in: </p>
<pre><code>u'Hello'
</code></pre>
<p>My guess is that it indicates "unicode", is it correct?</p>
<p>If so, since when is it available?</p>
| 92 | 2010-03-17T18:43:20Z | 2,465,020 | <p><strong>All strings meant for humans should use u"".</strong></p>
<p>I found that the following mindset helps a lot when dealing with Python string. <strong>All</strong> python manifest strings should use <code>u""</code> syntax, the <code>""</code> syntax is for byte arrays, only.</p>
<p>Before the bashing begins... | 2 | 2010-03-17T18:51:57Z | [
"python",
"syntax"
] |
What's the u prefix in a python string | 2,464,959 | <p>Like in: </p>
<pre><code>u'Hello'
</code></pre>
<p>My guess is that it indicates "unicode", is it correct?</p>
<p>If so, since when is it available?</p>
| 92 | 2010-03-17T18:43:20Z | 16,741,817 | <p>The u in <code>u'Some String'</code> means that your string is a <em>unicode string</em>. </p>
<p><em>Q: I'm in a terrible, awful hurry and I landed here from google. I'm trying to write this data to a file and I'm getting an error and I need the dead simplest, probably flawed, solution this second.</em></p>
<p>... | 58 | 2013-05-24T18:55:03Z | [
"python",
"syntax"
] |
What's the u prefix in a python string | 2,464,959 | <p>Like in: </p>
<pre><code>u'Hello'
</code></pre>
<p>My guess is that it indicates "unicode", is it correct?</p>
<p>If so, since when is it available?</p>
| 92 | 2010-03-17T18:43:20Z | 27,378,987 | <p>Its Unicode.</p>
<p>Just put the variable between <code>str()</code> and it will work fine</p>
<p>But in case u have two lists like following :</p>
<pre><code>a = ['co32','co36']
b = [u'co32',u'co36']
</code></pre>
<p>if u check <code>set(a)==set(b)</code> ,it will come as False but if you do as follows: </p>
<... | 0 | 2014-12-09T12:28:47Z | [
"python",
"syntax"
] |
Artificial Intelligence in online game using Google App Engine | 2,465,056 | <p>I am currently in the planning stages of a game for google app engine, but cannot wrap my head around how I am going to handle AI. I intend to have persistant NPCs that will move about the map, but short of writing a program that generates the same XML requests I use to control player actions, than run it on anothe... | 2 | 2010-03-17T18:59:49Z | 2,465,142 | <p>Will your game be turn based or real time?</p>
<p>Either way, I think you have 2 options to look into. One is to use the Cron feature so you can schedule NPC updates at regular intervals, the other is to stick a "update NPCs" task into the Task Queue every time a human player moves.</p>
| 3 | 2010-03-17T19:11:58Z | [
"python",
"google-app-engine",
"artificial-intelligence"
] |
Artificial Intelligence in online game using Google App Engine | 2,465,056 | <p>I am currently in the planning stages of a game for google app engine, but cannot wrap my head around how I am going to handle AI. I intend to have persistant NPCs that will move about the map, but short of writing a program that generates the same XML requests I use to control player actions, than run it on anothe... | 2 | 2010-03-17T18:59:49Z | 2,471,015 | <p>If the game is turn based then it would probably be best to avoid the Cron task and just update the NPCs every time the player moves. I'm not sure how big of a map you are planning on but you may consider even having the player object find the NPCs that are close to it and call their AI routine. That way NPCs that ... | 2 | 2010-03-18T15:26:32Z | [
"python",
"google-app-engine",
"artificial-intelligence"
] |
Artificial Intelligence in online game using Google App Engine | 2,465,056 | <p>I am currently in the planning stages of a game for google app engine, but cannot wrap my head around how I am going to handle AI. I intend to have persistant NPCs that will move about the map, but short of writing a program that generates the same XML requests I use to control player actions, than run it on anothe... | 2 | 2010-03-17T18:59:49Z | 2,471,126 | <p>Bear in mind that you can also break up your updates into multiple requests (internally): do a bit of work, redirect to the same handler but different state; do more work; etc. (I'm failing somehow to comment on Peter Recore's answer, which is where this really belongs.)</p>
<p>I see that the free service only all... | 2 | 2010-03-18T15:37:36Z | [
"python",
"google-app-engine",
"artificial-intelligence"
] |
RotatingFileHandler throws an exception when delay parameter is set | 2,465,073 | <p>When I run the following code under Python 2.6</p>
<pre><code>import logging
from logging.handlers import RotatingFileHandler
rfh = RotatingFileHandler("testing.log", delay=True)
logging.getLogger().addHandler(rfh)
logging.warning("Boo!")
</code></pre>
<p>then the last line throws <code>AttributeError: RotatingFi... | 3 | 2010-03-17T19:02:06Z | 2,465,133 | <p>I think I've just figured this out:</p>
<p>So it looks like one of the parent <code>__init__</code> methods somewhere up the class hierarchy isn't getting called when delay is set. Indeed, examining the source code to the file <code>logging/__init__.py</code> in my Python install, I see the following code in the <... | 0 | 2010-03-17T19:11:10Z | [
"python",
"logging",
"handlers"
] |
RotatingFileHandler throws an exception when delay parameter is set | 2,465,073 | <p>When I run the following code under Python 2.6</p>
<pre><code>import logging
from logging.handlers import RotatingFileHandler
rfh = RotatingFileHandler("testing.log", delay=True)
logging.getLogger().addHandler(rfh)
logging.warning("Boo!")
</code></pre>
<p>then the last line throws <code>AttributeError: RotatingFi... | 3 | 2010-03-17T19:02:06Z | 2,466,705 | <p>I've investigated this issue: it was fixed in Python SVN r68829 dated 20 Jan, 2009. This was after the release of 2.6.1 but before the release of 2.6.2.</p>
<p>Please upgrade to Python 2.6.2, or a later version.</p>
<p>I've updated <a href="http://bugs.python.org/issue8165" rel="nofollow">the bug you filed</a>. BT... | 4 | 2010-03-17T23:44:49Z | [
"python",
"logging",
"handlers"
] |
Working with multiple input and output files in Python | 2,465,130 | <p>I need to open multiple files (2 input and 2 output files), do complex manipulations on the lines from input files and then append results at the end of 2 output files. I am currently using the following approach:</p>
<pre><code>in_1 = open(input_1)
in_2 = open(input_2)
out_1 = open(output_1, "w")
out_2 = open(outp... | 0 | 2010-03-17T19:10:50Z | 2,465,152 | <p><a href="http://docs.python.org/library/contextlib.html#contextlib.nested"><code>contextlib.nested()</code></a> allows you to chain multiple context managers in a single statement:</p>
<pre><code>with contextlib.nested(open(...), open(...), ...) as (in_1, in_2, ...):
....
</code></pre>
| 5 | 2010-03-17T19:13:31Z | [
"file",
"python"
] |
Python crashes when plotting with matplotlib in module importing swig generated wrapper | 2,465,146 | <p>I have a python module that imports a module generated with swig. When I try to call the show() function of matplotlib later in that module, python crashes without any hint, what went wrong. When I comment the import statement with the swig generated module out, everything works fine.
Does anybody have a clue to wha... | 2 | 2010-03-17T19:12:35Z | 2,465,319 | <p>I'd start with running the script under gdb and looking at the stack trace. Recent versions of gdb have built in support for python debugging.</p>
<pre><code>$ gdb python
(gdb) run /path/to/script.py
# wait for crash #
(gdb) bt
# stack trace here #
</code></pre>
<p>More <a href="http://wiki.python.org/moin/Debugg... | 1 | 2010-03-17T19:42:53Z | [
"python",
"crash",
"matplotlib",
"swig",
"show"
] |
Python crashes when plotting with matplotlib in module importing swig generated wrapper | 2,465,146 | <p>I have a python module that imports a module generated with swig. When I try to call the show() function of matplotlib later in that module, python crashes without any hint, what went wrong. When I comment the import statement with the swig generated module out, everything works fine.
Does anybody have a clue to wha... | 2 | 2010-03-17T19:12:35Z | 14,418,197 | <p>I suspect that you call figure.show instead of plt.show()</p>
<p>The following script crash:</p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([25, 43, 65], [3500, 5500, 5800])
fig.show() # use plt.show() instead
</code></pre>
<p>This script is working fine:</p... | 1 | 2013-01-19T19:48:44Z | [
"python",
"crash",
"matplotlib",
"swig",
"show"
] |
Splitting only long words in string | 2,465,356 | <p>I have some random string, let's say :</p>
<pre><code>s = "This string has some verylongwordsneededtosplit"
</code></pre>
<p>I'm trying to write a function trunc_string(string, len) that takes string as argument to operate on and 'len' as the number of chars after long words will be splitted.</p>
<p>The result sh... | 1 | 2010-03-17T19:48:50Z | 2,465,411 | <p>Why not:</p>
<pre><code> def truncate_long_words(s, num):
"""Splits long words in string"""
words = s.split()
for word in words:
if len(word) > num:
for i in xrange(0,len(word),num):
yield word[i:i+num]
else:
yield word
for t in... | 3 | 2010-03-17T19:56:54Z | [
"python",
"string",
"split"
] |
Splitting only long words in string | 2,465,356 | <p>I have some random string, let's say :</p>
<pre><code>s = "This string has some verylongwordsneededtosplit"
</code></pre>
<p>I'm trying to write a function trunc_string(string, len) that takes string as argument to operate on and 'len' as the number of chars after long words will be splitted.</p>
<p>The result sh... | 1 | 2010-03-17T19:48:50Z | 2,465,424 | <p>Abusing regex:</p>
<pre><code>import re
def trunc_string(s, num):
re.sub("(\\w{%d}\\B)" % num, "\\1 ", s)
assert "This string has some verylongwo rdsneededt osplit" == trunc_string("This string has some verylongwordsneededtosplit", 10)
</code></pre>
<p>(Edit: adopted simplification by Brian. Thanks. But I kept... | 2 | 2010-03-17T19:58:52Z | [
"python",
"string",
"split"
] |
Splitting only long words in string | 2,465,356 | <p>I have some random string, let's say :</p>
<pre><code>s = "This string has some verylongwordsneededtosplit"
</code></pre>
<p>I'm trying to write a function trunc_string(string, len) that takes string as argument to operate on and 'len' as the number of chars after long words will be splitted.</p>
<p>The result sh... | 1 | 2010-03-17T19:48:50Z | 2,465,536 | <pre><code>def split_word(word, length=10):
return (word[n:n+length] for n in range(0, len(word), length))
string = "This string has some verylongwordsneededtosplit"
print [item for word in string.split() for item in split_word(word)]
# ['This', 'string', 'has', 'some', 'verylongwo', 'rdsneededt', 'osplit']
</cod... | 6 | 2010-03-17T20:17:44Z | [
"python",
"string",
"split"
] |
Splitting only long words in string | 2,465,356 | <p>I have some random string, let's say :</p>
<pre><code>s = "This string has some verylongwordsneededtosplit"
</code></pre>
<p>I'm trying to write a function trunc_string(string, len) that takes string as argument to operate on and 'len' as the number of chars after long words will be splitted.</p>
<p>The result sh... | 1 | 2010-03-17T19:48:50Z | 13,135,887 | <p>an option is the textwrap module<br>
<a href="http://docs.python.org/2/library/textwrap.html" rel="nofollow">http://docs.python.org/2/library/textwrap.html</a></p>
<p>example usage:</p>
<pre><code>>>> import textwrap
>>> s = "This string has some verylongwordsneededtosplit"
>>> list = te... | 4 | 2012-10-30T09:18:37Z | [
"python",
"string",
"split"
] |
python on usb stick | 2,465,593 | <p>Is there any free and open-source option to run python from an usb-stick on Windows system (i.e. python installed on an usb-stick ) and can run on any Windows system just by pluging-in the usb-stick?</p>
| 8 | 2010-03-17T20:24:21Z | 2,465,611 | <p>Try <a href="http://www.portablepython.com/" rel="nofollow">Portable Python</a>.</p>
| 10 | 2010-03-17T20:26:07Z | [
"python",
"portable-applications"
] |
python on usb stick | 2,465,593 | <p>Is there any free and open-source option to run python from an usb-stick on Windows system (i.e. python installed on an usb-stick ) and can run on any Windows system just by pluging-in the usb-stick?</p>
| 8 | 2010-03-17T20:24:21Z | 11,511,803 | <p>I have also been recently concerned about getting a portable Python/Django development environment I could use on any computers without installing anything by just pluging the USB stick.</p>
<p>Maybe it is too late for your case but I made a tutorial on my blog:
<a href="http://webdevon.com/setting-up-a-django-deve... | 0 | 2012-07-16T20:10:58Z | [
"python",
"portable-applications"
] |
Custom keys for Google App Engine models (Python) | 2,465,675 | <p>First off, I'm relatively new to Google App Engine, so I'm probably doing something silly.</p>
<p>Say I've got a model Foo:</p>
<pre><code>class Foo(db.Model):
name = db.StringProperty()
</code></pre>
<p>I want to use <code>name</code> as a unique key for every <code>Foo</code> object. How is this done?</p>
<... | 12 | 2010-03-17T20:34:22Z | 2,465,757 | <p>Here is a pretty thorough discussion of unqiueness with the AppEngine datastore:
<a href="http://stackoverflow.com/questions/1185628/how-do-i-define-a-unique-property-for-a-model-in-google-app-engine">http://stackoverflow.com/questions/1185628/how-do-i-define-a-unique-property-for-a-model-in-google-app-engine</a></p... | 2 | 2010-03-17T20:45:55Z | [
"python",
"google-app-engine",
"gae-datastore",
"primary-key"
] |
Custom keys for Google App Engine models (Python) | 2,465,675 | <p>First off, I'm relatively new to Google App Engine, so I'm probably doing something silly.</p>
<p>Say I've got a model Foo:</p>
<pre><code>class Foo(db.Model):
name = db.StringProperty()
</code></pre>
<p>I want to use <code>name</code> as a unique key for every <code>Foo</code> object. How is this done?</p>
<... | 12 | 2010-03-17T20:34:22Z | 2,466,007 | <p>I've used the code below in a project before. It will work as long as the field on which you're basing your key name on is required.</p>
<pre><code>class NamedModel(db.Model):
"""A Model subclass for entities which automatically generate their own key
names on creation. See documentation for _generate_key ... | 13 | 2010-03-17T21:20:54Z | [
"python",
"google-app-engine",
"gae-datastore",
"primary-key"
] |
Generating a list of values a regex COULD match in Python | 2,465,719 | <p>I'm trying to use a regex as an input, and from there generate all the possible values that the regex would match.</p>
<p>So, for example, if the regex is "three-letter words starting with a, and ending in c," then the code would generate a list with the values [aac, abc, acc, adc, a1c....].</p>
<p>Is there an eas... | 2 | 2010-03-17T20:40:24Z | 2,465,786 | <p>You don't want to do this. Most of the result sets will be huge, and some will be infinite. Instead use a sequence of test vectors and apply the regex against each in turn:</p>
<pre><code>vectors = (
'foo',
'bar',
...
)
for result in (re.match(someregex, entry) for entry in vectors):
...
</code></pre>
| 4 | 2010-03-17T20:49:25Z | [
"python",
"regex"
] |
Generating a list of values a regex COULD match in Python | 2,465,719 | <p>I'm trying to use a regex as an input, and from there generate all the possible values that the regex would match.</p>
<p>So, for example, if the regex is "three-letter words starting with a, and ending in c," then the code would generate a list with the values [aac, abc, acc, adc, a1c....].</p>
<p>Is there an eas... | 2 | 2010-03-17T20:40:24Z | 2,465,817 | <p>Some regular expressions match a finite number of input strings, but many (most?) match an infinite number of input strings. It's kind of like asking 'given the python language grammar, generate all possible python programs'. You probably could write a program to list them all in sequence if you tried (though it wou... | 0 | 2010-03-17T20:53:50Z | [
"python",
"regex"
] |
Generating a list of values a regex COULD match in Python | 2,465,719 | <p>I'm trying to use a regex as an input, and from there generate all the possible values that the regex would match.</p>
<p>So, for example, if the regex is "three-letter words starting with a, and ending in c," then the code would generate a list with the values [aac, abc, acc, adc, a1c....].</p>
<p>Is there an eas... | 2 | 2010-03-17T20:40:24Z | 2,468,247 | <p>Here's a brute force solution that should work. It has a running time of O(L^max_length) (where L is the size of the alphabet), so use it at your own risk.</p>
<pre><code>def all_matching_strings(alphabet, max_length, regex):
"""Find the list of all strings over 'alphabet' of length up to 'max_length' that match 'r... | 7 | 2010-03-18T08:01:25Z | [
"python",
"regex"
] |
Generating a list of values a regex COULD match in Python | 2,465,719 | <p>I'm trying to use a regex as an input, and from there generate all the possible values that the regex would match.</p>
<p>So, for example, if the regex is "three-letter words starting with a, and ending in c," then the code would generate a list with the values [aac, abc, acc, adc, a1c....].</p>
<p>Is there an eas... | 2 | 2010-03-17T20:40:24Z | 2,468,405 | <p>The set of matching strings is infinite if and only if there is a quantifier (+ or *) in your regexp. Your question doesn't seem to aim at those patterns. I rather believe that the <a href="http://docs.python.org/library/itertools.html#itertools.product" rel="nofollow">product</a> function from <code>itertools</code... | 1 | 2010-03-18T08:42:41Z | [
"python",
"regex"
] |
How to copy a dictionary and only edit the copy | 2,465,921 | <p>Can someone please explain this to me? This doesn't make any sense to me.</p>
<p>I copy a dictionary into another and edit the second and both are changed. Why is this happening?</p>
<pre><code>>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2
{'key2': 'value2'... | 190 | 2010-03-17T21:07:06Z | 2,465,932 | <p>Python <em>never</em> implicitly copies objects. When you set <code>dict2 = dict1</code>, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state.</p>
<p>If you want to copy the dict (which is rare), you have to do so exp... | 240 | 2010-03-17T21:09:08Z | [
"python",
"python-3.x",
"dictionary"
] |
How to copy a dictionary and only edit the copy | 2,465,921 | <p>Can someone please explain this to me? This doesn't make any sense to me.</p>
<p>I copy a dictionary into another and edit the second and both are changed. Why is this happening?</p>
<pre><code>>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2
{'key2': 'value2'... | 190 | 2010-03-17T21:07:06Z | 2,465,936 | <p><code>dict2 = dict1</code> does not copy the dictionary. It simply gives you the programmer a second way (<code>dict2</code>) to refer to the same dictionary.</p>
| 6 | 2010-03-17T21:09:44Z | [
"python",
"python-3.x",
"dictionary"
] |
How to copy a dictionary and only edit the copy | 2,465,921 | <p>Can someone please explain this to me? This doesn't make any sense to me.</p>
<p>I copy a dictionary into another and edit the second and both are changed. Why is this happening?</p>
<pre><code>>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2
{'key2': 'value2'... | 190 | 2010-03-17T21:07:06Z | 2,465,951 | <p>When you assign <code>dict2 = dict1</code>, you are not making a copy of <code>dict1</code>, it results in <code>dict2</code> being just another name for <code>dict1</code>.</p>
<p>To copy the mutable types like dictionaries, use <code>copy</code> / <code>deepcopy</code> of the <a href="http://docs.python.org/libra... | 145 | 2010-03-17T21:11:00Z | [
"python",
"python-3.x",
"dictionary"
] |
How to copy a dictionary and only edit the copy | 2,465,921 | <p>Can someone please explain this to me? This doesn't make any sense to me.</p>
<p>I copy a dictionary into another and edit the second and both are changed. Why is this happening?</p>
<pre><code>>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2
{'key2': 'value2'... | 190 | 2010-03-17T21:07:06Z | 2,466,752 | <p>Every variable in python (stuff like <code>dict1</code> or <code>str</code> or <code>__builtins__</code> is a pointer to some hidden platonic "object" inside the machine.</p>
<p>If you set <code>dict1 = dict2</code>,you just point <code>dict1</code> to the same object (or memory location, or whatever analogy you li... | 6 | 2010-03-17T23:57:26Z | [
"python",
"python-3.x",
"dictionary"
] |
How to copy a dictionary and only edit the copy | 2,465,921 | <p>Can someone please explain this to me? This doesn't make any sense to me.</p>
<p>I copy a dictionary into another and edit the second and both are changed. Why is this happening?</p>
<pre><code>>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2
{'key2': 'value2'... | 190 | 2010-03-17T21:07:06Z | 2,466,910 | <p>This confused me too, initially, because I was coming from a C background.</p>
<p>In C, a variable is a location in memory with a defined type. Assigning to a variable copies the data into the variable's memory location.</p>
<p>But in Python, variables act more like pointers to objects. So assigning one variable t... | 4 | 2010-03-18T00:39:58Z | [
"python",
"python-3.x",
"dictionary"
] |
How to copy a dictionary and only edit the copy | 2,465,921 | <p>Can someone please explain this to me? This doesn't make any sense to me.</p>
<p>I copy a dictionary into another and edit the second and both are changed. Why is this happening?</p>
<pre><code>>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2
{'key2': 'value2'... | 190 | 2010-03-17T21:07:06Z | 22,214,248 | <p>You can also just make a new dictionary with a dictionary comprehension. This avoids importing copy.</p>
<pre><code>dout = dict((k,v) for k,v in mydict.items())
</code></pre>
<p>Of course in python >= 2.7 you can do:</p>
<pre><code>dout = {k:v for k,v in mydict.items()}
</code></pre>
<p>But for backwards compat... | 21 | 2014-03-06T03:28:22Z | [
"python",
"python-3.x",
"dictionary"
] |
How to copy a dictionary and only edit the copy | 2,465,921 | <p>Can someone please explain this to me? This doesn't make any sense to me.</p>
<p>I copy a dictionary into another and edit the second and both are changed. Why is this happening?</p>
<pre><code>>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2
{'key2': 'value2'... | 190 | 2010-03-17T21:07:06Z | 22,341,377 | <pre><code>>>> x={'a': 1, 'b': {'m': 4, 'n': 5, 'o': 6}, 'c': 3}
>>> u=x.copy()
>>> v=dict(x)
>>> import copy
>>> w=copy.deepcopy(x)
>>> x['a']=10
>>> x
{'a': 10, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> u
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, '... | 40 | 2014-03-12T03:23:16Z | [
"python",
"python-3.x",
"dictionary"
] |
requiring set of files to be made before running function in Ruffus pipeline | 2,465,953 | <p>I'm using ruffus to write a pipeline. I have a function that gets called in parallel many times and it creates several files. I'd like to make a function "combineFiles()" that gets called after all those files have been made. Since they run in parallel on a cluster, they will not all finish together. I wrote a f... | 1 | 2010-03-17T21:11:20Z | 2,523,368 | <p>I am the developer of Ruffus. I am not sure I entirely understand what you are trying to do but here goes:</p>
<p>Waiting for jobs which take a different amount of time to finish in order to run the next stage of your pipeline is exactly what Ruffus is about so this hopefully is straightforward.</p>
<p>The first q... | 2 | 2010-03-26T13:03:06Z | [
"python",
"distributed-computing",
"cluster-computing",
"pipeline"
] |
Twisted: why is it that passing a deferred callback to a deferred thread makes the thread blocking all of a sudden? | 2,466,000 | <p>I unsuccessfully tried using txredis (the non blocking twisted api for redis) for a persisting message queue I'm trying to set up with a scrapy project I am working on. I found that although the client was not blocking, it became much slower than it could have been because what should have been one event in the reac... | 6 | 2010-03-17T21:18:42Z | 2,466,250 | <p>Well, as the <a href="http://twistedmatrix.com/documents/current/core/howto/gendefer.html">twisted docs</a> say:</p>
<blockquote>
<p>Deferreds do not make the code
magically not block</p>
</blockquote>
<p>Whenever you're using blocking code, such as <code>sleep</code>, you have to defer it to a new thread.</p>... | 12 | 2010-03-17T22:06:48Z | [
"python",
"multithreading",
"twisted",
"redis"
] |
Twisted: why is it that passing a deferred callback to a deferred thread makes the thread blocking all of a sudden? | 2,466,000 | <p>I unsuccessfully tried using txredis (the non blocking twisted api for redis) for a persisting message queue I'm trying to set up with a scrapy project I am working on. I found that although the client was not blocking, it became much slower than it could have been because what should have been one event in the reac... | 6 | 2010-03-17T21:18:42Z | 2,472,388 | <p>On a related note, you could probably gain a lot by using a Redis client created specifically for Twisted, such as this one: <a href="http://github.com/deldotdr/txRedis" rel="nofollow">http://github.com/deldotdr/txRedis</a></p>
| 0 | 2010-03-18T18:27:38Z | [
"python",
"multithreading",
"twisted",
"redis"
] |
Twisted: why is it that passing a deferred callback to a deferred thread makes the thread blocking all of a sudden? | 2,466,000 | <p>I unsuccessfully tried using txredis (the non blocking twisted api for redis) for a persisting message queue I'm trying to set up with a scrapy project I am working on. I found that although the client was not blocking, it became much slower than it could have been because what should have been one event in the reac... | 6 | 2010-03-17T21:18:42Z | 3,686,616 | <p>There's also an up-to-date Redis client for twisted which already supports the new protocol and features of Redis 2.x. You should definetely give it a try. It's called txredisapi.</p>
<p>For the persistent message queue, I'd recommend RestMQ. A redis-based message queue system built on top of cyclone and txredisapi... | 1 | 2010-09-10T16:58:19Z | [
"python",
"multithreading",
"twisted",
"redis"
] |
Set attributes from dictionary in python | 2,466,191 | <p>Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object?</p>
<p>Something like this:</p>
<pre><code> dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }
e = Employee( dict )
print e.name # Oscar
print e.age + 10 # 42
</code></pre>
<p>I... | 39 | 2010-03-17T21:54:59Z | 2,466,207 | <p>Sure, something like this:</p>
<pre><code>class Employee(object):
def __init__(self, initial_data):
for key in initial_data:
setattr(self, key, initial_data[key])
</code></pre>
<p><em>Update</em></p>
<p>As Brent Nash suggests, you can make this more flexible by allowing keyword arguments a... | 73 | 2010-03-17T21:57:33Z | [
"python",
"initialization"
] |
Set attributes from dictionary in python | 2,466,191 | <p>Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object?</p>
<p>Something like this:</p>
<pre><code> dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }
e = Employee( dict )
print e.name # Oscar
print e.age + 10 # 42
</code></pre>
<p>I... | 39 | 2010-03-17T21:54:59Z | 2,466,232 | <p>You can access the attributes of an object with <code>__dict__</code>, and call the update method on it:</p>
<pre><code>>>> class Employee(object):
... def __init__(self, _dict):
... self.__dict__.update(_dict)
...
>>> dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }
>&... | 7 | 2010-03-17T22:02:00Z | [
"python",
"initialization"
] |
Set attributes from dictionary in python | 2,466,191 | <p>Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object?</p>
<p>Something like this:</p>
<pre><code> dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }
e = Employee( dict )
print e.name # Oscar
print e.age + 10 # 42
</code></pre>
<p>I... | 39 | 2010-03-17T21:54:59Z | 2,466,295 | <p>I think that answer using <code>settattr</code> are the way to go if you really need to support <code>dict</code>. </p>
<p>But if <code>Employee</code> object is just a structure which you can access with dot syntax (<code>.name</code>) instead of dict syntax (<code>['name']</code>), you can use <a href="http://do... | 4 | 2010-03-17T22:15:23Z | [
"python",
"initialization"
] |
Set attributes from dictionary in python | 2,466,191 | <p>Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object?</p>
<p>Something like this:</p>
<pre><code> dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }
e = Employee( dict )
print e.name # Oscar
print e.age + 10 # 42
</code></pre>
<p>I... | 39 | 2010-03-17T21:54:59Z | 2,466,380 | <p>Setting attributes in this way is almost certainly not the best way to solve a problem. Either:</p>
<ol>
<li><p>You know what all the fields should be ahead of time. In that case, you can set all the attributes explicitly. This would look like</p>
<pre><code>class Employee(object):
def __init__(self, name, las... | 20 | 2010-03-17T22:31:43Z | [
"python",
"initialization"
] |
Set attributes from dictionary in python | 2,466,191 | <p>Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object?</p>
<p>Something like this:</p>
<pre><code> dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }
e = Employee( dict )
print e.name # Oscar
print e.age + 10 # 42
</code></pre>
<p>I... | 39 | 2010-03-17T21:54:59Z | 7,406,431 | <p>Why not just use attribute names as keys to a dictionary?</p>
<pre><code>class StructMyDict(dict):
def __getattr__(self, name):
try:
return self[name]
except KeyError as e:
raise AttributeError(e)
def __setattr__(self, name, value):
self[name] = value... | 4 | 2011-09-13T18:08:42Z | [
"python",
"initialization"
] |
Set attributes from dictionary in python | 2,466,191 | <p>Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object?</p>
<p>Something like this:</p>
<pre><code> dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }
e = Employee( dict )
print e.name # Oscar
print e.age + 10 # 42
</code></pre>
<p>I... | 39 | 2010-03-17T21:54:59Z | 23,399,131 | <p>similar to using a dict, you could just use kwargs like so:</p>
<pre><code>class Person:
def __init__(self, **kwargs):
self.properties = kwargs
def get_property(self, key):
return self.properties.get(key, None)
def main():
timmy = Person(color = 'red')
print(timmy.get_property... | 1 | 2014-04-30T22:27:22Z | [
"python",
"initialization"
] |
Set attributes from dictionary in python | 2,466,191 | <p>Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object?</p>
<p>Something like this:</p>
<pre><code> dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }
e = Employee( dict )
print e.name # Oscar
print e.age + 10 # 42
</code></pre>
<p>I... | 39 | 2010-03-17T21:54:59Z | 25,651,609 | <p>say for example</p>
<pre><code>class A():
def __init__(self):
self.x=7
self.y=8
self.z="name"
</code></pre>
<p>if you want to set the attributes at once</p>
<pre><code>d = {'x':100,'y':300,'z':"blah"}
a = A()
a.__dict__.update(d)
</code></pre>
| 1 | 2014-09-03T18:50:02Z | [
"python",
"initialization"
] |
How to generate SSH key pairs with Python | 2,466,401 | <p>I'm attempting to write a script to generate SSH Identity key pairs for me.</p>
<pre><code>from M2Crypto import RSA
key = RSA.gen_key(1024, 65337)
key.save_key("/tmp/my.key", cipher=None)
</code></pre>
<p>The file <code>/tmp/my.key</code> looks great now.</p>
<p>By running <code>ssh-keygen -y -f /tmp/my.key > ... | 19 | 2010-03-17T22:35:40Z | 2,466,479 | <p>Can you get the AAAA...Dfg== string out of it while it's an object? If so, you could simply open a file yourself and save that instead of using the built in save_pub_key function.</p>
| 0 | 2010-03-17T22:53:11Z | [
"python",
"ssh",
"m2crypto",
"ssh-keys"
] |
How to generate SSH key pairs with Python | 2,466,401 | <p>I'm attempting to write a script to generate SSH Identity key pairs for me.</p>
<pre><code>from M2Crypto import RSA
key = RSA.gen_key(1024, 65337)
key.save_key("/tmp/my.key", cipher=None)
</code></pre>
<p>The file <code>/tmp/my.key</code> looks great now.</p>
<p>By running <code>ssh-keygen -y -f /tmp/my.key > ... | 19 | 2010-03-17T22:35:40Z | 2,466,482 | <p>Just guessing... but have you tried something like this?:</p>
<pre><code>print "ssh-rsa " + "".join([ l.strip() for l in open('/tmp/my.key.pub') if not l.startswith('-----')])
</code></pre>
| 0 | 2010-03-17T22:53:51Z | [
"python",
"ssh",
"m2crypto",
"ssh-keys"
] |
How to generate SSH key pairs with Python | 2,466,401 | <p>I'm attempting to write a script to generate SSH Identity key pairs for me.</p>
<pre><code>from M2Crypto import RSA
key = RSA.gen_key(1024, 65337)
key.save_key("/tmp/my.key", cipher=None)
</code></pre>
<p>The file <code>/tmp/my.key</code> looks great now.</p>
<p>By running <code>ssh-keygen -y -f /tmp/my.key > ... | 19 | 2010-03-17T22:35:40Z | 2,466,522 | <p>I don't know of such a library in Python.</p>
<p>You might find the <a href="http://www.lag.net/paramiko/" rel="nofollow">paramiko</a> library useful (also <a href="http://pypi.python.org/pypi/paramiko" rel="nofollow">available from PyPI</a>). It implements the SSH protocol, and has functionality for handling exist... | 0 | 2010-03-17T23:01:58Z | [
"python",
"ssh",
"m2crypto",
"ssh-keys"
] |
How to generate SSH key pairs with Python | 2,466,401 | <p>I'm attempting to write a script to generate SSH Identity key pairs for me.</p>
<pre><code>from M2Crypto import RSA
key = RSA.gen_key(1024, 65337)
key.save_key("/tmp/my.key", cipher=None)
</code></pre>
<p>The file <code>/tmp/my.key</code> looks great now.</p>
<p>By running <code>ssh-keygen -y -f /tmp/my.key > ... | 19 | 2010-03-17T22:35:40Z | 2,466,864 | <p>How about using <code>subprocess</code> to invoke <code>ssh-keygen</code>?</p>
<pre><code>from subprocess import Popen, PIPE
import shlex
def get_pub_key(path):
args = shlex.split('ssh-keygen -y -f')
args.append(path)
p = Popen(args, stdout=PIPE)
stdout = p.communicate()[0]
if p.returncode != 0... | 1 | 2010-03-18T00:24:17Z | [
"python",
"ssh",
"m2crypto",
"ssh-keys"
] |
How to generate SSH key pairs with Python | 2,466,401 | <p>I'm attempting to write a script to generate SSH Identity key pairs for me.</p>
<pre><code>from M2Crypto import RSA
key = RSA.gen_key(1024, 65337)
key.save_key("/tmp/my.key", cipher=None)
</code></pre>
<p>The file <code>/tmp/my.key</code> looks great now.</p>
<p>By running <code>ssh-keygen -y -f /tmp/my.key > ... | 19 | 2010-03-17T22:35:40Z | 2,466,998 | <p>The key used by ssh is just base64 encoded, i don't know M2Crypto very much, but after a quick overview it seems you could do what you want this way:</p>
<pre><code>import os
from base64 import b64encode
from M2Crypto import RSA
key = RSA.gen_key(1024, 65537)
raw_key = key.pub()[1]
b64key = b64encode(r... | 3 | 2010-03-18T01:06:09Z | [
"python",
"ssh",
"m2crypto",
"ssh-keys"
] |
How to generate SSH key pairs with Python | 2,466,401 | <p>I'm attempting to write a script to generate SSH Identity key pairs for me.</p>
<pre><code>from M2Crypto import RSA
key = RSA.gen_key(1024, 65337)
key.save_key("/tmp/my.key", cipher=None)
</code></pre>
<p>The file <code>/tmp/my.key</code> looks great now.</p>
<p>By running <code>ssh-keygen -y -f /tmp/my.key > ... | 19 | 2010-03-17T22:35:40Z | 3,939,477 | <p>The base64 decoded version of ssh-keygen output to the contents of key.pub() the format of the keyfile is</p>
<pre><code>b64encode('\x00\x00\x00\x07ssh-rsa%s%s' % (key.pub()[0], key.pub()[1]))
</code></pre>
| 2 | 2010-10-15T04:19:02Z | [
"python",
"ssh",
"m2crypto",
"ssh-keys"
] |
How to generate SSH key pairs with Python | 2,466,401 | <p>I'm attempting to write a script to generate SSH Identity key pairs for me.</p>
<pre><code>from M2Crypto import RSA
key = RSA.gen_key(1024, 65337)
key.save_key("/tmp/my.key", cipher=None)
</code></pre>
<p>The file <code>/tmp/my.key</code> looks great now.</p>
<p>By running <code>ssh-keygen -y -f /tmp/my.key > ... | 19 | 2010-03-17T22:35:40Z | 5,454,266 | <p>Edit 05/09/2012:</p>
<p>I just realize that pyrcypto already have this:</p>
<pre><code>import os
from Crypto.PublicKey import RSA
key = RSA.generate(2048, os.urandom)
print key.exportKey('OpenSSH')
</code></pre>
<p>This code works for me:</p>
<pre><code>import os
from Crypto.PublicKey import RSA
key = RSA.gene... | 5 | 2011-03-28T03:10:13Z | [
"python",
"ssh",
"m2crypto",
"ssh-keys"
] |
How to generate SSH key pairs with Python | 2,466,401 | <p>I'm attempting to write a script to generate SSH Identity key pairs for me.</p>
<pre><code>from M2Crypto import RSA
key = RSA.gen_key(1024, 65337)
key.save_key("/tmp/my.key", cipher=None)
</code></pre>
<p>The file <code>/tmp/my.key</code> looks great now.</p>
<p>By running <code>ssh-keygen -y -f /tmp/my.key > ... | 19 | 2010-03-17T22:35:40Z | 9,458,516 | <p>Here is an example using the Twisted Conch library which leverages PyCrypto under the covers. You can find the API documentation at <a href="http://twistedmatrix.com/documents/current/api/twisted.conch.ssh.keys.html" rel="nofollow">http://twistedmatrix.com/documents/current/api/twisted.conch.ssh.keys.html</a>:</p>
... | 1 | 2012-02-26T23:58:40Z | [
"python",
"ssh",
"m2crypto",
"ssh-keys"
] |
How to generate SSH key pairs with Python | 2,466,401 | <p>I'm attempting to write a script to generate SSH Identity key pairs for me.</p>
<pre><code>from M2Crypto import RSA
key = RSA.gen_key(1024, 65337)
key.save_key("/tmp/my.key", cipher=None)
</code></pre>
<p>The file <code>/tmp/my.key</code> looks great now.</p>
<p>By running <code>ssh-keygen -y -f /tmp/my.key > ... | 19 | 2010-03-17T22:35:40Z | 22,449,476 | <p>Just in case there are any future travellers looking to do this. The RSA module support writing out the public key in OpenSSH format now (possibly didn't at the time of earlier posts). So I think you can do what you need with:</p>
<pre><code>from os import chmod
from Crypto.PublicKey import RSA
key = RSA.generate(... | 18 | 2014-03-17T08:15:30Z | [
"python",
"ssh",
"m2crypto",
"ssh-keys"
] |
How to generate SSH key pairs with Python | 2,466,401 | <p>I'm attempting to write a script to generate SSH Identity key pairs for me.</p>
<pre><code>from M2Crypto import RSA
key = RSA.gen_key(1024, 65337)
key.save_key("/tmp/my.key", cipher=None)
</code></pre>
<p>The file <code>/tmp/my.key</code> looks great now.</p>
<p>By running <code>ssh-keygen -y -f /tmp/my.key > ... | 19 | 2010-03-17T22:35:40Z | 39,126,754 | <p>Use <code>cryptography</code>! <code>pycrypto</code> is not in active development anymore and if possible you should be using cryptography. Since June it's possible to generate SSH public keys as well:</p>
<pre><code>from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.... | 3 | 2016-08-24T14:55:21Z | [
"python",
"ssh",
"m2crypto",
"ssh-keys"
] |
Will pywin32 extensions work on Windows 7? | 2,466,639 | <p>Will the <a href="http://sourceforge.net/projects/pywin32/files/" rel="nofollow">pywin32 extensions</a> work on Windows 7?</p>
<p>If not, are there plans for Windows 7 extensions for Python?</p>
| 1 | 2010-03-17T23:24:31Z | 2,466,682 | <p>pywin32 extensions works fine on Windows 7.</p>
| 1 | 2010-03-17T23:36:31Z | [
"python",
"windows-7"
] |
How to upload 6000 record to Google Datastore from csv file | 2,466,742 | <p><a href="http://code.google.com/appengine/docs/python/tools/uploadingdata.html" rel="nofollow">http://code.google.com/appengine/docs/python/tools/uploadingdata.html</a> is not clearly understand. Where i should call the bulkloader.py or appcfg.py? Should i import the csv file to local Google App Engine SDK first? Ho... | 2 | 2010-03-17T23:53:48Z | 2,466,826 | <p>Set Up remote_api, the docs have <a href="http://code.google.com/appengine/docs/python/tools/uploadingdata.html" rel="nofollow">instructions</a> for both java and python and then run bulkloader.py locally :</p>
<pre><code>bulkloader.py --dump --app_id=<app-id> --url=http://<appname>.appspot.com/remote_a... | 4 | 2010-03-18T00:16:11Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
Clear command line output from Python [Eclipse] | 2,466,866 | <p>I'm using Eclipse for writing Python, and I want to be able to easily clear the screen. I've seen <a href="http://stackoverflow.com/questions/517970/how-to-clear-python-interpreter-console">this question</a>, and tried (among other things suggested there) the following solution</p>
<pre><code>import os
def clear()... | 4 | 2010-03-18T00:25:00Z | 2,531,385 | <p>The problem with running it in eclipse is that <code>cls</code> uses ANSI escape sequences to clear the screen. What I mean by this is that to clear the screen, <code>cls</code> writes a string such as <code>"\033[[80;j"</code> to the output buffer. The native console (the one outside of eclipse) interprets this as ... | 2 | 2010-03-27T23:51:43Z | [
"python",
"eclipse",
"clear"
] |
Clear command line output from Python [Eclipse] | 2,466,866 | <p>I'm using Eclipse for writing Python, and I want to be able to easily clear the screen. I've seen <a href="http://stackoverflow.com/questions/517970/how-to-clear-python-interpreter-console">this question</a>, and tried (among other things suggested there) the following solution</p>
<pre><code>import os
def clear()... | 4 | 2010-03-18T00:25:00Z | 2,558,224 | <p>Clearing in outputs is actually not possible. The best hack is to print full of line breaks.
IDEs like Eclipse never simulate terminals properly.</p>
| 0 | 2010-04-01T05:02:24Z | [
"python",
"eclipse",
"clear"
] |
Clear command line output from Python [Eclipse] | 2,466,866 | <p>I'm using Eclipse for writing Python, and I want to be able to easily clear the screen. I've seen <a href="http://stackoverflow.com/questions/517970/how-to-clear-python-interpreter-console">this question</a>, and tried (among other things suggested there) the following solution</p>
<pre><code>import os
def clear()... | 4 | 2010-03-18T00:25:00Z | 26,698,182 | <p>As its just eclipse problem I suppose it will not affect your final product if you want to clean your final users' screen while for eclipse environment there is a little button in top-right of the console screen which enables you from cleaning it.</p>
| 0 | 2014-11-02T10:12:16Z | [
"python",
"eclipse",
"clear"
] |
slicing behaviour question of a list of lists | 2,466,941 | <p>I got a function like</p>
<pre><code>def f():
...
...
return [list1, list2]
</code></pre>
<p>this returns a list of lists</p>
<pre><code>[[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]]
</code></pre>
<p>now when I do the following:</p>
<pre><code>for i in range(0,2):print f()[i][0:10]
<... | 3 | 2010-03-18T00:49:22Z | 2,466,955 | <p>A pythonic loop would be:</p>
<pre><code>for list in f()[0:2]:
print list[0:10]
</code></pre>
<p>But depending on what you want to achieve, list comprehension might be even better.</p>
<p>Or you make use of Pythons <a href="http://docs.python.org/library/functions.html#map" rel="nofollow"><code>map()</code></... | 0 | 2010-03-18T00:53:07Z | [
"python",
"function",
"slice"
] |
slicing behaviour question of a list of lists | 2,466,941 | <p>I got a function like</p>
<pre><code>def f():
...
...
return [list1, list2]
</code></pre>
<p>this returns a list of lists</p>
<pre><code>[[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]]
</code></pre>
<p>now when I do the following:</p>
<pre><code>for i in range(0,2):print f()[i][0:10]
<... | 3 | 2010-03-18T00:49:22Z | 2,466,962 | <p>The second slice slices the sequence returned from the first slice, so yes, you will have to loop somehow in order to slice within:</p>
<pre><code>[x[0:10] for x in f()[0:2]]
</code></pre>
| 9 | 2010-03-18T00:54:45Z | [
"python",
"function",
"slice"
] |
slicing behaviour question of a list of lists | 2,466,941 | <p>I got a function like</p>
<pre><code>def f():
...
...
return [list1, list2]
</code></pre>
<p>this returns a list of lists</p>
<pre><code>[[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]]
</code></pre>
<p>now when I do the following:</p>
<pre><code>for i in range(0,2):print f()[i][0:10]
<... | 3 | 2010-03-18T00:49:22Z | 2,466,966 | <p>The reason why these two behave differently is because <code>f()[0:2][0:10]</code> works like this:</p>
<ol>
<li><code>f()</code> gives you a list of lists.</li>
<li><code>[0:2]</code> gives you a list containing the first two elements in the list of lists. Since the elements in the list of lists are lists, this i... | 6 | 2010-03-18T00:55:11Z | [
"python",
"function",
"slice"
] |
Django site on Nginx+FastCGI goes (504 gateway timeout) | 2,466,963 | <p>Sometimes my whole Django based site goes into 504 gateway timeout errors so none page can be displayed.</p>
<p>Is it possible to write a shell program and cronjob it run every 5 minutes to detect such errors and restart FastCGI process if needed?</p>
<p>I'm currently using command below to restart FastCGI in case... | 2 | 2010-03-18T00:54:51Z | 2,487,291 | <p>Perhaps you should find out <em>why</em> the site starts serving 504 errors first - check the logs (or add logging if you don't have enough information), and fix whatever the problem is. Alternatively, you may find nginx + apache + mod_wsgi a more stable approach - nginx is a fantastic front-end webserver for servin... | 3 | 2010-03-21T13:48:40Z | [
"python",
"django",
"timeout",
"fastcgi",
"restart"
] |
Django site on Nginx+FastCGI goes (504 gateway timeout) | 2,466,963 | <p>Sometimes my whole Django based site goes into 504 gateway timeout errors so none page can be displayed.</p>
<p>Is it possible to write a shell program and cronjob it run every 5 minutes to detect such errors and restart FastCGI process if needed?</p>
<p>I'm currently using command below to restart FastCGI in case... | 2 | 2010-03-18T00:54:51Z | 2,815,271 | <p>I think if you are having this problem, then <a href="http://supervisord.org" rel="nofollow">supervisor</a> is your friend. A very good friend. Like daemontools, except easy config , lots of help and non root usage. </p>
<p>You should try to find the problem for sure, but regardless, an hour of prep means that y... | 0 | 2010-05-12T00:02:11Z | [
"python",
"django",
"timeout",
"fastcgi",
"restart"
] |
What does this code from AuthKit do? (where are these functions and methods defined?) | 2,467,013 | <p>I am trying to <a href="http://wiki.pylonshq.com/display/authkitcookbook/Implement+Your+Own+Authentication+Method" rel="nofollow">implement my own authentication method for AuthKit</a> and am trying to figure out how some of the built-in methods work. In particular, I'm trying to figure out how to update the <code>R... | 0 | 2010-03-18T01:09:27Z | 2,467,172 | <p>Looking at that source I see it has an (evil)</p>
<pre><code>from paste.httpheaders import *
</code></pre>
<p>that is one way otherwise-mysterious barenames could suddenly appear in the code (which is exactly why this idiom is a very, very bad practice). I can't be sure that's how those identifiers suddenly and i... | 1 | 2010-03-18T02:09:15Z | [
"python",
"authkit"
] |
How to get "paster request" to use config host value instead of localhost? | 2,467,021 | <p>I'm trying to access my pylons application via cron job to send notifications to my users. The way I'm doing this is by running the application using something like:</p>
<pre><code>paster request myconfig.ini /maintenance/do
</code></pre>
<p>In the actual controller I check for the "paste.command_request" to block... | 1 | 2010-03-18T01:11:36Z | 2,472,365 | <p>What I pretty much ended up doing was the following paster command:</p>
<pre><code>paster request myconfig.ini /maintenance/do --header=HOST:<USE_THIS_HOST>
</code></pre>
<p>Where is the domain name I wanted my users to see in their email. You can even add in the IP address if you are testing the applicatio... | 1 | 2010-03-18T18:20:33Z | [
"python",
"routes",
"pylons",
"paster"
] |
Django and Reportlab Question | 2,467,042 | <p>I have written this small Django view to return pdf.</p>
<pre><code>@login_required
def code_view(request,myid):
try:
deal = Deal.objects.get(id=myid)
except:
raise Http404
header = deal.header
code = deal.code
response = HttpResponse(mimetype='application/pdf')
response['Con... | 7 | 2010-03-18T01:19:10Z | 2,467,742 | <p>Reportlab can handle some basic HTML formatting (<code><b></code>, <code><i></code>), not sure if it can do lists. You could use <a href="http://pypi.python.org/pypi/pisa/" rel="nofollow"><code>pisa</code></a> for HTML to PDF conversion. Then you could also use <code><img></code> tag for image incl... | 2 | 2010-03-18T05:43:14Z | [
"python",
"django",
"pdf",
"reportlab"
] |
Django and Reportlab Question | 2,467,042 | <p>I have written this small Django view to return pdf.</p>
<pre><code>@login_required
def code_view(request,myid):
try:
deal = Deal.objects.get(id=myid)
except:
raise Http404
header = deal.header
code = deal.code
response = HttpResponse(mimetype='application/pdf')
response['Con... | 7 | 2010-03-18T01:19:10Z | 2,700,286 | <p>You should move to the next level and use DocTemplates.
Images are quite easy, but using bullets is really hard - you have to define styles and more!</p>
<p>I use a set of classes like the below:</p>
<pre><code># -*- coding: utf-8 -*-
from django.utils.encoding import smart_str
from reportlab.lib.colors import Co... | 9 | 2010-04-23T16:33:48Z | [
"python",
"django",
"pdf",
"reportlab"
] |
Python : Check for runtime errors | 2,467,161 | <p>I wrote a python module. Running python filename.py, only checks for syntax errors. Is there a tool, which checks for runtime errors also, like concatenating int with string etc..</p>
<p>Thank you<br>
Bala</p>
<blockquote>
<p>Update:
Scripts are mainly about setting up a hadoop cluster in the cloud. I am not s... | 1 | 2010-03-18T02:06:54Z | 2,467,182 | <p>You could write a unit test for your module. That way it will execute your code and any runtime errors (or even better, test failures) will be reported.</p>
<p>If you choose to go down this route, <a href="http://docs.python.org/library/unittest.html" rel="nofollow">http://docs.python.org/library/unittest.html</a> ... | 2 | 2010-03-18T02:11:45Z | [
"python",
"compilation"
] |
Python : Check for runtime errors | 2,467,161 | <p>I wrote a python module. Running python filename.py, only checks for syntax errors. Is there a tool, which checks for runtime errors also, like concatenating int with string etc..</p>
<p>Thank you<br>
Bala</p>
<blockquote>
<p>Update:
Scripts are mainly about setting up a hadoop cluster in the cloud. I am not s... | 1 | 2010-03-18T02:06:54Z | 2,467,186 | <p>Traditionally, if not writing full-fledged unit-tests and/or doc-tests (writing lots of tests is of course best practice!), one at least puts in every module a <code>def main():</code> function to exercise it and ends the module with</p>
<pre><code>if __name__ == '__main__':
main()
</code></pre>
<p>so <code>main... | 2 | 2010-03-18T02:12:35Z | [
"python",
"compilation"
] |
GAE - Getting TypeError requiring class instance be passed to class's own method | 2,467,201 | <p>I'm really new to programming... I set up a class to give supporting information for Google's User API user object. I store this info in the datastore using db.model. </p>
<p>When I call the okstatus method of my user_info class using this code:</p>
<pre><code>elif user_info.okstatus(user):
self.response.out.w... | 1 | 2010-03-18T02:20:20Z | 2,467,225 | <p><code>self</code> must be an instance of the class. Since you never actually <strong>use</strong> it, you can simply make all of these methods into functions (and changing the <code>self.status</code> cases to just <code>status</code>).</p>
<p>If you're a "class fetishist", and absolutely insist on keeping the fun... | 1 | 2010-03-18T02:29:25Z | [
"python",
"google-app-engine",
"class",
"methods",
"typeerror"
] |
Dynamically evaluating simple boolean logic in Python | 2,467,590 | <p>I've got some dynamically-generated boolean logic expressions, like:</p>
<ul>
<li>(A or B) and (C or D)</li>
<li>A or (A and B)</li>
<li>A</li>
<li><em>empty - evaluates to True</em></li>
</ul>
<p>The placeholders get replaced with booleans. Should I,</p>
<ol>
<li>Convert this information to a Python expression l... | 10 | 2010-03-18T04:49:55Z | 2,467,611 | <p>If you set up dicts with the locals and globals you care about then you should be able to safely pass them along with the expression into <a href="http://docs.python.org/library/functions.html#eval"><code>eval()</code></a>.</p>
| 6 | 2010-03-18T04:55:41Z | [
"python",
"tree",
"logic",
"boolean",
"boolean-logic"
] |
Dynamically evaluating simple boolean logic in Python | 2,467,590 | <p>I've got some dynamically-generated boolean logic expressions, like:</p>
<ul>
<li>(A or B) and (C or D)</li>
<li>A or (A and B)</li>
<li>A</li>
<li><em>empty - evaluates to True</em></li>
</ul>
<p>The placeholders get replaced with booleans. Should I,</p>
<ol>
<li>Convert this information to a Python expression l... | 10 | 2010-03-18T04:49:55Z | 2,467,674 | <p>It shouldn't be difficult at all to write a evaluator that can handle this, for example using <a href="http://pyparsing.wikispaces.com/">pyparsing</a>. You only have a few operations to handle (and, or, and grouping?), so you should be able to parse and evaluate it yourself.</p>
<p>You shouldn't need to explicitly ... | 10 | 2010-03-18T05:16:41Z | [
"python",
"tree",
"logic",
"boolean",
"boolean-logic"
] |
Dynamically evaluating simple boolean logic in Python | 2,467,590 | <p>I've got some dynamically-generated boolean logic expressions, like:</p>
<ul>
<li>(A or B) and (C or D)</li>
<li>A or (A and B)</li>
<li>A</li>
<li><em>empty - evaluates to True</em></li>
</ul>
<p>The placeholders get replaced with booleans. Should I,</p>
<ol>
<li>Convert this information to a Python expression l... | 10 | 2010-03-18T04:49:55Z | 2,472,414 | <p><b>Here's a small (possibly, 74 lines including whitespace) module I built in about an hour and a half (plus almost an hour to refactoring):</b></p>
<pre><code>str_to_token = {'True':True,
'False':False,
'and':lambda left, right: left and right,
'or':lambda left, righ... | 13 | 2010-03-18T18:33:23Z | [
"python",
"tree",
"logic",
"boolean",
"boolean-logic"
] |
Dynamically evaluating simple boolean logic in Python | 2,467,590 | <p>I've got some dynamically-generated boolean logic expressions, like:</p>
<ul>
<li>(A or B) and (C or D)</li>
<li>A or (A and B)</li>
<li>A</li>
<li><em>empty - evaluates to True</em></li>
</ul>
<p>The placeholders get replaced with booleans. Should I,</p>
<ol>
<li>Convert this information to a Python expression l... | 10 | 2010-03-18T04:49:55Z | 12,393,084 | <p>Sounds like a piece of cake using SymPy logic module. They even have an example of that on the docs: <a href="http://docs.sympy.org/0.7.1/modules/logic.html" rel="nofollow">http://docs.sympy.org/0.7.1/modules/logic.html</a></p>
| 4 | 2012-09-12T17:02:07Z | [
"python",
"tree",
"logic",
"boolean",
"boolean-logic"
] |
C/C++ for Core Logic Development of a Web Application? | 2,467,807 | <p>Can C/C++ be choice of keeping all your logic (business/domain) for web application?</p>
<p>Why?</p>
<p>I've two resources (cousins) having knowledge on C/C++ and me also good in C/C++, Python, HTML, CSS and JavaScript. </p>
<p>We like to utilize our free time to work on our some good ideas we developed together.... | 2 | 2010-03-18T06:03:07Z | 2,467,826 | <p>C/C++ and Python can be integrated <a href="http://docs.python.org/extending/index.html" rel="nofollow">fairly easily</a>, but Python really should be a snap for anyone that knows C well to pick up in a week.</p>
| 2 | 2010-03-18T06:08:42Z | [
"c++",
"python",
"c"
] |
C/C++ for Core Logic Development of a Web Application? | 2,467,807 | <p>Can C/C++ be choice of keeping all your logic (business/domain) for web application?</p>
<p>Why?</p>
<p>I've two resources (cousins) having knowledge on C/C++ and me also good in C/C++, Python, HTML, CSS and JavaScript. </p>
<p>We like to utilize our free time to work on our some good ideas we developed together.... | 2 | 2010-03-18T06:03:07Z | 2,468,907 | <p>I don't think you should use a compiled language (at least not c++) for web programming. I thought about doing this once too but remember that for any change you'll have to compile etc.</p>
<p>Facebook uses php and it's hip hop application changes php into c++. Maybe you should take a look at that.</p>
<p>Of cours... | 0 | 2010-03-18T10:10:38Z | [
"c++",
"python",
"c"
] |
C/C++ for Core Logic Development of a Web Application? | 2,467,807 | <p>Can C/C++ be choice of keeping all your logic (business/domain) for web application?</p>
<p>Why?</p>
<p>I've two resources (cousins) having knowledge on C/C++ and me also good in C/C++, Python, HTML, CSS and JavaScript. </p>
<p>We like to utilize our free time to work on our some good ideas we developed together.... | 2 | 2010-03-18T06:03:07Z | 2,476,462 | <p>cython <a href="http://wwww.cython.org" rel="nofollow">http://wwww.cython.org</a> is a nice way to interface python and C/C++</p>
| 0 | 2010-03-19T10:28:13Z | [
"c++",
"python",
"c"
] |
Python: UnicodeEncodeError when reading from stdin | 2,467,928 | <p>When running a Python program that reads from stdin, I get the following error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 320: ordinal not in range(128)
</code></pre>
<p>How can I fix it?</p>
<p>Note: The error occurs internal to antlr and the line looks like that:</p>
<... | 6 | 2010-03-18T06:36:30Z | 2,467,956 | <p>The problem is, that when reading from stdin, python decodes
it using the system default encoding:</p>
<pre><code>>>> import sys
>>> sys.getdefaultencoding()
'ascii'
</code></pre>
<p>The input is very likely UTF-8 or Windows-CP-1252, so the program
chokes on non-ASCII-characters.</p>
<p>To conve... | 13 | 2010-03-18T06:41:02Z | [
"python",
"unicode",
"antlr",
"stdin"
] |
Python: UnicodeEncodeError when reading from stdin | 2,467,928 | <p>When running a Python program that reads from stdin, I get the following error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 320: ordinal not in range(128)
</code></pre>
<p>How can I fix it?</p>
<p>Note: The error occurs internal to antlr and the line looks like that:</p>
<... | 6 | 2010-03-18T06:36:30Z | 2,467,957 | <p>You're not getting this error on input, you're getting this error when trying to output the read data. You should be decoding data you read, and throwing the unicodes around instead of dealing with bytestrings the whole time.</p>
| 1 | 2010-03-18T06:41:10Z | [
"python",
"unicode",
"antlr",
"stdin"
] |
Python: UnicodeEncodeError when reading from stdin | 2,467,928 | <p>When running a Python program that reads from stdin, I get the following error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 320: ordinal not in range(128)
</code></pre>
<p>How can I fix it?</p>
<p>Note: The error occurs internal to antlr and the line looks like that:</p>
<... | 6 | 2010-03-18T06:36:30Z | 5,349,117 | <p>Here is an excellent writedown about how Python handles encodings:</p>
<p><a href="http://evanjones.ca/python-utf8.html" rel="nofollow">How to use UTF-8 with Python</a></p>
| 1 | 2011-03-18T07:18:43Z | [
"python",
"unicode",
"antlr",
"stdin"
] |
Python: override __init__ args in __new__ | 2,468,112 | <p>I have a <code>__new__</code> method as follows:</p>
<pre><code>class MyClass(object):
def __new__(cls, *args):
new_args = []
args.sort()
prev = args.pop(0)
while args:
next = args.pop(0)
if prev.compare(next):
prev = prev.combine(next)
else:
... | 0 | 2010-03-18T07:23:03Z | 2,468,174 | <p>Since you don't even necessarily create a MyClass object, why not just put new into a separate function <code>new(*args)</code> that returns a <code>MyClass</code> or <code>SomeOtherClass</code> object as necessary?</p>
<p>This will be a bit neater since you know that everywhere you put MyClass() you get a MyClass ... | 0 | 2010-03-18T07:39:18Z | [
"python",
"object"
] |
Python: override __init__ args in __new__ | 2,468,112 | <p>I have a <code>__new__</code> method as follows:</p>
<pre><code>class MyClass(object):
def __new__(cls, *args):
new_args = []
args.sort()
prev = args.pop(0)
while args:
next = args.pop(0)
if prev.compare(next):
prev = prev.combine(next)
else:
... | 0 | 2010-03-18T07:23:03Z | 2,468,229 | <p><strong>Edit</strong>: Came up with a better solution - the following wasn't behaving consistently enough.</p>
<hr>
<p>I've solved my own question by stumbling on some unexpectedly simple behaviour:</p>
<pre><code>return cls(*new_args)
</code></pre>
<p>instead of</p>
<pre><code>return super(MyClass, cls).__new_... | 1 | 2010-03-18T07:53:59Z | [
"python",
"object"
] |
Python: override __init__ args in __new__ | 2,468,112 | <p>I have a <code>__new__</code> method as follows:</p>
<pre><code>class MyClass(object):
def __new__(cls, *args):
new_args = []
args.sort()
prev = args.pop(0)
while args:
next = args.pop(0)
if prev.compare(next):
prev = prev.combine(next)
else:
... | 0 | 2010-03-18T07:23:03Z | 2,484,444 | <p>The solution I went with in the end was to modify the newly created object in the <code>__new__</code> and remove the <code>__init__</code> method altogether:</p>
<pre><code>def __new__(cls, *args):
... # as above
new_self = super(MyClass, cls).__new__(cls)
new_self.args = new_args
return new_self
#def... | 2 | 2010-03-20T19:41:05Z | [
"python",
"object"
] |
I want to find the span tag beween the LI tag and its attributes but no luck | 2,468,278 | <p>I want to find the span tag beween the LI tag and its attributes. Trying with beautful soap but no luck. Details of my code. Is any one point me right methodlogy</p>
<p>In this this code, my getId function should return me id = "0_False-2"</p>
<p>Any one know right method?</p>
<hr>
<pre><code>from BeautifulSoup ... | -2 | 2010-03-18T08:10:37Z | 2,468,360 | <p>I am sure someone can show you the BS way, but here's my approach. Just plain old Python string manipulation.</p>
<pre><code>html = '<ul>\
<li class="line">&nbsp;</li>\
<li class="folder-open-last" id="0">\
<img style="float: left;" class="trigger" src="/media/images/spacer.gif" borde... | 0 | 2010-03-18T08:34:10Z | [
"python",
"html",
"beautifulsoup"
] |
Python | How to create dynamic and expandable dictionaries | 2,468,334 | <p>I want to create a Python dictionary which holds values in a multidimensional accept and it should be able to expand, this is the structure that the values should be stored :-</p>
<pre><code>userdata = {'data':[{'username':'Ronny Leech','age':'22','country':'Siberia'},{'username':'Cronulla James','age':'34','countr... | 4 | 2010-03-18T08:26:30Z | 2,468,374 | <pre><code>userdata = { "data":[]}
def fil_userdata():
for i in xrange(0,5):
user = {}
user["name"]=...
user["age"]=...
user["country"]=...
add_user(user)
def add_user(user):
userdata["data"].append(user)
</code></pre>
<p>or shorter:</p>
<pre><code>def gen_user():
return {"name":"foo", "ag... | 9 | 2010-03-18T08:36:08Z | [
"python"
] |
Python | How to create dynamic and expandable dictionaries | 2,468,334 | <p>I want to create a Python dictionary which holds values in a multidimensional accept and it should be able to expand, this is the structure that the values should be stored :-</p>
<pre><code>userdata = {'data':[{'username':'Ronny Leech','age':'22','country':'Siberia'},{'username':'Cronulla James','age':'34','countr... | 4 | 2010-03-18T08:26:30Z | 2,468,376 | <p>What's the purpose of the outer <code>data</code> dict?</p>
<p>One possibility is not to use <code>username</code> as a key, but rather the username itself.</p>
<p>It seems like you are trying to use dicts as a database, but I'm not sure it's a good fit. </p>
| 1 | 2010-03-18T08:36:34Z | [
"python"
] |
Remove linebreak at specific position in textfile | 2,468,460 | <p>I have a large textfile, which has linebreaks at column 80 due to console width. Many of the lines in the textfile are not 80 characters long, and are not affected by the linebreak. In pseudocode, this is what I want:</p>
<ul>
<li>Iterate through lines in file</li>
<li>If line matches this regex pattern: ^(.{80})\n... | 0 | 2010-03-18T08:54:47Z | 2,468,584 | <p>Here's some code which should to the trick</p>
<pre><code>def remove_linebreaks(textfile, position=81):
"""
textfile : an file opened in 'r' mode
position : the index on a line at which \n must be removed
return a string with the \n at position removed
"""
fixed_lines = []
for line in t... | 1 | 2010-03-18T09:15:54Z | [
"python",
"regex",
"line-breaks"
] |
Remove linebreak at specific position in textfile | 2,468,460 | <p>I have a large textfile, which has linebreaks at column 80 due to console width. Many of the lines in the textfile are not 80 characters long, and are not affected by the linebreak. In pseudocode, this is what I want:</p>
<ul>
<li>Iterate through lines in file</li>
<li>If line matches this regex pattern: ^(.{80})\n... | 0 | 2010-03-18T08:54:47Z | 2,468,621 | <p>Here is an example of how to use regular expressions to archive this. But regular expressions aren't the best solution everywhere and in this case, i think not using regular expressions is more efficient. Anyway, here is the solution:</p>
<pre><code>text = re.sub(r'(?<=^.{80})\n', '', text)
</code></pre>
<p>You... | 0 | 2010-03-18T09:23:20Z | [
"python",
"regex",
"line-breaks"
] |
Remove linebreak at specific position in textfile | 2,468,460 | <p>I have a large textfile, which has linebreaks at column 80 due to console width. Many of the lines in the textfile are not 80 characters long, and are not affected by the linebreak. In pseudocode, this is what I want:</p>
<ul>
<li>Iterate through lines in file</li>
<li>If line matches this regex pattern: ^(.{80})\n... | 0 | 2010-03-18T08:54:47Z | 2,468,649 | <pre><code>f=open("file")
for line in f:
if len(line)==81:
n=f.next()
line=line.rstrip()+n
print line.rstrip()
f.close()
</code></pre>
| 1 | 2010-03-18T09:26:33Z | [
"python",
"regex",
"line-breaks"
] |
Remove linebreak at specific position in textfile | 2,468,460 | <p>I have a large textfile, which has linebreaks at column 80 due to console width. Many of the lines in the textfile are not 80 characters long, and are not affected by the linebreak. In pseudocode, this is what I want:</p>
<ul>
<li>Iterate through lines in file</li>
<li>If line matches this regex pattern: ^(.{80})\n... | 0 | 2010-03-18T08:54:47Z | 2,468,949 | <p>Consider this.</p>
<pre><code>def merge_lines( line_iter ):
buffer = ''
for line in line_iter:
if len(line) <= 80:
yield buffer + line
buffer= ''
else:
buffer += line[:-1] # remove '\n'
with open('myFile','r') as source:
with open('copy of myFile',... | 1 | 2010-03-18T10:16:40Z | [
"python",
"regex",
"line-breaks"
] |
How to call function that takes an argument in a Django template? | 2,468,804 | <p>I'm passing to Django's template a function, which returns some records.
I want to call this function and iterate over its result. </p>
<pre><code>{% for item in my_func(10) %}
</code></pre>
<p>That doesn't work.
I've tried to set the function's return value to a variable and iterate over the variable, but ther... | 30 | 2010-03-18T09:53:37Z | 2,468,830 | <p>You cannot call a function that requires arguments in a template. <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags">Write</a> a template tag or filter instead.</p>
| 35 | 2010-03-18T09:58:02Z | [
"python",
"django",
"function",
"variables",
"django-templates"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.