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 |
|---|---|---|---|---|---|---|---|---|---|
Comments in string and strings in comments | 2,575,810 | <p>I am trying to count characters in comments included in C code using Python and Regex, but no success. I can erase strings first to get rid of comments in strings, but this will erase string in comments too and result will be bad ofc. Is there any chance to ask by using regex to not match strings in comments or vice... | 0 | 2010-04-04T20:40:41Z | 2,575,830 | <p>No, not really.</p>
<p>Regex is not the correct tool to parse nested structures like you describe; instead you will need to parse the C syntax (or the "dumb subset" of it you're interested in, anyway), and you might find regex helpful in that. A relatively simple state machine with three states (CODE, STRING, COMM... | 6 | 2010-04-04T20:47:46Z | [
"python",
"regex"
] |
Comments in string and strings in comments | 2,575,810 | <p>I am trying to count characters in comments included in C code using Python and Regex, but no success. I can erase strings first to get rid of comments in strings, but this will erase string in comments too and result will be bad ofc. Is there any chance to ask by using regex to not match strings in comments or vice... | 0 | 2010-04-04T20:40:41Z | 2,583,780 | <p>You can strip out all strings that aren't in comments by searching for the regular expression:</p>
<pre><code>'[^'\r\n]+'|(//.*|/\*(?s:.*?)\*/)
</code></pre>
<p>and replacing with:</p>
<pre><code>$1
</code></pre>
<p>Essentially, this searches for the regex <code>string|(comment)</code> which matches a string or ... | 2 | 2010-04-06T09:27:51Z | [
"python",
"regex"
] |
strange behavior in python | 2,575,847 | <p>The tags might not be accurate since I am not sure where the problem is.</p>
<p>I have a module where I am trying to read some data from a socket, and write the results into a file (append) It looks something like this, (only relevant parts included)</p>
<pre><code>if __name__ == "__main__":
<some init code... | 0 | 2010-04-04T20:53:33Z | 2,575,910 | <p>You really ought to use <code>Thread.join()</code> for your main loop to wait for a thread to finish:</p>
<pre><code>if __name__ == "__main__":
<some init code>
threads = []
for line in file:
t = Thread(target=foo, args=(line,))
t.start()
threads.append(t)
for t in thre... | 1 | 2010-04-04T21:11:12Z | [
"python",
"namespaces",
"multithreading"
] |
strange behavior in python | 2,575,847 | <p>The tags might not be accurate since I am not sure where the problem is.</p>
<p>I have a module where I am trying to read some data from a socket, and write the results into a file (append) It looks something like this, (only relevant parts included)</p>
<pre><code>if __name__ == "__main__":
<some init code... | 0 | 2010-04-04T20:53:33Z | 2,576,153 | <p>When you had (simplifying to the important part)</p>
<pre><code>def foo(text):
writeResults(line, result)
</code></pre>
<p><code>foo</code>, not having a local variable <code>line</code>, was using the <em>global</em> variable by that name... which happens to be the one set (in the main thread) by <code>for li... | 1 | 2010-04-04T22:44:19Z | [
"python",
"namespaces",
"multithreading"
] |
strange behavior in python | 2,575,847 | <p>The tags might not be accurate since I am not sure where the problem is.</p>
<p>I have a module where I am trying to read some data from a socket, and write the results into a file (append) It looks something like this, (only relevant parts included)</p>
<pre><code>if __name__ == "__main__":
<some init code... | 0 | 2010-04-04T20:53:33Z | 2,576,210 | <p>To avoid the global variable called <code>line</code>, you should write a function called <code>main</code> that does the job. Then the variable is local to the <code>main</code> function.</p>
<p>Make your program look like this:</p>
<pre><code>def main(args):
# ... init ...
for line in file:
# ...... | 1 | 2010-04-04T23:08:12Z | [
"python",
"namespaces",
"multithreading"
] |
ImportError and Django driving me crazy | 2,575,859 | <p>OK, I have the following directory structure (it's a django project):</p>
<pre>
-> project
--> app
</pre>
<p>and within the app folder, there is a scraper.py file which needs to reference a class defined within models.py</p>
<p>I'm trying to do the following:</p>
<pre><code>
import urllib2
import os
import sys
i... | 2 | 2010-04-04T20:58:34Z | 2,575,870 | <p>You don't indicate if <code>project</code> is located in <code>/home/userspace/Development/</code>. I'll assume that it is.</p>
<p>Make sure there's an (empty by default) file named <code>__init__.py</code> in <code>project</code> and another one in <code>app</code>.</p>
<p><strong>EDIT:</strong> Next thing to tr... | 0 | 2010-04-04T21:02:10Z | [
"python",
"django",
"django-models",
"importerror"
] |
ImportError and Django driving me crazy | 2,575,859 | <p>OK, I have the following directory structure (it's a django project):</p>
<pre>
-> project
--> app
</pre>
<p>and within the app folder, there is a scraper.py file which needs to reference a class defined within models.py</p>
<p>I'm trying to do the following:</p>
<pre><code>
import urllib2
import os
import sys
i... | 2 | 2010-04-04T20:58:34Z | 2,575,926 | <pre><code>import sys
sys.path.append ('/path/to/the/project')
from django.core.management import setup_environ
import settings
setup_environ(settings)
from app.models import MyModel
</code></pre>
| 2 | 2010-04-04T21:16:42Z | [
"python",
"django",
"django-models",
"importerror"
] |
ImportError and Django driving me crazy | 2,575,859 | <p>OK, I have the following directory structure (it's a django project):</p>
<pre>
-> project
--> app
</pre>
<p>and within the app folder, there is a scraper.py file which needs to reference a class defined within models.py</p>
<p>I'm trying to do the following:</p>
<pre><code>
import urllib2
import os
import sys
i... | 2 | 2010-04-04T20:58:34Z | 2,577,118 | <p>Whoa whoa whoa. You should never <strong>ever</strong> have to put your project name in any of your app code. You should be able to reuse app code across multiple projects with no changes. Pinax does this really well and I highly recommend checking it out for a lot of django best practices.</p>
<p>The worst thing y... | 1 | 2010-04-05T05:58:56Z | [
"python",
"django",
"django-models",
"importerror"
] |
Searching for specific HTML string using Python | 2,575,872 | <p>What modules would be the best to write a python program that searches through hundreds of html documents and deletes a certain string of html that is given.
For instance, if I have an html doc that has <code><a href="test.html">Test</a></code> and I want to delete this out of every html page that has it... | 1 | 2010-04-04T21:02:56Z | 2,575,885 | <p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow"><code>BeautifulSoup</code></a> or <a href="http://codespeak.net/lxml/" rel="nofollow"><code>lxml</code></a>.</p>
| 1 | 2010-04-04T21:06:20Z | [
"python",
"html"
] |
Searching for specific HTML string using Python | 2,575,872 | <p>What modules would be the best to write a python program that searches through hundreds of html documents and deletes a certain string of html that is given.
For instance, if I have an html doc that has <code><a href="test.html">Test</a></code> and I want to delete this out of every html page that has it... | 1 | 2010-04-04T21:02:56Z | 2,575,896 | <p><a href="http://docs.python.org/library/htmllib.html" rel="nofollow">htmllib</a></p>
<blockquote>
<p>This module defines a class which can serve as a base for parsing text
files formatted in the HyperText Mark-up Language (HTML). The class is
not directly concerned with I/O â it must be provided with input ... | 0 | 2010-04-04T21:09:18Z | [
"python",
"html"
] |
Searching for specific HTML string using Python | 2,575,872 | <p>What modules would be the best to write a python program that searches through hundreds of html documents and deletes a certain string of html that is given.
For instance, if I have an html doc that has <code><a href="test.html">Test</a></code> and I want to delete this out of every html page that has it... | 1 | 2010-04-04T21:02:56Z | 2,575,899 | <p>If the string you are searching for will be in the HTML literally, then simple string replacement will be fine:</p>
<pre><code>old_html = open(html_file).read()
new_html = old_html.replace(my_string, "")
if new_html != old_html:
open(html_file, "w").write(new_html)
</code></pre>
<p>As an example of the string ... | 5 | 2010-04-04T21:09:54Z | [
"python",
"html"
] |
Beginner problems with references to arrays in python 3.1.1 | 2,575,952 | <p>As part of the last assignment in a beginner python programing class, I have been assigned a traveling sales man problem. I settled on a recursive function to find each permutation and the sum of the distances between the destinations, however, I am have a lot of problems with references. Arrays in different instanc... | 1 | 2010-04-04T21:23:32Z | 2,576,149 | <p>Slicing a list (by using <code>[:]</code> as you do) does not create a deep copy -- it creates a shallow copy. That means that if the list contains references to other lists, the copy will contain the same <em>references</em> -- not references to <em>new lists</em>. Put another way, only the list itself is copied,... | 1 | 2010-04-04T22:43:36Z | [
"python"
] |
Repetitive content in docstrings | 2,575,959 | <p>What are good ways to deal with repetitive content in docstrings? I have many functions that take 'standard' arguments, which have to be explained in the docstring, but it would be nice to write the relevant parts of the docstring only once, as this would be much easier to maintain and update. I naively tried the fo... | 3 | 2010-04-04T21:26:21Z | 2,575,982 | <p><code>__doc__</code> is assignable on most user-defined types:</p>
<pre><code>arg_a = "a: a very common argument"
def test(a):
pass
test.__doc__ = '''
Arguments:
%s
''' % arg_a
</code></pre>
| 3 | 2010-04-04T21:35:29Z | [
"python",
"docstring"
] |
Repetitive content in docstrings | 2,575,959 | <p>What are good ways to deal with repetitive content in docstrings? I have many functions that take 'standard' arguments, which have to be explained in the docstring, but it would be nice to write the relevant parts of the docstring only once, as this would be much easier to maintain and update. I naively tried the fo... | 3 | 2010-04-04T21:26:21Z | 2,575,988 | <p>There is no obvious way to do this as far as I know (at least not without explicitely reassigning <code>__doc__</code> as Ignacio suggests).</p>
<p>But I think this would be a terrible thing to do. Consider this:</p>
<p>What if I am navigating through your code and reading this docstring on the 300-th line of your... | 3 | 2010-04-04T21:36:49Z | [
"python",
"docstring"
] |
Repetitive content in docstrings | 2,575,959 | <p>What are good ways to deal with repetitive content in docstrings? I have many functions that take 'standard' arguments, which have to be explained in the docstring, but it would be nice to write the relevant parts of the docstring only once, as this would be much easier to maintain and update. I naively tried the fo... | 3 | 2010-04-04T21:26:21Z | 2,575,999 | <p>As the other answers say, you need to change the <code>__doc__</code> member of the function object. A good way to do this is to use a decorator that will perform the formatting on the docstring:</p>
<pre><code>def fixdocstring(func):
func.__doc__ = func.__doc__.replace('<arg_a>', 'a: a very common argume... | 4 | 2010-04-04T21:41:21Z | [
"python",
"docstring"
] |
How can I include custom modules in a Django app | 2,576,060 | <p>I'm really new to Python and Django. I created a class in Python that I would like to use in a Django application. It doesn't seem like it belongs in it's own application, how can I include it in my django app?</p>
<p>Thank you!</p>
| 2 | 2010-04-04T22:07:08Z | 2,576,069 | <p>Put it <a href="http://docs.python.org/tutorial/modules.html">in a module somewhere</a> and import it.</p>
| 6 | 2010-04-04T22:12:35Z | [
"python",
"django",
"module"
] |
How do I view this in an easy format to read? (JSON) | 2,576,265 | <p><a href="https://search.twitter.com/search.json?q=doug" rel="nofollow">https://search.twitter.com/search.json?q=doug</a></p>
<p>How do I read this like VIEW SOURCE, so that I know what I'm looking at?
Is there a website that can prettify it for me?</p>
<p>BTW, I use python</p>
| 0 | 2010-04-04T23:30:34Z | 2,576,276 | <p>Parse it, then use <a href="http://docs.python.org/library/pprint.html" rel="nofollow"><code>pprint</code></a>:</p>
<pre><code>data = json.load(...)
pprint.pprint(data)
</code></pre>
| 2 | 2010-04-04T23:34:41Z | [
"python",
"xml",
"json",
"http",
"twitter"
] |
How do I view this in an easy format to read? (JSON) | 2,576,265 | <p><a href="https://search.twitter.com/search.json?q=doug" rel="nofollow">https://search.twitter.com/search.json?q=doug</a></p>
<p>How do I read this like VIEW SOURCE, so that I know what I'm looking at?
Is there a website that can prettify it for me?</p>
<p>BTW, I use python</p>
| 0 | 2010-04-04T23:30:34Z | 2,576,278 | <p>Insert a carriage return after every comma with your favorite search and replace utility. If you know Python then you shouldn't have any trouble getting it even prettier than that. </p>
| -1 | 2010-04-04T23:35:00Z | [
"python",
"xml",
"json",
"http",
"twitter"
] |
How do I view this in an easy format to read? (JSON) | 2,576,265 | <p><a href="https://search.twitter.com/search.json?q=doug" rel="nofollow">https://search.twitter.com/search.json?q=doug</a></p>
<p>How do I read this like VIEW SOURCE, so that I know what I'm looking at?
Is there a website that can prettify it for me?</p>
<p>BTW, I use python</p>
| 0 | 2010-04-04T23:30:34Z | 2,660,430 | <p>You can also use something like <a href="http://hurl.it/hurls/0c2d071eff63d0006a3f056f6f095e02afe25f74/549c11edea1f99d95db0edc38b1ef6f6fea9091b" rel="nofollow">http://hurl.it</a>.</p>
| 1 | 2010-04-17T23:10:02Z | [
"python",
"xml",
"json",
"http",
"twitter"
] |
How do I view this in an easy format to read? (JSON) | 2,576,265 | <p><a href="https://search.twitter.com/search.json?q=doug" rel="nofollow">https://search.twitter.com/search.json?q=doug</a></p>
<p>How do I read this like VIEW SOURCE, so that I know what I'm looking at?
Is there a website that can prettify it for me?</p>
<p>BTW, I use python</p>
| 0 | 2010-04-04T23:30:34Z | 2,660,445 | <p>Personally, I use <a href="https://addons.mozilla.org/en-US/firefox/addon/10869" rel="nofollow">JSONView</a> for Firefox, which does a good job formatting and colour-highlighting JSON.</p>
| 1 | 2010-04-17T23:15:18Z | [
"python",
"xml",
"json",
"http",
"twitter"
] |
Using Python tuples as vectors | 2,576,296 | <p>I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice.</p>
<p>The trouble is when I need to implement things like addition and scalar multiplication. If <code>a</code> and <code>b</code> are vectors, and <code>c</code> is a... | 4 | 2010-04-04T23:39:43Z | 2,576,304 | <p>Since pretty much all of the sequence manipulation functions return lists, that's pretty much what you're going to have to do.</p>
| 0 | 2010-04-04T23:42:18Z | [
"python",
"tuples"
] |
Using Python tuples as vectors | 2,576,296 | <p>I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice.</p>
<p>The trouble is when I need to implement things like addition and scalar multiplication. If <code>a</code> and <code>b</code> are vectors, and <code>c</code> is a... | 4 | 2010-04-04T23:39:43Z | 2,576,310 | <p>Why not create your own class, making use of 2 Cartesian point member variables? (sorry if the syntax is a little off, my python is rusty)</p>
<pre><code>class point:
def __init__(self,x,y):
self.x=x
self.y=y
#etc
def add(self,p):
return point(self.x + p.x, self.y + p.y)
cl... | 3 | 2010-04-04T23:45:30Z | [
"python",
"tuples"
] |
Using Python tuples as vectors | 2,576,296 | <p>I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice.</p>
<p>The trouble is when I need to implement things like addition and scalar multiplication. If <code>a</code> and <code>b</code> are vectors, and <code>c</code> is a... | 4 | 2010-04-04T23:39:43Z | 2,576,311 | <p><a href="http://numpy.scipy.org/">NumPy</a> supports various algebraic operations with its arrays.</p>
| 9 | 2010-04-04T23:45:36Z | [
"python",
"tuples"
] |
Using Python tuples as vectors | 2,576,296 | <p>I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice.</p>
<p>The trouble is when I need to implement things like addition and scalar multiplication. If <code>a</code> and <code>b</code> are vectors, and <code>c</code> is a... | 4 | 2010-04-04T23:39:43Z | 2,576,404 | <p>Immutable types are pretty rare in Python and third-party extensions thereof; the OP rightly claims "there are enough uses for linear algebra that it doesn't seem likely I have to roll my own" -- but all the existing types I know that do linear algebra are <strong>mutable</strong>! So, as the OP is adamant on immut... | 9 | 2010-04-05T00:20:54Z | [
"python",
"tuples"
] |
Using Python tuples as vectors | 2,576,296 | <p>I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice.</p>
<p>The trouble is when I need to implement things like addition and scalar multiplication. If <code>a</code> and <code>b</code> are vectors, and <code>c</code> is a... | 4 | 2010-04-04T23:39:43Z | 2,577,527 | <p>By inheriting from tuple, you can make a nice Vector class pretty easily. Here's enough code to provide addition of vectors, and multiplication of a vector by a scalar. It gives you arbitrary length vectors, and can work with complex numbers, ints, or floats.</p>
<pre><code>class Vector(tuple):
def __add__(self... | 7 | 2010-04-05T08:34:52Z | [
"python",
"tuples"
] |
Using Python tuples as vectors | 2,576,296 | <p>I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice.</p>
<p>The trouble is when I need to implement things like addition and scalar multiplication. If <code>a</code> and <code>b</code> are vectors, and <code>c</code> is a... | 4 | 2010-04-04T23:39:43Z | 11,531,384 | <p>Although using a library like NumPy seems to be the resolution for the OP, I think there is still some value in a simple solution which does not require additional libraries and which you can stay immutable, with iterables.</p>
<p>Using the <code>itertools</code> and <code>operators</code> modules:</p>
<pre><code>... | 5 | 2012-07-17T21:50:51Z | [
"python",
"tuples"
] |
Using Python tuples as vectors | 2,576,296 | <p>I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice.</p>
<p>The trouble is when I need to implement things like addition and scalar multiplication. If <code>a</code> and <code>b</code> are vectors, and <code>c</code> is a... | 4 | 2010-04-04T23:39:43Z | 38,029,996 | <p>For occasional use, a Python 3 solution without repeating lambdas is possible via using the standard operator package:</p>
<pre><code>from operator import add, mul
a = (1, 2, 3)
b = (4, 5, 6)
print(tuple(map(add, a , b)))
print(tuple(map(mul, a , b)))
</code></pre>
<p>which prints:</p>
<pre><code>(5, 7, 9)
(4, ... | 0 | 2016-06-25T15:25:03Z | [
"python",
"tuples"
] |
Do alternate python implementation version numbers imply that they provide the same syntax? | 2,576,320 | <p>for example Jython is at version 2.5.1, does that imply a parallel fidelity to cpython syntax when it was at version 2.5.1?</p>
| 5 | 2010-04-04T23:49:14Z | 2,576,337 | <p>That is correct, or very close. Jython and IronPython have changed their numbering scheme to match the CPython version whose features they most closely implement.</p>
| 1 | 2010-04-04T23:58:19Z | [
"python"
] |
Do alternate python implementation version numbers imply that they provide the same syntax? | 2,576,320 | <p>for example Jython is at version 2.5.1, does that imply a parallel fidelity to cpython syntax when it was at version 2.5.1?</p>
| 5 | 2010-04-04T23:49:14Z | 2,576,341 | <p>Generally yes, but there's technically nothing stopping alternate implementations from choosing whatever version numbers they want.</p>
<p>It's also important to note that just because Jython 2.5.1 is intended to match CPython 2.5.1, doesn't mean that they're going to behave exactly the same or be entirely compatib... | 2 | 2010-04-05T00:00:06Z | [
"python"
] |
Do alternate python implementation version numbers imply that they provide the same syntax? | 2,576,320 | <p>for example Jython is at version 2.5.1, does that imply a parallel fidelity to cpython syntax when it was at version 2.5.1?</p>
| 5 | 2010-04-04T23:49:14Z | 2,576,420 | <p>The syntax (and feature set) are controlled strictly by the first two numbers -- every <code>2.5.*</code> is claiming to implement the same syntax and feature set (in terms of language definition, <em>not</em> of aspects the language-reference manual explicitly leaves up to the implementation: for example, both Jyth... | 1 | 2010-04-05T00:26:41Z | [
"python"
] |
Start PyGTK cellrenderer edit from code | 2,576,481 | <p>I have a treeview with an editable CellRendererText:</p>
<pre><code>self.renderer = gtk.CellRendererText()
self.renderer.set_property('editable', True)
</code></pre>
<p>But now I need to launch the edition from code instead from user, this is to focus the user attention in the fact he just created a new row and ne... | 3 | 2010-04-05T01:03:08Z | 2,576,633 | <blockquote>
<pre><code>def set_cursor(path, focus_column=None, start_editing=False)
</code></pre>
<p>... If <em>column</em> is specified, and <em>start_editing</em> is True, then editing should be started in the specified cell. This method is often followed by the <code>gtk.Widget.grab_focus()</code> method to gi... | 5 | 2010-04-05T02:19:04Z | [
"python",
"user-interface",
"gtk",
"pygtk",
"gnome"
] |
Does python's httplib.HTTPConnection block? | 2,576,534 | <p>I am unsure whether or not the following code is a blocking operation in python:</p>
<pre><code>import httplib
import urllib
def do_request(server, port, timeout, remote_url):
conn = httplib.HTTPConnection(server, port, timeout=timeout)
conn.request("POST", remote_url, urllib.urlencode(query_dictionary, Tr... | 2 | 2010-04-05T01:30:06Z | 2,576,628 | <p>Unless you go to lengths to prevent it, <code>IO</code> will always block.</p>
<p>Although you can do <a href="http://docs.python.org/release/2.6.5/library/asyncore.html#asyncore-example-basic-http-client" rel="nofollow">asynchronous requests</a>, you will have to make you entire program async-friendly. <strong><em... | 4 | 2010-04-05T02:16:02Z | [
"python"
] |
Using Python How can I read the bits in a byte? | 2,576,712 | <p>I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc.</p>
<p>Is there any equivalent bit reader in python?</p>
| 20 | 2010-04-05T02:57:27Z | 2,576,713 | <p>The smallest unit you'll be able to work with is a byte. To work at the bit level you need to use <a href="http://wiki.python.org/moin/BitwiseOperators">bitwise operators</a>.</p>
<pre><code>x = 3
#Check if the 1st bit is set:
x&1 != 0
#Returns True
#Check if the 2nd bit is set:
x&2 != 0
#Returns True
#C... | 14 | 2010-04-05T02:58:18Z | [
"python",
"byte",
"bits"
] |
Using Python How can I read the bits in a byte? | 2,576,712 | <p>I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc.</p>
<p>Is there any equivalent bit reader in python?</p>
| 20 | 2010-04-05T02:57:27Z | 2,576,790 | <p>You won't be able to read each bit one by one - you have to read it byte by byte. You can easily extract the bits out, though:</p>
<pre><code>f = open("myfile", 'rb')
# read one byte
byte = f.read(1)
# convert the byte to an integer representation
byte = ord(byte)
# now convert to string of 1s and 0s
byte = bin(byt... | 10 | 2010-04-05T03:30:10Z | [
"python",
"byte",
"bits"
] |
Using Python How can I read the bits in a byte? | 2,576,712 | <p>I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc.</p>
<p>Is there any equivalent bit reader in python?</p>
| 20 | 2010-04-05T02:57:27Z | 2,576,841 | <p>There are two possible ways to return the i-th bit of a byte. The "first bit" could refer to the high-order bit or it could refer to the lower order bit.</p>
<p>Here is a function that takes a string and index as parameters and returns the value of the bit at that location. As written, it treats the low-order bit... | 2 | 2010-04-05T03:52:45Z | [
"python",
"byte",
"bits"
] |
Using Python How can I read the bits in a byte? | 2,576,712 | <p>I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc.</p>
<p>Is there any equivalent bit reader in python?</p>
| 20 | 2010-04-05T02:57:27Z | 2,577,487 | <p>Read the bits from a file, low bits first.</p>
<pre><code>def bits(f):
bytes = (ord(b) for b in f.read())
for b in bytes:
for i in xrange(8):
yield (b >> i) & 1
for b in bits(open('binary-file.bin', 'r')):
print b
</code></pre>
| 18 | 2010-04-05T08:22:42Z | [
"python",
"byte",
"bits"
] |
Using Python How can I read the bits in a byte? | 2,576,712 | <p>I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc.</p>
<p>Is there any equivalent bit reader in python?</p>
| 20 | 2010-04-05T02:57:27Z | 26,788,075 | <p>This is pretty fast I would think:</p>
<pre><code>import itertools
data = range(10)
format = "{:0>8b}".format
newdata = (False if n == '0' else True for n in itertools.chain.from_iterable(map(format, data)))
print(newdata) # prints tons of True and False
</code></pre>
| 0 | 2014-11-06T19:44:19Z | [
"python",
"byte",
"bits"
] |
Using Python How can I read the bits in a byte? | 2,576,712 | <p>I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc.</p>
<p>Is there any equivalent bit reader in python?</p>
| 20 | 2010-04-05T02:57:27Z | 30,197,656 | <p>With <code>numpy</code> it is easy like this:</p>
<pre><code>Bytes = numpy.fromfile(filename, dtype = "uint8")
Bits = numpy.unpackbits(Bytes)
</code></pre>
<p>More info here:<br>
<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html" rel="nofollow">http://docs.scipy.org/doc/numpy/referen... | 3 | 2015-05-12T17:26:13Z | [
"python",
"byte",
"bits"
] |
Using Python How can I read the bits in a byte? | 2,576,712 | <p>I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc.</p>
<p>Is there any equivalent bit reader in python?</p>
| 20 | 2010-04-05T02:57:27Z | 30,255,020 | <p>Supposing you have a file called bloom_filter.bin which contains an array of bits and you want to read the entire file and use those bits in an array.</p>
<p>First create the array where the bits will be stored after reading,</p>
<pre><code>from bitarray import bitarray
a=bitarray(size) #same as the numb... | 0 | 2015-05-15T08:34:37Z | [
"python",
"byte",
"bits"
] |
Using Python How can I read the bits in a byte? | 2,576,712 | <p>I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc.</p>
<p>Is there any equivalent bit reader in python?</p>
| 20 | 2010-04-05T02:57:27Z | 37,189,643 | <p>To read a byte from a file: <code>bytestring = open(filename, 'rb').read(1)</code>. Note: the file is opened in the <em>binary</em> mode.</p>
<p>To get bits, convert the bytestring into an integer: <code>byte = bytestring[0]</code> (Python 3) or <code>byte = ord(bytestring[0])</code> (Python 2) and extract the desi... | 0 | 2016-05-12T14:16:43Z | [
"python",
"byte",
"bits"
] |
Pushing data once a URL is requested | 2,576,715 | <p>Given, when a user requests <code>/foo</code> on my server, I send the following HTTP response (not closing the connection):</p>
<pre><code>Content-Type: multipart/x-mixed-replace; boundary=-----------------------
-----------------------
Content-Type: text/html
<a href="/bar">foo</a>
</code></pre>
<p... | 7 | 2010-04-05T02:58:48Z | 2,577,571 | <p>If the problem is to pass some command from /bar application to /foo application and you are using some servlet-like approach (the Python code is loaded once and not for each request as in CGI), you can just change some class property of the /foo application and be ready to react to the change in the /foo instance (... | 1 | 2010-04-05T08:50:01Z | [
"python",
"wsgi"
] |
Pushing data once a URL is requested | 2,576,715 | <p>Given, when a user requests <code>/foo</code> on my server, I send the following HTTP response (not closing the connection):</p>
<pre><code>Content-Type: multipart/x-mixed-replace; boundary=-----------------------
-----------------------
Content-Type: text/html
<a href="/bar">foo</a>
</code></pre>
<p... | 7 | 2010-04-05T02:58:48Z | 2,579,570 | <p>Not sure if this is quite what you're looking for, but there is a fairly old way of doing server push using a mime content of multipart/x-mixed-replace </p>
<p>Basically you compose the response as a mime object with content type multipart/x-mixed-replace, and send the first "version" of a document down. The browse... | -1 | 2010-04-05T16:40:28Z | [
"python",
"wsgi"
] |
Pushing data once a URL is requested | 2,576,715 | <p>Given, when a user requests <code>/foo</code> on my server, I send the following HTTP response (not closing the connection):</p>
<pre><code>Content-Type: multipart/x-mixed-replace; boundary=-----------------------
-----------------------
Content-Type: text/html
<a href="/bar">foo</a>
</code></pre>
<p... | 7 | 2010-04-05T02:58:48Z | 2,675,876 | <p>No complete answer, but:</p>
<p>In your question, you're describing a <a href="http://en.wikipedia.org/wiki/Comet_(programming)" rel="nofollow">Comet</a>-style architecture. Regarding support of Comet-style techniques in Python/WSGI, there is a <a href="http://stackoverflow.com/questions/960969/python-comet-server"... | 1 | 2010-04-20T14:23:21Z | [
"python",
"wsgi"
] |
Pushing data once a URL is requested | 2,576,715 | <p>Given, when a user requests <code>/foo</code> on my server, I send the following HTTP response (not closing the connection):</p>
<pre><code>Content-Type: multipart/x-mixed-replace; boundary=-----------------------
-----------------------
Content-Type: text/html
<a href="/bar">foo</a>
</code></pre>
<p... | 7 | 2010-04-05T02:58:48Z | 2,676,293 | <p>I have created some small example (just for fun, you know :))</p>
<pre><code>import threading
num = 0
cond = threading.Condition()
def app(environ, start_response):
global num
cond.acquire()
num += 1
cond.notifyAll()
cond.release()
start_response("200 OK", [("Content-Type", "multipart/x-... | 1 | 2010-04-20T15:16:46Z | [
"python",
"wsgi"
] |
Python's preferred comparison operators | 2,576,826 | <p>Is it preferred to do:</p>
<pre><code>if x is y:
return True
</code></pre>
<p>or</p>
<pre><code>if x == y
return True
</code></pre>
<p>Same thing for "is not"</p>
| 23 | 2010-04-05T03:48:18Z | 2,576,840 | <p>Depends. <code>is</code> and <code>is not</code> do identity comparison, which is good for <code>None</code>, <code>Ellipsis</code>, or making sure that two objects are the same. Otherwise, use <code>==</code> or <code>!=</code>.</p>
| 4 | 2010-04-05T03:52:05Z | [
"python",
"comparison"
] |
Python's preferred comparison operators | 2,576,826 | <p>Is it preferred to do:</p>
<pre><code>if x is y:
return True
</code></pre>
<p>or</p>
<pre><code>if x == y
return True
</code></pre>
<p>Same thing for "is not"</p>
| 23 | 2010-04-05T03:48:18Z | 2,576,847 | <p><code>x is y</code> is different than <code>x == y</code>.</p>
<p><code>x is y</code> is true if and only if <code>id(x) == id(y)</code> -- that is, <code>x</code> and <code>y</code> have to be one and the same object (with the same <code>id</code>s).</p>
<p>For all built-in Python objects (like strings, lists, ... | 40 | 2010-04-05T03:54:25Z | [
"python",
"comparison"
] |
Python's preferred comparison operators | 2,576,826 | <p>Is it preferred to do:</p>
<pre><code>if x is y:
return True
</code></pre>
<p>or</p>
<pre><code>if x == y
return True
</code></pre>
<p>Same thing for "is not"</p>
| 23 | 2010-04-05T03:48:18Z | 2,577,494 | <p><code>x is y</code> compares the identities of the two objects, and is asking <em>'are <code>x</code> and <code>y</code> different names for the same object?'</em> It is equivalent to <code>id(x) == id(y)</code>.</p>
<p><code>x == y</code> uses the equality operator and asks the looser question <em>'are <code>x</co... | 15 | 2010-04-05T08:25:02Z | [
"python",
"comparison"
] |
Python's preferred comparison operators | 2,576,826 | <p>Is it preferred to do:</p>
<pre><code>if x is y:
return True
</code></pre>
<p>or</p>
<pre><code>if x == y
return True
</code></pre>
<p>Same thing for "is not"</p>
| 23 | 2010-04-05T03:48:18Z | 2,577,589 | <ul>
<li><strong><code>==</code></strong> and <strong><code>!=</code></strong> are object <em>value</em> comparison operators</li>
<li><strong><code>is</code></strong> and <strong><code>is not</code></strong> are object <em>identity</em> comparison operators</li>
</ul>
<p>as others have already said, <strong><code>is<... | 9 | 2010-04-05T08:55:52Z | [
"python",
"comparison"
] |
Cache the result of a MySQLdb database query in memory | 2,576,867 | <p>Our application fetches the correct database server from a pool of database servers. So each query is really 2 queries, and they look like this:</p>
<ol>
<li>Fetch the correct DB server</li>
<li>Execute the query</li>
</ol>
<p>We do this so we can take DB servers online and offline as necessary, as well as for lo... | 2 | 2010-04-05T04:04:40Z | 2,576,900 | <p>Just make a cache(python dict) which stores the first query and return it everytime, clear the cache every N mins, for this you make a decorator or cache class e.g.</p>
<pre><code>import time
cache = {}
lastTime = time.time()
def timedCacheDecorator(func):
def wrap(*args, **kwargs):
key = str(args)+... | 2 | 2010-04-05T04:19:12Z | [
"python",
"caching",
"pylons",
"mysql"
] |
Cache the result of a MySQLdb database query in memory | 2,576,867 | <p>Our application fetches the correct database server from a pool of database servers. So each query is really 2 queries, and they look like this:</p>
<ol>
<li>Fetch the correct DB server</li>
<li>Execute the query</li>
</ol>
<p>We do this so we can take DB servers online and offline as necessary, as well as for lo... | 2 | 2010-04-05T04:04:40Z | 2,757,315 | <p>The easiest way would be to use the beaker cache, which is a library built into the pylons framework.</p>
<p>In your model class import the beaker decorator:</p>
<pre><code>from pylons.decorators.cache import beaker_cache
</code></pre>
<p>Then on your function header, where you make the database call, add the fol... | 1 | 2010-05-03T10:11:24Z | [
"python",
"caching",
"pylons",
"mysql"
] |
Python socket error on UDP data receive. (10054) | 2,576,926 | <p>I currently have a problem using UDP and Python socket module. We have a server and clients. The problem occurs when we send data to a user. It's possible that user may have closed their connection to the server through a client crash, disconnect by ISP, or some other improper method. As such, it is possible to send... | 3 | 2010-04-05T04:28:28Z | 2,578,143 | <p>Well, it seems obvious.</p>
<ol>
<li>UDP doesn't have connections, so <code>Client.connect</code> is wrong</li>
<li>You're storing the client address in the <code>Server.connected</code> <code>dict</code>. When the client is closed, nobody will be there to receive what you're sending.</li>
</ol>
<p>Getting network... | 1 | 2010-04-05T11:39:58Z | [
"python",
"sockets",
"client",
"udp"
] |
Python socket error on UDP data receive. (10054) | 2,576,926 | <p>I currently have a problem using UDP and Python socket module. We have a server and clients. The problem occurs when we send data to a user. It's possible that user may have closed their connection to the server through a client crash, disconnect by ISP, or some other improper method. As such, it is possible to send... | 3 | 2010-04-05T04:28:28Z | 2,578,517 | <p>The problem is far simpler than it looks. Use socket.recv() rather than socket.recvfrom() - I made this change locally and your code then works.</p>
| 2 | 2010-04-05T13:12:20Z | [
"python",
"sockets",
"client",
"udp"
] |
Python socket error on UDP data receive. (10054) | 2,576,926 | <p>I currently have a problem using UDP and Python socket module. We have a server and clients. The problem occurs when we send data to a user. It's possible that user may have closed their connection to the server through a client crash, disconnect by ISP, or some other improper method. As such, it is possible to send... | 3 | 2010-04-05T04:28:28Z | 2,578,794 | <p>Firstly this is possibly platform specific and you don't mention the platform that you're running on; however, 10054 is <code>WSAECONNRESET</code> so I'm guessing a Windows platform of some kind.</p>
<p>Secondly as previously pointed out there is no connection with UDP. Your call to <code>Connect()</code> in the cl... | 6 | 2010-04-05T14:11:08Z | [
"python",
"sockets",
"client",
"udp"
] |
Getting data from external program | 2,576,956 | <p>I need a method to get the data from an external editor.</p>
<pre><code>def _get_content():
from subprocess import call
file = open(file, "w").write(some_name)
call(editor + " " + file, shell=True)
file.close()
file = open(file)
x = file.readlines()
[snip]
</code></pre>
<p>I per... | 1 | 2010-04-05T04:47:23Z | 2,576,967 | <p>This is the way all programs do it, AFAIK. Certainly all version control systems that I've used create a temporary file, pass it to the editor and retrieve the result when the editor exits, just as you have.</p>
| 3 | 2010-04-05T04:52:08Z | [
"python"
] |
Getting data from external program | 2,576,956 | <p>I need a method to get the data from an external editor.</p>
<pre><code>def _get_content():
from subprocess import call
file = open(file, "w").write(some_name)
call(editor + " " + file, shell=True)
file.close()
file = open(file)
x = file.readlines()
[snip]
</code></pre>
<p>I per... | 1 | 2010-04-05T04:47:23Z | 2,576,974 | <p>an editor just lets you edit a file interactively. you can also edit files with Python. there's no need to call external editor.</p>
<pre><code>for line in open("file"):
print "editing line ", line
# eg replace strings
line = line.replace("somestring","somenewstring")
print line
</code></pre>
| 1 | 2010-04-05T04:54:21Z | [
"python"
] |
Getting data from external program | 2,576,956 | <p>I need a method to get the data from an external editor.</p>
<pre><code>def _get_content():
from subprocess import call
file = open(file, "w").write(some_name)
call(editor + " " + file, shell=True)
file.close()
file = open(file)
x = file.readlines()
[snip]
</code></pre>
<p>I per... | 1 | 2010-04-05T04:47:23Z | 2,581,571 | <p>I'd recommend using a list, not a string:</p>
<pre><code>def _get_content(editor, initial=""):
from subprocess import call
from tempfile import NamedTemporaryFile
# Create the initial temporary file.
with NamedTemporaryFile(delete=False) as tf:
tfName = tf.name
tf.write(initial)
... | 2 | 2010-04-05T22:33:32Z | [
"python"
] |
Python: How to display the calculated MD5 value in my browser? | 2,577,041 | <p>I was given this Python code that would calculate an MD5 value for any phrase:</p>
<pre><code>import md5
md5.new("Nobody inspects the spammish repetition").digest()
</code></pre>
<p>(The phrase here is: "Nobody inspects the spammish repetition")</p>
<p>What I want to do is display this value in my browser. How do... | 0 | 2010-04-05T05:19:20Z | 2,577,046 | <p><code>.hexdigest()</code> is what you want.</p>
| 3 | 2010-04-05T05:21:23Z | [
"python",
"google-app-engine",
"md5"
] |
Python: How to display the calculated MD5 value in my browser? | 2,577,041 | <p>I was given this Python code that would calculate an MD5 value for any phrase:</p>
<pre><code>import md5
md5.new("Nobody inspects the spammish repetition").digest()
</code></pre>
<p>(The phrase here is: "Nobody inspects the spammish repetition")</p>
<p>What I want to do is display this value in my browser. How do... | 0 | 2010-04-05T05:19:20Z | 2,577,088 | <p>In order to display the hexdigest in your browser you need to have some sort of web framework (in this case in python) that handles all the web serving for you.</p>
<p>Here's an example using <a href="http://webpy.org" rel="nofollow">web.py</a> (I've copied the default example and adjusted for the md5). But you can... | 4 | 2010-04-05T05:43:23Z | [
"python",
"google-app-engine",
"md5"
] |
Blackjack game reshuffling problem-edited | 2,577,047 | <p>I am trying to make a blackjack game where before each new round, the program checks to make sure that the deck has 7 cards per player. And if it doesn't, the deck clears, repopulates, and reshuffles. I have most of the problem down, but for some reason at the start of every deal it reshuffles the deck more than onc... | 0 | 2010-04-05T05:21:42Z | 2,577,058 | <p>You're checking it again and again, inside the loop, and while you distribute the cards, the deck is being reduced, I think (can't see the <code>Deck.give</code> method on your code to know for sure).</p>
<p>You probably want to check only once, move the check to outside the loop.</p>
<pre><code>def deal(self, han... | 2 | 2010-04-05T05:28:30Z | [
"python"
] |
Blackjack game reshuffling problem-edited | 2,577,047 | <p>I am trying to make a blackjack game where before each new round, the program checks to make sure that the deck has 7 cards per player. And if it doesn't, the deck clears, repopulates, and reshuffles. I have most of the problem down, but for some reason at the start of every deal it reshuffles the deck more than onc... | 0 | 2010-04-05T05:21:42Z | 2,577,064 | <p><code>for hand in hands:</code></p>
<p>Do you <em>really</em> want to run that logic for each hand?</p>
| 1 | 2010-04-05T05:29:47Z | [
"python"
] |
Blackjack game reshuffling problem-edited | 2,577,047 | <p>I am trying to make a blackjack game where before each new round, the program checks to make sure that the deck has 7 cards per player. And if it doesn't, the deck clears, repopulates, and reshuffles. I have most of the problem down, but for some reason at the start of every deal it reshuffles the deck more than onc... | 0 | 2010-04-05T05:21:42Z | 2,580,618 | <p>Nosklo pointed out one problem (checking it inside the loop) but there is a second problem.</p>
<p>the condition</p>
<pre><code>if len(self.cards)>=7*(len(hands)):
</code></pre>
<p>is checking if the number of cards is greater than the number needed and if so,clears the deck, populates and shuffles.</p>
<p>Wh... | 1 | 2010-04-05T19:30:59Z | [
"python"
] |
what is the 'extra' mean in this django code | 2,577,252 | <pre><code>TOPIC_COUNT_SQL = """
SELECT COUNT(*)
FROM topics_topic
WHERE
topics_topic.object_id = maps_map.id AND
topics_topic.content_type_id = %s
"""
MEMBER_COUNT_SQL = """
SELECT COUNT(*)
FROM maps_map_members
WHERE maps_map_members.map_id = maps_map.id
"""
maps = maps.extra(select=SortedDict([
('member... | 0 | 2010-04-05T06:50:41Z | 2,577,260 | <p>It's a <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none" rel="nofollow">method of <code>QuerySet</code></a>.</p>
| 1 | 2010-04-05T06:53:45Z | [
"python",
"sql",
"django"
] |
HttpResponseRedirect question | 2,577,306 | <p>Cant we send a dictionary variable when using HttpResponseRedirect</p>
<pre><code> render_to_response('edited/display.html',context_instance=RequestContext(request,{'newlist': newlist}))
//How can the dictionary and the request sent back again
//sumthing like this
return HttpResponseRedirect('... | 2 | 2010-04-05T07:13:26Z | 2,577,312 | <p>From <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponseRedirect" rel="nofollow">the documentation</a>:</p>
<blockquote>
<p>The constructor takes a single argument -- the path to redirect to. This can be a fully qualified URL (e.g. 'http://www.yahoo.com/search/') or an abs... | 0 | 2010-04-05T07:15:37Z | [
"python",
"django",
"django-views"
] |
HttpResponseRedirect question | 2,577,306 | <p>Cant we send a dictionary variable when using HttpResponseRedirect</p>
<pre><code> render_to_response('edited/display.html',context_instance=RequestContext(request,{'newlist': newlist}))
//How can the dictionary and the request sent back again
//sumthing like this
return HttpResponseRedirect('... | 2 | 2010-04-05T07:13:26Z | 2,577,408 | <p>Response redirect as name suggests, redirects the user's browser to new URL, so it doesn't make any sense to pass anything else except the new location in HttpResponseRedirect</p>
<p>If you want to pass some data, so that in the <code>view</code> of new location url you can check for that data, pass it as url argum... | 4 | 2010-04-05T07:48:52Z | [
"python",
"django",
"django-views"
] |
HttpResponseRedirect question | 2,577,306 | <p>Cant we send a dictionary variable when using HttpResponseRedirect</p>
<pre><code> render_to_response('edited/display.html',context_instance=RequestContext(request,{'newlist': newlist}))
//How can the dictionary and the request sent back again
//sumthing like this
return HttpResponseRedirect('... | 2 | 2010-04-05T07:13:26Z | 2,577,591 | <p>What you are really looking for, I think is the <code>redirect</code> function introduced in 1.1</p>
<p>You can instead use, for your case,</p>
<pre><code>redirect(view_name,view_parameter)
</code></pre>
<p>For that, it may be necessary to modify your view first, to take the new_list parameter, or pass to it, the... | 0 | 2010-04-05T08:56:56Z | [
"python",
"django",
"django-views"
] |
HttpResponseRedirect question | 2,577,306 | <p>Cant we send a dictionary variable when using HttpResponseRedirect</p>
<pre><code> render_to_response('edited/display.html',context_instance=RequestContext(request,{'newlist': newlist}))
//How can the dictionary and the request sent back again
//sumthing like this
return HttpResponseRedirect('... | 2 | 2010-04-05T07:13:26Z | 8,550,724 | <p>So let me add another answer additional to existing ones:</p>
<pre><code>my_url = reverse("my_app.views.my_path") + "?action_result=124"
return HttpResponseRedirect(my_url)
</code></pre>
<p>reverse function is: <code>from django.core.urlresolvers import reverse</code></p>
| 2 | 2011-12-18T08:58:25Z | [
"python",
"django",
"django-views"
] |
Python - Access a class from a list using a key | 2,577,549 | <p>Is there any way to make a list of classes behave like a set in python?</p>
<p>Basically, I'm working on a piece of software that does some involved string comparison, and I have a custom class for handling the strings. Therefore, there is an instance of the class for each string.</p>
<p>As a result, I have a larg... | 1 | 2010-04-05T08:42:24Z | 2,577,567 | <p>As I remember "set" and "dict" uses also <code>__hash__</code></p>
<p>From <a href="http://docs.python.org/library/stdtypes.html#mapping-types-dict" rel="nofollow">Python 2.x doc</a>:</p>
<blockquote>
<p>A dictionaryâs keys are <em>almost</em> arbitrary values. Values that are not <a href="http://docs.python.o... | 1 | 2010-04-05T08:49:18Z | [
"python",
"class"
] |
Python - Access a class from a list using a key | 2,577,549 | <p>Is there any way to make a list of classes behave like a set in python?</p>
<p>Basically, I'm working on a piece of software that does some involved string comparison, and I have a custom class for handling the strings. Therefore, there is an instance of the class for each string.</p>
<p>As a result, I have a larg... | 1 | 2010-04-05T08:42:24Z | 2,577,581 | <p>Set and dict use the value returned by an object's <code>__hash__</code> method to look up the object, so this will do what you want:</p>
<pre><code>>>class a:
... def __init__(self, x):
... self.var = x
...
... def __hash__(self):
... return hash(self.var)
</code></pre>
| 1 | 2010-04-05T08:53:48Z | [
"python",
"class"
] |
Python - Access a class from a list using a key | 2,577,549 | <p>Is there any way to make a list of classes behave like a set in python?</p>
<p>Basically, I'm working on a piece of software that does some involved string comparison, and I have a custom class for handling the strings. Therefore, there is an instance of the class for each string.</p>
<p>As a result, I have a larg... | 1 | 2010-04-05T08:42:24Z | 2,577,615 | <p>Just write a class that behaves a bit like a mapping:</p>
<pre><code>class ClassDict(object):
def __init__(self):
self.classes = {}
def add(self, cls):
self.classes[cls.__name__] = cls
def remove(self, cls):
if self.classes[cls.__name__] == cls:
del self.classes[cls.__name__]
else:
... | 2 | 2010-04-05T09:04:10Z | [
"python",
"class"
] |
Python - Access a class from a list using a key | 2,577,549 | <p>Is there any way to make a list of classes behave like a set in python?</p>
<p>Basically, I'm working on a piece of software that does some involved string comparison, and I have a custom class for handling the strings. Therefore, there is an instance of the class for each string.</p>
<p>As a result, I have a larg... | 1 | 2010-04-05T08:42:24Z | 2,577,619 | <p>Do you want something like this</p>
<pre><code>class A(object):
ALL_INSTANCES = {}
def __init__(self, text):
self.text = text
self.ALL_INSTANCES[self.text] = self
a1 = A("hello")
a2 = A("world")
print A.ALL_INSTANCES["hello"]
</code></pre>
<p>output:</p>
<pre><code><__main__.A objec... | 0 | 2010-04-05T09:07:20Z | [
"python",
"class"
] |
Python - Access a class from a list using a key | 2,577,549 | <p>Is there any way to make a list of classes behave like a set in python?</p>
<p>Basically, I'm working on a piece of software that does some involved string comparison, and I have a custom class for handling the strings. Therefore, there is an instance of the class for each string.</p>
<p>As a result, I have a larg... | 1 | 2010-04-05T08:42:24Z | 2,577,799 | <p>Why don't you just do:</p>
<pre><code>>>> v = MyStr("Hello")
>>> x = {}
>>> x[v.val]=v
>>> x["Hello"]
MyStr("Hello")
</code></pre>
<p>Why go through all the trouble of trying to create a hand-rolled dict that uses different keys than the ones you pass in? (i.e. "Hello" instead o... | 2 | 2010-04-05T10:02:39Z | [
"python",
"class"
] |
Python newbie: trying to create a script that opens a file and replaces words | 2,577,671 | <p>im trying to create a script that opens a file and replace every 'hola' with 'hello'.</p>
<pre><code>f=open("kk.txt","w")
for line in f:
if "hola" in line:
line=line.replace('hola','hello')
f.close()
</code></pre>
<p>But im getting this error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>... | 4 | 2010-04-05T09:25:10Z | 2,577,680 | <p>You've opened the file for writing, but you're reading from it. Open the original file for reading and a new file for writing. After the replacement, rename the original out and the new one in.</p>
| 4 | 2010-04-05T09:27:35Z | [
"python",
"file-manipulation"
] |
Python newbie: trying to create a script that opens a file and replaces words | 2,577,671 | <p>im trying to create a script that opens a file and replace every 'hola' with 'hello'.</p>
<pre><code>f=open("kk.txt","w")
for line in f:
if "hola" in line:
line=line.replace('hola','hello')
f.close()
</code></pre>
<p>But im getting this error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>... | 4 | 2010-04-05T09:25:10Z | 2,577,692 | <p>You could also have a look at the <a href="http://docs.python.org/reference/compound_stmts.html#with" rel="nofollow">with</a> statement.</p>
| 3 | 2010-04-05T09:31:14Z | [
"python",
"file-manipulation"
] |
Python newbie: trying to create a script that opens a file and replaces words | 2,577,671 | <p>im trying to create a script that opens a file and replace every 'hola' with 'hello'.</p>
<pre><code>f=open("kk.txt","w")
for line in f:
if "hola" in line:
line=line.replace('hola','hello')
f.close()
</code></pre>
<p>But im getting this error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>... | 4 | 2010-04-05T09:25:10Z | 2,577,694 | <pre><code>open('test.txt', 'w').write(open('test.txt', 'r').read().replace('hola', 'hello'))
</code></pre>
<p>Or if you want to properly close the file:</p>
<pre><code>with open('test.txt', 'r') as src:
src_text = src.read()
with open('test.txt', 'w') as dst:
dst.write(src_text.replace('hola', 'hello'))
</c... | 7 | 2010-04-05T09:31:28Z | [
"python",
"file-manipulation"
] |
Python newbie: trying to create a script that opens a file and replaces words | 2,577,671 | <p>im trying to create a script that opens a file and replace every 'hola' with 'hello'.</p>
<pre><code>f=open("kk.txt","w")
for line in f:
if "hola" in line:
line=line.replace('hola','hello')
f.close()
</code></pre>
<p>But im getting this error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>... | 4 | 2010-04-05T09:25:10Z | 2,577,715 | <p>Your main issue is that you're opening the file for writing first. When you open a file for writing, <em>the contents of the file are deleted</em>, which makes it quite difficult to do replacements! If you want to replace words in the file, you have a three-step process:</p>
<ol>
<li>Read the file into a string</li... | 4 | 2010-04-05T09:38:39Z | [
"python",
"file-manipulation"
] |
Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory | 2,577,819 | <p>i would like to replace the lines </p>
<p><code>function *{</code> </p>
<p>by </p>
<pre><code>function *{echo "The function starts here."
</code></pre>
<p>where * is what ever.</p>
<p>Any idea how to do that in Python?</p>
<p>Regards</p>
<p>Javi</p>
| 0 | 2010-04-05T10:07:48Z | 2,577,831 | <p>Apply a regular expression replace to the text. The module you are looking for is <code>re</code>.</p>
| 0 | 2010-04-05T10:11:31Z | [
"python",
"regex"
] |
Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory | 2,577,819 | <p>i would like to replace the lines </p>
<p><code>function *{</code> </p>
<p>by </p>
<pre><code>function *{echo "The function starts here."
</code></pre>
<p>where * is what ever.</p>
<p>Any idea how to do that in Python?</p>
<p>Regards</p>
<p>Javi</p>
| 0 | 2010-04-05T10:07:48Z | 2,577,840 | <pre><code>re.compile(r'(^function .*{)', re.M).sub(r'\1echo "The function starts here."', s)
</code></pre>
| 3 | 2010-04-05T10:14:56Z | [
"python",
"regex"
] |
Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory | 2,577,819 | <p>i would like to replace the lines </p>
<p><code>function *{</code> </p>
<p>by </p>
<pre><code>function *{echo "The function starts here."
</code></pre>
<p>where * is what ever.</p>
<p>Any idea how to do that in Python?</p>
<p>Regards</p>
<p>Javi</p>
| 0 | 2010-04-05T10:07:48Z | 2,577,844 | <p>if all your scripts are "well coded",</p>
<pre><code>import fileinput,os
root="/path"
path=os.path.join(root,"mydir")
os.chdir(path)
for file in os.listdir("."):
if os.path.isfile(file) and file.endswith(".txt"): # do for txt files
for line in fileinput.FileInput(file,inplace=1):
line=line.r... | 1 | 2010-04-05T10:16:57Z | [
"python",
"regex"
] |
Best DataMining Database | 2,577,967 | <p>I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. </p>
<p>Sales department makes a CSV dump every week and I need to mak... | 14 | 2010-04-05T10:59:47Z | 2,577,979 | <p>You probably do need a full relational DBMS, if not right now, very soon. If you start now while your problems and data are simple and straightforward then when they become complex and difficult you will have plenty of experience with at least one DBMS to help you. You probably don't need MySQL on all desktops, yo... | 12 | 2010-04-05T11:04:21Z | [
"python",
"database",
"nosql",
"data-mining"
] |
Best DataMining Database | 2,577,967 | <p>I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. </p>
<p>Sales department makes a CSV dump every week and I need to mak... | 14 | 2010-04-05T10:59:47Z | 2,577,983 | <p>Here is a performance benchmark of different database suits ->
<a href="http://www.sqlite.org/cvstrac/wiki?p=SpeedComparison" rel="nofollow">Database Speed Comparison</a></p>
<p>I'm not sure how objective the above comparison is though, seeing as it's hosted on <a href="http://www.sqlite.org" rel="nofollow">sqlite.... | 1 | 2010-04-05T11:05:42Z | [
"python",
"database",
"nosql",
"data-mining"
] |
Best DataMining Database | 2,577,967 | <p>I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. </p>
<p>Sales department makes a CSV dump every week and I need to mak... | 14 | 2010-04-05T10:59:47Z | 2,578,080 | <p>Have you done any bench marking to confirm that it is the text files that are slowing you down? If you haven't, there's a good chance that tweaking some other part of the code will speed things up so that it's fast enough.</p>
| 1 | 2010-04-05T11:24:54Z | [
"python",
"database",
"nosql",
"data-mining"
] |
Best DataMining Database | 2,577,967 | <p>I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. </p>
<p>Sales department makes a CSV dump every week and I need to mak... | 14 | 2010-04-05T10:59:47Z | 2,578,310 | <p>If you have that problem with a CSV file, maybe you can just pickle the dictionary and generate a pickle "binary" file with <code>pickle.HIGHEST_PROTOCOL</code> option. It can be faster to read and you get a smaller file. You can load the CSV file once and then generate the pickled file, allowing faster load in next... | 0 | 2010-04-05T12:23:00Z | [
"python",
"database",
"nosql",
"data-mining"
] |
Best DataMining Database | 2,577,967 | <p>I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. </p>
<p>Sales department makes a CSV dump every week and I need to mak... | 14 | 2010-04-05T10:59:47Z | 2,578,659 | <p>It sounds like each department has their own feudal database, and this implies a lot of unnecessary redundancy and inefficiency.</p>
<p>Instead of transferring hundreds of megabytes to everyone across your network, why not keep your data in MySQL and have the departments upload <em>their</em> data to the database, ... | 1 | 2010-04-05T13:43:13Z | [
"python",
"database",
"nosql",
"data-mining"
] |
Best DataMining Database | 2,577,967 | <p>I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. </p>
<p>Sales department makes a CSV dump every week and I need to mak... | 14 | 2010-04-05T10:59:47Z | 2,578,751 | <p>Does the machine this process runs on have sufficient memory and bandwidth to handle this efficiently? Putting MySQL on a slow machine and recoding the tool to use MySQL rather than text files could potentially be far more costly than simply adding memory or upgrading the machine.</p>
| 1 | 2010-04-05T14:03:38Z | [
"python",
"database",
"nosql",
"data-mining"
] |
Best DataMining Database | 2,577,967 | <p>I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. </p>
<p>Sales department makes a CSV dump every week and I need to mak... | 14 | 2010-04-05T10:59:47Z | 2,581,460 | <p>Take a look at mongodb.</p>
| 0 | 2010-04-05T22:03:43Z | [
"python",
"database",
"nosql",
"data-mining"
] |
Best DataMining Database | 2,577,967 | <p>I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. </p>
<p>Sales department makes a CSV dump every week and I need to mak... | 14 | 2010-04-05T10:59:47Z | 2,582,847 | <h2>Quick Summary</h2>
<ul>
<li>You need enough memory(RAM) to solve your problem efficiently. I think you should upgrade memory?? When reading the excellent <a href="http://highscalability.com/">High Scalability</a> Blog you will notice that for big sites to solve there problem efficiently they store the complete pro... | 15 | 2010-04-06T05:33:43Z | [
"python",
"database",
"nosql",
"data-mining"
] |
Best DataMining Database | 2,577,967 | <p>I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. </p>
<p>Sales department makes a CSV dump every week and I need to mak... | 14 | 2010-04-05T10:59:47Z | 2,981,162 | <p>It has been a couple of months since I posted this question and I wanted to let you all know how I solved this problem. I am using Berkeley DB with the module bsddb instead loading all the data in a Python dictionary. I am not fully happy, but my users are.
My next step is trying to get a shared server with redis, b... | 1 | 2010-06-05T16:40:16Z | [
"python",
"database",
"nosql",
"data-mining"
] |
Python 2.5.2: trying to open files recursively | 2,578,022 | <p>The script below should open all the files inside the folder 'pruebaba' recursively but I get this error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>
File
"/home/tirengarfio/Desktop/prueba.py",
line 8, in
f = open(file,'r') IOError: [Errno 21] Is a directory</p>
</blockquote>
<p>This ... | 6 | 2010-04-05T11:14:21Z | 2,578,049 | <p>You're trying to open everything you see. One thing you tried to open was a directory; you need to check if an entry <a href="http://docs.python.org/library/os.path.html#os.path.isfile" rel="nofollow">is a file</a> or <a href="http://docs.python.org/library/os.path.html#os.path.isdir" rel="nofollow">is a directory<... | 1 | 2010-04-05T11:18:38Z | [
"python"
] |
Python 2.5.2: trying to open files recursively | 2,578,022 | <p>The script below should open all the files inside the folder 'pruebaba' recursively but I get this error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>
File
"/home/tirengarfio/Desktop/prueba.py",
line 8, in
f = open(file,'r') IOError: [Errno 21] Is a directory</p>
</blockquote>
<p>This ... | 6 | 2010-04-05T11:14:21Z | 2,578,059 | <p>Use <a href="http://docs.python.org/library/os#os.walk"><code>os.walk</code></a>. It recursively walks into directory and subdirectories, and already gives you separate variables for files and directories.</p>
<pre><code>import re
import os
from __future__ import with_statement
PATH = "/home/tirengarfio/Desktop/pr... | 10 | 2010-04-05T11:21:02Z | [
"python"
] |
Python 2.5.2: trying to open files recursively | 2,578,022 | <p>The script below should open all the files inside the folder 'pruebaba' recursively but I get this error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>
File
"/home/tirengarfio/Desktop/prueba.py",
line 8, in
f = open(file,'r') IOError: [Errno 21] Is a directory</p>
</blockquote>
<p>This ... | 6 | 2010-04-05T11:14:21Z | 2,578,063 | <p>os.listdir lists both files <em>and</em> directories. You should check if what you're trying to open really is a file with <a href="http://docs.python.org/library/os.path.html#os.path.isfile" rel="nofollow">os.path.isfile</a></p>
| 1 | 2010-04-05T11:21:26Z | [
"python"
] |
Why is the destructor called when the CPython garbage collector is disabled? | 2,578,098 | <p>I'm trying to understand the internals of the CPython garbage collector, specifically when the destructor is called. So far, the behavior is intuitive, but the following case trips me up:</p>
<ol>
<li>Disable the GC.</li>
<li>Create an object, then remove a reference to it.</li>
<li>The object is destroyed and the ... | 6 | 2010-04-05T11:28:14Z | 2,578,109 | <p>Python has both <em>reference counting</em> garbage collection and <em>cyclic</em> garbage collection, and it's the latter that the <code>gc</code> module controls. Reference counting can't be disabled, and hence still happens when the cyclic garbage collector is switched off.</p>
<p>Since there are no references l... | 9 | 2010-04-05T11:31:07Z | [
"python",
"garbage-collection",
"cpython"
] |
Why is the destructor called when the CPython garbage collector is disabled? | 2,578,098 | <p>I'm trying to understand the internals of the CPython garbage collector, specifically when the destructor is called. So far, the behavior is intuitive, but the following case trips me up:</p>
<ol>
<li>Disable the GC.</li>
<li>Create an object, then remove a reference to it.</li>
<li>The object is destroyed and the ... | 6 | 2010-04-05T11:28:14Z | 2,578,135 | <p>Depending on your definition of garbage collector, CPython has two garbage collectors, the reference counting one, and the other one.<br>
The reference counter is always working, and cannot be turned off, as it's quite a fast and lightweight one that does not sigificantly affect the run time of the system.<br>
The o... | 4 | 2010-04-05T11:38:38Z | [
"python",
"garbage-collection",
"cpython"
] |
Why is the destructor called when the CPython garbage collector is disabled? | 2,578,098 | <p>I'm trying to understand the internals of the CPython garbage collector, specifically when the destructor is called. So far, the behavior is intuitive, but the following case trips me up:</p>
<ol>
<li>Disable the GC.</li>
<li>Create an object, then remove a reference to it.</li>
<li>The object is destroyed and the ... | 6 | 2010-04-05T11:28:14Z | 2,578,798 | <p>The docs <a href="http://docs.python.org/extending/newtypes.html#supporting-cyclic-garbage-collection" rel="nofollow">here</a> explain how what's called "the optional garbage collector" is actually a collector of <em>cyclic</em> garbage (the kind that reference counting wouldn't catch). Reference counting is explai... | 4 | 2010-04-05T14:11:59Z | [
"python",
"garbage-collection",
"cpython"
] |
How to check if a network path exist? | 2,578,177 | <p>What is the best way to know if a network path(e.g. //192.168.1.1/test) exist using python in linux?</p>
| 1 | 2010-04-05T09:05:14Z | 2,578,566 | <p>If by "path" you mean an internet URL, you'll want to look at the urllib module.</p>
<pre><code>from urllib import urlopen
try:
urlopen(path)
except IOError:
pass # does not exist
else:
pass # does exist
</code></pre>
<p>If by "path" you mean a Windows UNC, then you'll want to use the os module.</p>
<... | 2 | 2010-04-05T13:24:40Z | [
"python",
"linux",
"networking"
] |
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django | 2,578,540 | <p>I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Althou... | 20 | 2010-04-05T13:18:44Z | 2,578,576 | <p><a href="http://codeigniter.com/" rel="nofollow">CodeIgniter</a> is a great PHP framework that is fast and has excellent documentation. Start reading through their user guide and it will give you a good idea how to work with the framework.</p>
| 3 | 2010-04-05T13:26:55Z | [
"python",
"django",
"cakephp",
"web-frameworks",
"yii"
] |
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django | 2,578,540 | <p>I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Althou... | 20 | 2010-04-05T13:18:44Z | 2,578,635 | <p>This is a very subjective question but personally I'd recommend Django. Python is a very nice language to use and the Django framework is small, easy to use, well documented and also has a pretty active community.</p>
<p>This choice was made partly because of my dislike for PHP though, so take the recommendation wi... | 29 | 2010-04-05T13:38:37Z | [
"python",
"django",
"cakephp",
"web-frameworks",
"yii"
] |
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django | 2,578,540 | <p>I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Althou... | 20 | 2010-04-05T13:18:44Z | 2,578,670 | <p>Most of the frameworks out there nowadays are fast enough to serve whatever needs you will have. It really depends on in which environment you feel most comfortable. Though there are nuances here and there, MVC frameworks share a lot of the same principles, so whichever you choose to use is really a matter of which ... | 26 | 2010-04-05T13:44:39Z | [
"python",
"django",
"cakephp",
"web-frameworks",
"yii"
] |
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django | 2,578,540 | <p>I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Althou... | 20 | 2010-04-05T13:18:44Z | 2,579,156 | <p>Extending Matchu:</p>
<p>Or, -If you like PHP more- its time to learn/growup about other things like Python. Its not hard to learn, and when you get started it gets very enjoyable.</p>
<p>Many people has done the PHPtoPython/Django port, like Mozilla, Netgeo, Nasa, <a href="http://www.reddit.com/r/django/comments/... | 0 | 2010-04-05T15:22:16Z | [
"python",
"django",
"cakephp",
"web-frameworks",
"yii"
] |
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django | 2,578,540 | <p>I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Althou... | 20 | 2010-04-05T13:18:44Z | 2,579,251 | <p>I've worked with CakePHP and Django and I really recommend Django. I don't know too much about CodeIgniter, but I remember ruling it out when I was evaluating frameworks myself about a year ago. CakePHP seemed much more developed at the time.</p>
<p>First of all, the Django community is much bigger and has spent a ... | 13 | 2010-04-05T15:38:18Z | [
"python",
"django",
"cakephp",
"web-frameworks",
"yii"
] |
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django | 2,578,540 | <p>I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Althou... | 20 | 2010-04-05T13:18:44Z | 2,844,890 | <p>If for the PHP part I would choose CodeIgniter - it doesn't get too much into your way. But it doesn't have any code/view/model generators out of the box, you need to type a bit.</p>
<p>But languages other than PHP appear to be more <em>sexy</em>.</p>
| 0 | 2010-05-16T18:15:01Z | [
"python",
"django",
"cakephp",
"web-frameworks",
"yii"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.