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
Eclipse smart quotes - like in Textmate
1,730,351
<p>Happy Friday — Does anyone know if eclipse has the notion of smart quotes like Textmate. The way it works is to select some words and quote them by simply hitting the <kbd>"</kbd> key? I'm a newbie here so be gentle. FWIW - I'm using pydev in Eclipse.</p> <p>Thanks</p> <p><strong>Rephrase</strong></p> <p>Wha...
4
2009-11-13T16:33:22Z
6,914,871
<p>Here is one written in Autohotkey:</p> <pre><code>#NoEnv SetWorkingDir %A_ScriptDir% SendMode Input #InstallKeybdHook #UseHook On (:: if GetKeyState("ScrollLock","T") { sel := GetSelection(1) if sel PasteText("(" sel ")") else Send ( sel := "" } ...
0
2011-08-02T15:52:41Z
[ "python", "eclipse", "ide", "development-environment", "pydev" ]
Eclipse smart quotes - like in Textmate
1,730,351
<p>Happy Friday — Does anyone know if eclipse has the notion of smart quotes like Textmate. The way it works is to select some words and quote them by simply hitting the <kbd>"</kbd> key? I'm a newbie here so be gentle. FWIW - I'm using pydev in Eclipse.</p> <p>Thanks</p> <p><strong>Rephrase</strong></p> <p>Wha...
4
2009-11-13T16:33:22Z
7,961,242
<p>In the latest PyDev, it should work exactly as you want already (tested in PyDev 2.2.3 -- this was actually around for some time already).</p>
1
2011-11-01T00:25:02Z
[ "python", "eclipse", "ide", "development-environment", "pydev" ]
How to find where a function was imported from in Python?
1,730,466
<p>I have a Python module with a function in it:</p> <pre><code> == bar.py == def foo(): pass == EOF == </code></pre> <p>And then I import it into the global namespace like so:</p> <pre><code>from bar import * </code></pre> <p>So now the function <code>foo</code> is available to me. If I print it:</p> <pre><c...
8
2009-11-13T16:49:12Z
1,730,492
<p><code>foo.__module__</code> should return <code>bar</code></p> <p>If you need more info, you can get it from <code>sys.modules['bar']</code>, its <code>__file__</code> and <code>__package__</code> attributes may be interesting.</p>
17
2009-11-13T16:52:08Z
[ "python", "module" ]
How to find where a function was imported from in Python?
1,730,466
<p>I have a Python module with a function in it:</p> <pre><code> == bar.py == def foo(): pass == EOF == </code></pre> <p>And then I import it into the global namespace like so:</p> <pre><code>from bar import * </code></pre> <p>So now the function <code>foo</code> is available to me. If I print it:</p> <pre><c...
8
2009-11-13T16:49:12Z
1,730,523
<p>Try this:</p> <pre><code>help(foo.func_name) </code></pre>
1
2009-11-13T16:55:16Z
[ "python", "module" ]
How to find where a function was imported from in Python?
1,730,466
<p>I have a Python module with a function in it:</p> <pre><code> == bar.py == def foo(): pass == EOF == </code></pre> <p>And then I import it into the global namespace like so:</p> <pre><code>from bar import * </code></pre> <p>So now the function <code>foo</code> is available to me. If I print it:</p> <pre><c...
8
2009-11-13T16:49:12Z
1,731,211
<p>Instead of </p> <pre><code>from bar import * </code></pre> <p>use </p> <pre><code>from bar import foo </code></pre> <p>Using the <code>from ... import *</code> syntax is a bad programming style precisely because it makes it hard to know where elements of your namespace come from.</p>
1
2009-11-13T19:07:23Z
[ "python", "module" ]
Principal component analysis in Python
1,730,600
<p>I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html"><code>numpy.linalg.eigh</code></a>?</p> <p>I don't just want to use singular v...
94
2009-11-13T17:04:31Z
1,730,690
<p>You might have a look at <a href="http://mdp-toolkit.sourceforge.net/">MDP</a>. </p> <p>I have not had the chance to test it myself, but I've bookmarked it exactly for the PCA functionality.</p>
28
2009-11-13T17:19:46Z
[ "python", "numpy", "scipy", "pca" ]
Principal component analysis in Python
1,730,600
<p>I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html"><code>numpy.linalg.eigh</code></a>?</p> <p>I don't just want to use singular v...
94
2009-11-13T17:04:31Z
1,731,082
<p><a href="http://folk.uio.no/henninri/pca%5Fmodule/" rel="nofollow">Here</a> is another implementation of a PCA module for python using numpy, scipy and C-extensions. The module carries out PCA using either a SVD or the NIPALS (Nonlinear Iterative Partial Least Squares) algorithm which is implemented in C.</p>
4
2009-11-13T18:42:57Z
[ "python", "numpy", "scipy", "pca" ]
Principal component analysis in Python
1,730,600
<p>I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html"><code>numpy.linalg.eigh</code></a>?</p> <p>I don't just want to use singular v...
94
2009-11-13T17:04:31Z
1,731,092
<p><a href="http://matplotlib.sourceforge.net/api/mlab_api.html">matplotlib.mlab</a> has a <a href="http://matplotlib.sourceforge.net/api/mlab_api.html#matplotlib.mlab.PCA">PCA implementation</a>.</p>
30
2009-11-13T18:44:50Z
[ "python", "numpy", "scipy", "pca" ]
Principal component analysis in Python
1,730,600
<p>I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html"><code>numpy.linalg.eigh</code></a>?</p> <p>I don't just want to use singular v...
94
2009-11-13T17:04:31Z
1,732,758
<p>I just finish reading the book <a href="http://seat.massey.ac.nz/personal/s.r.marsland/MLBook.html">Machine Learning: An Algorithmic Perspective</a>. All code examples in the book was written by Python(and almost with Numpy). The code snippet of <a href="http://seat.massey.ac.nz/personal/s.r.marsland/Code/10/pca.py"...
7
2009-11-14T00:29:28Z
[ "python", "numpy", "scipy", "pca" ]
Principal component analysis in Python
1,730,600
<p>I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html"><code>numpy.linalg.eigh</code></a>?</p> <p>I don't just want to use singular v...
94
2009-11-13T17:04:31Z
1,736,415
<p>SVD should work fine with 460 dimensions. It takes about 7 seconds on my Atom netbook. The eig() method takes <em>more</em> time (as it should, it uses more floating point operations) and will almost always be less accurate. </p> <p>If you have less than 460 examples then what you want to do is diagonalize the scat...
13
2009-11-15T02:59:26Z
[ "python", "numpy", "scipy", "pca" ]
Principal component analysis in Python
1,730,600
<p>I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html"><code>numpy.linalg.eigh</code></a>?</p> <p>I don't just want to use singular v...
94
2009-11-13T17:04:31Z
2,629,704
<p>Months later, here's a small class PCA, and a picture:</p> <pre><code>#!/usr/bin/env python """ a small class for Principal Component Analysis Usage: p = PCA( A, fraction=0.90 ) In: A: an array of e.g. 1000 observations x 20 variables, 1000 rows x 20 columns fraction: use principal components that accou...
63
2010-04-13T13:04:55Z
[ "python", "numpy", "scipy", "pca" ]
Principal component analysis in Python
1,730,600
<p>I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html"><code>numpy.linalg.eigh</code></a>?</p> <p>I don't just want to use singular v...
94
2009-11-13T17:04:31Z
11,829,306
<p>You do not need full Singular Value Decomposition (SVD) at it computes all eigenvalues and eigenvectors and can be prohibitive for large matrices. <a href="http://scipy.org/" rel="nofollow">scipy</a> and its sparse module provide generic linear algrebra functions working on both sparse and dense matrices, among whic...
3
2012-08-06T13:31:02Z
[ "python", "numpy", "scipy", "pca" ]
Principal component analysis in Python
1,730,600
<p>I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html"><code>numpy.linalg.eigh</code></a>?</p> <p>I don't just want to use singular v...
94
2009-11-13T17:04:31Z
12,273,032
<p>PCA using <code>numpy.linalg.svd</code> is super easy. Here's a simple demo:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.misc import lena # the underlying signal is a sinusoidally modulated image img = lena() t = np.arange(100) time = np.sin(0.1*t) real = time[:,np.newaxis,np.newax...
37
2012-09-05T00:28:27Z
[ "python", "numpy", "scipy", "pca" ]
Principal component analysis in Python
1,730,600
<p>I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html"><code>numpy.linalg.eigh</code></a>?</p> <p>I don't just want to use singular v...
94
2009-11-13T17:04:31Z
14,263,875
<p>You can quite easily "roll" your own using <code>scipy.linalg</code> (assuming a pre-centered dataset <code>data</code>):</p> <pre><code>covmat = data.dot(data.T) evs, evmat = scipy.linalg.eig(covmat) </code></pre> <p>Then <code>evs</code> are your eigenvalues, and <code>evmat</code> is your projection matrix.</p>...
8
2013-01-10T17:34:50Z
[ "python", "numpy", "scipy", "pca" ]
Principal component analysis in Python
1,730,600
<p>I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html"><code>numpy.linalg.eigh</code></a>?</p> <p>I don't just want to use singular v...
94
2009-11-13T17:04:31Z
18,389,738
<p>You can use sklearn:</p> <pre><code>import sklearn.decomposition as deco import numpy as np x = (x - np.mean(x, 0)) / np.std(x, 0) # You need to normalize your data first pca = deco.PCA(n_components) # n_components is the components number after reduction x_r = pca.fit(x).transform(x) print ('explained variance (f...
25
2013-08-22T19:58:02Z
[ "python", "numpy", "scipy", "pca" ]
Alternatives to wx.lib.masked.NumCtrl
1,730,647
<p><br> In a wxPython application I'm developing I need a lot of input fields for numbers (integers and floats), so I tried using wx.lib.masked.NumCtrl, but my users now tell me that it's quite uncomfortable to use (and I agree with them). </p> <p>Is there an alternative widget implementation I can use, or should I ju...
1
2009-11-13T17:11:47Z
1,732,110
<p>In the usual wxPython distribution there's IntCtrl, and then a few other GUI controls like Slider, Spin, FloatSpin, and KnobCtrl.</p> <p>There's also the <a href="http://code.enthought.com/projects/traits/" rel="nofollow">Enthought Traits</a> approach, and the <a href="http://code.enthought.com/projects/traits/docs...
1
2009-11-13T21:43:03Z
[ "python", "wxpython" ]
More pythonic way of skipping header lines
1,730,649
<p>Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?</p> <p>In other words, a neater way of doing this</p> <pre><code>fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() </code></pre>
9
2009-11-13T17:12:24Z
1,730,661
<pre><code>for line in open('data.txt'): if line.startswith('#'): continue # work with line </code></pre> <p>of course, if your commented lines are only at the beginning of the file, you might use some optimisations.</p>
14
2009-11-13T17:15:07Z
[ "python" ]
More pythonic way of skipping header lines
1,730,649
<p>Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?</p> <p>In other words, a neater way of doing this</p> <pre><code>fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() </code></pre>
9
2009-11-13T17:12:24Z
1,730,662
<p>If you want to filter out <em>all</em> comment lines (not just those at the start of the file):</p> <pre><code>for line in file("data.txt"): if not line.startswith("#"): # process line </code></pre> <p>If you only want to skip those at the start then see <a href="http://stackoverflow.com/users/20713/ephemien...
6
2009-11-13T17:15:12Z
[ "python" ]
More pythonic way of skipping header lines
1,730,649
<p>Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?</p> <p>In other words, a neater way of doing this</p> <pre><code>fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() </code></pre>
9
2009-11-13T17:12:24Z
1,730,674
<p>You could make a generator that loops over the file that skips those lines:</p> <pre><code>fin = open("data.txt") fileiter = (l for l in fin if not l.startswith('#')) for line in fileiter: ... </code></pre>
4
2009-11-13T17:16:57Z
[ "python" ]
More pythonic way of skipping header lines
1,730,649
<p>Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?</p> <p>In other words, a neater way of doing this</p> <pre><code>fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() </code></pre>
9
2009-11-13T17:12:24Z
1,730,691
<p>You could use a generator function</p> <pre><code>def readlines(filename): fin = open(filename) for line in fin: if not line.startswith("#"): yield line </code></pre> <p>and use it like</p> <pre><code>for line in readlines("data.txt"): # do things pass </code></pre> <p>Dependi...
5
2009-11-13T17:19:55Z
[ "python" ]
More pythonic way of skipping header lines
1,730,649
<p>Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?</p> <p>In other words, a neater way of doing this</p> <pre><code>fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() </code></pre>
9
2009-11-13T17:12:24Z
1,730,741
<pre><code>from itertools import dropwhile for line in dropwhile(lambda line: line.startswith('#'), file('data.txt')): pass </code></pre>
10
2009-11-13T17:27:28Z
[ "python" ]
More pythonic way of skipping header lines
1,730,649
<p>Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?</p> <p>In other words, a neater way of doing this</p> <pre><code>fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() </code></pre>
9
2009-11-13T17:12:24Z
1,730,755
<p>You could do something like</p> <pre><code>def drop(n, seq): for i, x in enumerate(seq): if i &gt;= n: yield x </code></pre> <p>And then say</p> <pre><code>for line in drop(1, file(filename)): # whatever </code></pre>
2
2009-11-13T17:29:41Z
[ "python" ]
More pythonic way of skipping header lines
1,730,649
<p>Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?</p> <p>In other words, a neater way of doing this</p> <pre><code>fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() </code></pre>
9
2009-11-13T17:12:24Z
1,730,990
<p>At this stage in my arc of learning Python, I find this most Pythonic:</p> <pre><code>def iscomment(s): return s.startswith('#') from itertools import dropwhile with open(filename, 'r') as f: for line in dropwhile(iscomment, f): # do something with line </code></pre> <p>to skip all of the lines at t...
14
2009-11-13T18:23:31Z
[ "python" ]
More pythonic way of skipping header lines
1,730,649
<p>Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?</p> <p>In other words, a neater way of doing this</p> <pre><code>fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() </code></pre>
9
2009-11-13T17:12:24Z
1,731,793
<p>I like @iWerner's generator function idea. One small change to his code and it does what the question asked for. </p> <pre><code>def readlines(filename): f = open(filename) # discard first lines that start with '#' for line in f: if not line.lstrip().startswith("#"): break yield...
2
2009-11-13T20:44:53Z
[ "python" ]
More pythonic way of skipping header lines
1,730,649
<p>Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?</p> <p>In other words, a neater way of doing this</p> <pre><code>fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() </code></pre>
9
2009-11-13T17:12:24Z
1,734,032
<p>As a practical matter if I knew I was dealing with reasonable sized text files (anything which will comfortably fit in memory) then I'd problem go with something like:</p> <pre><code>f = open("data.txt") lines = [ x for x in f.readlines() if x[0] != "#" ] </code></pre> <p>... to snarf in the whole file and filter ...
5
2009-11-14T11:51:55Z
[ "python" ]
gqlQuery returns object, want list of keys
1,730,694
<p><em>Is there a way to convert the GqlQuery object to an array of keys, or is there a way to force the query to return an array of keys?</em> For example:</p> <pre><code>items = db.GqlQuery("SELECT __key__ FROM Items") </code></pre> <p>returns an object containing the keys:</p> <pre><code>&lt;google.appengine.ex...
1
2009-11-13T17:20:40Z
1,730,995
<p>Certainly - you can fetch the results by calling .fetch(count) on the GqlQuery object. This is the recommended way, in fact - iterating fetches results in batches, and so is less efficient.</p>
3
2009-11-13T18:23:46Z
[ "python", "google-app-engine", "gql" ]
Pack program *and* dynamically loaded files into single executable? (python + pygame, or language agnostic)
1,730,742
<p>There are plenty of great answers to questions about making a standalone executable, but I can't figure out how to pack art assets (or dynamically loaded files) into it as well. Why would I want to do this? Because it would be great to distribute a simple (throw away) game that lives entirely in a single executabl...
0
2009-11-13T17:27:30Z
1,730,774
<p>Game development is not field of expertise, but if you haven't already checked out py2exe, I would strongly recommend that you do. It seems to me that any and all scripting import statements will be taken care of by py2exe.</p> <p>Hope this helps</p>
1
2009-11-13T17:32:30Z
[ "python", "pygame", "executable", "packaging" ]
Is there an existing Python class that can hold any user attributes?
1,730,769
<p>I can use this when I need multiple objects with different attributes:</p> <pre><code>class struct(object): def __init__(self,*args,**kwargs): for key,val in kwargs.items(): setattr(self,key,val) </code></pre> <p>But I'm wondering if there isn't a built-in already?</p>
2
2009-11-13T17:31:37Z
1,730,787
<p>Unless I'm not understanding your question, isn't this what we use a <code>dict</code> for? Sure, it's notationally slightly different, but an object's attributes are internally still stored in a <code>dict</code> (namely <code>__dict__</code>). It's a matter of notation.</p> <p>But, if you insist, then this is one...
9
2009-11-13T17:35:58Z
[ "python", "struct" ]
Is there an existing Python class that can hold any user attributes?
1,730,769
<p>I can use this when I need multiple objects with different attributes:</p> <pre><code>class struct(object): def __init__(self,*args,**kwargs): for key,val in kwargs.items(): setattr(self,key,val) </code></pre> <p>But I'm wondering if there isn't a built-in already?</p>
2
2009-11-13T17:31:37Z
1,730,812
<p>I'm not certain why you're not using a dictionary for this.</p> <pre><code>x = {} x.update([(1, 2), (3, 4), (5, 6)]) print x </code></pre> <p>result </p> <pre><code>{1: 2, 3: 4, 5: 6} </code></pre> <p>or</p> <pre><code>x.update(a=2, b=4, c=6) </code></pre> <p>results in</p> <pre><code>{'a': 2, 'c': 6, 'b': 4}...
3
2009-11-13T17:40:44Z
[ "python", "struct" ]
Is there an existing Python class that can hold any user attributes?
1,730,769
<p>I can use this when I need multiple objects with different attributes:</p> <pre><code>class struct(object): def __init__(self,*args,**kwargs): for key,val in kwargs.items(): setattr(self,key,val) </code></pre> <p>But I'm wondering if there isn't a built-in already?</p>
2
2009-11-13T17:31:37Z
1,731,376
<p>I have wondered the same thing. I enjoy the convenience of <code>x.foo</code> instead of <code>x["foo"]</code>; a single period is far easier to type (and get correct) than all of <code>[""]</code>.</p> <p>The advantage of a dict is that <em>anything</em> can be a key. (Well, anything hashable.) But when I have ...
3
2009-11-13T19:31:47Z
[ "python", "struct" ]
Nonblocking webserver on .Net for Comet applications
1,730,986
<p>I am trying to implement a Comet style (e.g. chat) application using IronPython. While I don't need to scale to twitter like dimensions, it is vital that the response time is lightening fast. All the possibilities in Python (<a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a>, <a href="http://www.t...
3
2009-11-13T18:22:54Z
1,756,682
<p>There sure is. Check out <a href="http://www.frozenmountain.com/websync" rel="nofollow">WebSync</a>, a full comet solution for .NET/IIS. To my knowledge, it's the only full implementation of comet for .NET available today. You can use the on-demand version for free (up to a limit), or pick up the server version to h...
2
2009-11-18T15:12:48Z
[ ".net", "python", "ironpython", "comet" ]
Python code to accept many different formats of US phone numbers?
1,731,025
<p>I'm reading in lots of user entered data that represent phone numbers from files. They are all slightly entered in differently:</p> <pre> 5555555555 555-555-5555 555-555/5555 1555-555-5555 etc... </pre> <p>How could I easily parse in all of these phone numbers in Python and produce a canonical output like: 555-55...
0
2009-11-13T18:30:36Z
1,731,044
<p>I'm not american, but this works with russian phone numbers... maybe it applies to american ones too?</p> <ol> <li>Discard all non-number characters</li> <li>Validate amount of the numbers left</li> <li>Insert several dashes in appropriate places</li> </ol>
6
2009-11-13T18:34:44Z
[ "python" ]
Python code to accept many different formats of US phone numbers?
1,731,025
<p>I'm reading in lots of user entered data that represent phone numbers from files. They are all slightly entered in differently:</p> <pre> 5555555555 555-555-5555 555-555/5555 1555-555-5555 etc... </pre> <p>How could I easily parse in all of these phone numbers in Python and produce a canonical output like: 555-55...
0
2009-11-13T18:30:36Z
1,731,045
<p>take only the numbers with a regex. then find out if they appended the 1 (NO area code starts with 1). if it's there, remove it otherwise, format the 10 digits the way you want. </p> <pre><code>import re pnumber = re.sub("[^0-9]", "", input_number) if pnumber[0] == 1: pnumber = pnumber[1:]#strip 1st char if it'...
3
2009-11-13T18:34:52Z
[ "python" ]
Python code to accept many different formats of US phone numbers?
1,731,025
<p>I'm reading in lots of user entered data that represent phone numbers from files. They are all slightly entered in differently:</p> <pre> 5555555555 555-555-5555 555-555/5555 1555-555-5555 etc... </pre> <p>How could I easily parse in all of these phone numbers in Python and produce a canonical output like: 555-55...
0
2009-11-13T18:30:36Z
1,731,059
<p>Dive into Python has a section on parsing phone numbers</p> <p><a href="http://www.diveintopython.org/regular%5Fexpressions/phone%5Fnumbers.html" rel="nofollow">http://www.diveintopython.org/regular%5Fexpressions/phone%5Fnumbers.html</a></p>
9
2009-11-13T18:37:51Z
[ "python" ]
Python code to accept many different formats of US phone numbers?
1,731,025
<p>I'm reading in lots of user entered data that represent phone numbers from files. They are all slightly entered in differently:</p> <pre> 5555555555 555-555-5555 555-555/5555 1555-555-5555 etc... </pre> <p>How could I easily parse in all of these phone numbers in Python and produce a canonical output like: 555-55...
0
2009-11-13T18:30:36Z
1,731,088
<pre><code>def extractNumber(s): """take a string phone number and extract it to the legal string""" target = "" for char in s: try: target += int(s) except ValueError: target += '-' return target </code></pre>
0
2009-11-13T18:43:48Z
[ "python" ]
Python code to accept many different formats of US phone numbers?
1,731,025
<p>I'm reading in lots of user entered data that represent phone numbers from files. They are all slightly entered in differently:</p> <pre> 5555555555 555-555-5555 555-555/5555 1555-555-5555 etc... </pre> <p>How could I easily parse in all of these phone numbers in Python and produce a canonical output like: 555-55...
0
2009-11-13T18:30:36Z
1,731,097
<p>Decide which formats you want to recognize, then create a regular expression matching each one grouping the different parts of the number (like area code, prefix etc). Finally use a substitution to generate the canonical output you desire.</p> <p>Example:</p> <p>to match</p> <pre><code>xxx-xxx-xxxx -&gt; \d{3}...
0
2009-11-13T18:46:25Z
[ "python" ]
Python code to accept many different formats of US phone numbers?
1,731,025
<p>I'm reading in lots of user entered data that represent phone numbers from files. They are all slightly entered in differently:</p> <pre> 5555555555 555-555-5555 555-555/5555 1555-555-5555 etc... </pre> <p>How could I easily parse in all of these phone numbers in Python and produce a canonical output like: 555-55...
0
2009-11-13T18:30:36Z
1,731,110
<p>After a little preparation with <a href="http://docs.python.org/library/string.html?highlight=maketrans#string.maketrans" rel="nofollow"><code>string.maketrans</code></a>, strings' <a href="http://docs.python.org/library/string.html?highlight=maketrans#string.translate" rel="nofollow">translate</a> method affords ve...
2
2009-11-13T18:49:19Z
[ "python" ]
Process two files at the same time in Python
1,731,102
<p>I have information about 12340 cars. This info is stored sequentially in two different files:</p> <ol> <li>car_names.txt, which contains one line for the name of each car</li> <li>car_descriptions.txt, which contains the descriptions of each car. So 40 lines for each one, where the 6th line reads @CAR_NAME</li> </o...
3
2009-11-13T18:47:36Z
1,731,117
<pre><code>for line1, line2 in zip(file(filename1), file(filename2)): # do your thing </code></pre> <p>or similar</p>
0
2009-11-13T18:51:05Z
[ "python", "string" ]
Process two files at the same time in Python
1,731,102
<p>I have information about 12340 cars. This info is stored sequentially in two different files:</p> <ol> <li>car_names.txt, which contains one line for the name of each car</li> <li>car_descriptions.txt, which contains the descriptions of each car. So 40 lines for each one, where the 6th line reads @CAR_NAME</li> </o...
3
2009-11-13T18:47:36Z
1,731,133
<p>12340 is not any data (in sense that there are much bigger data to process on the market).</p> <p>Even better approach would use build in sqlite module. If not use some simple format like CSV for example. This is a structure organized. If not use threads, you could process two files simultaneously. </p>
0
2009-11-13T18:54:05Z
[ "python", "string" ]
Process two files at the same time in Python
1,731,102
<p>I have information about 12340 cars. This info is stored sequentially in two different files:</p> <ol> <li>car_names.txt, which contains one line for the name of each car</li> <li>car_descriptions.txt, which contains the descriptions of each car. So 40 lines for each one, where the 6th line reads @CAR_NAME</li> </o...
3
2009-11-13T18:47:36Z
1,731,180
<p>I'm not sure if I completely understand what you're trying to do, is something like this?</p> <pre><code>f1 = open ('car_names.txt') f2 = open ('car_descriptions.txt') for car_name in f1.readlines (): for i in range (6): # echo the first 6 lines print f2.readline () assert f2.readl...
8
2009-11-13T19:02:30Z
[ "python", "string" ]
Process two files at the same time in Python
1,731,102
<p>I have information about 12340 cars. This info is stored sequentially in two different files:</p> <ol> <li>car_names.txt, which contains one line for the name of each car</li> <li>car_descriptions.txt, which contains the descriptions of each car. So 40 lines for each one, where the 6th line reads @CAR_NAME</li> </o...
3
2009-11-13T18:47:36Z
1,731,193
<p>Reading <code>car_names.txt</code> will save you a piddling amount of memory (really really tiny by today's standards;-) but it absolutely won't be any faster than slurping it down at one gulp (best case it will be exactly the same speed, probably even a little bit slower unless your underlying operating system and ...
4
2009-11-13T19:04:22Z
[ "python", "string" ]
Process two files at the same time in Python
1,731,102
<p>I have information about 12340 cars. This info is stored sequentially in two different files:</p> <ol> <li>car_names.txt, which contains one line for the name of each car</li> <li>car_descriptions.txt, which contains the descriptions of each car. So 40 lines for each one, where the 6th line reads @CAR_NAME</li> </o...
3
2009-11-13T18:47:36Z
1,731,539
<p>First, make a generator that retrieves the car name from a sequence. You could yield every 7th line; I've made mine yield whatever line follows the line that starts with <code>@CAR_NAME</code>:</p> <pre><code>def car_names(seq): yieldnext=False for line in seq: if yieldnext: yield line yiel...
9
2009-11-13T20:00:12Z
[ "python", "string" ]
Process two files at the same time in Python
1,731,102
<p>I have information about 12340 cars. This info is stored sequentially in two different files:</p> <ol> <li>car_names.txt, which contains one line for the name of each car</li> <li>car_descriptions.txt, which contains the descriptions of each car. So 40 lines for each one, where the 6th line reads @CAR_NAME</li> </o...
3
2009-11-13T18:47:36Z
1,803,941
<p>I think this fits the question:</p> <ul> <li>it reads the description file one line at a time</li> <li>when it sees @CAR_NAME, it still emits it, but replaces the next line in the description file with the next line from the names file <hr></li> </ul> <pre><code> def merge_car_descriptions(namefile, descrfile): ...
0
2009-11-26T14:21:40Z
[ "python", "string" ]
Getting only one dimension of indexes from the getSelectedIndexes function in QT?
1,731,272
<p>I'm working on a small project in QT (well, pyQT4 actually, but it shouldn't matter too much) and I've run into the following problem. I have a <code>QTableView</code> with several rows and columns. I have set the selection mode to be rows only. When I call <code>getSelectedIndexes()</code> on my <code>QTableView</c...
0
2009-11-13T19:19:10Z
1,731,815
<p>The selection is maintained by <code>QItemSelectionModel</code>, which provides a method called <a href="http://doc.trolltech.com/4.5/qitemselectionmodel.html#selectedRows" rel="nofollow"><code>selectedRows()</code></a> that does what you want. For example:</p> <pre><code>myTableView-&gt;selectionModel()-&gt;select...
4
2009-11-13T20:47:30Z
[ "python", "qt", "qt4", "indexing", "pyqt4" ]
How do I check the HTTP status code of an object without downloading it?
1,731,298
<pre><code>&gt;&gt;&gt; a=urllib.urlopen('http://www.domain.com/bigvideo.avi') &gt;&gt;&gt; a.getcode() 404 &gt;&gt;&gt; a=urllib.urlopen('http://www.google.com/') &gt;&gt;&gt; a.getcode() 200 </code></pre> <p>My question is...bigvideo.avi is 500MB. Does my script first download the file, then check it? Or, can it imm...
4
2009-11-13T19:22:30Z
1,731,351
<p>i think your code already does that. you never call the read() method on the response, so you are never actually downloading the file's contents.</p> <p>better yet... you could send an HTTP HEAD request using <a href="http://docs.python.org/library/httplib.html" rel="nofollow">httplib</a> instead of doing the HTTP ...
0
2009-11-13T19:28:35Z
[ "python", "http" ]
How do I check the HTTP status code of an object without downloading it?
1,731,298
<pre><code>&gt;&gt;&gt; a=urllib.urlopen('http://www.domain.com/bigvideo.avi') &gt;&gt;&gt; a.getcode() 404 &gt;&gt;&gt; a=urllib.urlopen('http://www.google.com/') &gt;&gt;&gt; a.getcode() 200 </code></pre> <p>My question is...bigvideo.avi is 500MB. Does my script first download the file, then check it? Or, can it imm...
4
2009-11-13T19:22:30Z
1,731,369
<p>Yes, it will fetch the file.</p> <p>I think what you really want to do is send a HTTP HEAD request (which basically asks the server not for the data itself, but for the headers only). you can look <a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">here</a>.</p>
1
2009-11-13T19:30:47Z
[ "python", "http" ]
How do I check the HTTP status code of an object without downloading it?
1,731,298
<pre><code>&gt;&gt;&gt; a=urllib.urlopen('http://www.domain.com/bigvideo.avi') &gt;&gt;&gt; a.getcode() 404 &gt;&gt;&gt; a=urllib.urlopen('http://www.google.com/') &gt;&gt;&gt; a.getcode() 200 </code></pre> <p>My question is...bigvideo.avi is 500MB. Does my script first download the file, then check it? Or, can it imm...
4
2009-11-13T19:22:30Z
1,731,388
<p>You want to actually tell the server <em>not</em> to send the full content of the file. HTTP has a mechanism for this called "HEAD" that is an alternative to "GET". It works the same way, but the server only sends you the headers, none of the actual content.</p> <p>That'll save at least one of you bandwidth, while ...
16
2009-11-13T19:33:29Z
[ "python", "http" ]
How to get two random records with Django
1,731,346
<p>How do I get two distinct random records using Django? I've seen questions about how to get one but I need to get two random records and they must differ.</p>
18
2009-11-13T19:27:42Z
1,731,371
<p><code>Object.objects.order_by('?')[:2]</code></p> <p>This would return two random-ordered records. You can add </p> <pre><code>distinct() </code></pre> <p>if there are records with the same value in your dataset.</p>
5
2009-11-13T19:31:01Z
[ "python", "django", "django-models", "random", "sql-order-by" ]
How to get two random records with Django
1,731,346
<p>How do I get two distinct random records using Django? I've seen questions about how to get one but I need to get two random records and they must differ.</p>
18
2009-11-13T19:27:42Z
1,731,373
<p>If you specify the random operator in the ORM I'm pretty sure it will give you two distinct random results won't it?</p> <pre><code>MyModel.objects.order_by('?')[:2] # 2 random results. </code></pre>
17
2009-11-13T19:31:24Z
[ "python", "django", "django-models", "random", "sql-order-by" ]
How to get two random records with Django
1,731,346
<p>How do I get two distinct random records using Django? I've seen questions about how to get one but I need to get two random records and they must differ.</p>
18
2009-11-13T19:27:42Z
6,405,601
<p>The <code>order_by('?')[:2]</code> solution suggested by other answers is actually an extraordinarily bad thing to do for tables that have large numbers of rows. It results in an <code>ORDER BY RAND()</code> SQL query. As an example, here's how mysql handles that (the situation is not much different for other databa...
74
2011-06-19T23:03:35Z
[ "python", "django", "django-models", "random", "sql-order-by" ]
How to get two random records with Django
1,731,346
<p>How do I get two distinct random records using Django? I've seen questions about how to get one but I need to get two random records and they must differ.</p>
18
2009-11-13T19:27:42Z
20,437,227
<p>About sampling n random values from a sequence, the random lib could be used,</p> <pre><code>random.Random().sample(range(0,last),2) </code></pre> <p>will featch 2 random samples from 0 to last-1</p>
4
2013-12-07T03:31:15Z
[ "python", "django", "django-models", "random", "sql-order-by" ]
How to get two random records with Django
1,731,346
<p>How do I get two distinct random records using Django? I've seen questions about how to get one but I need to get two random records and they must differ.</p>
18
2009-11-13T19:27:42Z
38,497,778
<p>For the future readers.</p> <p>Get the the list of ids of all records:</p> <pre><code>my_ids = MyModel.objects.values_list('id', flat=True) </code></pre> <p>Then pick n random ids from all of the above ids:</p> <pre><code>n = 2 rand_ids = random.sample(my_ids, n) </code></pre> <p>And get records for these ids:<...
1
2016-07-21T07:32:07Z
[ "python", "django", "django-models", "random", "sql-order-by" ]
How to get two random records with Django
1,731,346
<p>How do I get two distinct random records using Django? I've seen questions about how to get one but I need to get two random records and they must differ.</p>
18
2009-11-13T19:27:42Z
40,028,117
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>from django.db import models from random import randint from django.db.models.aggregates import Count class ProductMana...
0
2016-10-13T18:12:11Z
[ "python", "django", "django-models", "random", "sql-order-by" ]
httplib in Python to get the status code...but it is too tricky?
1,731,657
<pre><code>&gt;&gt;&gt; import httplib &gt;&gt;&gt; conn = httplib.HTTPConnection("www.google.com") &gt;&gt;&gt; conn.request("HEAD", "/index.html") &gt;&gt;&gt; res = conn.getresponse() &gt;&gt;&gt; print res.status, res.reason 200 OK </code></pre> <p>This code will get the HTTP status code. However, notice that I s...
0
2009-11-13T20:22:03Z
1,731,679
<p>According to the <code>spec</code> you're supposed to split it up like that, maybe Python could abstract that out for you a bit, they're probably just giving you straight access to the header so you know exactly how it's being formatted, which is really the preference.</p>
0
2009-11-13T20:26:46Z
[ "python", "regex", "http", "http-headers" ]
httplib in Python to get the status code...but it is too tricky?
1,731,657
<pre><code>&gt;&gt;&gt; import httplib &gt;&gt;&gt; conn = httplib.HTTPConnection("www.google.com") &gt;&gt;&gt; conn.request("HEAD", "/index.html") &gt;&gt;&gt; res = conn.getresponse() &gt;&gt;&gt; print res.status, res.reason 200 OK </code></pre> <p>This code will get the HTTP status code. However, notice that I s...
0
2009-11-13T20:22:03Z
1,731,697
<p>Maybe you are better off using the URL library instead?</p> <p>In Python 2, use <a href="http://docs.python.org/library/urllib2.html" rel="nofollow"><code>urllib2</code></a>:</p> <pre><code>&gt;&gt;&gt; import urllib2 &gt;&gt;&gt; url = urllib2.urlopen("http://www.google.com/index.html") &gt;&gt;&gt; url.getcode()...
6
2009-11-13T20:28:55Z
[ "python", "regex", "http", "http-headers" ]
httplib in Python to get the status code...but it is too tricky?
1,731,657
<pre><code>&gt;&gt;&gt; import httplib &gt;&gt;&gt; conn = httplib.HTTPConnection("www.google.com") &gt;&gt;&gt; conn.request("HEAD", "/index.html") &gt;&gt;&gt; res = conn.getresponse() &gt;&gt;&gt; print res.status, res.reason 200 OK </code></pre> <p>This code will get the HTTP status code. However, notice that I s...
0
2009-11-13T20:22:03Z
1,731,702
<p>The <code>connect</code> method takes a server argument (with an optional port). You have to split the connection with the resource you actually want.</p> <p>For a simpler way to download web resources directly, you could go with <code>urllib2</code> but <code>urllib2</code> only supports GET or POST methods, no HE...
2
2009-11-13T20:29:32Z
[ "python", "regex", "http", "http-headers" ]
httplib in Python to get the status code...but it is too tricky?
1,731,657
<pre><code>&gt;&gt;&gt; import httplib &gt;&gt;&gt; conn = httplib.HTTPConnection("www.google.com") &gt;&gt;&gt; conn.request("HEAD", "/index.html") &gt;&gt;&gt; res = conn.getresponse() &gt;&gt;&gt; print res.status, res.reason 200 OK </code></pre> <p>This code will get the HTTP status code. However, notice that I s...
0
2009-11-13T20:22:03Z
1,731,715
<p>I like urllib2, sample code:</p> <pre><code>import urllib2 res = urllib2.urlopen('http://google.com/index.html') res.getCode() #contains code </code></pre> <p>I something went wrong, you'll get an exception you can catch.</p> <p><strong>EDIT:</strong> Thanks, changes <code>res.code</code> to <code>res.getCode()</...
0
2009-11-13T20:32:10Z
[ "python", "regex", "http", "http-headers" ]
httplib in Python to get the status code...but it is too tricky?
1,731,657
<pre><code>&gt;&gt;&gt; import httplib &gt;&gt;&gt; conn = httplib.HTTPConnection("www.google.com") &gt;&gt;&gt; conn.request("HEAD", "/index.html") &gt;&gt;&gt; res = conn.getresponse() &gt;&gt;&gt; print res.status, res.reason 200 OK </code></pre> <p>This code will get the HTTP status code. However, notice that I s...
0
2009-11-13T20:22:03Z
1,731,800
<p>Alternatively, if you expect that actually downloading the data is problematic and you really need the <code>HEAD</code> method, you could parse the URL using <a href="http://docs.python.org/library/urlparse.html" rel="nofollow"><code>urlparse</code></a>:</p> <pre><code>&gt;&gt;&gt; import httplib &gt;&gt;&gt; impo...
4
2009-11-13T20:45:30Z
[ "python", "regex", "http", "http-headers" ]
httplib in Python to get the status code...but it is too tricky?
1,731,657
<pre><code>&gt;&gt;&gt; import httplib &gt;&gt;&gt; conn = httplib.HTTPConnection("www.google.com") &gt;&gt;&gt; conn.request("HEAD", "/index.html") &gt;&gt;&gt; res = conn.getresponse() &gt;&gt;&gt; print res.status, res.reason 200 OK </code></pre> <p>This code will get the HTTP status code. However, notice that I s...
0
2009-11-13T20:22:03Z
1,731,878
<p>Keep in mind that not all web servers support HEAD on each resource so you'll end up retrieving the resource anyway. You should write code accordingly.</p>
0
2009-11-13T20:58:06Z
[ "python", "regex", "http", "http-headers" ]
Where can I find a Python lib documentation?
1,731,727
<p>Am looking for a full and official Python standard lib reference. I can't seem to find proper documentation for Python's built-in library anywhere, similar to javadocs. Perhaps I'm not looking hard enough. </p> <p>Thanks</p>
1
2009-11-13T20:33:32Z
1,731,740
<p>Googling for "python standard library" .. <a href="http://docs.python.org/library/" rel="nofollow">first result</a>.</p>
14
2009-11-13T20:35:56Z
[ "python", "documentation", "built-in" ]
Where can I find a Python lib documentation?
1,731,727
<p>Am looking for a full and official Python standard lib reference. I can't seem to find proper documentation for Python's built-in library anywhere, similar to javadocs. Perhaps I'm not looking hard enough. </p> <p>Thanks</p>
1
2009-11-13T20:33:32Z
1,731,750
<p>help(x) in the interpreter will give you full documentation of anything within the standard library.</p>
6
2009-11-13T20:37:37Z
[ "python", "documentation", "built-in" ]
Where can I find a Python lib documentation?
1,731,727
<p>Am looking for a full and official Python standard lib reference. I can't seem to find proper documentation for Python's built-in library anywhere, similar to javadocs. Perhaps I'm not looking hard enough. </p> <p>Thanks</p>
1
2009-11-13T20:33:32Z
1,731,769
<p>There is a good set of official documents here: <a href="http://docs.python.org/library/" rel="nofollow">python.org</a></p>
1
2009-11-13T20:42:12Z
[ "python", "documentation", "built-in" ]
Where can I find a Python lib documentation?
1,731,727
<p>Am looking for a full and official Python standard lib reference. I can't seem to find proper documentation for Python's built-in library anywhere, similar to javadocs. Perhaps I'm not looking hard enough. </p> <p>Thanks</p>
1
2009-11-13T20:33:32Z
1,734,308
<p>If you use firefox, you should give a try to <a href="http://www.edgewall.org/python-sidebar/" rel="nofollow">the Edgewall Python Sidebar</a>.</p>
1
2009-11-14T14:00:22Z
[ "python", "documentation", "built-in" ]
Is there a 'multimap' implementation in Python?
1,731,971
<p>I am new to Python, and I am familiar with implementations of <a href="http://en.wikipedia.org/wiki/Multimap">Multimaps</a> in <a href="http://www.sgi.com/tech/stl/Multimap.html">other</a> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html">languages</a>. Does Pyt...
36
2009-11-13T21:14:58Z
1,731,989
<p>Such a thing is not present in the standard library. You can use a <a href="http://docs.python.org/3.1/library/collections.html#collections.defaultdict"><code>defaultdict</code></a> though:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; md = defaultdict(list) &gt;&gt;&gt; md[1].append(...
73
2009-11-13T21:18:40Z
[ "python", "dictionary" ]
Is there a 'multimap' implementation in Python?
1,731,971
<p>I am new to Python, and I am familiar with implementations of <a href="http://en.wikipedia.org/wiki/Multimap">Multimaps</a> in <a href="http://www.sgi.com/tech/stl/Multimap.html">other</a> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html">languages</a>. Does Pyt...
36
2009-11-13T21:14:58Z
1,731,990
<p>I do not clearly understand the semantics of your example</p> <pre><code>a[1] = 'a' a[1] = 'b' #?? </code></pre> <p>Is second line <code>a[1] = 'b'</code> supposed to replace the element at [1]. If yes, then you need to use dictionary. If not - you need to use dictionary of lists (as already suggested)</p>
-2
2009-11-13T21:19:01Z
[ "python", "dictionary" ]
Is there a 'multimap' implementation in Python?
1,731,971
<p>I am new to Python, and I am familiar with implementations of <a href="http://en.wikipedia.org/wiki/Multimap">Multimaps</a> in <a href="http://www.sgi.com/tech/stl/Multimap.html">other</a> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html">languages</a>. Does Pyt...
36
2009-11-13T21:14:58Z
4,191,405
<p>There is no multi-map in the Python standard libs currently.</p> <p>WebOb has a <a href="http://pythonpaste.org/webob/webob/multidict.py.html" rel="nofollow">MultiDict</a> class used to represent HTML form values, and it is used by a few Python Web frameworks, so the implementation is battle tested. </p> <p>Werkze...
1
2010-11-16T05:16:09Z
[ "python", "dictionary" ]
Is there a 'multimap' implementation in Python?
1,731,971
<p>I am new to Python, and I am familiar with implementations of <a href="http://en.wikipedia.org/wiki/Multimap">Multimaps</a> in <a href="http://www.sgi.com/tech/stl/Multimap.html">other</a> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html">languages</a>. Does Pyt...
36
2009-11-13T21:14:58Z
4,192,253
<p>The standard way to write this in Python is with a dict whose elements are each a <code>list</code> or <code>set</code>. As <a href="http://stackoverflow.com/questions/1731971/is-there-multimap-implementation-in-python/1731989#1731989">stephan202 says</a>, you can somewhat automate this with a defaultdict, but you...
1
2010-11-16T08:26:57Z
[ "python", "dictionary" ]
Is there a 'multimap' implementation in Python?
1,731,971
<p>I am new to Python, and I am familiar with implementations of <a href="http://en.wikipedia.org/wiki/Multimap">Multimaps</a> in <a href="http://www.sgi.com/tech/stl/Multimap.html">other</a> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html">languages</a>. Does Pyt...
36
2009-11-13T21:14:58Z
17,873,086
<p>Stephan202 has the right answer, use <code>defaultdict</code>. But if you want something with the interface of C++ STL multimap and much worse performance, you can do this:</p> <pre><code>multimap = [] multimap.append( (3,'a') ) multimap.append( (2,'x') ) multimap.append( (3,'b') ) multimap.sort() </code></pre> <p...
2
2013-07-26T04:46:08Z
[ "python", "dictionary" ]
Is there a 'multimap' implementation in Python?
1,731,971
<p>I am new to Python, and I am familiar with implementations of <a href="http://en.wikipedia.org/wiki/Multimap">Multimaps</a> in <a href="http://www.sgi.com/tech/stl/Multimap.html">other</a> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html">languages</a>. Does Pyt...
36
2009-11-13T21:14:58Z
22,272,587
<p>Or subclass <code>dict</code>:</p> <pre><code>class Multimap(dict): def __setitem__(self, key, value): if key not in self: dict.__setitem__(self, key, [value]) # call super method to avoid recursion else self[key].append(value) </code></pre>
2
2014-03-08T17:28:18Z
[ "python", "dictionary" ]
Is there a 'multimap' implementation in Python?
1,731,971
<p>I am new to Python, and I am familiar with implementations of <a href="http://en.wikipedia.org/wiki/Multimap">Multimaps</a> in <a href="http://www.sgi.com/tech/stl/Multimap.html">other</a> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html">languages</a>. Does Pyt...
36
2009-11-13T21:14:58Z
23,981,416
<p>Just for future visitors. Currently there is a python implementation of Multimap. It's available via <a href="https://pypi.python.org/pypi/MultiMap">pypi</a></p>
8
2014-06-01T15:29:33Z
[ "python", "dictionary" ]
How to play sound till the user hits a key?
1,731,986
<p>First thought of implementing this using threads but python doesnt have a way for killing threads. I have read the other topic on killing threads. Is there any proper platform independent way of doing this?</p>
0
2009-11-13T21:18:00Z
1,731,994
<p>Can you be more specific? This could be done in pygame, but you'd need to open a graphical window.</p>
0
2009-11-13T21:19:39Z
[ "python", "tkinter" ]
How to play sound till the user hits a key?
1,731,986
<p>First thought of implementing this using threads but python doesnt have a way for killing threads. I have read the other topic on killing threads. Is there any proper platform independent way of doing this?</p>
0
2009-11-13T21:18:00Z
1,732,038
<p>I think you'd better use a Tk timer for ringing periodically, and then stop it when you get the key press.</p> <p>See <a href="http://www.java2s.com/Code/Python/GUI-Tk/Clockevent.htm" rel="nofollow">http://www.java2s.com/Code/Python/GUI-Tk/Clockevent.htm</a> for an example how to use timer.</p> <p>Thus you will av...
0
2009-11-13T21:26:16Z
[ "python", "tkinter" ]
Override save_model on Django InlineModelAdmin
1,732,151
<p>I have a model that has a <code>user</code> field that needs to be auto-populated from the currently logged in user. I can get it working as specified <a href="http://www.b-list.org/weblog/2008/dec/24/admin/">here</a> if the <code>user</code> field is in a standard ModalAdmin, but if the model I'm working with is in...
15
2009-11-13T21:52:03Z
1,734,497
<p>Does the other model save the user? In that case you could use the <code>post_save</code> signal to add that information to the set of the inlined model. </p>
0
2009-11-14T15:09:18Z
[ "python", "django" ]
Override save_model on Django InlineModelAdmin
1,732,151
<p>I have a model that has a <code>user</code> field that needs to be auto-populated from the currently logged in user. I can get it working as specified <a href="http://www.b-list.org/weblog/2008/dec/24/admin/">here</a> if the <code>user</code> field is in a standard ModalAdmin, but if the model I'm working with is in...
15
2009-11-13T21:52:03Z
1,768,338
<p>Have you tried implementing custom validation in the admin as it is described in the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">documentation</a>? Overriding the clean_user() function on the model form might do the trick for you.</p> <p>Ano...
0
2009-11-20T04:26:38Z
[ "python", "django" ]
Override save_model on Django InlineModelAdmin
1,732,151
<p>I have a model that has a <code>user</code> field that needs to be auto-populated from the currently logged in user. I can get it working as specified <a href="http://www.b-list.org/weblog/2008/dec/24/admin/">here</a> if the <code>user</code> field is in a standard ModalAdmin, but if the model I'm working with is in...
15
2009-11-13T21:52:03Z
2,171,222
<p>Only the <code>save_model</code> for the model you're editing is executed, instead you will need to use the <code>post_save</code> signal to update inlined data.</p> <p>(Not really a duplicate, but essentially the same question is being answered in <a href="http://stackoverflow.com/questions/2164539/do-inline-model...
2
2010-01-31T09:48:10Z
[ "python", "django" ]
Override save_model on Django InlineModelAdmin
1,732,151
<p>I have a model that has a <code>user</code> field that needs to be auto-populated from the currently logged in user. I can get it working as specified <a href="http://www.b-list.org/weblog/2008/dec/24/admin/">here</a> if the <code>user</code> field is in a standard ModalAdmin, but if the model I'm working with is in...
15
2009-11-13T21:52:03Z
3,494,626
<p>I had a similar issue with a user field I was trying to populate in an inline model. In my case, the parent model also had the user field defined so I overrode <code>save</code> on the child model as follows:</p> <pre><code>class inline_model: parent = models.ForeignKey(parent_model) modified_by = models.Fo...
1
2010-08-16T15:27:03Z
[ "python", "django" ]
Override save_model on Django InlineModelAdmin
1,732,151
<p>I have a model that has a <code>user</code> field that needs to be auto-populated from the currently logged in user. I can get it working as specified <a href="http://www.b-list.org/weblog/2008/dec/24/admin/">here</a> if the <code>user</code> field is in a standard ModalAdmin, but if the model I'm working with is in...
15
2009-11-13T21:52:03Z
29,596,310
<p>Here's what I think is the best solution. Took me a while to find it... this answer gave me the clues: <a href="http://stackoverflow.com/a/24462173/2453104">http://stackoverflow.com/a/24462173/2453104</a></p> <p>On your admin.py: </p> <pre><code>class YourInline(admin.TabularInline): model = YourInlineModel ...
8
2015-04-13T00:38:34Z
[ "python", "django" ]
Override save_model on Django InlineModelAdmin
1,732,151
<p>I have a model that has a <code>user</code> field that needs to be auto-populated from the currently logged in user. I can get it working as specified <a href="http://www.b-list.org/weblog/2008/dec/24/admin/">here</a> if the <code>user</code> field is in a standard ModalAdmin, but if the model I'm working with is in...
15
2009-11-13T21:52:03Z
30,387,234
<p>I know I'm late to the party, but here's my situation and what I came up with, which might be useful to someone else in the future. </p> <p>I have 4 inline models that need the currently logged in user. </p> <ul> <li>2 as a created_by type field. (only set once on creation)</li> <li>and the 2 others as a closed_by...
2
2015-05-22T02:01:35Z
[ "python", "django" ]
The correct case&format of variable and methods and for Python
1,732,234
<p>So I know some languages have expected conventions.</p> <p>PHP - <code>underscore_case()</code> [for the most part, lolo]</p> <p>Java - <code>camelCase()</code></p> <p>C# - <code>PascalCase()</code></p> <p>etc.</p> <p>What's the "Pythonic" naming convention? I know it doesn't matter in the end but just wonder...
3
2009-11-13T22:12:21Z
1,732,239
<p>Two words: <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>.</p> <p>PEP 8 is the (de facto) Python style guide. Some highlights from this document (I left some stuff out on purpose; go read the original document for the ins and outs): </p> <ul> <li><p><strong>Package and Module Names</st...
6
2009-11-13T22:13:24Z
[ "python", "camelcasing", "pascal-case" ]
The correct case&format of variable and methods and for Python
1,732,234
<p>So I know some languages have expected conventions.</p> <p>PHP - <code>underscore_case()</code> [for the most part, lolo]</p> <p>Java - <code>camelCase()</code></p> <p>C# - <code>PascalCase()</code></p> <p>etc.</p> <p>What's the "Pythonic" naming convention? I know it doesn't matter in the end but just wonder...
3
2009-11-13T22:12:21Z
1,732,241
<p>Read <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>.</p> <p>It's a style guide for Python code, written by Python's creator, Guido van Rossum. </p> <p>Incidentally, the answer to your question is to use <code>underscore_case</code> for variables and function names, and <code>PascalCas...
4
2009-11-13T22:14:12Z
[ "python", "camelcasing", "pascal-case" ]
The correct case&format of variable and methods and for Python
1,732,234
<p>So I know some languages have expected conventions.</p> <p>PHP - <code>underscore_case()</code> [for the most part, lolo]</p> <p>Java - <code>camelCase()</code></p> <p>C# - <code>PascalCase()</code></p> <p>etc.</p> <p>What's the "Pythonic" naming convention? I know it doesn't matter in the end but just wonder...
3
2009-11-13T22:12:21Z
1,732,352
<p>Seven words: <a href="http://code.google.com/p/soc/wiki/PythonStyleGuide" rel="nofollow">Google Summer of Code Python Style Guide</a></p> <blockquote> <p><em>Note that some naming conventions differ from PEP8 and instead follow the original Google Python Style guide from which this style guide originated.</em></p...
1
2009-11-13T22:39:12Z
[ "python", "camelcasing", "pascal-case" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
1,732,477
<p>You could use a test runner that would do this for you. <a href="https://nose.readthedocs.org/en/latest/">nose</a> is very good for example. When run, it will find tests in the current tree and run them.</p> <p>Updated:</p> <p>Here's some code from my pre-nose days. You probably don't want the explicit list of ...
57
2009-11-13T23:12:06Z
[ "python", "unit-testing", "testing" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
1,735,277
<p>Well by studying the code above a bit (specifically using <code>TextTestRunner</code> and <code>defaultTestLoader</code>), I was able to get pretty close. Eventually I fixed my code by also just passing all test suites to a single suites constructor, rather than adding them "manually", which fixed my other problems....
27
2009-11-14T19:18:22Z
[ "python", "unit-testing", "testing" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
6,887,071
<p>If you want to run all the tests from various test case classes and you're happy to specify them explicitly then you can do it like this: </p> <pre><code>from unittest import TestLoader, TextTestRunner, TestSuite from uclid.test.test_symbols import TestSymbols from uclid.test.test_patterns import TestPatterns if _...
16
2011-07-31T01:58:04Z
[ "python", "unit-testing", "testing" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
9,311,779
<p>I have used the <code>discover</code> method and an overloading of <code>load_tests</code> to achieve this result in a (minimal, I think) number lines of code:</p> <pre><code>def load_tests(loader, tests, pattern): ''' Discover and load all unit tests in all files named ``*_test.py`` in ``./src/`` ''' suite = T...
9
2012-02-16T13:04:49Z
[ "python", "unit-testing", "testing" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
15,630,454
<p>With Python 2.7 and higher you don't have to write new code or use third-party tools to do this; recursive test execution via the command line is built-in.</p> <pre><code>python -m unittest discover &lt;test_directory&gt; # or python -m unittest discover -s &lt;directory&gt; -p '*_test.py' </code></pre> <p>You can...
139
2013-03-26T06:09:40Z
[ "python", "unit-testing", "testing" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
19,780,932
<p>I tried various approaches but all seem flawed or I have to makeup some code, that's annoying. But there's a convinient way under linux, that is simply to find every test through certain pattern and then invoke them one by one.</p> <pre><code>find . -name 'Test*py' -exec python '{}' \; </code></pre> <p>and most ...
5
2013-11-05T02:24:33Z
[ "python", "unit-testing", "testing" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
24,562,019
<p>Based on the answer of <a href="http://stackoverflow.com/a/1735277/104143">Stephen Cagle</a> I added support for nested test modules.</p> <pre><code>import fnmatch import os import unittest def all_test_modules(root_dir, pattern): test_file_names = all_files_in(root_dir, pattern) return [path_to_module(str...
0
2014-07-03T19:37:12Z
[ "python", "unit-testing", "testing" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
24,890,716
<p>I use PyDev/LiClipse and haven't really figured out how to run all tests at once from the GUI. (edit: you right click the root test folder and choose <code>Run as -&gt; Python unit-test</code></p> <p>This is my current workaround:</p> <pre><code>import unittest def load_tests(loader, tests, pattern): return l...
1
2014-07-22T14:53:27Z
[ "python", "unit-testing", "testing" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
25,843,259
<p>Because Test discovery seems to be a complete subject, there is some dedicated framework to test discovery : </p> <ul> <li><a href="https://nose.readthedocs.org/en/latest/" rel="nofollow">nose</a></li> <li><a href="http://pytest.org/latest/goodpractises.html#python-test-discovery" rel="nofollow">Py.Test</a></li> </...
0
2014-09-15T08:00:01Z
[ "python", "unit-testing", "testing" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
30,422,863
<p>Here is my approach by creating <a href="https://github.com/mycognitive/ads_tests/blob/master/selenium/run_tests.py" rel="nofollow">a wrapper</a> to run tests from the command line:</p> <pre><code>#!/usr/bin/env python3 import os, sys, unittest, argparse, inspect, logging if __name__ == '__main__': # Parse arg...
-1
2015-05-24T11:13:48Z
[ "python", "unit-testing", "testing" ]
how to run all Python unit tests in a directory
1,732,438
<p>So I have a directory that contains my Python unit test. Each unit test module is of the form "test_*.py". I am attempting to make a file called "all_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
95
2009-11-13T23:01:39Z
31,893,792
<p>In case of a <em>packaged</em> library or application, you don't want to do it. <code>setuptools</code> <a href="https://pythonhosted.org/setuptools/setuptools.html#test-build-package-and-run-a-unittest-suite" rel="nofollow">will do it for you</a>. </p> <blockquote> <p>To use this command, your project’s tests ...
2
2015-08-08T13:51:07Z
[ "python", "unit-testing", "testing" ]
Django ease of building a RESTful interface
1,732,452
<p>I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This is rather straightforward to do without the use of frameworks, but ...
10
2009-11-13T23:03:56Z
1,732,498
<p>It can respond with any kind of data. JSON/XML/PDF/pictures/CSV... </p> <p>Django itself comes with a <a href="http://docs.djangoproject.com/en/dev/topics/serialization/" rel="nofollow">set of serializers</a>.</p> <p><strong>Edit</strong></p> <p>I just had a look at at <a href="http://bitbucket.org/jespern/django...
2
2009-11-13T23:16:29Z
[ "python", "django", "rest" ]
Django ease of building a RESTful interface
1,732,452
<p>I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This is rather straightforward to do without the use of frameworks, but ...
10
2009-11-13T23:03:56Z
1,732,520
<p>This is probably pretty easy to do.</p> <p>URL mappings are easy to construct, for example:</p> <pre><code>urlpatterns = patterns('books.views', (r'^books/$', 'index'), (r'^books/(\d+)/$', 'get')) </code></pre> <p>Django supports <a href="http://docs.djangoproject.com/en/dev/topics/serialization/">model seria...
15
2009-11-13T23:20:36Z
[ "python", "django", "rest" ]
Django ease of building a RESTful interface
1,732,452
<p>I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This is rather straightforward to do without the use of frameworks, but ...
10
2009-11-13T23:03:56Z
1,732,636
<p>A little over a year ago, I wrote a REST web service in Django for a large Seattle company that does streaming media on the Internet.</p> <p>Django was excellent for the purpose. As "a paid nerd" observed, the Django URL config is wonderful: you can set up your URLs just the way you want them, and have it serve up...
1
2009-11-13T23:53:02Z
[ "python", "django", "rest" ]
Django ease of building a RESTful interface
1,732,452
<p>I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This is rather straightforward to do without the use of frameworks, but ...
10
2009-11-13T23:03:56Z
1,736,390
<p>Take a look at Piston, it's a mini-framework for Django for creating RESTful APIs.</p> <p>A recent blog post by Eric Holscher provides some more insight on the PROs of using Piston: <a href="http://ericholscher.com/blog/2009/nov/11/large-problems-django-mostly-solved-rest-api/" rel="nofollow">Large Problems in Djan...
3
2009-11-15T02:43:11Z
[ "python", "django", "rest" ]
Django ease of building a RESTful interface
1,732,452
<p>I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This is rather straightforward to do without the use of frameworks, but ...
10
2009-11-13T23:03:56Z
1,739,518
<p>(I had to edit out the most obvious links.)</p> <p>+1 for <code>piston</code> - (link above). I had used <code>apibuilder</code> (Washington Times open source) in the past, but <a href="http://bitbucket.org/jespern/django-piston/wiki/Home" rel="nofollow">Piston</a> works easier for me. The most difficult thing for ...
4
2009-11-16T00:46:32Z
[ "python", "django", "rest" ]
Django ease of building a RESTful interface
1,732,452
<p>I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This is rather straightforward to do without the use of frameworks, but ...
10
2009-11-13T23:03:56Z
1,791,400
<p>Regarding your comment about not liking 3rd party code - that's too bad because the <strong>pluggable apps are one of django's greatest features</strong>. Like others answered, piston will do most of the work for you. </p>
2
2009-11-24T16:56:15Z
[ "python", "django", "rest" ]
Packaging resources with setuptools/distribute
1,732,619
<p>I'm developing an Python egg that has several .txt dependencies (they're templates used to generate files by the egg itself), and I'm struggling to get those dependencies copied to <code>site-packages</code> during <code>setup.py install</code>. According to the <a href="http://packages.python.org/distribute/setupto...
9
2009-11-13T23:49:26Z
1,732,741
<p>Have you looked at the setuptools documentation for including package data here: <a href="http://peak.telecommunity.com/DevCenter/setuptools#including-data-files" rel="nofollow">http://peak.telecommunity.com/DevCenter/setuptools#including-data-files</a></p> <p>Basically, you just need to set <code>include_package_d...
4
2009-11-14T00:23:45Z
[ "python", "setuptools", "distribute", "pypi" ]
What is a suitable buffer for Python's struct module
1,732,660
<p>In Python I'm accessing a binary file by reading it into a string and then using <code>struct.unpack(...)</code>. Now I want to write to that string using <code>struct.pack_into(...)</code>, but I get the error <em>"Cannot use string as modifiable buffer"</em>. What would be a suitable buffer for use with the <code>...
8
2009-11-14T00:01:21Z
1,732,698
<p>If you aren't trying to pack it into a specific object, just use <a href="http://docs.python.org/library/struct.html#struct.pack"><code>struct.pack</code></a> to return a string.</p> <p>Otherwise, <a href="http://docs.python.org/library/ctypes.html#ctypes.create%5Fstring%5Fbuffer"><code>ctypes.create_string_buffer<...
6
2009-11-14T00:12:45Z
[ "python", "binary", "buffering" ]