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 |
|---|---|---|---|---|---|---|---|---|---|
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my... | 327 | 2009-06-12T18:25:02Z | 25,326,140 | <p>using <code>json.loads</code></p>
<pre><code>>>> import json
>>> h = '{"foo":"bar", "foo2":"bar2"}'
>>> type(h)
<type 'str'>
>>> d = json.loads(h)
>>> d
{u'foo': u'bar', u'foo2': u'bar2'}
>>> type(d)
<type 'dict'>
</code></pre>
| 29 | 2014-08-15T12:07:45Z | [
"python",
"string",
"dictionary"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my... | 327 | 2009-06-12T18:25:02Z | 25,527,687 | <p>Use Json. the ast library consumes a lot of memory and and slower. I have a process that needs to read a text file of 156Mb. Ast with 5 minutes delay for the conversion dictionary Json and 1 minutes using 60% less memory!</p>
| 11 | 2014-08-27T12:50:13Z | [
"python",
"string",
"dictionary"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my... | 327 | 2009-06-12T18:25:02Z | 38,066,510 | <p>To OP's example:</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>We can use <a href="https://pypi.python.org/pypi/PyYAML" rel="nofollow">Yaml</a> to deal with this kind of non-standard json in string:</p>
<pre><code>>>> import yaml
>>> s = "{'muffin' : 'lolz', 'foo' : ... | 0 | 2016-06-28T03:20:03Z | [
"python",
"string",
"dictionary"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my... | 327 | 2009-06-12T18:25:02Z | 38,671,887 | <pre><code>string = "{'server1':'value','server2':'value'}"
#Now removing { and }
s = string.replace("{" ,"");
finalstring = s.replace("}" , "");
#Splitting the string based on , we get key value pairs
list = finalstring.split(",")
dict ={}
for i in list:
#Get Key Value pairs separately to store in dictionary
... | 0 | 2016-07-30T08:19:39Z | [
"python",
"string",
"dictionary"
] |
Efficient Tuple List Comparisons | 988,346 | <p>I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.</p>
<p>I have a large list of four element tuples in the format:</p>
<p>(ID number, Type, Start Index, End Index) </p>
<p>Previously in the code, I have searched through thousands of blocks of text for two spec... | 2 | 2009-06-12T18:47:07Z | 988,455 | <p><strong>Solution:</strong></p>
<pre><code>result = [(l1 + l2[1:])
for l1 in list1
for l2 in list2
if (l1[0] == l2[0] and l1[3] < l2[2])
]
</code></pre>
<p>... with test code:</p>
<pre><code>list1 = [(1, 'Type1', 20, 30,),
(2, 'Type1', 20, 30,),
(3, '... | 1 | 2009-06-12T19:04:22Z | [
"python",
"algorithm",
"list",
"tuples"
] |
Efficient Tuple List Comparisons | 988,346 | <p>I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.</p>
<p>I have a large list of four element tuples in the format:</p>
<p>(ID number, Type, Start Index, End Index) </p>
<p>Previously in the code, I have searched through thousands of blocks of text for two spec... | 2 | 2009-06-12T18:47:07Z | 988,462 | <p>I don't know how many types you have. But If we assume you have only type 1 and type 2, then it sounds like a problem similar to a merge sort. Doing it with a merge sort, you make a single pass through the list. </p>
<p>Take two indexes, one for type 1 and one for type 2 (I1, I2). Sort the list by id, start1. S... | 1 | 2009-06-12T19:05:42Z | [
"python",
"algorithm",
"list",
"tuples"
] |
Efficient Tuple List Comparisons | 988,346 | <p>I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.</p>
<p>I have a large list of four element tuples in the format:</p>
<p>(ID number, Type, Start Index, End Index) </p>
<p>Previously in the code, I have searched through thousands of blocks of text for two spec... | 2 | 2009-06-12T18:47:07Z | 988,509 | <p>I recently did something like this. I might not be understanding your problem but here goes.</p>
<p>I would use a dictionary:</p>
<pre><code>from collections import defaultdict:
masterdictType1=defaultDict(dict)
masterdictType2=defaultdict(dict)
for item in myList:
if item[1]=Type1
if item[0] not in m... | 1 | 2009-06-12T19:14:35Z | [
"python",
"algorithm",
"list",
"tuples"
] |
Efficient Tuple List Comparisons | 988,346 | <p>I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.</p>
<p>I have a large list of four element tuples in the format:</p>
<p>(ID number, Type, Start Index, End Index) </p>
<p>Previously in the code, I have searched through thousands of blocks of text for two spec... | 2 | 2009-06-12T18:47:07Z | 988,650 | <p>Assuming there are lots of entries for each ID, I would (pseudo-code)</p>
<pre>
for each ID:
for each type2 substring of that ID:
store it in an ordered list, sorted by start point
for each type1 substring of that ID:
calculate the end point (or whatever)
look... | 0 | 2009-06-12T19:38:37Z | [
"python",
"algorithm",
"list",
"tuples"
] |
Efficient Tuple List Comparisons | 988,346 | <p>I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.</p>
<p>I have a large list of four element tuples in the format:</p>
<p>(ID number, Type, Start Index, End Index) </p>
<p>Previously in the code, I have searched through thousands of blocks of text for two spec... | 2 | 2009-06-12T18:47:07Z | 988,992 | <p>Could I check, by <em>before</em>, do you mean <em>immediately</em> before (ie. <code>t1_a, t2_b, t2_c, t2_d</code> should just give the pair <code>(t1_a, t2_b)</code>, or do you want all pairs where a type1 value occurs <em>anywhere</em> before a type2 one within the same block. (ie <code>(t1_a, t2_b), (t1_a, t2_c... | 0 | 2009-06-12T20:53:47Z | [
"python",
"algorithm",
"list",
"tuples"
] |
Python string find | 989,170 | <p>I want to find a certain substring inside a string. The string is stored in a list of strings. How can i do it? </p>
| 2 | 2009-06-12T21:34:52Z | 989,179 | <p>So you're searching for all the strings in a list of strings that contain a certain substring? This will do it:</p>
<pre><code>DATA = ['Hello', 'Python', 'World']
SEARCH_STRING = 'n'
print [s for s in DATA if SEARCH_STRING in s]
# Prints ['Python']
</code></pre>
<p><strong>Edit</strong> at Andrew's suggestion: Yo... | 4 | 2009-06-12T21:37:07Z | [
"python"
] |
Python string find | 989,170 | <p>I want to find a certain substring inside a string. The string is stored in a list of strings. How can i do it? </p>
| 2 | 2009-06-12T21:34:52Z | 989,184 | <p>have you looked <a href="http://docs.python.org/library/string.html" rel="nofollow">here</a> it is very simple to do, just do a search in the python documentation</p>
| 0 | 2009-06-12T21:38:37Z | [
"python"
] |
What's the point of os.error? | 989,259 | <p>Why does Python's <code>os</code> module contain <a href="http://docs.python.org/library/os.html#os.error"><code>error</code>, an alias for <code>OSError</code></a>?</p>
<p>Is there a reason to ever spell it <code>os.error</code>? <code>OSError</code> certainly seems more consistent with all the other built-in exce... | 7 | 2009-06-12T21:58:41Z | 989,266 | <p>The documentation for <a href="http://docs.python.org/library/exceptions.html#exceptions.OSError"><code>OSError</code></a> says that it was added in version 1.5.2. My guess is that <code>error</code> predates this a little and in an effort to remain backwards-compatible to code written for Python before 1.5.2 <code>... | 6 | 2009-06-12T22:02:24Z | [
"python"
] |
python string input problem with whitespace! | 989,276 | <p>my input is something like this </p>
<p>23 + 45 = astart</p>
<p>for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this </p>
<p>SyntaxError: invalid syntax</p>
<p>the code is this </p>
<pre><code>k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i... | 1 | 2009-06-12T22:05:41Z | 989,293 | <p>Edit: as pointed out by Triptych, the generator object isn't the problem. The partition solution is still good and holds even for invalid inputs</p>
<p><strike>calling <code>(... for ...)</code> only returns a generator object, not a tuple</p>
<p>try one of the following:</p>
<pre><code>a,b=[str(i) for i in k.spl... | 1 | 2009-06-12T22:10:04Z | [
"python"
] |
python string input problem with whitespace! | 989,276 | <p>my input is something like this </p>
<p>23 + 45 = astart</p>
<p>for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this </p>
<p>SyntaxError: invalid syntax</p>
<p>the code is this </p>
<pre><code>k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i... | 1 | 2009-06-12T22:05:41Z | 989,405 | <p>Testing with Python 2.5.2, your code ran OK as long as I only had the same spacing
on either side of the + and = in the code and input.</p>
<p>You appear to have two spaces on either side of them in the code, but only one on either
side in the input. Also - you do not have to use the str(i) in a generator. You ca... | 2 | 2009-06-12T22:46:53Z | [
"python"
] |
python string input problem with whitespace! | 989,276 | <p>my input is something like this </p>
<p>23 + 45 = astart</p>
<p>for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this </p>
<p>SyntaxError: invalid syntax</p>
<p>the code is this </p>
<pre><code>k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i... | 1 | 2009-06-12T22:05:41Z | 989,566 | <p>I think I'd just use a simple regular expression:</p>
<pre><code># Set up a few regular expressions
parser = re.compile("(\d+)\+(\d+)=(.+)")
spaces = re.compile("\s+")
# Grab input
input = raw_input()
# Remove all whitespace
input = spaces.sub('',input)
# Parse away
num1, num2, result = m.match(input)
</code></p... | 1 | 2009-06-13T00:05:54Z | [
"python"
] |
python string input problem with whitespace! | 989,276 | <p>my input is something like this </p>
<p>23 + 45 = astart</p>
<p>for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this </p>
<p>SyntaxError: invalid syntax</p>
<p>the code is this </p>
<pre><code>k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i... | 1 | 2009-06-12T22:05:41Z | 989,621 | <p>You could just use:</p>
<pre><code>a, b, c = raw_input().replace('+',' ').replace('=', ' ').split()
</code></pre>
<p>Or [Edited to add] - here's another one that avoids creating the extra intermediate strings:</p>
<pre><code>a, b, c = raw_input().split()[::2]
</code></pre>
<p>Hrm - just realized that second one ... | 1 | 2009-06-13T00:36:49Z | [
"python"
] |
python string input problem with whitespace! | 989,276 | <p>my input is something like this </p>
<p>23 + 45 = astart</p>
<p>for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this </p>
<p>SyntaxError: invalid syntax</p>
<p>the code is this </p>
<pre><code>k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i... | 1 | 2009-06-12T22:05:41Z | 989,823 | <p>Rather than trying to solve your problem, I thought I'd point out a basic step you could take to try to understand why you're getting a syntax error: print your intermediate products. </p>
<pre><code>k=raw_input()
print k.split(' + ')
a,b=(str(i) for i in k.split(' + '))
print b.split(' = ')
b,c=(str(i)... | 0 | 2009-06-13T03:01:07Z | [
"python"
] |
Getting the first and last item in a python for loop | 989,665 | <p>Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?</p>
<pre><code>from calendar import Calendar
cal = Calendar(6)
month_dates = cal.itermonthdates(year, month)
for date in month_dates:
if (is first item): # this is fake
month_star... | 6 | 2009-06-13T00:57:36Z | 989,673 | <p>How about this?</p>
<pre><code>for i, date in enumerate(month_dates):
if i == 0:
month_start = date
month_end = date
</code></pre>
<p><code>enumerate()</code> lets you find the first one, and the <code>date</code> variable falls out of the loop to give you the last one.</p>
| 10 | 2009-06-13T01:02:34Z | [
"python",
"for-loop"
] |
Getting the first and last item in a python for loop | 989,665 | <p>Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?</p>
<pre><code>from calendar import Calendar
cal = Calendar(6)
month_dates = cal.itermonthdates(year, month)
for date in month_dates:
if (is first item): # this is fake
month_star... | 6 | 2009-06-13T00:57:36Z | 989,674 | <p>I would just force it into a list at the beginning:</p>
<pre><code>from calendar import Calendar, SUNDAY
cal = Calendar(SUNDAY)
month_dates = list(cal.itermonthdates(year, month))
month_start = month_dates[0]
month_end = month_dates[-1]
</code></pre>
<p>Since there can only be 42 days (counting leading and taili... | 10 | 2009-06-13T01:02:49Z | [
"python",
"for-loop"
] |
Getting the first and last item in a python for loop | 989,665 | <p>Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?</p>
<pre><code>from calendar import Calendar
cal = Calendar(6)
month_dates = cal.itermonthdates(year, month)
for date in month_dates:
if (is first item): # this is fake
month_star... | 6 | 2009-06-13T00:57:36Z | 989,752 | <p>For this specific problem, I think I would go with Matthew Flaschen's solution. It seems the most straightforward to me.</p>
<p>If your question is meant to be taken more generally, though, for any generator (with an unknown and possibly large number of elements), then something more like RichieHindle's approach m... | 2 | 2009-06-13T01:58:39Z | [
"python",
"for-loop"
] |
Getting the first and last item in a python for loop | 989,665 | <p>Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?</p>
<pre><code>from calendar import Calendar
cal = Calendar(6)
month_dates = cal.itermonthdates(year, month)
for date in month_dates:
if (is first item): # this is fake
month_star... | 6 | 2009-06-13T00:57:36Z | 989,772 | <p>Richie's got the right idea. Simpler:</p>
<pre><code>month_dates = cal.itermonthdates(year, month)
month_start = month_dates.next()
for month_end in month_dates: pass # bletcherous
</code></pre>
| 11 | 2009-06-13T02:20:45Z | [
"python",
"for-loop"
] |
Python and psycopg2 - raw sql select from table with integer criteria | 989,833 | <p>It should be simple, bit I've spent the last hour searching for the answer. This is using psycopg2 on python 2.6. </p>
<p>I need something like this:</p>
<pre><code> special_id = 5
sql = """
select count(*) as ct,
from some_table tbl
where tbl.id = %(the_id)
"""
cursor... | 0 | 2009-06-13T03:11:52Z | 989,843 | <p>Per <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">PEP 249</a>, since in psycopg2 <code>paramstyle</code> is <code>pyformat</code>, you need to use <code>%(the_id)s</code> even for non-strings -- trust it to do the right thing.</p>
<p>BTW, internet searches will work better if you use the correct... | 2 | 2009-06-13T03:18:53Z | [
"python"
] |
How do I draw out specific data from an opened url in Python using urllib2? | 989,872 | <p>I'm new to Python and am playing around with making a very basic web crawler. For instance, I have made a simple function to load a page that shows the high scores for an online game. So I am able to get the source code of the html page, but I need to draw specific numbers from that page. For instance, the webpage l... | 3 | 2009-06-13T03:38:04Z | 989,886 | <p>You can use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> to parse the HTML.</p>
| 3 | 2009-06-13T03:41:54Z | [
"python",
"urllib2"
] |
How do I draw out specific data from an opened url in Python using urllib2? | 989,872 | <p>I'm new to Python and am playing around with making a very basic web crawler. For instance, I have made a simple function to load a page that shows the high scores for an online game. So I am able to get the source code of the html page, but I need to draw specific numbers from that page. For instance, the webpage l... | 3 | 2009-06-13T03:38:04Z | 989,920 | <p>As another poster mentioned, <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> is a wonderful tool for this job. </p>
<p>Here's the entire, ostentatiously-commented program. It could use a lot of error tolerance, but as long as you enter a valid username, it will pull all the scores from th... | 11 | 2009-06-13T03:55:17Z | [
"python",
"urllib2"
] |
How to find out the arity of a method in Python | 990,016 | <p>I'd like to find out the arity of a method in Python (the number of parameters that it receives).
Right now I'm doing this:</p>
<pre><code>def arity(obj, method):
return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
class Foo:
def bar(self, bla):
pass
arity(Foo(), "bar") # =>... | 25 | 2009-06-13T05:07:17Z | 990,022 | <p>Module <code>inspect</code> from Python's standard library is your friend -- see <a href="http://docs.python.org/library/inspect.html">the online docs</a>! <code>inspect.getargspec(func)</code> returns a tuple with four items, <code>args, varargs, varkw, defaults</code>: <code>len(args)</code> is the "primary arity... | 38 | 2009-06-13T05:13:14Z | [
"python",
"metaprogramming"
] |
How to find out the arity of a method in Python | 990,016 | <p>I'd like to find out the arity of a method in Python (the number of parameters that it receives).
Right now I'm doing this:</p>
<pre><code>def arity(obj, method):
return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
class Foo:
def bar(self, bla):
pass
arity(Foo(), "bar") # =>... | 25 | 2009-06-13T05:07:17Z | 990,034 | <p>you can use a decorator to decorate methods e.g.</p>
<pre><code>def arity(method):
def _arity():
return method.func_code.co_argcount - 1 # remove self
method.arity = _arity
return method
class Foo:
@arity
def bar(self, bla):
pass
print Foo().bar.arity()
</code></pre>
<p>As alex said now its ... | 4 | 2009-06-13T05:21:57Z | [
"python",
"metaprogramming"
] |
How to find out the arity of a method in Python | 990,016 | <p>I'd like to find out the arity of a method in Python (the number of parameters that it receives).
Right now I'm doing this:</p>
<pre><code>def arity(obj, method):
return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
class Foo:
def bar(self, bla):
pass
arity(Foo(), "bar") # =>... | 25 | 2009-06-13T05:07:17Z | 990,039 | <p>Ideally, you'd want to monkey-patch the arity function as a method on Python functors. Here's how:</p>
<pre><code>def arity(self, method):
return getattr(self.__class__, method).func_code.co_argcount - 1
functor = arity.__class__
functor.arity = arity
arity.__class__.arity = arity
</code></pre>
<p>But, CPyth... | 2 | 2009-06-13T05:23:51Z | [
"python",
"metaprogramming"
] |
How to find out the arity of a method in Python | 990,016 | <p>I'd like to find out the arity of a method in Python (the number of parameters that it receives).
Right now I'm doing this:</p>
<pre><code>def arity(obj, method):
return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
class Foo:
def bar(self, bla):
pass
arity(Foo(), "bar") # =>... | 25 | 2009-06-13T05:07:17Z | 990,060 | <p>here is another attempt using metaclass, as i use python 2.5, but with 2.6 you could easily decorate the class</p>
<p>metaclass can also be defined at module level, so it works for all classes</p>
<pre><code>from types import FunctionType
def arity(unboundmethod):
def _arity():
return unboundmethod.fu... | 0 | 2009-06-13T05:39:34Z | [
"python",
"metaprogramming"
] |
How to find out the arity of a method in Python | 990,016 | <p>I'd like to find out the arity of a method in Python (the number of parameters that it receives).
Right now I'm doing this:</p>
<pre><code>def arity(obj, method):
return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
class Foo:
def bar(self, bla):
pass
arity(Foo(), "bar") # =>... | 25 | 2009-06-13T05:07:17Z | 990,942 | <p>This is the only way that I can think of that should be 100% effective (at least with regard to whether the function is user-defined or written in C) at determining a function's (minimum) arity. However, you should be sure that this function won't cause any side-effects and that it won't throw a TypeError:</p>
<pr... | 2 | 2009-06-13T16:08:13Z | [
"python",
"metaprogramming"
] |
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux? | 990,102 | <p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p>
<p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating... | 15 | 2009-06-13T06:14:47Z | 990,154 | <p>Another solution is:
<a href="http://docs.python.org/library/multiprocessing.html">http://docs.python.org/library/multiprocessing.html</a></p>
<p>Note 1: This is <strong>not</strong> a limitation of the Python language, but of CPython implementation.</p>
<p>Note 2: With regard to affinity, your OS shouldn't have a... | 8 | 2009-06-13T06:49:25Z | [
"python",
"multithreading",
"multicore",
"gil",
"python-stackless"
] |
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux? | 990,102 | <p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p>
<p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating... | 15 | 2009-06-13T06:14:47Z | 990,323 | <p>I've found the following rule of thumb sufficient over the years: If the workers are dependent on some shared state, I use one multiprocessing process per core (CPU bound), and per core a fix pool of worker threads (I/O bound). The OS will take care of assigining the different Python processes to the cores.</p>
| 1 | 2009-06-13T08:37:38Z | [
"python",
"multithreading",
"multicore",
"gil",
"python-stackless"
] |
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux? | 990,102 | <p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p>
<p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating... | 15 | 2009-06-13T06:14:47Z | 990,436 | <p>I have never heard of anyone using taskset for a performance gain with Python. Doesn't mean it can't happen in your case, but definitely publish your results so others can critique your benchmarking methods and provide validation.</p>
<p>Personally though, I would decouple your I/O threads from the CPU bound threa... | 5 | 2009-06-13T09:51:55Z | [
"python",
"multithreading",
"multicore",
"gil",
"python-stackless"
] |
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux? | 990,102 | <p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p>
<p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating... | 15 | 2009-06-13T06:14:47Z | 991,325 | <p>The Python GIL is per Python interpreter. That means the only to avoid problems with it while doing multiprocessing is simply starting multiple interpreters (i.e. using seperate processes instead of threads for concurrency) and then using some other IPC primitive for communication between the processes (such as sock... | 1 | 2009-06-13T19:21:22Z | [
"python",
"multithreading",
"multicore",
"gil",
"python-stackless"
] |
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux? | 990,102 | <p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p>
<p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating... | 15 | 2009-06-13T06:14:47Z | 1,005,639 | <p>Until such time as the GIL is removed from Python, co-routines may be used in place of threads. I have it on good authority that this strategy has been implemented by two successful start-ups, using greenlets in at least one case.</p>
| 1 | 2009-06-17T07:43:33Z | [
"python",
"multithreading",
"multicore",
"gil",
"python-stackless"
] |
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux? | 990,102 | <p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p>
<p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating... | 15 | 2009-06-13T06:14:47Z | 8,204,625 | <p>An interesting solution is the experiment reported by Ryan Kelly on his blog: <a href="http://www.rfk.id.au/blog/entry/a-gil-adventure-threading2/" rel="nofollow">http://www.rfk.id.au/blog/entry/a-gil-adventure-threading2/</a></p>
The results seems very satisfactory.</p>
| 3 | 2011-11-20T20:51:04Z | [
"python",
"multithreading",
"multicore",
"gil",
"python-stackless"
] |
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux? | 990,102 | <p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p>
<p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating... | 15 | 2009-06-13T06:14:47Z | 8,926,548 | <p>This is a pretty old question but since everytime I search about information related to python and performance on multi-core systems this post is always on the result list, I would not let this past before me an do not share my thoughts.</p>
<p>You can use the multiprocessing module that rather than create threads ... | 0 | 2012-01-19T13:10:17Z | [
"python",
"multithreading",
"multicore",
"gil",
"python-stackless"
] |
How do convert unicode escape sequences to unicode characters in a python string | 990,169 | <p>When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python?</p>
| 20 | 2009-06-13T06:56:27Z | 990,183 | <p>I suspect that it's acutally working correctly. By default, Python displays strings in ASCII encoding, since not all terminals support unicode. If you actually print the string, though, it should work. See the following example:</p>
<pre><code>>>> u'\xcfa'
u'\xcfa'
>>> print u'\xcfa'
Ãa
</code... | 4 | 2009-06-13T07:02:20Z | [
"python",
"unicode"
] |
How do convert unicode escape sequences to unicode characters in a python string | 990,169 | <p>When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python?</p>
| 20 | 2009-06-13T06:56:27Z | 992,314 | <p>Assuming Python sees the name as a normal string, you'll first have to decode it to unicode:</p>
<pre><code>>>> name
'Christensen Sk\xf6ld'
>>> unicode(name, 'latin-1')
u'Christensen Sk\xf6ld'
</code></pre>
<p>Another way of achieving this:</p>
<pre><code>>>> name.decode('latin-1')
u'Ch... | 24 | 2009-06-14T06:46:22Z | [
"python",
"unicode"
] |
How do convert unicode escape sequences to unicode characters in a python string | 990,169 | <p>When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python?</p>
| 20 | 2009-06-13T06:56:27Z | 12,083,259 | <p>Given a byte string with Unicode escapes <code>b"\N{SNOWMAN}"</code>, <code>b"\N{SNOWMAN}".decode('unicode-escape)</code> will produce the expected Unicode string <code>u'\u2603'</code>.</p>
| 5 | 2012-08-23T00:36:28Z | [
"python",
"unicode"
] |
How to get a reference to current module's attributes in Python | 990,422 | <p>What I'm trying to do would look like this in the command line:</p>
<pre><code>>>> import mymodule
>>> names = dir(mymodule)
</code></pre>
<p>How can I get a reference to all the names defined in <code>mymodule</code> from within <code>mymodule</code> itself?</p>
<p>Something like this:</p>
<pr... | 78 | 2009-06-13T09:45:03Z | 990,450 | <p>Just use globals()</p>
<blockquote>
<p>globals() â Return a dictionary
representing the current global symbol
table. This is always the dictionary
of the current module (inside a
function or method, this is the module
where it is defined, not the module
from which it is called).</p>
</blockquote>
<... | 87 | 2009-06-13T10:01:56Z | [
"python"
] |
How to get a reference to current module's attributes in Python | 990,422 | <p>What I'm trying to do would look like this in the command line:</p>
<pre><code>>>> import mymodule
>>> names = dir(mymodule)
</code></pre>
<p>How can I get a reference to all the names defined in <code>mymodule</code> from within <code>mymodule</code> itself?</p>
<p>Something like this:</p>
<pr... | 78 | 2009-06-13T09:45:03Z | 991,115 | <p>Also check out the built-in <a href="http://docs.python.org/2/library/inspect.html" rel="nofollow">inspect</a> module. It can be very handy.</p>
| 9 | 2009-06-13T17:32:18Z | [
"python"
] |
How to get a reference to current module's attributes in Python | 990,422 | <p>What I'm trying to do would look like this in the command line:</p>
<pre><code>>>> import mymodule
>>> names = dir(mymodule)
</code></pre>
<p>How can I get a reference to all the names defined in <code>mymodule</code> from within <code>mymodule</code> itself?</p>
<p>Something like this:</p>
<pr... | 78 | 2009-06-13T09:45:03Z | 991,158 | <p>As previously mentioned, globals gives you a dictionary as opposed to dir() which gives you a list of the names defined in the module. The way I typically see this done is like this:</p>
<pre><code>import sys
dir(sys.modules[__name__])
</code></pre>
| 102 | 2009-06-13T17:53:16Z | [
"python"
] |
Python LDAP Authentication from remote web server | 990,459 | <p>I have a django application hosted on webfaction which now has a static/private ip.</p>
<p>Our network in the office is obviously behind a firewall and the AD server is running behind this firewall. From inside the network i can authenticate using python-ldap with the AD's internal IP address and the port 389 and a... | 0 | 2009-06-13T10:09:05Z | 991,550 | <p>There are quite a few components between your hosted django application and your internal AD. You will need to test each to see if everything in the pathways between them is correct.</p>
<p>So your AD server is sitting behind your firewall. Your firewall has ip "a.b.c.d" and all traffic to the firewall ip on port 3... | 0 | 2009-06-13T21:29:41Z | [
"python",
"active-directory",
"ldap",
"webserver"
] |
Python LDAP Authentication from remote web server | 990,459 | <p>I have a django application hosted on webfaction which now has a static/private ip.</p>
<p>Our network in the office is obviously behind a firewall and the AD server is running behind this firewall. From inside the network i can authenticate using python-ldap with the AD's internal IP address and the port 389 and a... | 0 | 2009-06-13T10:09:05Z | 992,795 | <p>I would recommend against opening the port on the firewall directly to LDAP. Instead I would suggest making an SSH tunnel. This will put the necessary encryptionn around the LDAP traffic. Here is an example.</p>
<pre><code>ssh -N -p 22 username@ldapserver -L 2222/localhost/389
</code></pre>
<p>This assumes that th... | 3 | 2009-06-14T13:00:59Z | [
"python",
"active-directory",
"ldap",
"webserver"
] |
how to take a matrix in python? | 990,469 | <p>i want to create a matrix of size 1234*5678 with it being filled with 1 to 5678 in row major order?>..!! </p>
| 1 | 2009-06-13T10:19:27Z | 990,491 | <p><a href="http://bytes.com/topic/python/answers/594203-please-how-create-matrix-python" rel="nofollow">Here's a forum post</a> that has some code examples of what you are trying to achieve.</p>
| 1 | 2009-06-13T10:37:15Z | [
"python"
] |
how to take a matrix in python? | 990,469 | <p>i want to create a matrix of size 1234*5678 with it being filled with 1 to 5678 in row major order?>..!! </p>
| 1 | 2009-06-13T10:19:27Z | 990,510 | <p>Or just use <a href="http://numpy.scipy.org/" rel="nofollow">Numerical Python</a> if you want to do some mathematical stuff on matrix too (like multiplication, ...). If they use row major order for the matrix layout in memory I can't tell you but it gets coverd in their documentation</p>
| 2 | 2009-06-13T11:00:28Z | [
"python"
] |
how to take a matrix in python? | 990,469 | <p>i want to create a matrix of size 1234*5678 with it being filled with 1 to 5678 in row major order?>..!! </p>
| 1 | 2009-06-13T10:19:27Z | 990,553 | <p>I think you will need to use numpy to hold such a big matrix efficiently , not just computation. You have ~5e6 items of 4/8 bytes means 20/40 Mb in pure C already, several times of that in python without an efficient data structure (a list of rows, each row a list).</p>
<p>Now, concerning your question:</p>
<pre><... | 6 | 2009-06-13T11:38:56Z | [
"python"
] |
Using doctest "result parser" within unit-tests in Python? | 990,500 | <p>I recently faced a problem about combining unit tests and doctests in Python. I worked around this problem in other way, but I still have question about it.</p>
<p>Python's doctest module parses docstrings in a module and run commands following ">>> " at the beginning of each line and compare the output of it and t... | 2 | 2009-06-13T10:46:53Z | 990,630 | <p>See <a href="http://docs.python.org/library/doctest.html#doctest.OutputChecker.check%5Foutput" rel="nofollow"><code>doctest.OutputChecker.check_output()</code></a></p>
| 2 | 2009-06-13T13:00:27Z | [
"python",
"unit-testing",
"testing",
"documentation",
"doctest"
] |
How to leave/exit/deactivate a python virtualenv? | 990,754 | <p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p>
<pre><code>me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$
</code></pre>
<p>However, how do I exit all virtual machines an... | 662 | 2009-06-13T14:15:36Z | 990,779 | <p>Usually, activating a virtualenv gives you a shell function named:</p>
<pre><code>$ deactivate
</code></pre>
<p>which puts things back to normal.</p>
<p><strong>Edit:</strong> I have just looked specifically again at the code for virtualenvwrapper, and, yes, it too supports "deactivate" as the way to escape from ... | 1,129 | 2009-06-13T14:31:00Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] |
How to leave/exit/deactivate a python virtualenv? | 990,754 | <p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p>
<pre><code>me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$
</code></pre>
<p>However, how do I exit all virtual machines an... | 662 | 2009-06-13T14:15:36Z | 27,429,748 | <p>Had the same problem myself while working on an installer script, I took a look at what the <em>bin/activate_this.py</em> did and reversed it. </p>
<p>Example:</p>
<pre><code>#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
# path to virtualenv
venv_path = os.path.join('/home', 'sixdays', '.virtual... | -1 | 2014-12-11T18:18:42Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] |
How to leave/exit/deactivate a python virtualenv? | 990,754 | <p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p>
<pre><code>me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$
</code></pre>
<p>However, how do I exit all virtual machines an... | 662 | 2009-06-13T14:15:36Z | 27,947,686 | <p>I defined an <a href="http://askubuntu.com/questions/17536/how-do-i-create-a-permanent-bash-alias">alias</a> <strong>workoff</strong> as the opposite of workon:</p>
<pre><code>alias workoff='deactivate'
</code></pre>
<p>Easy to remember:</p>
<pre><code>[bobstein@host ~]$ workon django_project
(django_project)[bob... | 17 | 2015-01-14T16:23:13Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] |
How to leave/exit/deactivate a python virtualenv? | 990,754 | <p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p>
<pre><code>me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$
</code></pre>
<p>However, how do I exit all virtual machines an... | 662 | 2009-06-13T14:15:36Z | 29,586,756 | <p>$ deactivate </p>
<p>If this doesn't work , try
$ source deactivate</p>
| 2 | 2015-04-12T06:41:08Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] |
How to leave/exit/deactivate a python virtualenv? | 990,754 | <p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p>
<pre><code>me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$
</code></pre>
<p>However, how do I exit all virtual machines an... | 662 | 2009-06-13T14:15:36Z | 33,932,473 | <p>to activate python virtual environment:</p>
<pre><code>$cd ~/python-venv/
$./bin/activate
</code></pre>
<p>to deactivate:</p>
<pre><code>$deactivate
</code></pre>
| 4 | 2015-11-26T07:06:58Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] |
How to leave/exit/deactivate a python virtualenv? | 990,754 | <p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p>
<pre><code>me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$
</code></pre>
<p>However, how do I exit all virtual machines an... | 662 | 2009-06-13T14:15:36Z | 39,263,132 | <p>You can use <code>virtualenvwrapper</code> in order to ease the way you work with <code>virtualenv</code></p>
<p>Installing <code>virtualenvwrapper</code></p>
<pre><code>pip install virtualenvwrapper
</code></pre>
<p>If you are using standard shell, open your <code>~/.bashrc</code> or <code>~/.zshrc</code> if you... | -1 | 2016-09-01T05:13:21Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] |
Reclassing an instance in Python | 990,758 | <p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p>
<p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subcla... | 45 | 2009-06-13T14:17:41Z | 990,790 | <p>Heheh, fun example.</p>
<p>"Reclassing" is pretty weird, at first glance. What about the 'copy constructor' approach? You can do this with the Reflection-like <code>hasattr</code>, <code>getattr</code> and <code>setattr</code>. This code will copy everything from one object to another, unless it already exists. If ... | 1 | 2009-06-13T14:43:34Z | [
"subclass",
"python"
] |
Reclassing an instance in Python | 990,758 | <p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p>
<p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subcla... | 45 | 2009-06-13T14:17:41Z | 990,859 | <p>I will say this is perfectly fine, if it works for you.</p>
| -1 | 2009-06-13T15:21:50Z | [
"subclass",
"python"
] |
Reclassing an instance in Python | 990,758 | <p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p>
<p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subcla... | 45 | 2009-06-13T14:17:41Z | 990,876 | <p>I'm not sure that the use of inheritance is best in this case (at least with regards to "reclassing"). It seems like you're on the right track, but it sounds like composition or aggregation would be best for this. Here's an example of what I'm thinking of (in untested, pseudo-esque code):</p>
<pre><code>from copy... | 11 | 2009-06-13T15:31:03Z | [
"subclass",
"python"
] |
Reclassing an instance in Python | 990,758 | <p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p>
<p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subcla... | 45 | 2009-06-13T14:17:41Z | 990,915 | <p>This technique seems reasonably Pythonic to me. Composition would also be a good choice, but assigning to <code>__class__</code> is perfectly valid (see <a href="http://code.activestate.com/recipes/68429/" rel="nofollow">here</a> for a recipe that uses it in a slightly different way).</p>
| 1 | 2009-06-13T15:53:16Z | [
"subclass",
"python"
] |
Reclassing an instance in Python | 990,758 | <p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p>
<p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subcla... | 45 | 2009-06-13T14:17:41Z | 991,202 | <p>This is fine. I've used this idiom plenty of times. One thing to keep in mind though is that this idea doesn't play well with old-style classes and various C extensions. Normally this wouldn't be an issue, but since you are using an external library you'll just have to make sure you're not dealing with any old-st... | 3 | 2009-06-13T18:13:46Z | [
"subclass",
"python"
] |
Reclassing an instance in Python | 990,758 | <p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p>
<p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subcla... | 45 | 2009-06-13T14:17:41Z | 991,262 | <p>Reclassing instances like this is done in <a href="http://selenic.com/mercurial/">Mercurial</a> (a distributed revision control system) when extensions (plugins) want to change the object that represent the local repository. The object is called <code>repo</code> and is initially a <code>localrepo</code> instance. I... | 14 | 2009-06-13T18:47:45Z | [
"subclass",
"python"
] |
Reclassing an instance in Python | 990,758 | <p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p>
<p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subcla... | 45 | 2009-06-13T14:17:41Z | 3,284,809 | <p>"The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change it's class." - Head First Design Pattern. Something very similar write Gamma et.al. in their Design Patterns book. (I have it at my other place, so no quote). I think that's the whole point of ... | 3 | 2010-07-19T20:31:20Z | [
"subclass",
"python"
] |
Reclassing an instance in Python | 990,758 | <p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p>
<p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subcla... | 45 | 2009-06-13T14:17:41Z | 23,684,684 | <p>In ojrac's answer, the <code>break</code> breaks out of the <code>for</code>-loop and doesn't test any more attributes. I think it makes more sense to just use the <code>if</code>-statement to decide what to do with each attribute one at a time, and continue through the <code>for</code>-loop over all attributes. O... | 0 | 2014-05-15T17:10:40Z | [
"subclass",
"python"
] |
Closing file opened by ConfigParser | 990,867 | <p>I have the following:</p>
<pre><code>config = ConfigParser()
config.read('connections.cfg')
sections = config.sections()
</code></pre>
<p>How can I close the file opened with <code>config.read</code>?</p>
<p>In my case, as new sections/data are added to the <code>config.cfg</code> file, I update my wxtree widget.... | 8 | 2009-06-13T15:28:14Z | 990,927 | <p>To test your suspicion, use <a href="http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.readfp" rel="nofollow">ConfigParser.readfp()</a> and handle opening and closing of the file by yourself. Make the <code>readfp</code> call after the changes are made.</p>
<pre><code>config = ConfigPars... | 4 | 2009-06-13T16:01:03Z | [
"python",
"configparser"
] |
Closing file opened by ConfigParser | 990,867 | <p>I have the following:</p>
<pre><code>config = ConfigParser()
config.read('connections.cfg')
sections = config.sections()
</code></pre>
<p>How can I close the file opened with <code>config.read</code>?</p>
<p>In my case, as new sections/data are added to the <code>config.cfg</code> file, I update my wxtree widget.... | 8 | 2009-06-13T15:28:14Z | 990,933 | <p>Use <a href="http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.readfp" rel="nofollow">readfp</a> instead of read:</p>
<pre><code>with open('connections.cfg') as fp:
config = ConfigParser()
config.readfp(fp)
sections = config.sections()
</code></pre>
| 8 | 2009-06-13T16:03:27Z | [
"python",
"configparser"
] |
Closing file opened by ConfigParser | 990,867 | <p>I have the following:</p>
<pre><code>config = ConfigParser()
config.read('connections.cfg')
sections = config.sections()
</code></pre>
<p>How can I close the file opened with <code>config.read</code>?</p>
<p>In my case, as new sections/data are added to the <code>config.cfg</code> file, I update my wxtree widget.... | 8 | 2009-06-13T15:28:14Z | 990,959 | <p>The difference between <code>ConfigParser</code> and <code>RawConfigParser</code> is that <code>ConfigParser</code> will attempt to "magically" expand references to other config variables, like so:</p>
<pre><code>x = 9000 %(y)s
y = spoons
</code></pre>
<p>In this case, <code>x</code> will be <code>9000 spoons</cod... | 5 | 2009-06-13T16:21:01Z | [
"python",
"configparser"
] |
Closing file opened by ConfigParser | 990,867 | <p>I have the following:</p>
<pre><code>config = ConfigParser()
config.read('connections.cfg')
sections = config.sections()
</code></pre>
<p>How can I close the file opened with <code>config.read</code>?</p>
<p>In my case, as new sections/data are added to the <code>config.cfg</code> file, I update my wxtree widget.... | 8 | 2009-06-13T15:28:14Z | 16,666,375 | <p><code>ConfigParser.read(filenames)</code> actually takes care of that for you.</p>
<p>While coding I have encountered this issue and found myself asking myself the very same question: </p>
<blockquote>
<p><em>Reading basically means I also have to close this resource after I'm done with it, right?</em></p>
</blo... | 11 | 2013-05-21T09:20:18Z | [
"python",
"configparser"
] |
String reversal in Python | 990,934 | <p>I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?</p>
<p>I am not able to convert the integer into a list so not able to apply the reverse function.</p>
| 7 | 2009-06-13T16:03:35Z | 990,939 | <p>Code:</p>
<pre><code>>>> n = 1234
>>> print str(n)[::-1]
4321
</code></pre>
| 4 | 2009-06-13T16:07:53Z | [
"python"
] |
String reversal in Python | 990,934 | <p>I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?</p>
<p>I am not able to convert the integer into a list so not able to apply the reverse function.</p>
| 7 | 2009-06-13T16:03:35Z | 990,940 | <p>You can use the slicing operator to reverse a string:</p>
<pre><code>s = "hello, world"
s = s[::-1]
print s # prints "dlrow ,olleh"
</code></pre>
<p>To convert an integer to a string, reverse it, and convert it back to an integer, you can do:</p>
<pre><code>x = 314159
x = int(str(x)[::-1])
print x # prints 9514... | 30 | 2009-06-13T16:07:54Z | [
"python"
] |
String reversal in Python | 990,934 | <p>I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?</p>
<p>I am not able to convert the integer into a list so not able to apply the reverse function.</p>
| 7 | 2009-06-13T16:03:35Z | 990,943 | <pre><code>>>> int(''.join(reversed(str(12345))))
54321
</code></pre>
| 2 | 2009-06-13T16:09:59Z | [
"python"
] |
How to calculate a mod b in python? | 991,027 | <p>Is there a modulo function in the python <code>math</code> library?</p>
<p>Isn't <code>15 % 4</code>, 3? But <code>15 mod 4</code> is 1, right?</p>
| 53 | 2009-06-13T16:57:21Z | 991,034 | <p>There's the <code>%</code> sign. It's not just for the remainder, it is the modulo operation.</p>
| 86 | 2009-06-13T16:59:23Z | [
"python"
] |
How to calculate a mod b in python? | 991,027 | <p>Is there a modulo function in the python <code>math</code> library?</p>
<p>Isn't <code>15 % 4</code>, 3? But <code>15 mod 4</code> is 1, right?</p>
| 53 | 2009-06-13T16:57:21Z | 991,037 | <p>Why don't you use % ?</p>
<pre><code>
print 4 % 2 # 0
</code></pre>
| 8 | 2009-06-13T16:59:38Z | [
"python"
] |
How to calculate a mod b in python? | 991,027 | <p>Is there a modulo function in the python <code>math</code> library?</p>
<p>Isn't <code>15 % 4</code>, 3? But <code>15 mod 4</code> is 1, right?</p>
| 53 | 2009-06-13T16:57:21Z | 991,043 | <p><code>mod = a % b</code></p>
<p>This stores the result of <code>a mod b</code> in the variable <code>mod</code>.</p>
<p>And you are right, <code>15 mod 4</code> is 3, which is exactly what python returns:</p>
<pre><code>>>> 15 % 4
3
</code></pre>
<p>@Macarse: Yes, but that is true for any \= construct i... | 13 | 2009-06-13T17:00:46Z | [
"python"
] |
How to calculate a mod b in python? | 991,027 | <p>Is there a modulo function in the python <code>math</code> library?</p>
<p>Isn't <code>15 % 4</code>, 3? But <code>15 mod 4</code> is 1, right?</p>
| 53 | 2009-06-13T16:57:21Z | 991,053 | <pre><code>>>> 15 % 4
3
>>>
</code></pre>
<p>The modulo gives the remainder after integer division.</p>
| 19 | 2009-06-13T17:06:26Z | [
"python"
] |
How to calculate a mod b in python? | 991,027 | <p>Is there a modulo function in the python <code>math</code> library?</p>
<p>Isn't <code>15 % 4</code>, 3? But <code>15 mod 4</code> is 1, right?</p>
| 53 | 2009-06-13T16:57:21Z | 992,639 | <p>you can also try <code>divmod(x, y)</code> which returns a tuple <code>(x / y, x % y)</code></p>
| 25 | 2009-06-14T10:58:40Z | [
"python"
] |
an error in taking an input in python | 991,220 | <p>111111111111111111111111111111111111111111111111111111111111</p>
<p>when i take this as input , it appends an L at the end like this </p>
<p>111111111111111111111111111111111111111111111111111111111111L</p>
<p>thus affecting my calculations on it .. how can i remove it?</p>
<pre><code>import math
t=raw_input()
l... | 0 | 2009-06-13T18:24:05Z | 991,226 | <p>It's being input as a Long Integer, which should behave just like any other number in terms of doing calculations. It's only when you display it using <a href="http://docs.python.org/library/functions.html#repr" rel="nofollow"><code>repr</code></a> (or something that invokes <code>repr</code>, like printing a list)... | 3 | 2009-06-13T18:26:32Z | [
"python"
] |
an error in taking an input in python | 991,220 | <p>111111111111111111111111111111111111111111111111111111111111</p>
<p>when i take this as input , it appends an L at the end like this </p>
<p>111111111111111111111111111111111111111111111111111111111111L</p>
<p>thus affecting my calculations on it .. how can i remove it?</p>
<pre><code>import math
t=raw_input()
l... | 0 | 2009-06-13T18:24:05Z | 991,231 | <p>Are you sure that L is really part of it? When you print such large numbers, Python will append an L to indicate it's a long integer object.</p>
| 0 | 2009-06-13T18:28:12Z | [
"python"
] |
an error in taking an input in python | 991,220 | <p>111111111111111111111111111111111111111111111111111111111111</p>
<p>when i take this as input , it appends an L at the end like this </p>
<p>111111111111111111111111111111111111111111111111111111111111L</p>
<p>thus affecting my calculations on it .. how can i remove it?</p>
<pre><code>import math
t=raw_input()
l... | 0 | 2009-06-13T18:24:05Z | 991,245 | <p>As RichieHindle noticed in his answer, it is being represented as a Long Integer. You can read about the different ways that numbers can be represented in Python at the following <a href="http://www.python.org/doc/2.5.2/lib/typesnumeric.html" rel="nofollow">page</a>.</p>
<p>When I use numbers that large in Python,... | 2 | 2009-06-13T18:35:59Z | [
"python"
] |
an error in taking an input in python | 991,220 | <p>111111111111111111111111111111111111111111111111111111111111</p>
<p>when i take this as input , it appends an L at the end like this </p>
<p>111111111111111111111111111111111111111111111111111111111111L</p>
<p>thus affecting my calculations on it .. how can i remove it?</p>
<pre><code>import math
t=raw_input()
l... | 0 | 2009-06-13T18:24:05Z | 991,301 | <p>It looks like there are two distinct things happening here. First, as the other posters have noted, the L suffix simply indicates that Python has converted the input value to a long integer. The second issue is on this line:</p>
<pre><code>a=(0.5 + 2.5*(k %2))*k + k % 2
</code></pre>
<p>This implicitly results in ... | 3 | 2009-06-13T19:09:26Z | [
"python"
] |
an error in taking an input in python | 991,220 | <p>111111111111111111111111111111111111111111111111111111111111</p>
<p>when i take this as input , it appends an L at the end like this </p>
<p>111111111111111111111111111111111111111111111111111111111111L</p>
<p>thus affecting my calculations on it .. how can i remove it?</p>
<pre><code>import math
t=raw_input()
l... | 0 | 2009-06-13T18:24:05Z | 991,421 | <p>Another way to avoid numerical errors in python is to use Decimal type instead of standard float. </p>
<p>Please refer to <a href="http://docs.python.org/library/decimal.html" rel="nofollow">official docs</a></p>
| 2 | 2009-06-13T20:12:46Z | [
"python"
] |
Deleting files by type in Python on Windows | 991,279 | <p>I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type.</p>
<p>Say the directory is \myfolder</p>
<p>I want to delete all files that are .config files, but nothing to the other ones.
How would I do this?</p>
<p>Thanks Kindly</p>
| 6 | 2009-06-13T19:00:23Z | 991,302 | <p>I would do something like the following:</p>
<pre><code>import os
files = os.listdir("myfolder")
for f in files:
if not os.path.isdir(f) and ".config" in f:
os.remove(f)
</code></pre>
<p>It lists the files in a directory and if it's not a directory and the filename has ".config" anywhere in it, delete it. Y... | 4 | 2009-06-13T19:10:30Z | [
"python",
"file"
] |
Deleting files by type in Python on Windows | 991,279 | <p>I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type.</p>
<p>Say the directory is \myfolder</p>
<p>I want to delete all files that are .config files, but nothing to the other ones.
How would I do this?</p>
<p>Thanks Kindly</p>
| 6 | 2009-06-13T19:00:23Z | 991,306 | <p>Use the <a href="http://docs.python.org/library/glob.html"><code>glob</code></a> module:</p>
<pre><code>import os
from glob import glob
for f in glob ('myfolder/*.config'):
os.unlink (f)
</code></pre>
| 15 | 2009-06-13T19:13:30Z | [
"python",
"file"
] |
Deleting files by type in Python on Windows | 991,279 | <p>I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type.</p>
<p>Say the directory is \myfolder</p>
<p>I want to delete all files that are .config files, but nothing to the other ones.
How would I do this?</p>
<p>Thanks Kindly</p>
| 6 | 2009-06-13T19:00:23Z | 991,311 | <p>Here ya go:</p>
<pre><code>import os
# Return all files in dir, and all its subdirectories, ending in pattern
def gen_files(dir, pattern):
for dirname, subdirs, files in os.walk(dir):
for f in files:
if f.endswith(pattern):
yield os.path.join(dirname, f)
# Remove all files in the cu... | 1 | 2009-06-13T19:16:40Z | [
"python",
"file"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 991,372 | <p>You want to use a <a href="http://docs.python.org/library/stdtypes.html#dict" rel="nofollow">dict</a>.</p>
<pre><code>#!/usr/bin/env python
input = "this is a string"
d = {}
for c in input:
try:
d[c] += 1
except:
d[c] = 1
for k in d.keys():
print "%s: %d" % (k, d[k])
</code></pre>
| 2 | 2009-06-13T19:50:38Z | [
"python"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 991,374 | <pre><code>import collections
d = collections.defaultdict(int)
for c in thestring:
d[c] += 1
</code></pre>
<p>A <code>collections.defaultdict</code> is like a <code>dict</code> (subclasses it, actually), but when an entry is sought and not found, instead of reporting it doesn't have it, it makes it and inserts it... | 79 | 2009-06-13T19:51:22Z | [
"python"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 991,376 | <p>You can use a dictionary:</p>
<pre><code>s = "asldaksldkalskdla"
dict = {}
for letter in s:
if letter not in dict.keys():
dict[letter] = 1
else:
dict[letter] += 1
print dict
</code></pre>
| 1 | 2009-06-13T19:52:17Z | [
"python"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 991,379 | <p>My first idea was to do this:</p>
<pre><code>chars = "abcdefghijklmnopqrstuvwxyz"
check_string = "i am checking this string to see how many times each character appears"
for char in chars:
count = check_string.count(char)
if count > 1:
print char, count
</code></pre>
<p>This is not a good idea, however... | 18 | 2009-06-13T19:54:45Z | [
"python"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 991,475 | <p>This is the shortest, most practical I can comeup with without importing extra modules.</p>
<pre><code>text = "hello cruel world. This is a sample text"
d = dict.fromkeys(text, 0)
for c in text: d[c] += 1
</code></pre>
<p>print d['a'] would output 2</p>
<p>And it's also fast.</p>
| 12 | 2009-06-13T20:40:15Z | [
"python"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 991,520 | <p>I can count the number of days I know Python on my two hands so forgive me if I answer something silly :)</p>
<p>Instead of using a dict, I thought why not use a list? I'm not sure how lists and dictionaries are implemented in Python so this would have to be measured to know what's faster. </p>
<p>If this was C++ ... | 1 | 2009-06-13T21:07:54Z | [
"python"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 993,044 | <p>Python 2.7+ includes the <a href="http://docs.python.org/dev/py3k/library/collections.html#collections.Counter" rel="nofollow">collections.Counter</a> class:</p>
<pre><code>import collections
results = collections.Counter(the_string)
print(results)
</code></pre>
| 17 | 2009-06-14T15:39:00Z | [
"python"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 20,486,518 | <p>Here is the solution..</p>
<pre><code>my_list=[]
history=""
history_count=0
my_str="happppyyyy"
for letter in my_str:
if letter in history:
my_list.remove((history,history_count))
history=letter
history_count+=1
else:
history_count=0
history_count+=1
histor... | 0 | 2013-12-10T05:03:16Z | [
"python"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 27,667,665 | <p>If someone is looking for the simplest way without <code>collections</code> module. I guess this will be helpful:</p>
<pre><code>>>> s = "asldaksldkalskdla"
>>> {i:s.count(i) for i in set(s)}
{'a': 4, 'd': 3, 'k': 3, 's': 3, 'l': 4}
</code></pre>
<p>or</p>
<pre><code>>>> [(i,s.count(i))... | 2 | 2014-12-27T13:22:49Z | [
"python"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 28,789,528 | <pre><code>dict = {}
for i in set(str):
b = str.count(i, 0, len(str))
dict[i] = b
print dict
</code></pre>
<p>If my string is:</p>
<pre><code>str = "this is string!"
</code></pre>
<p>Above code will print:</p>
<pre><code>{'!': 1, ' ': 2, 'g': 1, 'i': 3, 'h': 1, 'n': 1, 's': 3, 'r': 1, 't': 2}
</code></pre>
| 2 | 2015-03-01T02:46:12Z | [
"python"
] |
Counting repeated characters in a string in Python | 991,350 | <p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?</p>
<p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated... | 21 | 2009-06-13T19:37:41Z | 32,354,951 | <p>this will show a dict of characters with occurrence count</p>
<pre><code>str = 'aabcdefghijklmnopqrstuvwxyz'
mydict = {}
for char in str:
mydict[char]=mydict.get(char,0)+1
print mydict
</code></pre>
| 1 | 2015-09-02T13:45:46Z | [
"python"
] |
re.search() breaks for key in form.keys() loop | 991,351 | <p>Perhaps I am just crazy or missing something really basic. Why would this happen?</p>
<p>If I use this url</p>
<p>index.cgi?mode=pos&pos_mode=checkout&0_name=Shampoo&0_type=Product&0_price=4.50&0_qty=1&0_total=4.50</p>
<p>which runs this code</p>
<pre><code>form = cgi.FieldStorage()
for... | 0 | 2009-06-13T19:38:04Z | 991,377 | <p>Perhaps you get an error? Try checking types of all keys or anything you suspect could be wrong.</p>
| 1 | 2009-06-13T19:53:14Z | [
"python"
] |
re.search() breaks for key in form.keys() loop | 991,351 | <p>Perhaps I am just crazy or missing something really basic. Why would this happen?</p>
<p>If I use this url</p>
<p>index.cgi?mode=pos&pos_mode=checkout&0_name=Shampoo&0_type=Product&0_price=4.50&0_qty=1&0_total=4.50</p>
<p>which runs this code</p>
<pre><code>form = cgi.FieldStorage()
for... | 0 | 2009-06-13T19:38:04Z | 991,380 | <p>Are you getting an exception? Check your server logs. Have you done:</p>
<pre><code>import re
</code></pre>
<p>at the top of the script? Try wrapping the code in <code>try</code> / <code>except</code>.</p>
| 3 | 2009-06-13T19:54:45Z | [
"python"
] |
Code reuse between django and appengine Model classes | 991,611 | <p>I created a custom django.auth User class which works with Google Appengine, but it involves a fair amount of copied code (practically every method).</p>
<p>It isn't possible to create a subclass because appengine and django have different database models with their own metaclass magic. </p>
<p>So my question is t... | 1 | 2009-06-13T22:00:40Z | 991,712 | <p>Im not sure I understand your question right. Why would you need to define
another "User" class if Django already provides the same functionality ? </p>
<p>You could also just import the "User" class and add a ForeignKey to each model
requiring a "user" attribute.</p>
| 0 | 2009-06-13T22:56:01Z | [
"python",
"django",
"google-app-engine",
"django-authentication"
] |
Code reuse between django and appengine Model classes | 991,611 | <p>I created a custom django.auth User class which works with Google Appengine, but it involves a fair amount of copied code (practically every method).</p>
<p>It isn't possible to create a subclass because appengine and django have different database models with their own metaclass magic. </p>
<p>So my question is t... | 1 | 2009-06-13T22:00:40Z | 996,521 | <p>You might want to take a look at what the django helper or app-engine-patch does.</p>
<p>Helper: <a href="http://code.google.com/p/google-app-engine-django/" rel="nofollow">http://code.google.com/p/google-app-engine-django/</a>
Patch: <a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">http://code.g... | 0 | 2009-06-15T14:44:56Z | [
"python",
"django",
"google-app-engine",
"django-authentication"
] |
Very simple Python script, puzzling behaviour | 991,784 | <p>first of all, I'm not a programmer, so the answer to this might be completely obvious to someone more experienced.
I was playing around with python(2.5) to solve some probability puzzle, however I kept getting results which were way off from the mark I thought they should be. So after some experimenting, I managed t... | 1 | 2009-06-13T23:35:57Z | 991,791 | <p>The result depends on whether line 13:</p>
<pre><code>sub[random.randint(0,9)] = 1
</code></pre>
<p>hits the same index as one of lines 11 or 12:</p>
<pre><code>sub[first] = 1
sub[second] = 1
</code></pre>
<p>You protect <code>second</code> from being the same as <code>first</code>, but you don't protect that th... | 3 | 2009-06-13T23:40:14Z | [
"python"
] |
Very simple Python script, puzzling behaviour | 991,784 | <p>first of all, I'm not a programmer, so the answer to this might be completely obvious to someone more experienced.
I was playing around with python(2.5) to solve some probability puzzle, however I kept getting results which were way off from the mark I thought they should be. So after some experimenting, I managed t... | 1 | 2009-06-13T23:35:57Z | 991,810 | <p>BTW, for the best way to "generate 3 different randomly distributed integers between 0 and 9 included", I heartily recommend <code>a, b, c = random.sample(xrange(10), 3)</code> [[s/xrange/range/ in Python 3.0]] rather than the <code>while</code> loops you're using.</p>
| 5 | 2009-06-13T23:51:38Z | [
"python"
] |
Changing brightness of the Macbook(Pro) keyboard backlight | 991,813 | <p>Programaticly, how can I modify the brightness of the backlit keyboard on a Macbook or Macbook Pro using Python?</p>
| 3 | 2009-06-13T23:52:27Z | 991,823 | <p>Amit Singh discusses these undocumented APIs in this <a href="http://www.osxbook.com/book/bonus/chapter10/light/" rel="nofollow">online bonus chapter</a>, but does so using C -- I'm not sure if a Python extension exists to do the same work from Python, perhaps as part of PyObjC (otherwise, such an extension would ha... | 8 | 2009-06-13T23:58:38Z | [
"python",
"osx",
"hardware"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.