title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
How can I print only every third index in Perl or Python?
1,464,923
<p>How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.</p>
5
2009-09-23T09:27:09Z
1,465,560
<p>Perl 5.10 new <a href="http://perldoc.perl.org/functions/state.html" rel="nofollow">state</a> variables comes in very handy here:</p> <pre><code>my @every_third = grep { state $n = 0; ++$n % 3 == 0 } @list; </code></pre> <p><br> Also note you can provide a list of elements to slice:</p> <pre><code>my @every_third = @list[ 2, 5, 8 ]; # returns 3rd, 5th &amp; 9th items in list </code></pre> <p>You can dynamically create this slice list using <a href="http://perldoc.perl.org/functions/map.html" rel="nofollow">map</a> (see Gugod's excellent <a href="http://stackoverflow.com/questions/1464923/how-can-i-print-only-every-third-index-in-perl-or-python/1466696#1466696">answer</a>) or a subroutine: </p> <pre><code>my @every_third = @list[ loop( start =&gt; 2, upto =&gt; $#list, by =&gt; 3 ) ]; sub loop { my ( %p ) = @_; my @list; for ( my $i = $p{start} || 0; $i &lt;= $p{upto}; $i += $p{by} ) { push @list, $i; } return @list; } </code></pre> <p><br></p> <p><strong>Update:</strong></p> <p>Regarding runrig's comment... this is "one way" to make it work within a loop:</p> <pre><code>my @every_third = sub { grep { state $n = 0; ++$n % 3 == 0 } @list }-&gt;(); </code></pre> <p>/I3az/</p>
8
2009-09-23T12:01:48Z
[ "python", "arrays", "perl" ]
How can I print only every third index in Perl or Python?
1,464,923
<p>How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.</p>
5
2009-09-23T09:27:09Z
1,465,724
<p><strong>Perl:</strong></p> <p>As with draegtun's answer, but using a count var:</p> <pre><code>my $i; my @new = grep {not ++$i % 3} @list; </code></pre>
15
2009-09-23T12:39:48Z
[ "python", "arrays", "perl" ]
How can I print only every third index in Perl or Python?
1,464,923
<p>How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.</p>
5
2009-09-23T09:27:09Z
1,466,626
<pre> @array = qw(1 2 3 4 5 6 7 8 9); print @array[(grep { ($_ + 1) % 3 == 0 } (1..$#array))]; </pre>
1
2009-09-23T15:10:05Z
[ "python", "arrays", "perl" ]
How can I print only every third index in Perl or Python?
1,464,923
<p>How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.</p>
5
2009-09-23T09:27:09Z
1,466,696
<p>Perl:</p> <pre><code># The initial array my @a = (1..100); # Copy it, every 3rd elements my @b = @a[ map { 3 * $_ } 0..$#a/3 ]; # Print it. space-delimited $, = " "; say @b; </code></pre>
7
2009-09-23T15:22:02Z
[ "python", "arrays", "perl" ]
How can I print only every third index in Perl or Python?
1,464,923
<p>How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.</p>
5
2009-09-23T09:27:09Z
1,468,355
<p>You could do a slice in Perl.</p> <pre><code>my @in = ( 1..10 ); # need only 1/3 as many indexes. my @index = 1..(@in/3); # adjust the indexes. $_ = 3 * $_ - 1 for @index; # These would also work # $_ *= 3, --$_ for @index; # --($_ *= 3) for @index my @out = @in[@index]; </code></pre>
4
2009-09-23T20:33:05Z
[ "python", "arrays", "perl" ]
How to clone a key in Amazon S3 using Python (and boto)?
1,464,961
<p>I have a file contained in a key in my S3 bucket. I want to create a new key, which will contain the same file. Is it possible to do without downloading that file? I'm looking for a solution in Python (and preferably boto library).</p>
13
2009-09-23T09:34:45Z
1,465,978
<p>S3 allows object by object copy. The CopyObject operation creates a copy of an object when you specify the key and bucket of a source object and the key and bucket of a target destination. Not sure if boto has a compact implementation.</p>
2
2009-09-23T13:24:33Z
[ "python", "amazon-s3", "boto" ]
How to clone a key in Amazon S3 using Python (and boto)?
1,464,961
<p>I have a file contained in a key in my S3 bucket. I want to create a new key, which will contain the same file. Is it possible to do without downloading that file? I'm looking for a solution in Python (and preferably boto library).</p>
13
2009-09-23T09:34:45Z
1,466,148
<p>Browsing through boto's source code I found that the Key object has a "copy" method. Thanks for your suggestion about CopyObject operation.</p>
4
2009-09-23T13:53:09Z
[ "python", "amazon-s3", "boto" ]
How to clone a key in Amazon S3 using Python (and boto)?
1,464,961
<p>I have a file contained in a key in my S3 bucket. I want to create a new key, which will contain the same file. Is it possible to do without downloading that file? I'm looking for a solution in Python (and preferably boto library).</p>
13
2009-09-23T09:34:45Z
2,417,977
<p>Where bucket is the destination bucket:</p> <pre><code>bucket.copy_key(new_key,source_bucket,source_key) </code></pre>
13
2010-03-10T15:13:01Z
[ "python", "amazon-s3", "boto" ]
How to clone a key in Amazon S3 using Python (and boto)?
1,464,961
<p>I have a file contained in a key in my S3 bucket. I want to create a new key, which will contain the same file. Is it possible to do without downloading that file? I'm looking for a solution in Python (and preferably boto library).</p>
13
2009-09-23T09:34:45Z
4,969,587
<p>Although nobody asked, I thought it might be relevant to show how to do this with <code>simples3</code>:</p> <pre><code>&gt;&gt;&gt; b.copy("my_bucket/file.txt", "file_copy.txt", acl="public") </code></pre> <p>I'm not sure what Boto does here, but it's worth noting that the permissions (ACL) will <em>not</em> be copied by S3, it will be reset to "private" if nothing else is specified. To copy the ACL, you have to ask for it first.</p>
2
2011-02-11T13:33:46Z
[ "python", "amazon-s3", "boto" ]
How to clone a key in Amazon S3 using Python (and boto)?
1,464,961
<p>I have a file contained in a key in my S3 bucket. I want to create a new key, which will contain the same file. Is it possible to do without downloading that file? I'm looking for a solution in Python (and preferably boto library).</p>
13
2009-09-23T09:34:45Z
7,366,501
<p>Note that the 'copy' method on the Key object has a "preserve_acl" parameter (False by default) that will copy the source's ACL to the destination object.</p>
0
2011-09-09T19:24:44Z
[ "python", "amazon-s3", "boto" ]
How to clone a key in Amazon S3 using Python (and boto)?
1,464,961
<p>I have a file contained in a key in my S3 bucket. I want to create a new key, which will contain the same file. Is it possible to do without downloading that file? I'm looking for a solution in Python (and preferably boto library).</p>
13
2009-09-23T09:34:45Z
21,517,001
<pre><code>from boto.s3.key import Key #Get source key from bucket by name source_key = source_bucket.get_key(source_key_name) #Copy source key to a new bucket with a new key name (can be the same as source) #Note: source_key is Key source_key.copy(dest_bucket_name,dest_key_name) #The signature of boto's Key class: def copy(self, dst_bucket, dst_key, metadata=None, reduced_redundancy=False, preserve_acl=False, encrypt_key=False, validate_dst_bucket=True) #set preserve_acl=True to copy the acl from the source key </code></pre>
9
2014-02-02T22:18:26Z
[ "python", "amazon-s3", "boto" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
1,465,078
<p>If you want to make it easier on yourself, there are CentOS RPMs for new Python versions floating around the net. E.g. see:</p> <p><a href="http://www.geekymedia.com/python%5F26%5Fcentos.html" rel="nofollow">http://www.geekymedia.com/python%5F26%5Fcentos.html</a></p>
3
2009-09-23T10:02:10Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
1,465,105
<p>No, that's it. You might want to make sure you have all optional library headers installed too so you don't have to recompile it later. They are listed in the documentation I think.</p> <p>Also, you can install it even in the standard path if you do <code>make altinstall</code>. That way it won't override your current default "python".</p>
23
2009-09-23T10:08:08Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
1,498,060
<p><a href="http://chrislea.com/2009/09/09/easy-python-2-6-django-on-centos-5/">Chris Lea</a> provides a YUM repository for python26 RPMs that can co-exist with the 'native' 2.4 that is needed for quite a few admin tools on CentOS.</p> <p>Quick instructions that worked at least for me:</p> <pre><code>$ sudo rpm -Uvh http://yum.chrislea.com/centos/5/i386/chl-release-5-3.noarch.rpm $ sudo rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CHL $ sudo yum install python26 $ python26 </code></pre>
12
2009-09-30T13:18:24Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
1,580,510
<p>When I've run into similar situations, I generally avoid the package manager, especially if it would be embarrassing to break something, i.e. a production server. Instead, I would go to Activestate and download their binary package:</p> <p><a href="https://www.activestate.com/activepython/downloads/">https://www.activestate.com/activepython/downloads/</a></p> <p>This is installed by running a script which places everything into a folder and does not touch any system files. In fact, you don't even need root permissions to set it up. Then I change the name of the binary to something like apy26, add that folder to the end of the PATH and start coding. If you install packages with <code>apy26 setup.py install</code>or if you use virtualenv and easyinstall, then you have just as flexible a python environment as you need without touching the system standard python.</p> <p>Edits... Recently I've done some work to build a portable Python binary for Linux that should run on any distro with no external dependencies. This means that any binary shared libraries needed by the portable Python module are part of the build, included in the tarball and installed in Python's private directory structure. This way you can install Python for your application without interfering with the system installed Python.</p> <p><a href="https://github.com/wavetossed/pybuild">My github site</a> has a build script which has been thoroughly tested on Ubuntu Lucid 10.04 LTS both 32 and 64 bit installs. I've also built it on Debian Etch but that was a while ago and I can't guarantee that I haven't changed something. The easiest way to do this is you just put your choice of Ubuntu Lucid in a virtual machine, checkout the script with <code>git clone git://github.com/wavetossed/pybuild.git</code> and then run the script. </p> <p>Once you have it built, use the tarball on any recent Linux distro. There is one little wrinkle with moving it to a directory other than <code>/data1/packages/python272</code> which is that you have to run the included <code>patchelf</code> to set the interpreter path BEFORE you move the directory. This affects any binaries in <code>/data1/packages/python272/bin</code></p> <p>All of this is based on building with RUNPATH and copying the dependent shared libraries. Even though the script is in several files, it is effectively one long shell script arranged in the style of /etc/rc.d directories.</p>
28
2009-10-16T21:24:22Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
1,980,736
<p>you can always make your own RPM:</p> <p><a href="http://www.grenadepod.com/2009/12/26/building-python-2-6-4-rpm-for-centos-5-4/" rel="nofollow">http://www.grenadepod.com/2009/12/26/building-python-2-6-4-rpm-for-centos-5-4/</a></p>
1
2009-12-30T15:26:38Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
2,779,993
<p>Late to the party, but the OP should have gone with <a href="http://pypi.python.org/pypi/zc.buildout/1.4.3" rel="nofollow">Buildout</a> or <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">Virtualenv</a>, and sidestepped the problem completely.</p> <p>I am currently working on a Centos server, well, toiling away would be the proper term and I can assure everyone that the only way I am able to blink back the tears whilst using the software equivalents of fire hardened spears, is buildout. </p>
2
2010-05-06T09:32:23Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
4,122,184
<p>You could also use the <a href="http://fedoraproject.org/wiki/EPEL">EPEL-repository</a>, and then do <code>sudo yum install python26</code> to install python 2.6</p>
75
2010-11-08T08:13:04Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
4,766,355
<p>Missing Dependency: libffi.so.5 is here : </p> <p><a href="ftp://ftp.pbone.net/mirror/centos.karan.org/el5/extras/testing/i386/RPMS/libffi-3.0.5-1.el5.kb.i386.rpm" rel="nofollow">ftp://ftp.pbone.net/mirror/centos.karan.org/el5/extras/testing/i386/RPMS/libffi-3.0.5-1.el5.kb.i386.rpm</a></p>
1
2011-01-22T05:31:31Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
5,001,536
<p>No need to do yum or make your own RPM. Build <code>python26</code> from source.</p> <pre><code>wget https://www.python.org/ftp/python/2.6.6/Python-2.6.6.tgz tar -zxvf Python-2.6.6.tgz cd Python-2.6.6 ./configure &amp;&amp; make &amp;&amp; make install </code></pre> <p>There can be a <strong>dependency error</strong> use </p> <pre><code>yum install gcc cc </code></pre> <p>Add the install path (<code>/usr/local/bin/python</code> by default) to <code>~/.bash_profile</code>.</p> <p>It will not break <code>yum</code> or any other things which are dependent on <code>python24</code>.</p>
21
2011-02-15T08:58:21Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
5,283,606
<pre><code>rpm -Uvh http://yum.chrislea.com/centos/5/i386/chl-release-5-3.noarch.rpm rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CHL rpm -Uvh ftp://ftp.pbone.net/mirror/centos.karan.org/el5/extras/testing/i386/RPMS/libffi-3.0.5-1.el5.kb.i386.rpm yum install python26 python26 </code></pre> <p>for dos that just dont know :=)</p>
1
2011-03-12T15:59:41Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
8,352,224
<p>Try epel</p> <pre><code>wget http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm sudo rpm -ivh epel-release-5-4.noarch.rpm sudo yum install python26 </code></pre> <p>The python executable will be available at <code>/usr/bin/python26</code></p> <pre><code>mkdir -p ~/bin ln -s /usr/bin/python26 ~/bin/python export PATH=~/bin:$PATH # Append this to your ~/.bash_profile for persistence </code></pre> <p>Now, <code>python</code> command will execute <code>python 2.6</code></p>
29
2011-12-02T05:43:45Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
17,437,929
<p>I unistalled the original version of python (2.6.6) and install 2.7(with option <code>make &amp;&amp; make altinstall</code>) but when I tried install something with yum didn't work.</p> <p>So I solved this issue as follow:</p> <ol> <li><code># ln -s /usr/local/bin/python /usr/bin/python</code></li> <li>Download the RPM package python-2.6.6-36.el6.i686.rpm from <a href="http://rpm.pbone.net/index.php3/stat/4/idpl/20270470/dir/centos_6/com/python-2.6.6-36.el6.i686.rpm.html" rel="nofollow">http://rpm.pbone.net/index.php3/stat/4/idpl/20270470/dir/centos_6/com/python-2.6.6-36.el6.i686.rpm.html</a></li> <li>Execute as root <code>rpm -Uvh python-2.6.6-36.el6.i686.rpm</code></li> </ol> <p>Done</p>
0
2013-07-03T00:31:37Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
17,652,946
<pre><code># yum groupinstall "Development tools" # yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel </code></pre> <p><strong>Download and install Python 3.3.0</strong></p> <pre><code># wget http://python.org/ftp/python/3.3.0/Python-3.3.0.tar.bz2 # tar xf Python-3.3.0.tar.bz2 # cd Python-3.3.0 # ./configure --prefix=/usr/local # make &amp;&amp; make altinstall </code></pre> <p><strong>Download and install Distribute for Python 3.3</strong></p> <pre><code># wget http://pypi.python.org/packages/source/d/distribute/distribute-0.6.35.tar.gz # tar xf distribute-0.6.35.tar.gz # cd distribute-0.6.35 # python3.3 setup.py install </code></pre> <p><strong>Install and use virtualenv for Python 3.3</strong></p> <pre><code># easy_install-3.3 virtualenv # virtualenv-3.3 --distribute otherproject New python executable in otherproject/bin/python3.3 Also creating executable in otherproject/bin/python Installing distribute...................done. Installing pip................done. # source otherproject/bin/activate # python --version Python 3.3.0 </code></pre>
1
2013-07-15T11:14:34Z
[ "python", "centos", "rpath" ]
Install python 2.6 in CentOS
1,465,036
<p>I have a shell that runs CentOS.</p> <p>For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.</p> <p>From what I've read, a number of things will break if you upgrade to 2.5.</p> <p>I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a <code>./configure --prefix=/opt</code> which is where I want it to end up. Can I now just <code>make, make install</code> ? Or is there more?</p>
81
2009-09-23T09:53:04Z
24,663,766
<p>When you install your python version (in this case it is python2.6) then issue this command to create your <code>virtualenv</code>:</p> <pre><code>virtualenv -p /usr/bin/python2.6 /your/virtualenv/path/here/ </code></pre>
3
2014-07-09T21:02:43Z
[ "python", "centos", "rpath" ]
How do you determine a processing time in Python?
1,465,146
<p>I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.</p> <p>In java, I would write:</p> <pre><code>long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore; </code></pre> <p>I'm sure it's even easier in Python. Can anyone help?</p>
22
2009-09-23T10:19:55Z
1,465,159
<pre><code>python -m timeit -h </code></pre>
1
2009-09-23T10:23:11Z
[ "python", "datetime" ]
How do you determine a processing time in Python?
1,465,146
<p>I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.</p> <p>In java, I would write:</p> <pre><code>long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore; </code></pre> <p>I'm sure it's even easier in Python. Can anyone help?</p>
22
2009-09-23T10:19:55Z
1,465,167
<p>Equivalent in python would be:</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; tic = time.clock() &gt;&gt;&gt; toc = time.clock() &gt;&gt;&gt; toc - tic </code></pre> <p>It's not clear what are you trying to do that for? Are you trying to find the best performing method? Then you should prob have a look at <a href="http://docs.python.org/library/timeit.html"><code>timeit</code></a>.</p>
38
2009-09-23T10:24:28Z
[ "python", "datetime" ]
How do you determine a processing time in Python?
1,465,146
<p>I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.</p> <p>In java, I would write:</p> <pre><code>long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore; </code></pre> <p>I'm sure it's even easier in Python. Can anyone help?</p>
22
2009-09-23T10:19:55Z
1,465,170
<p>Use timeit. <a href="http://docs.python.org/library/timeit.html">http://docs.python.org/library/timeit.html</a></p>
7
2009-09-23T10:24:47Z
[ "python", "datetime" ]
How do you determine a processing time in Python?
1,465,146
<p>I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.</p> <p>In java, I would write:</p> <pre><code>long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore; </code></pre> <p>I'm sure it's even easier in Python. Can anyone help?</p>
22
2009-09-23T10:19:55Z
14,739,514
<p>Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use <code>timeit</code>'s <code>default_timer()</code>: </p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; tic=timeit.default_timer() &gt;&gt;&gt; # Do Stuff &gt;&gt;&gt; toc=timeit.default_timer() &gt;&gt;&gt; toc - tic #elapsed time in seconds </code></pre> <p>This will return the elapsed wall clock (real) time, not CPU time. And as described in the <a href="http://docs.python.org/2/library/timeit.html"><code>timeit</code> documentation</a> chooses the most precise available real-world timer depending on the platform. </p> <p>ALso, beginning with Python 3.3 this same functionality is available with the <a href="http://docs.python.org/3.3/library/time.html#time.perf_counter"><code>time.perf_counter</code></a> performance counter. Under 3.3+ timeit.default_timer() refers to this new counter.</p> <p>For more precise/complex performance calculations, <code>timeit</code> includes more sophisticated calls for automatically timing small code snippets including averaging run time over a defined set of repetitions.</p>
16
2013-02-06T21:51:25Z
[ "python", "datetime" ]
How do you determine a processing time in Python?
1,465,146
<p>I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.</p> <p>In java, I would write:</p> <pre><code>long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore; </code></pre> <p>I'm sure it's even easier in Python. Can anyone help?</p>
22
2009-09-23T10:19:55Z
15,456,261
<p>If all you want is the time between two points in code (and it seems that's what you want) I have written <code>tic()</code> <code>toc()</code> functions ala Matlab's implementation. The basic use case is:</p> <pre><code>tic() ''' some code that runs for an interesting amount of time ''' toc() # OUTPUT: # Elapsed time is: 32.42123 seconds </code></pre> <p>Super, incredibly easy to use, a sort of fire-and-forget kind of code. It's available on Github's Gist <a href="https://gist.github.com/tylerhartley/5174230" rel="nofollow">https://gist.github.com/tylerhartley/5174230</a></p>
0
2013-03-17T00:16:28Z
[ "python", "datetime" ]
How do you determine a processing time in Python?
1,465,146
<p>I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.</p> <p>In java, I would write:</p> <pre><code>long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore; </code></pre> <p>I'm sure it's even easier in Python. Can anyone help?</p>
22
2009-09-23T10:19:55Z
34,646,985
<p>For some further information on how to determine the processing time, and a comparison of a few methods (some mentioned already in the answers of this post) - specifically, the difference between: </p> <pre><code>start = time.time() </code></pre> <p>versus the now obsolete (<a href="https://docs.python.org/3/library/time.html#time.clock" rel="nofollow">as of 3.3, time.clock() is deprecated</a>)</p> <pre><code>start = time.clock() </code></pre> <p>see this other article on Stackoverflow here: </p> <p><a href="http://stackoverflow.com/questions/85451/python-time-clock-vs-time-time-accuracy">Python - time.clock() vs. time.time() - accuracy?</a></p> <p>If nothing else, this will work good: </p> <pre><code>start = time.time() ... do something elapsed = (time.time() - start) </code></pre>
0
2016-01-07T03:40:20Z
[ "python", "datetime" ]
How do you determine a processing time in Python?
1,465,146
<p>I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.</p> <p>In java, I would write:</p> <pre><code>long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore; </code></pre> <p>I'm sure it's even easier in Python. Can anyone help?</p>
22
2009-09-23T10:19:55Z
37,283,317
<p>You can implement two <code>tic()</code> and <code>tac()</code> functions, where <code>tic()</code> captures the time which it is called, and <code>tac()</code> prints the time difference since <code>tic()</code> was called. Here is a short implementation:</p> <pre class="lang-py prettyprint-override"><code>import time _start_time = time.time() def tic(): global _start_time _start_time = time.time() def tac(): t_sec = round(time.time() - _start_time) (t_min, t_sec) = divmod(t_sec,60) (t_hour,t_min) = divmod(t_min,60) print('Time passed: {}hour:{}min:{}sec'.format(t_hour,t_min,t_sec)) </code></pre> <p>Now in your code you can use it as: </p> <pre><code>tic() do_some_stuff() tac() </code></pre> <p>and it will, for example, output:</p> <pre><code>Time passed: 0hour:7min:26sec </code></pre> <h2>See also:</h2> <ul> <li>Python's datetime library: <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">https://docs.python.org/2/library/datetime.html</a></li> <li>Python's time library: <a href="https://docs.python.org/2/library/time.html" rel="nofollow">https://docs.python.org/2/library/time.html</a></li> </ul>
1
2016-05-17T18:03:21Z
[ "python", "datetime" ]
vim syntax highlighting for jinja2?
1,465,240
<p>How do you do jinja2 aware syntax highlighting for vim?</p>
8
2009-09-23T10:42:29Z
1,465,251
<p>There appears to be a syntax highlighting file <a href="http://www.vim.org/scripts/script.php?script%5Fid=1856">here</a>.</p>
11
2009-09-23T10:45:00Z
[ "python", "vim", "jinja2", "vim-syntax-highlighting" ]
Trouble with positive look behind assertion in python regex
1,465,246
<p>Trying to use a reasonably long regex and it comes down to this small section that doesn't match how I'd expect it to.</p> <pre><code>&gt;&gt;&gt; re.search(r'(foo)((?&lt;==)bar)?', 'foo').groups() ('foo', None) &gt;&gt;&gt; re.search(r'(foo)((?&lt;==)bar)?', 'foo=bar').groups() ('foo', None) </code></pre> <p>The first one is what I'm after, the second should be returning <code>('foo', 'bar')</code>.</p> <p>I suspect I'm just misunderstanding how lookbehinds are meant to work, some some explanation would be great.</p>
1
2009-09-23T10:44:04Z
1,465,286
<p>Why don't you just use: </p> <pre><code>(foo)=?(bar)? </code></pre> <p>Also the following expression seems to be more correct as it captures the '=' within the full match, but your original expression does not capture that at all:</p> <pre><code>(foo).?((?&lt;==)bar)? </code></pre>
0
2009-09-23T10:53:26Z
[ "python", "regex" ]
Trouble with positive look behind assertion in python regex
1,465,246
<p>Trying to use a reasonably long regex and it comes down to this small section that doesn't match how I'd expect it to.</p> <pre><code>&gt;&gt;&gt; re.search(r'(foo)((?&lt;==)bar)?', 'foo').groups() ('foo', None) &gt;&gt;&gt; re.search(r'(foo)((?&lt;==)bar)?', 'foo=bar').groups() ('foo', None) </code></pre> <p>The first one is what I'm after, the second should be returning <code>('foo', 'bar')</code>.</p> <p>I suspect I'm just misunderstanding how lookbehinds are meant to work, some some explanation would be great.</p>
1
2009-09-23T10:44:04Z
1,465,295
<p>The look behind target is never included in the match - it's supposed to serve as an anchor, but not actually be consumed by the regex.</p> <p>The look behind pattern is only supposed to match if the current position is preceded by the target. In your case, after matching the "foo" in the string, the current position is at the "=", which is not preceded by a "=" - it's preceded by an "o".</p> <p>Another way to see this is by looking at the <a href="http://docs.python.org/library/re.html" rel="nofollow">re documentation</a> and reading</p> <blockquote> <p>Note that patterns which start with positive lookbehind assertions will never match at the beginning of the string being searched;</p> </blockquote> <p>After you match the <code>foo</code>, your look behind is trying to match at the beginning of (the remainder of) the string - this will never work.</p> <p>Others have suggested regexes that may probably serve you better, but I think you're probably looking for</p> <pre><code>&gt;&gt;&gt; re.search('(foo)(=(bar))?', 'foo=bar').groups() ('foo', '=bar', 'bar') </code></pre> <p>If you find the extra group is a little annoying, you could omit the inner "()"s and just chop the first character off the matched group...</p>
2
2009-09-23T10:55:29Z
[ "python", "regex" ]
Trouble with positive look behind assertion in python regex
1,465,246
<p>Trying to use a reasonably long regex and it comes down to this small section that doesn't match how I'd expect it to.</p> <pre><code>&gt;&gt;&gt; re.search(r'(foo)((?&lt;==)bar)?', 'foo').groups() ('foo', None) &gt;&gt;&gt; re.search(r'(foo)((?&lt;==)bar)?', 'foo=bar').groups() ('foo', None) </code></pre> <p>The first one is what I'm after, the second should be returning <code>('foo', 'bar')</code>.</p> <p>I suspect I'm just misunderstanding how lookbehinds are meant to work, some some explanation would be great.</p>
1
2009-09-23T10:44:04Z
1,465,310
<p>You probably just want <code>(foo)(?:=(bar))?</code> using a non-capturing group <code>(?:)</code>.</p> <p>A lookbehind assertion just looks to the left of the current position and checks whether the supplied expression matches or not. Hence your expression matches <code>foo</code> and then checks if the input to the left - the second <code>o</code> in <code>foo</code> - matches <code>=</code>. This of course always fails.</p>
1
2009-09-23T10:59:09Z
[ "python", "regex" ]
jinja2: get lengths of list
1,465,249
<p>How do I get the number of elements in a list in jinja2 template.</p> <p>For example, in python:</p> <pre><code>print template.render(products=[???]) </code></pre> <p>and in jinja2</p> <pre><code>&lt;span&gt;You have {{what goes here?}} products&lt;/span&gt; </code></pre>
112
2009-09-23T10:44:54Z
1,466,550
<pre><code>&lt;span&gt;You have {{products|length}} products&lt;/span&gt; </code></pre> <p>You can also use this syntax in expressions like</p> <pre><code>{% if products|length &gt; 1 %} </code></pre> <p>jinja2's builtin filters are documented <a href="http://jinja.pocoo.org/docs/templates/#builtin-filters">here</a>; and specifically, as you've already found, <a href="http://jinja.pocoo.org/docs/templates/#length"><code>length</code></a> (and its synonym <code>count</code>) is documented to:</p> <blockquote> <p>Return the number of items of a sequence or mapping.</p> </blockquote> <p>So, again as you've found, <code>{{products|count}}</code> (or equivalently <code>{{products|length}}</code>) in your template will give the "number of products" ("length of list")</p> <p>I think it's helpful, when feasible, to provide precise links to docs in an answer (as well as the immediate answer to the specific question asked) -- this way, one gets some idea of roughly where to look in the docs for future answers to similar questions (as well as immediate help for one's specific problem, where needed).</p>
187
2009-09-23T14:55:54Z
[ "python", "jinja2" ]
jinja2: get lengths of list
1,465,249
<p>How do I get the number of elements in a list in jinja2 template.</p> <p>For example, in python:</p> <pre><code>print template.render(products=[???]) </code></pre> <p>and in jinja2</p> <pre><code>&lt;span&gt;You have {{what goes here?}} products&lt;/span&gt; </code></pre>
112
2009-09-23T10:44:54Z
39,636,286
<p>Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.</p> <pre><code>{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %} &lt;li&gt; {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} &lt;/li&gt; {% endfor %} </code></pre>
0
2016-09-22T10:13:41Z
[ "python", "jinja2" ]
What is involved in adding to the standard Python API?
1,465,302
<p>What steps would be necessary, and what kind of maintenance would be expected if I wanted to contribute a module to the Python standard API? For example I have a module that encapsulates automated update functionality similar to Java's JNLP.</p>
4
2009-09-23T10:56:39Z
1,465,322
<p>Please look at <a href="http://www.python.org/dev/peps/pep-0002/" rel="nofollow">Python PEP 2</a> for details. You'll surely find more necessary information at the <a href="http://www.python.org/dev/peps/" rel="nofollow">PEP Index</a>, such as <a href="http://www.python.org/dev/peps/pep-0001/" rel="nofollow">PEP 1: PEP Purpose and Guidelines</a>.</p> <p>Have a look through the PEP index for previous PEPs which may have been rejected in the past.</p> <p>Of course you should also consult the <a href="http://mail.python.org/mailman/listinfo/python-dev" rel="nofollow">python-dev mailing list</a>.</p>
9
2009-09-23T11:02:56Z
[ "python", "api" ]
What is involved in adding to the standard Python API?
1,465,302
<p>What steps would be necessary, and what kind of maintenance would be expected if I wanted to contribute a module to the Python standard API? For example I have a module that encapsulates automated update functionality similar to Java's JNLP.</p>
4
2009-09-23T10:56:39Z
1,465,505
<p>First, look at modules on pypi. Download several that are related to what you're doing so you can see exactly what the state of the art is. </p> <p>For example, look at <code>easy_install</code> for an example of something like what you're proposing.</p> <p>After looking at other modules, write yours to look like theirs.</p> <p>Then publish information on your blog.</p> <p>When people show an interest, post it to SourceForge or something similar. This will allow you to get started slowly.</p> <p>When people start using it, you'll know exactly what kind of maintenance you need to do.</p> <p>Then, when demand ramps up, you can create the pypi information required to publish it on pypi.</p> <p>Finally, when it becomes so popular that people demand it be added to Python as a standard part of the library, many other folks will be involved in helping you mature your offering.</p>
2
2009-09-23T11:49:52Z
[ "python", "api" ]
mod_python interpreter's cache not getting reset on script change?
1,465,364
<p>I use mod_python.publisher to run Python code and discovered a problem: When I update a script the update doesn't always work right away and I get the same error I fixed with the update until I restart Apache.</p> <p>Sometimes it works right away, but sometimes not...but restarting Apache definitely always catches it up. It's a pain to have to restart Apache so much and I would think there is a better way to do this -- but what is it?</p>
0
2009-09-23T11:14:03Z
1,465,428
<p>This is the expected behavior of mod_python. Your code is loaded into memory and won't be refreshed until the server is restarted.</p> <p>You have two options:</p> <ol> <li><p>Set MaxRequestsPerChild 1 in your httpd.conf file to force Apache to reload everything for each request.</p></li> <li><p>Set PythonAutoReload to be On<br/> <a href="http://www.modpython.org/live/mod%5Fpython-3.2.5b/doc-html/dir-other-par.html" rel="nofollow">http://www.modpython.org/live/mod%5Fpython-3.2.5b/doc-html/dir-other-par.html</a></p></li> </ol> <p>But don't do that on a production server, as it will slow down the initialization time.</p>
3
2009-09-23T11:32:05Z
[ "python", "mod-python" ]
How can I implement decrease-key functionality in Python's heapq?
1,465,662
<p>I know it is possible to realize decrease-key functionality in O(log n) but I don't know how?</p>
24
2009-09-23T12:23:52Z
1,466,444
<p>To implement "decrease-key" effectively, you'd need to access the functionality "decrement this element AND swap this element with a child until heap condition is restore". In <a href="http://hg.python.org/cpython/file/2.7/Lib/heapq.py#l242">heapq.py</a>, that's called <code>_siftdown</code> (and similarly <code>_siftup</code> for INcrementing). So the good news is that the functions are there... the bad news is that their names start with an underscore, indicating they're considered "internal implementation details" and should not be accessed directly by application code (the next release of the standard library might change things around and break code using such "internals").</p> <p>It's up to you to decide whether you want to ignore the warning leading-<code>_</code>, use O(N) <code>heapify</code> instead of O(log N) sifting, or reimplement some or all of heapq's functionality to make the sifting primitives "exposed as public parts of the interface". Since heapq's data structure is documented and public (just a list), I think the best choice is probably a partial-reimplementation -- copy the sifting functions from heapq.py into your application code, essentially.</p>
23
2009-09-23T14:41:15Z
[ "python", "heap" ]
How can I implement decrease-key functionality in Python's heapq?
1,465,662
<p>I know it is possible to realize decrease-key functionality in O(log n) but I don't know how?</p>
24
2009-09-23T12:23:52Z
13,804,283
<p>Imagine you are using a heap as a priority queue, where you have a bunch of tasks represented by strings and each task has a key. For concreteness, look at: <code>task_list = [[7,"do laundry"], [3, "clean room"], [6, "call parents"]]</code> where each task in <code>task_list</code> is a list with a priority and description. If you run <code>heapq.heapify(task_list)</code>, you get your array to maintain the heap invariant. However, if you want to change the priority of "do laundry" to 1, you have no way of knowing where "do laundry" is in the heap without a linear scan through the heap (hence can't do decrease_key in logarithmic time). Note <code>decrease_key(heap, i, new_key)</code> requires you to know the index of the value to change in the heap.</p> <p>Even if you maintain a reference to each sublist and actually change the key, you still can't do it in log time. Since a list is just a reference to a bunch of mutable objects, you could try doing something like remember the original order of the task: (in this case that "do laundry" was the 0th task in your original <code>task_list</code>):</p> <pre><code>task_list = [[7, "do laundry"], [3, "clean room"], [6, "call parents"]] task_list_heap = task_list[:] # make a non-deep copy heapq.heapify(task_list_heap) # at this point: # task_list = [[7, 'do laundry'], [3, 'clean room'], [6, 'call parents']] # task_list_heap = [3, 'clean room'], [7, 'do laundry'], [6, 'call parents']] # Change key of first item of task_list (which was "do laundry") from 7 to 1. task_list[0][0] = 1 # Now: # task_list = [[1, 'do laundry'], [3, 'clean room'], [6, 'call parents']] # task_list_heap = [3, 'clean room'], [1, 'do laundry'], [6, 'call parents']] # task_list_heap violates heap invariant at the moment </code></pre> <p>However, you now need to call <code>heapq._siftdown(task_list_heap, 1)</code> to maintain the heap invariant in log time (<code>heapq.heapify</code> is linear time), but unfortunately we don't know the index of "do laundry" in <code>task_list_heap</code> (the <code>heap_index</code> in this case is 1).</p> <p>So we need to implement our heap keeps track of the <code>heap_index</code> of each object; e.g., have an <code>list</code> (for the heap) and a <code>dict</code> mapping each object to its index in the heap/list (that gets updated as the heap positions get swapped adding a constant factor to each swap). You could read through <a href="http://svn.python.org/projects/python/trunk/Lib/heapq.py" rel="nofollow">heapq.py</a> and implement yourself as the procedure is straightforward; however, others have implement this sort of <a href="http://pypi.python.org/pypi/HeapDict" rel="nofollow">HeapDict</a> already.</p>
1
2012-12-10T15:47:50Z
[ "python", "heap" ]
How can I implement decrease-key functionality in Python's heapq?
1,465,662
<p>I know it is possible to realize decrease-key functionality in O(log n) but I don't know how?</p>
24
2009-09-23T12:23:52Z
23,707,260
<p>The <a href="https://docs.python.org/2/library/heapq.html#priority-queue-implementation-notes" rel="nofollow">heapq documentation</a> has an entry on exactly how to do this.</p> <p>However, I have written a <code>heap</code> package that does exactly this (it is a wrapper around <code>heapq</code>). So if you have <code>pip</code> or <code>easy_install</code> you could do something like</p> <pre><code>pip install heap </code></pre> <p>Then in your code write</p> <pre><code>from heap.heap import heap h = heap() h['hello'] = 4 # Insert item with priority 4. h['hello'] = 2 # Update priority/decrease-key has same syntax as insert. </code></pre> <p>It <em>is</em> pretty new though, so might be full of bugs.</p>
3
2014-05-17T03:24:32Z
[ "python", "heap" ]
How can I implement decrease-key functionality in Python's heapq?
1,465,662
<p>I know it is possible to realize decrease-key functionality in O(log n) but I don't know how?</p>
24
2009-09-23T12:23:52Z
37,007,941
<p>Decrease-key is a must-have operation for many algorithms (Dijkstra's Algorithm, A*, OPTICS), i wonder why Python's built-in priority queue does not support it.</p> <p>Unfortunately, i wasn't able to download math4tots's package.</p> <p>But, i was able to find <a href="https://github.com/DanielStutzbach/heapdict" rel="nofollow">this</a> implementation by Daniel Stutzbach. Worked perfectly for me with Python 3.5.</p>
0
2016-05-03T15:12:58Z
[ "python", "heap" ]
Limiting results returned fromquery in django, python
1,465,734
<p>I've just started to learn how to do queries in my Django application, and I have a query that gets me the list of new users filtered by the date joined:</p> <pre><code>newUsers = User.objects.filter(is_active=True).order_by("-date_joined") </code></pre> <p>This as I understand it gives me ALL the users, sorted by date joined. How would I best limit it to get me the last N users?</p> <p>On this, does anyone recommend and reading material to learn more about these types of queries?</p>
3
2009-09-23T12:42:20Z
1,465,750
<pre><code>User.objects.filter(is_active=True).order_by("-date_joined")[:10] </code></pre> <p>will give you the last 10 users who joined. See <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#id4">the Django docs</a> for details.</p>
8
2009-09-23T12:45:43Z
[ "python", "django" ]
Limiting results returned fromquery in django, python
1,465,734
<p>I've just started to learn how to do queries in my Django application, and I have a query that gets me the list of new users filtered by the date joined:</p> <pre><code>newUsers = User.objects.filter(is_active=True).order_by("-date_joined") </code></pre> <p>This as I understand it gives me ALL the users, sorted by date joined. How would I best limit it to get me the last N users?</p> <p>On this, does anyone recommend and reading material to learn more about these types of queries?</p>
3
2009-09-23T12:42:20Z
1,465,777
<p>Use list slice operation on constructed queries e.g.</p> <p>For example, this returns the first 5 objects (LIMIT 5):</p> <pre><code>Entry.objects.all()[:5] </code></pre> <p>This returns the sixth through tenth objects (OFFSET 5 LIMIT 5):</p> <pre><code>Entry.objects.all()[5:10] </code></pre> <p>Read django documentation <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/queries/</a></p>
4
2009-09-23T12:48:45Z
[ "python", "django" ]
Limiting results returned fromquery in django, python
1,465,734
<p>I've just started to learn how to do queries in my Django application, and I have a query that gets me the list of new users filtered by the date joined:</p> <pre><code>newUsers = User.objects.filter(is_active=True).order_by("-date_joined") </code></pre> <p>This as I understand it gives me ALL the users, sorted by date joined. How would I best limit it to get me the last N users?</p> <p>On this, does anyone recommend and reading material to learn more about these types of queries?</p>
3
2009-09-23T12:42:20Z
1,465,820
<p>BTW, if u would just divide amount of all user, (for example, 10 per site) you should interest pagination in dJango, very helpful <a href="http://docs.djangoproject.com/en/dev/topics/pagination/#topics-pagination" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/pagination/#topics-pagination</a></p>
0
2009-09-23T12:57:48Z
[ "python", "django" ]
Limiting results returned fromquery in django, python
1,465,734
<p>I've just started to learn how to do queries in my Django application, and I have a query that gets me the list of new users filtered by the date joined:</p> <pre><code>newUsers = User.objects.filter(is_active=True).order_by("-date_joined") </code></pre> <p>This as I understand it gives me ALL the users, sorted by date joined. How would I best limit it to get me the last N users?</p> <p>On this, does anyone recommend and reading material to learn more about these types of queries?</p>
3
2009-09-23T12:42:20Z
1,465,844
<pre><code>User.objects.filter(is_active=True).order_by("-date_joined")[:10] </code></pre> <p>QuerySets are lazy [ <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/querysets/</a> ]. When you're slicing the list, it doesn't actually fetch all entries, load them up into a list, and then slice them. Instead, it fetches only the last 10 entries.</p>
2
2009-09-23T13:01:34Z
[ "python", "django" ]
appengine and no-ip.org
1,465,769
<p>I'd like to run an appengine app on a subdomain like something.no-ip.org instead of something.appspot.com is this doable? If so, can you please help me understand? :)</p> <p>Thank you so much for your help!</p>
0
2009-09-23T12:47:47Z
1,465,809
<p>No, you can't. <a href="http://code.google.com/appengine/articles/domains.html" rel="nofollow">http://code.google.com/appengine/articles/domains.html</a> clearly states that "To begin, you'll need to sign up for Google Apps. If you don't already own your domain, you can use Google Apps to register it." -- something.no-ip.org is a subdomain of no-ip.org, not a domain.</p>
0
2009-09-23T12:56:01Z
[ "python", "google-app-engine", "dns", "subdomain" ]
appengine and no-ip.org
1,465,769
<p>I'd like to run an appengine app on a subdomain like something.no-ip.org instead of something.appspot.com is this doable? If so, can you please help me understand? :)</p> <p>Thank you so much for your help!</p>
0
2009-09-23T12:47:47Z
1,478,506
<p>You should be able to do this, I haven't tried myself.</p> <p>The steps you would follow are:</p> <ol> <li>register something.no-ip.org with no-ip.org</li> <li>sign up for something.no-ip.org with google apps standard</li> <li>create your www.something.no-ip.org cname</li> <li>in the google apps domain manager, enable google app engine for www.something.no-ip.org and map an app to the www cname.</li> </ol> <p>This link is helpful for creating cnames and registering something.no-ip.org with google apps standard: <a href="http://www.google.com/support/a/bin/answer.py?hl=en&amp;answer=47945" rel="nofollow">http://www.google.com/support/a/bin/answer.py?hl=en&amp;answer=47945</a></p>
1
2009-09-25T17:09:54Z
[ "python", "google-app-engine", "dns", "subdomain" ]
appengine and no-ip.org
1,465,769
<p>I'd like to run an appengine app on a subdomain like something.no-ip.org instead of something.appspot.com is this doable? If so, can you please help me understand? :)</p> <p>Thank you so much for your help!</p>
0
2009-09-23T12:47:47Z
1,480,797
<p>You can't do this, because you don't own no-ip.org. In order to use a domain with App Engine, you have to set up Google Apps on the domain, and in order to do that, you must own the domain.</p> <p>As mentioned in the comments, buying your own domain is your best option.</p>
1
2009-09-26T08:46:59Z
[ "python", "google-app-engine", "dns", "subdomain" ]
appengine and no-ip.org
1,465,769
<p>I'd like to run an appengine app on a subdomain like something.no-ip.org instead of something.appspot.com is this doable? If so, can you please help me understand? :)</p> <p>Thank you so much for your help!</p>
0
2009-09-23T12:47:47Z
1,482,382
<p>You absolutely can run App Engine apps on your own domain. You need to have previously installed Google Apps for your domain:</p> <pre><code>http://www.google.com/a/cpanel/domain/new </code></pre> <p>After you do that, here are the steps:</p> <ol> <li>Create your App Engine app and upload it. You will get a default site on appid.appspot.com.</li> <li>Log in to your AppEngine account at <a href="http://appengine.google.com/" rel="nofollow">http://appengine.google.com/</a></li> <li>Select your application to go to the management console.</li> <li>Click on "Versions" link in the left column</li> <li>Click the Add Domain button</li> <li>Type your domain name (that you own) and click Add Domain...</li> </ol> <p>This will take you to your Google Apps for Domains account manager, where you can add your AppEngine app to your account, and associate it with the sub-domain of your choosing (like www.your-domain.com).</p> <p>Note that you'll also need to update your DNS settings to point your new domain to Google. For example, if you want www.your-domain.com to point to your App Engine application, you'll need to add a CNAME record at your domain registrar to point to 'ghs.google.com'.</p> <p>Note that App Engine DOES NOT support hosting your app at a 'naked domain', e.g., directly at 'your-domain.com'. But, if you use GoDaddy (and most other registrars), you can redirect all requests to 'your-domain.com' to go to the equivalent URL on 'www.your-domain.com'.</p>
1
2009-09-26T23:17:33Z
[ "python", "google-app-engine", "dns", "subdomain" ]
appengine and no-ip.org
1,465,769
<p>I'd like to run an appengine app on a subdomain like something.no-ip.org instead of something.appspot.com is this doable? If so, can you please help me understand? :)</p> <p>Thank you so much for your help!</p>
0
2009-09-23T12:47:47Z
12,418,038
<p>I believe <a href="http://support.google.com/a/bin/answer.py?hl=en&amp;answer=47945" rel="nofollow">http://support.google.com/a/bin/answer.py?hl=en&amp;answer=47945</a> will answer this question! Yes, you can use no-ip. Still researching this, but it is by using CNAME. I'm looking for a way to use my no-ip subdomain as my email (ex. xxxxxx@xxxx.hopto.org).</p>
2
2012-09-14T04:15:11Z
[ "python", "google-app-engine", "dns", "subdomain" ]
Install mysqldb on snow leopard
1,465,846
<p>I am trying to get started on working with Python on Django I am by profession a PHP developer and have been told to set up django and python on my current apache and mysql setup however I am having trouble getting the Mysqldb module for python to work, I must of followed about 6 different set of instructions, I am running snow leopard and have mysql installed natively it is not part of MAMP or similar. Please can some tell me where I need to start and what steps I need to follew I would be most grateful.</p> <p>Thanks</p>
7
2009-09-23T13:01:50Z
1,465,902
<p>First and foremost, make sure that <a href="http://developer.apple.com/technology/Xcode.html" rel="nofollow">XCode</a> is installed. Without XCode, many pieces of the built-in Apache2 server important to developers are missing; most notably, the <a href="http://gcc.gnu.org/" rel="nofollow">GNU Compiler Collection</a>, which I would think to be requisite for MySQL bindings.</p>
2
2009-09-23T13:10:12Z
[ "python", "mysql", "django", "osx-snow-leopard" ]
Install mysqldb on snow leopard
1,465,846
<p>I am trying to get started on working with Python on Django I am by profession a PHP developer and have been told to set up django and python on my current apache and mysql setup however I am having trouble getting the Mysqldb module for python to work, I must of followed about 6 different set of instructions, I am running snow leopard and have mysql installed natively it is not part of MAMP or similar. Please can some tell me where I need to start and what steps I need to follew I would be most grateful.</p> <p>Thanks</p>
7
2009-09-23T13:01:50Z
1,466,664
<p>[Partial Answer]</p> <p>You'll have more fun pulling out your teeth. MySQL/Django/Mac is a disaster. This is the farthest I've gotten:</p> <p>Get <a href="http://pypi.python.org/packages/source/M/MySQL-python/MySQL-python-1.2.3c1.tar.gz" rel="nofollow">MySQLDB 1.2.3</a> Go into that and modify setup_posix.py:</p> <p>Change:</p> <pre><code>mysql_config.path = "mysql_config" </code></pre> <p>To (depending on the version number of your MySQL):</p> <pre><code>mysql_config.path = "/usr/local/mysql-5.1.34-osx10.5-x86_64/bin/mysql_config" </code></pre> <p>python setup.py build python setup.py install</p> <p>Here's a good <a href="http://www.mechanicalgirl.com/view/installing-django-with-mysql-on-mac-os-x/" rel="nofollow">article</a></p>
3
2009-09-23T15:17:05Z
[ "python", "mysql", "django", "osx-snow-leopard" ]
Install mysqldb on snow leopard
1,465,846
<p>I am trying to get started on working with Python on Django I am by profession a PHP developer and have been told to set up django and python on my current apache and mysql setup however I am having trouble getting the Mysqldb module for python to work, I must of followed about 6 different set of instructions, I am running snow leopard and have mysql installed natively it is not part of MAMP or similar. Please can some tell me where I need to start and what steps I need to follew I would be most grateful.</p> <p>Thanks</p>
7
2009-09-23T13:01:50Z
1,467,440
<p>I'd recomend installing macports (latest svn trunk) and installing mysql from there. </p> <p>sudo port install mysql5-server</p> <p>Download the MySQL-python-1.2.2 source</p> <p>make sure /opt/local/lib/mysql5/bin is in your path or edit site.cfg to include: </p> <pre><code>mysql_config = /opt/local/lib/mysql5/bin/mysql_config </code></pre> <p>Comment out line 38 of _mysql.c </p> <pre><code>// #define uint unsigned int </code></pre> <p>Then run:</p> <pre><code>sudo python setup.py install </code></pre> <p>should be all good.</p>
4
2009-09-23T17:18:08Z
[ "python", "mysql", "django", "osx-snow-leopard" ]
Install mysqldb on snow leopard
1,465,846
<p>I am trying to get started on working with Python on Django I am by profession a PHP developer and have been told to set up django and python on my current apache and mysql setup however I am having trouble getting the Mysqldb module for python to work, I must of followed about 6 different set of instructions, I am running snow leopard and have mysql installed natively it is not part of MAMP or similar. Please can some tell me where I need to start and what steps I need to follew I would be most grateful.</p> <p>Thanks</p>
7
2009-09-23T13:01:50Z
2,772,878
<ol> <li><p>Xcode was installed. </p></li> <li><p>Follow these instructions for setting up apache/php/mysql:</p> <p><a href="http://maestric.com/doc/mac/apache_php_mysql_snow_leopard" rel="nofollow">http://maestric.com/doc/mac/apache_php_mysql_snow_leopard</a></p></li> <li><p>I installed the free 32-bit version of EPD (this is optional but I wanted numpy/scipy).</p></li> <li><p>Make sure you have these lines in your ~/.profile (the second line is only if you installed EPD):</p> <pre><code>export PATH=/usr/local/mysql/bin/:/usr/local/bin:/usr/local/sbin:$PATH export PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:${PATH}" </code></pre></li> <li><p>Downloaded mysqldb and run:</p> <pre><code>python setup.py build sudo python setup.py install </code></pre></li> <li><p>Install the official release of Django or web2py. Everything worked after that. You can try the "Writing Your First Django App, Part 1" to test it out where in settings.py use:</p> <pre><code>DATABASE_ENGINE = 'mysql' DATABASE_NAME = 'Django Polls' DATABASE_USER = '*****' DATABASE_PASSWORD = '*****' DATABASE_HOST = '127.0.0.1' DATABASE_PORT = '3306' </code></pre></li> <li><p>I also use Navicat Lite and Sequel Pro for working with MySQL.</p></li> <li><p>Pydev is a nice IDE to use with Django.</p></li> </ol>
0
2010-05-05T11:51:42Z
[ "python", "mysql", "django", "osx-snow-leopard" ]
Install mysqldb on snow leopard
1,465,846
<p>I am trying to get started on working with Python on Django I am by profession a PHP developer and have been told to set up django and python on my current apache and mysql setup however I am having trouble getting the Mysqldb module for python to work, I must of followed about 6 different set of instructions, I am running snow leopard and have mysql installed natively it is not part of MAMP or similar. Please can some tell me where I need to start and what steps I need to follew I would be most grateful.</p> <p>Thanks</p>
7
2009-09-23T13:01:50Z
3,949,239
<ol> <li>Install the newest 64bit DMG version of MySQL. Remember to backup your databases if you already have MySQL installed.</li> <li><p>enter this line in terminal:</p> <p>sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql</p></li> <li><p>Edit the file setup_posix in the mysql-python installation directory.</p></li> </ol> <p>Change the line </p> <pre><code>mysql_config.path = "mysql_config" </code></pre> <p>to</p> <pre><code>mysql_config.path = "/usr/local/mysql/bin/mysql_config" </code></pre> <ol> <li>Myslq-Python needs a 64bit Version of Python. The new Python 2.7 64bit version creates an alias in /usr/local/bin/python.</li> <li><p>Enter the following lines in the mysql-python folder</p> <p><code>sudo /usr/local/bin/python setup.py clean</code></p> <p><code>sudo ARCHFLAGS="-arch x86_64"</code></p> <p><code>sudo /usr/local/bin/python setup.py build</code></p> <p><code>sudo /usr/local/bin/python setup.py install</code></p></li> </ol> <p>And finally try it out:</p> <pre><code>python import MySQLdb </code></pre>
0
2010-10-16T14:18:34Z
[ "python", "mysql", "django", "osx-snow-leopard" ]
Install mysqldb on snow leopard
1,465,846
<p>I am trying to get started on working with Python on Django I am by profession a PHP developer and have been told to set up django and python on my current apache and mysql setup however I am having trouble getting the Mysqldb module for python to work, I must of followed about 6 different set of instructions, I am running snow leopard and have mysql installed natively it is not part of MAMP or similar. Please can some tell me where I need to start and what steps I need to follew I would be most grateful.</p> <p>Thanks</p>
7
2009-09-23T13:01:50Z
5,445,398
<p>One of the key things here is to make sure you're running both MySQL and the Python adaptor in 64 bit. The default Python 2.6.1 install on Snow Leopard is 64 bit so you must install MySQL in 64 bit and build the MySQLdb adapter in 64 bit.</p> <ol> <li>Make sure you have the latest Xcode installed</li> <li>Install 64-bit MySQL from DMG - <a href="http://dev.mysql.com/downloads/mirror.php?id=401941#mirrors" rel="nofollow">http://dev.mysql.com/downloads/mirror.php?id=401941#mirrors</a></li> <li>Download MySQL-python-1.2.3 from <a href="http://download.sourceforge.net/sourceforge/mysql-python/MySQL-python-1.2.3.tar.gz" rel="nofollow">http://download.sourceforge.net/sourceforge/mysql-python/MySQL-python-1.2.3.tar.gz</a></li> <li><p>Extract and make the following edit to site.cfg:</p> <pre><code>mysql_config = /usr/local/mysql/bin/mysql_config </code></pre></li> <li><p>Then from your terminal run</p> <pre><code>ARCHFLAGS="-arch x86_64" python setup.py build sudo python setup.py install </code></pre></li> </ol> <p>You should then open a Python shell and type:</p> <pre><code>import MySQLdb </code></pre> <p>If you don't get any errors you're golden.</p>
0
2011-03-26T21:18:45Z
[ "python", "mysql", "django", "osx-snow-leopard" ]
Install mysqldb on snow leopard
1,465,846
<p>I am trying to get started on working with Python on Django I am by profession a PHP developer and have been told to set up django and python on my current apache and mysql setup however I am having trouble getting the Mysqldb module for python to work, I must of followed about 6 different set of instructions, I am running snow leopard and have mysql installed natively it is not part of MAMP or similar. Please can some tell me where I need to start and what steps I need to follew I would be most grateful.</p> <p>Thanks</p>
7
2009-09-23T13:01:50Z
6,537,345
<p>On MAC OS X 10.6, Install the package as usual. The dynamic import error occurs because of wrong DYLD path. Export the path and open up a python terminal.</p> <p>$ sudo python setup.py clean</p> <p>$ sudo python setup.py build</p> <p>$ sudo python setup.py install</p> <p>$ <strong>export DYLD_LIBRARY_PATH=/usr/local/mysql/lib:$DYLD_LIBRARY_PATH</strong></p> <p>$python</p> <blockquote> <blockquote> <p>import MySQLdb</p> </blockquote> </blockquote> <p>Now import MySQLdb should work fine.</p> <p>You may also want to manually remove the build folder, before build and install. The clean command does not do a proper task of cleaning up the build files.</p>
7
2011-06-30T15:37:18Z
[ "python", "mysql", "django", "osx-snow-leopard" ]
Install mysqldb on snow leopard
1,465,846
<p>I am trying to get started on working with Python on Django I am by profession a PHP developer and have been told to set up django and python on my current apache and mysql setup however I am having trouble getting the Mysqldb module for python to work, I must of followed about 6 different set of instructions, I am running snow leopard and have mysql installed natively it is not part of MAMP or similar. Please can some tell me where I need to start and what steps I need to follew I would be most grateful.</p> <p>Thanks</p>
7
2009-09-23T13:01:50Z
11,188,521
<p>You could make your life a lot easier (especially on Lion) by just installing Mariadb instead:</p> <p><a href="http://mariadb.org/" rel="nofollow">http://mariadb.org/</a></p> <p>It's a drop-in replacement for MySQL and is plug&amp;play on OSX. The only thing you don't get is the MySQL system setting.</p>
0
2012-06-25T11:30:36Z
[ "python", "mysql", "django", "osx-snow-leopard" ]
python open built-in function: difference between modes a, a+, w, w+, and r+?
1,466,000
<p>In the python built-in <a href="http://docs.python.org/library/functions.html#open">open</a> function, what is the exact difference between the modes w, a, w+, a+, and r+?</p> <p>In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.</p>
224
2009-09-23T13:27:36Z
1,466,036
<p>The opening modes are exactly the same that C <strong><code>fopen()</code></strong> std library function.</p> <p><a href="http://www.manpagez.com/man/3/fopen/">The BSD <code>fopen</code> manpage</a> defines them as follows:</p> <pre class="lang-none prettyprint-override"><code> The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.): ``r'' Open text file for reading. The stream is positioned at the beginning of the file. ``r+'' Open for reading and writing. The stream is positioned at the beginning of the file. ``w'' Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file. ``w+'' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. ``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. ``a+'' Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. </code></pre>
302
2009-09-23T13:33:20Z
[ "python" ]
python open built-in function: difference between modes a, a+, w, w+, and r+?
1,466,000
<p>In the python built-in <a href="http://docs.python.org/library/functions.html#open">open</a> function, what is the exact difference between the modes w, a, w+, a+, and r+?</p> <p>In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.</p>
224
2009-09-23T13:27:36Z
1,466,037
<p>The options are the same as for the <a href="http://www.manpagez.com/man/3/fopen/">fopen function</a> in the C standard library:</p> <p><code>w</code> truncates the file, overwriting whatever was already there</p> <p><code>a</code> appends to the file, adding onto whatever was already there</p> <p><code>w+</code> opens for reading and writing, truncating the file but also allowing you to read back what's been written to the file</p> <p><code>a+</code> opens for appending and reading, allowing you both to append to the file and also read its contents</p>
34
2009-09-23T13:33:37Z
[ "python" ]
python open built-in function: difference between modes a, a+, w, w+, and r+?
1,466,000
<p>In the python built-in <a href="http://docs.python.org/library/functions.html#open">open</a> function, what is the exact difference between the modes w, a, w+, a+, and r+?</p> <p>In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.</p>
224
2009-09-23T13:27:36Z
26,006,976
<p>I hit upon this trying to figure out why you would use mode 'w+' versus 'w'. In the end, I just did some testing. I don't see much purpose for mode 'w+', as in both cases, the file is truncated to begin with. However, with the 'w+', you could read after writing by seeking back. If you tried any reading with 'w', it would throw an IOError. Reading without using seek with mode 'w+' isn't going to yield anything, since the file pointer will be after where you have written. </p>
5
2014-09-24T01:09:13Z
[ "python" ]
python open built-in function: difference between modes a, a+, w, w+, and r+?
1,466,000
<p>In the python built-in <a href="http://docs.python.org/library/functions.html#open">open</a> function, what is the exact difference between the modes w, a, w+, a+, and r+?</p> <p>In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.</p>
224
2009-09-23T13:27:36Z
30,566,011
<p>I noticed that every now and then I need to Google fopen all over again, just to build a mental image of what the primary differences between the modes are. So, I thought a diagram will be faster to read next time. Maybe someone else will find that helpful too.</p> <p><img src="http://i.stack.imgur.com/ExWNT.png" alt=""></p>
119
2015-06-01T05:13:40Z
[ "python" ]
python open built-in function: difference between modes a, a+, w, w+, and r+?
1,466,000
<p>In the python built-in <a href="http://docs.python.org/library/functions.html#open">open</a> function, what is the exact difference between the modes w, a, w+, a+, and r+?</p> <p>In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.</p>
224
2009-09-23T13:27:36Z
30,931,305
<p>Same info, just in table form</p> <pre><code> | r r+ w w+ a a+ ------------------|-------------------------- read | + + + + write | + + + + + create | + + + + truncate | + + position at start | + + + + position at end | + + </code></pre> <p>where meanings are: (just to avoid any misinterpretation)</p> <ul> <li>read - reading from file is allowed</li> <li><p>write - writing to file is allowed</p></li> <li><p>create - file is created if it does not exist yet</p></li> <li><p>trunctate - during opening of the file it is made empty (all content of the file is erased)</p></li> <li><p>position at start - after file is opened, initial position is set to the start of the file</p></li> <li>position at end - after file is opened, initial position is set to the end of the file</li> </ul>
40
2015-06-19T06:26:02Z
[ "python" ]
multiline checkbox in wxpython
1,466,140
<p>I'm working with wxpython (2.8) with python 2.5. is it possible to force a wx.CheckBox to display its label on multiple lines? I'd like to be able to do the same as wx.StaticText.Wrap(width)</p> <p>See the attached example: the wx.CheckBox is 200 px wide, but it's label does not fit in this space.</p> <p>Any help is really appreciated! Thanks a lot Mauro</p> <pre><code>#example starts here import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Hello World", size= (300,200)) self.panel = wx.Panel(self, -1) myVSizer = wx.BoxSizer(wx.VERTICAL) #instantiating a checkbox 200 px wide. but the label is too long cb = wx.CheckBox(self.panel, -1, label="This is a very very long label for 200 pixel wide cb!", size =wx.Size(200, -1)) myVSizer.Add( cb, 1) self.panel.SetSizer(myVSizer) myVSizer.Layout() app = wx.App(redirect=True) top = MyFrame() top.Show() app.MainLoop() </code></pre>
2
2009-09-23T13:52:06Z
1,466,379
<p>Changing your label to</p> <pre><code>label="This is a very very\n long label for 200\n pixel wide cb!" </code></pre> <p>should do it.</p> <p>That is, put in explicit <code>\n</code> characters.</p> <p><img src="http://i35.tinypic.com/akwia0.png" alt="alt text" /></p>
1
2009-09-23T14:32:24Z
[ "python", "wxpython" ]
multiline checkbox in wxpython
1,466,140
<p>I'm working with wxpython (2.8) with python 2.5. is it possible to force a wx.CheckBox to display its label on multiple lines? I'd like to be able to do the same as wx.StaticText.Wrap(width)</p> <p>See the attached example: the wx.CheckBox is 200 px wide, but it's label does not fit in this space.</p> <p>Any help is really appreciated! Thanks a lot Mauro</p> <pre><code>#example starts here import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Hello World", size= (300,200)) self.panel = wx.Panel(self, -1) myVSizer = wx.BoxSizer(wx.VERTICAL) #instantiating a checkbox 200 px wide. but the label is too long cb = wx.CheckBox(self.panel, -1, label="This is a very very long label for 200 pixel wide cb!", size =wx.Size(200, -1)) myVSizer.Add( cb, 1) self.panel.SetSizer(myVSizer) myVSizer.Layout() app = wx.App(redirect=True) top = MyFrame() top.Show() app.MainLoop() </code></pre>
2
2009-09-23T13:52:06Z
1,495,895
<p>Instead of using checkbox with text, use a no label checkbox with static text for desired effect e.g.</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Hello World", size=(300,200)) self.panel = wx.Panel(self, -1) myVSizer = wx.BoxSizer(wx.VERTICAL) # use checkbox + static text to wrap the text myHSizer = wx.BoxSizer(wx.HORIZONTAL) cb = wx.CheckBox(self.panel, -1, label="") label = wx.StaticText(self.panel, label="This is a very very long label for 100 pixel wide cb!", size=(100,-1)) label.Wrap(100) myHSizer.Add(cb, border=5, flag=wx.ALL) myHSizer.Add(label, border=5, flag=wx.ALL) myVSizer.Add(myHSizer) self.panel.SetSizer(myVSizer) myVSizer.Layout() app = wx.App(redirect=True) top = MyFrame() top.Show() app.MainLoop() </code></pre> <p>this has added benefit that with different layouts you can make text centre to checkbox, or on left or right or any other place</p>
1
2009-09-30T02:53:43Z
[ "python", "wxpython" ]
multiline checkbox in wxpython
1,466,140
<p>I'm working with wxpython (2.8) with python 2.5. is it possible to force a wx.CheckBox to display its label on multiple lines? I'd like to be able to do the same as wx.StaticText.Wrap(width)</p> <p>See the attached example: the wx.CheckBox is 200 px wide, but it's label does not fit in this space.</p> <p>Any help is really appreciated! Thanks a lot Mauro</p> <pre><code>#example starts here import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Hello World", size= (300,200)) self.panel = wx.Panel(self, -1) myVSizer = wx.BoxSizer(wx.VERTICAL) #instantiating a checkbox 200 px wide. but the label is too long cb = wx.CheckBox(self.panel, -1, label="This is a very very long label for 200 pixel wide cb!", size =wx.Size(200, -1)) myVSizer.Add( cb, 1) self.panel.SetSizer(myVSizer) myVSizer.Layout() app = wx.App(redirect=True) top = MyFrame() top.Show() app.MainLoop() </code></pre>
2
2009-09-23T13:52:06Z
3,070,519
<p>what about something like this? Flex! (I've made it a radio button to show that it still behaves like one)</p> <pre><code>import wx import textwrap class MultilineRadioButton(wx.RadioButton): def __init__(self, parent, id=-1, label=wx.EmptyString, wrap=10, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name=wx.RadioButtonNameStr): wx.RadioButton.__init__(self,parent,id,'',pos,size,style,validator,name) self._label = label self._wrap = wrap lines = self._label.split('\n') self._wrappedLabel = [] for line in lines: self._wrappedLabel.extend(textwrap.wrap(line,self._wrap)) self._textHOffset = 20 dc = wx.ClientDC(self) font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) dc.SetFont(font) maxWidth = 0 totalHeight = 0 lineHeight = 0 for line in self._wrappedLabel: width, height = dc.GetTextExtent(line) maxWidth = max(maxWidth,width) lineHeight = height totalHeight += lineHeight self._textHeight = totalHeight self.SetInitialSize(wx.Size(self._textHOffset + maxWidth,totalHeight)) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnPaint(self, event): dc = wx.PaintDC(self) self.Draw(dc) self.RefreshRect(wx.Rect(0,0,self._textHOffset,self.GetSize().height)) event.Skip() def Draw(self, dc): dc.Clear() font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) dc.SetFont(font) height = self.GetSize().height if height &gt; self._textHeight: offset = height / 2 - self._textHeight / 2 else: offset = 0 for line in self._wrappedLabel: width, height = dc.GetTextExtent(line) dc.DrawText(line,self._textHOffset,offset) offset += height class HFrame(wx.Frame): def __init__(self,pos=wx.DefaultPosition): wx.Frame.__init__(self,None,title="Hello World",size=wx.Size(600,400),pos=pos) self.panel = wx.Panel(self,-1) sizer = wx.BoxSizer(wx.HORIZONTAL) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) self.panel.SetSizer(sizer) sizer.Layout() class VFrame(wx.Frame): def __init__(self,pos=wx.DefaultPosition): wx.Frame.__init__(self,None,title="Hello World",size=wx.Size(600,400),pos=pos) self.panel = wx.Panel(self,-1) sizer = wx.BoxSizer(wx.VERTICAL) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) self.panel.SetSizer(sizer) sizer.Layout() app = wx.App(redirect=False) htop = HFrame(pos=wx.Point(0,50)) htop.Show() vtop = VFrame(pos=wx.Point(650,50)) vtop.Show() app.MainLoop() </code></pre>
3
2010-06-18T14:37:26Z
[ "python", "wxpython" ]
how to rewrite this loop in a more efficient way in python
1,466,282
<p>I have a loop of the following type:</p> <pre><code>a = range(10) b = [something] for i in range(len(a)-1): b.append(someFunction(b[-1], a[i], a[i+1])) </code></pre> <p>However the for-loop is killing a lot of performance. I have try to write a windows generator to give me 2 elements everything time but it still require explicit for-loop in the end. Is there a way to make this shorter and more efficient in a pythonic way?</p> <p>Thanks</p> <p>edit: I forgot the element in b.. sorry guys. However the solution to my previous problem is very helpful in other problem I have too. Thanks.</p>
1
2009-09-23T14:18:23Z
1,466,312
<p>For your initially stated problem of mapping a function over pairs of an input sequence the following will work, and is about as efficient as it gets while staying in Python land.</p> <pre><code>from itertools import tee a = range(10) a1, a2 = tee(a) a2.next() b = map(someFunction, a1, a2) </code></pre> <p>As for the expanded problem where you need to access the result of the previous iteration - this kind of inner state is present in the functional concept unfold. But Python doesn't include an unfold construct, and for a good reason for loops are more readable in this case and most likely faster too. As for making it more Pythonic, I suggest lifting the pairwise iteration out to a function and create an explicit loop variable. </p> <pre><code>def pairwise(seq): a, b = tee(seq) b.next() return izip(a, b) def unfold_over_pairwise(unfolder, seq, initial): state = initial for cur_item, next_item in pairwise(seq): state = unfolder(state, cur_item, next_item) yield state b = [something] b.extend(unfold_over_pairwise(someFunction, a, initial=b[-1])) </code></pre> <p>If the looping overhead really is a problem, then someFunction must be something really simple. In that case it probably is best to write the whole loop in a faster language, such as C.</p>
4
2009-09-23T14:22:43Z
[ "python", "list", "list-comprehension" ]
how to rewrite this loop in a more efficient way in python
1,466,282
<p>I have a loop of the following type:</p> <pre><code>a = range(10) b = [something] for i in range(len(a)-1): b.append(someFunction(b[-1], a[i], a[i+1])) </code></pre> <p>However the for-loop is killing a lot of performance. I have try to write a windows generator to give me 2 elements everything time but it still require explicit for-loop in the end. Is there a way to make this shorter and more efficient in a pythonic way?</p> <p>Thanks</p> <p>edit: I forgot the element in b.. sorry guys. However the solution to my previous problem is very helpful in other problem I have too. Thanks.</p>
1
2009-09-23T14:18:23Z
1,466,344
<p>Consider this</p> <pre><code>def make_b( a, seed ): yield seed for a,b in zip( a[:-1], a[1:] ): seed= someFunction( seed, a, b ) yield seed </code></pre> <p>Which lets you do this</p> <pre><code>a = xrange(10) b= list(make_b(a,something)) </code></pre> <p>Note that you can often use this: </p> <pre><code>b = make_b(a) </code></pre> <p>Instead of actually creating <code>b</code> as a list. <code>b</code> as a generator function saves you considerable storage (and some time) because you may not really need a <code>list</code> object in the first place. Often, you only need something iterable.</p> <p>Similarly for <code>a</code>. It does not have to be a <code>list</code>, merely something iterable -- like a generator function with a <code>yield</code> statement.</p>
8
2009-09-23T14:27:06Z
[ "python", "list", "list-comprehension" ]
how to rewrite this loop in a more efficient way in python
1,466,282
<p>I have a loop of the following type:</p> <pre><code>a = range(10) b = [something] for i in range(len(a)-1): b.append(someFunction(b[-1], a[i], a[i+1])) </code></pre> <p>However the for-loop is killing a lot of performance. I have try to write a windows generator to give me 2 elements everything time but it still require explicit for-loop in the end. Is there a way to make this shorter and more efficient in a pythonic way?</p> <p>Thanks</p> <p>edit: I forgot the element in b.. sorry guys. However the solution to my previous problem is very helpful in other problem I have too. Thanks.</p>
1
2009-09-23T14:18:23Z
1,466,652
<p>Some loop or other will always be around, but one possibility that might reduce overhead is:</p> <pre><code>import itertools def generate(a, item): a1, a2 = itertools.tee(a) next(a2) for x1, x2 in itertools.izip(a1, a2): item = someFunction(item, x1, x2) yield item </code></pre> <p>to be used as:</p> <pre><code>b.extend(generate(a, b[-1])) </code></pre>
2
2009-09-23T15:14:36Z
[ "python", "list", "list-comprehension" ]
how to rewrite this loop in a more efficient way in python
1,466,282
<p>I have a loop of the following type:</p> <pre><code>a = range(10) b = [something] for i in range(len(a)-1): b.append(someFunction(b[-1], a[i], a[i+1])) </code></pre> <p>However the for-loop is killing a lot of performance. I have try to write a windows generator to give me 2 elements everything time but it still require explicit for-loop in the end. Is there a way to make this shorter and more efficient in a pythonic way?</p> <p>Thanks</p> <p>edit: I forgot the element in b.. sorry guys. However the solution to my previous problem is very helpful in other problem I have too. Thanks.</p>
1
2009-09-23T14:18:23Z
1,467,322
<p>Try something like this:</p> <pre><code>a = range(10) b = [something] s = len(b) b+= [0] * (len(a) - 1) [ b.__setitem__(i, someFunction(b[i-1], a[i-s], a[i-s+1])) for i in range(s, len(b))] </code></pre> <p>Also:</p> <ul> <li>using functions from itertools should be useful also (earlier posts)</li> <li>maybe you can rewrite someFunction and use map instead of list comprehension</li> </ul>
0
2009-09-23T16:58:08Z
[ "python", "list", "list-comprehension" ]
Python gzip folder structure when zipping single file
1,466,287
<p>I'm using Python's gzip module to gzip content for a single file, using code similar to the example in the docs:</p> <pre><code>import gzip content = "Lots of content here" f = gzip.open('/home/joe/file.txt.gz', 'wb') f.write(content) f.close() </code></pre> <p>If I open the gz file in 7-zip, I see a folder hierarchy matching the path I wrote the gz to and my content is nested several folders deep, like /home/joe in the example above, or C: -> Documents and Settings -> etc in Windows.</p> <p>How can I get the one file that I'm zipping to just be in the root of the gz file?</p>
4
2009-09-23T14:18:58Z
1,466,335
<p>Why not just open the file without specifying a directory hierarchy (just do gzip.open("file.txt.gz"))?. Seems to me like that works. You can always copy the file to another location, if you need to.</p>
0
2009-09-23T14:25:35Z
[ "python", "gzip", "folders" ]
Python gzip folder structure when zipping single file
1,466,287
<p>I'm using Python's gzip module to gzip content for a single file, using code similar to the example in the docs:</p> <pre><code>import gzip content = "Lots of content here" f = gzip.open('/home/joe/file.txt.gz', 'wb') f.write(content) f.close() </code></pre> <p>If I open the gz file in 7-zip, I see a folder hierarchy matching the path I wrote the gz to and my content is nested several folders deep, like /home/joe in the example above, or C: -> Documents and Settings -> etc in Windows.</p> <p>How can I get the one file that I'm zipping to just be in the root of the gz file?</p>
4
2009-09-23T14:18:58Z
1,466,434
<p>You must use <a href="http://docs.python.org/library/gzip.html" rel="nofollow"><code>gzip.GzipFile</code></a> and supply a <code>fileobj</code>. If you do that, you can specify an arbitrary filename for the header of the gz file.</p>
2
2009-09-23T14:40:19Z
[ "python", "gzip", "folders" ]
Python gzip folder structure when zipping single file
1,466,287
<p>I'm using Python's gzip module to gzip content for a single file, using code similar to the example in the docs:</p> <pre><code>import gzip content = "Lots of content here" f = gzip.open('/home/joe/file.txt.gz', 'wb') f.write(content) f.close() </code></pre> <p>If I open the gz file in 7-zip, I see a folder hierarchy matching the path I wrote the gz to and my content is nested several folders deep, like /home/joe in the example above, or C: -> Documents and Settings -> etc in Windows.</p> <p>How can I get the one file that I'm zipping to just be in the root of the gz file?</p>
4
2009-09-23T14:18:58Z
1,466,443
<p>It looks like you will have to use <code>GzipFile</code> directly: </p> <pre><code>import gzip content = "Lots of content here" real_f = open('/home/joe/file.txt.gz', 'wb') f = gzip.GZipFile('file.txt.gz', fileobj = realf) f.write(content) f.close() real_f.close() </code></pre> <p>It looks like <code>open</code> doesn't allow you to specify the fileobj separate from the filename.</p>
10
2009-09-23T14:41:12Z
[ "python", "gzip", "folders" ]
Python gzip folder structure when zipping single file
1,466,287
<p>I'm using Python's gzip module to gzip content for a single file, using code similar to the example in the docs:</p> <pre><code>import gzip content = "Lots of content here" f = gzip.open('/home/joe/file.txt.gz', 'wb') f.write(content) f.close() </code></pre> <p>If I open the gz file in 7-zip, I see a folder hierarchy matching the path I wrote the gz to and my content is nested several folders deep, like /home/joe in the example above, or C: -> Documents and Settings -> etc in Windows.</p> <p>How can I get the one file that I'm zipping to just be in the root of the gz file?</p>
4
2009-09-23T14:18:58Z
9,304,710
<p>If you set your current working directory to your output folder, you can then call gzip.open("file.txt.gz") and the gz file will be created without the hierarchy</p> <pre><code>import os import gzip content = "Lots of content here" outputPath = '/home/joe/file.txt.gz' origDir = os.getcwd() os.chdir(os.path.dirname(outputPath)) f = gzip.open(os.path.basename(outputPath), 'wb') f.write(content) f.close() os.chdir(origDir) </code></pre>
0
2012-02-16T02:32:54Z
[ "python", "gzip", "folders" ]
Problem when getting the content of a listbox with python and ctypes on win32
1,466,453
<p>I would like to get the content of a list box thanks to python and ctypes. </p> <pre><code>item_count = ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETCOUNT, 0, 0) items = [] for i in xrange(item_count): text_len = ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETTEXTLEN, i, 0) buffer = ctypes.create_string_buffer("", text_len+1) ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETTEXT, i, buffer) items.append(buffer.value) print items </code></pre> <p>The number of items is correct but the text is wrong. All text_len are 4 and the text values are something like '0\xd9\xee\x02\x90'</p> <p>I have tried to use a unicode buffer with a similar result.</p> <p>I don't find my error. Any idea? </p>
0
2009-09-23T14:42:35Z
1,466,556
<p>It looks like you need to use a packed structure for the result. I found an example online, perhaps this will assist you:</p> <p><a href="http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html" rel="nofollow">http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html</a></p> <pre><code># Programmer : Simon Brunning - simon@brunningonline.net # Date : 25 June 2003 def _getMultipleWindowValues(hwnd, getCountMessage, getValueMessage): '''A common pattern in the Win32 API is that in order to retrieve a series of values, you use one message to get a count of available items, and another to retrieve them. This internal utility function performs the common processing for this pattern. Arguments: hwnd Window handle for the window for which items should be retrieved. getCountMessage Item count message. getValueMessage Value retrieval message. Returns: Retrieved items.''' result = [] VALUE_LENGTH = 256 bufferlength_int = struct.pack('i', VALUE_LENGTH) # This is a C style int. valuecount = win32gui.SendMessage(hwnd, getCountMessage, 0, 0) for itemIndex in range(valuecount): valuebuffer = array.array('c', bufferlength_int + " " * (VALUE_LENGTH - len(bufferlength_int))) valueLength = win32gui.SendMessage(hwnd, getValueMessage, itemIndex, valuebuffer) result.append(valuebuffer.tostring()[:valueLength]) return result def getListboxItems(hwnd): '''Returns the items in a list box control. Arguments: hwnd Window handle for the list box. Returns: List box items. Usage example: TODO ''' return _getMultipleWindowValues(hwnd, getCountMessage=win32con.LB_GETCOUNT, getValueMessage=win32con.LB_GETTEXT) </code></pre>
0
2009-09-23T14:56:27Z
[ "python", "winapi", "ctypes" ]
Problem when getting the content of a listbox with python and ctypes on win32
1,466,453
<p>I would like to get the content of a list box thanks to python and ctypes. </p> <pre><code>item_count = ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETCOUNT, 0, 0) items = [] for i in xrange(item_count): text_len = ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETTEXTLEN, i, 0) buffer = ctypes.create_string_buffer("", text_len+1) ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETTEXT, i, buffer) items.append(buffer.value) print items </code></pre> <p>The number of items is correct but the text is wrong. All text_len are 4 and the text values are something like '0\xd9\xee\x02\x90'</p> <p>I have tried to use a unicode buffer with a similar result.</p> <p>I don't find my error. Any idea? </p>
0
2009-09-23T14:42:35Z
1,466,557
<p>If the list box in question is owner-drawn, this passage from the <a href="http://msdn.microsoft.com/en-us/library/bb761313%28VS.85%29.aspx" rel="nofollow">LB_GETTEXT</a> documentation may be relevant:</p> <blockquote> <p>If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the buffer pointed to by the lParam parameter will receive the value associated with the item (the item data).</p> </blockquote> <p>The four bytes you received certainly look like they may be a pointer, which is a typical value to store in the per-item data.</p>
1
2009-09-23T14:56:42Z
[ "python", "winapi", "ctypes" ]
Create a wrapper class to call a pre and post function around existing functions?
1,466,676
<p>I want to create a class that wraps another class so that when a function is run through the wrapper class a pre and post function is run as well. I want the wrapper class to work with any class without modification.</p> <p>For example if i have this class.</p> <pre><code>class Simple(object): def one(self): print "one" def two(self,two): print "two" + two def three(self): print "three" </code></pre> <p>I could use it like this...</p> <pre><code>number = Simple() number.one() number.two("2") </code></pre> <p>I have so far written this wrapper class...</p> <pre><code>class Wrapper(object): def __init__(self,wrapped_class): self.wrapped_class = wrapped_class() def __getattr__(self,attr): return self.wrapped_class.__getattribute__(attr) def pre(): print "pre" def post(): print "post" </code></pre> <p>Which I can call like this...</p> <pre><code>number = Wrapper(Simple) number.one() number.two("2") </code></pre> <p>Which can be used the same as above apart from changing the first line.</p> <p>What I want to happen is when calling a function through the wrapper class the pre function in the wrapper class gets called then the desired function in the wrapped class then the post function. I want to be able to do this without changing the wrapped class and also without changing the way the functions are called, only changing the syntax of how the instance of the class is created. eg number = Simple() vs number = Wrapper(Simple)</p>
6
2009-09-23T15:19:05Z
1,467,296
<p>You're almost there, you just need to do some introspection inside <code>__getattr__</code>, returning a new wrapped function when the original attribute is callable:</p> <pre><code>class Wrapper(object): def __init__(self,wrapped_class): self.wrapped_class = wrapped_class() def __getattr__(self,attr): orig_attr = self.wrapped_class.__getattribute__(attr) if callable(orig_attr): def hooked(*args, **kwargs): self.pre() result = orig_attr(*args, **kwargs) # prevent wrapped_class from becoming unwrapped if result == self.wrapped_class: return self self.post() return result return hooked else: return orig_attr def pre(self): print "&gt;&gt; pre" def post(self): print "&lt;&lt; post" </code></pre> <p>Now with this code:</p> <pre><code>number = Wrapper(Simple) print "\nCalling wrapped 'one':" number.one() print "\nCalling wrapped 'two':" number.two("2") </code></pre> <p>The result is:</p> <pre><code>Calling wrapped 'one': &gt;&gt; pre one &lt;&lt; post Calling wrapped 'two': &gt;&gt; pre two2 &lt;&lt; post </code></pre>
12
2009-09-23T16:52:33Z
[ "python" ]
Create a wrapper class to call a pre and post function around existing functions?
1,466,676
<p>I want to create a class that wraps another class so that when a function is run through the wrapper class a pre and post function is run as well. I want the wrapper class to work with any class without modification.</p> <p>For example if i have this class.</p> <pre><code>class Simple(object): def one(self): print "one" def two(self,two): print "two" + two def three(self): print "three" </code></pre> <p>I could use it like this...</p> <pre><code>number = Simple() number.one() number.two("2") </code></pre> <p>I have so far written this wrapper class...</p> <pre><code>class Wrapper(object): def __init__(self,wrapped_class): self.wrapped_class = wrapped_class() def __getattr__(self,attr): return self.wrapped_class.__getattribute__(attr) def pre(): print "pre" def post(): print "post" </code></pre> <p>Which I can call like this...</p> <pre><code>number = Wrapper(Simple) number.one() number.two("2") </code></pre> <p>Which can be used the same as above apart from changing the first line.</p> <p>What I want to happen is when calling a function through the wrapper class the pre function in the wrapper class gets called then the desired function in the wrapped class then the post function. I want to be able to do this without changing the wrapped class and also without changing the way the functions are called, only changing the syntax of how the instance of the class is created. eg number = Simple() vs number = Wrapper(Simple)</p>
6
2009-09-23T15:19:05Z
1,470,892
<p>I have just noticed in my original design there is no way of passing args and kwargs to the wrapped class, here is the answer updated to pass the inputs to the wrapped function...</p> <pre><code>class Wrapper(object): def __init__(self,wrapped_class,*args,**kargs): self.wrapped_class = wrapped_class(*args,**kargs) def __getattr__(self,attr): orig_attr = self.wrapped_class.__getattribute__(attr) if callable(orig_attr): def hooked(*args, **kwargs): self.pre() result = orig_attr(*args, **kwargs) self.post() return result return hooked else: return orig_attr def pre(self): print "&gt;&gt; pre" def post(self): print "&lt;&lt; post" </code></pre>
1
2009-09-24T10:42:59Z
[ "python" ]
Testing for cookie existence in Django
1,466,732
<p>Simple stuff here...</p> <p>if I try to reference a cookie in Django via</p> <pre><code>request.COOKIE["key"] </code></pre> <p>if the cookie doesn't exist that will throw a key error.</p> <p>For Django's <code>GET</code> and <code>POST</code>, since they are <code>QueryDict</code> objects, I can just do</p> <pre><code>if "foo" in request.GET </code></pre> <p>which is wonderfully sophisticated...</p> <p>what's the closest thing to this for cookies that isn't a Try/Catch block, if anything...</p>
2
2009-09-23T15:26:44Z
1,467,051
<p>First, it's </p> <pre><code>request.COOKIES </code></pre> <p>not <code>request.COOKIE</code>. Other one will throw you an error.</p> <p>Second, it's a dictionary (or, dictionary-like) object, so:</p> <pre><code>if "foo" in request.COOKIES.keys() </code></pre> <p>will give you what you need. If you want to get the value of the cookie, you can use:</p> <pre><code>request.COOKIES.get("key", None) </code></pre> <p>then, if there's no key <code>"key"</code>, you'll get a <code>None</code> instead of an exception.</p>
5
2009-09-23T16:13:08Z
[ "python", "django", "http", "cookies" ]
Testing for cookie existence in Django
1,466,732
<p>Simple stuff here...</p> <p>if I try to reference a cookie in Django via</p> <pre><code>request.COOKIE["key"] </code></pre> <p>if the cookie doesn't exist that will throw a key error.</p> <p>For Django's <code>GET</code> and <code>POST</code>, since they are <code>QueryDict</code> objects, I can just do</p> <pre><code>if "foo" in request.GET </code></pre> <p>which is wonderfully sophisticated...</p> <p>what's the closest thing to this for cookies that isn't a Try/Catch block, if anything...</p>
2
2009-09-23T15:26:44Z
1,467,053
<p><code>request.COOKIES</code> is a standard Python dictionary, so the same syntax works.</p> <p>Another way of doing it is:</p> <pre><code>request.COOKIES.get('key', 'default') </code></pre> <p>which returns the value if the key exists, otherwise 'default' - you can put anything you like in place of 'default'.</p>
17
2009-09-23T16:13:23Z
[ "python", "django", "http", "cookies" ]
Parameterized queries with psycopg2 / Python DB-API and PostgreSQL
1,466,741
<p>What's the best way to make psycopg2 pass parameterized queries to PostgreSQL? I don't want to write my own escpaing mechanisms or adapters and the psycopg2 source code and examples are difficult to read in a web browser.</p> <p>If I need to switch to something like PyGreSQL or another python pg adapter, that's fine with me. I just want simple parameterization.</p>
23
2009-09-23T15:28:13Z
1,467,978
<p>Here are a few examples you might find helpful</p> <pre><code>cursor.execute('SELECT * from table where id = %(some_id)d', {'some_id': 1234}) </code></pre> <p>Or you can dynamically build your query based on a dict of field name, value:</p> <pre><code>fields = ', '.join(my_dict.keys()) values = ', '.join(['%%(%s)s' % x for x in my_dict]) query = 'INSERT INTO some_table (%s) VALUES (%s)' % (fields, values) cursor.execute(query, my_dict) </code></pre> <p>Note: the fields must be defined in your code, <strong>not</strong> user input, otherwise you will be susceptible to SQL injection.</p>
9
2009-09-23T18:59:40Z
[ "python", "postgresql", "psycopg2" ]
Parameterized queries with psycopg2 / Python DB-API and PostgreSQL
1,466,741
<p>What's the best way to make psycopg2 pass parameterized queries to PostgreSQL? I don't want to write my own escpaing mechanisms or adapters and the psycopg2 source code and examples are difficult to read in a web browser.</p> <p>If I need to switch to something like PyGreSQL or another python pg adapter, that's fine with me. I just want simple parameterization.</p>
23
2009-09-23T15:28:13Z
1,471,178
<p><code>psycopg2</code> follows the rules for DB-API 2.0 (set down in <a href="http://www.python.org/dev/peps/pep-0249/">PEP-249</a>). That means you can call <code>execute</code> method from your <code>cursor</code> object and use the <code>pyformat</code> binding style, and it will do the escaping for you. For example, the following <em>should</em> be safe (and work):</p> <pre><code>cursor.execute("SELECT * FROM student WHERE last_name = %(lname)s", {"lname": "Robert'); DROP TABLE students;--"}) </code></pre>
45
2009-09-24T11:47:49Z
[ "python", "postgresql", "psycopg2" ]
Parameterized queries with psycopg2 / Python DB-API and PostgreSQL
1,466,741
<p>What's the best way to make psycopg2 pass parameterized queries to PostgreSQL? I don't want to write my own escpaing mechanisms or adapters and the psycopg2 source code and examples are difficult to read in a web browser.</p> <p>If I need to switch to something like PyGreSQL or another python pg adapter, that's fine with me. I just want simple parameterization.</p>
23
2009-09-23T15:28:13Z
32,743,279
<p>From the psycopg documentation</p> <p>(<a href="http://initd.org/psycopg/docs/usage.html" rel="nofollow">http://initd.org/psycopg/docs/usage.html</a>)</p> <blockquote> <blockquote> <p>Warning Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.</p> </blockquote> <p>The correct way to pass variables in a SQL command is using the second argument of the execute() method:</p> <p><code>SQL = "INSERT INTO authors (name) VALUES (%s);" # Note: no quotes</code></p> <p><code>data = ("O'Reilly", )</code></p> <p><code>cur.execute(SQL, data) # Note: no % operator</code></p> </blockquote>
3
2015-09-23T15:11:13Z
[ "python", "postgresql", "psycopg2" ]
Can SAP work with Python?
1,466,917
<p>Can Python be used to query a SAP database?</p>
15
2009-09-23T15:55:23Z
1,467,136
<p><a href="http://pysaprfc.sourceforge.net/">Python SAP RFC module</a> seems inactive - <a href="http://pysaprfc.cvs.sourceforge.net/viewvc/pysaprfc/pysaprfc/">last (insignificant ) commit</a> 2 years ago - but may serve you:</p> <blockquote> <p>Pysaprfc is a wrapper around SAP librfc (librfc32.dll on Windows, librfccm.so or librfc.so on Linux). It uses the excellent ctypes extension package by Thomas Heller to access librfc and to define SAP compatible datatypes. </p> </blockquote> <p>Modern SAP versions go the <a href="http://www.sdn.sap.com/irj/sdn/webservices"><code>Web Service</code> way</a> - you could build a <code>SAP Web Service</code> and consume it from <code>Python</code>.</p> <blockquote> <p>With SAP NetWeaver, developers can connect applications and data sources to integrate processes using Web services.</p> <p>In particular, developers can use one infrastructure to define, implement, and use Web services in an industry standards based way. SAP NetWeaver supports synchronous, asynchronous, stateful and stateless web service models - enabling developers to support different integration scenarios.</p> </blockquote> <p><a href="http://www.piersharding.com/download/python/sapnwrfc/"><code>sapnwrfc</code></a> supports this <code>SAP NetWeaver</code> functionality, <a href="http://pypi.python.org/pypi/sapnwrfc/">supersedes</a> the older RFC SDK, and is actively maintained.</p>
15
2009-09-23T16:24:26Z
[ "python", "sap", "abap" ]
Can SAP work with Python?
1,466,917
<p>Can Python be used to query a SAP database?</p>
15
2009-09-23T15:55:23Z
1,467,921
<p>Sap is NOT a database server. But with the Python SAP RFC module you can query most table quite easily. It is using some sap unsupported function ( that all the world is using). And this function has some limitation on field size and datatypes.</p>
4
2009-09-23T18:49:28Z
[ "python", "sap", "abap" ]
Can SAP work with Python?
1,466,917
<p>Can Python be used to query a SAP database?</p>
15
2009-09-23T15:55:23Z
1,468,422
<p>If you're talking about (what used to be named) the SAP Database AKA <a href="http://www.sapdb.org/">SapDb</a>, and is now <a href="http://www.sapdb.org/">MaxDB</a> (for a while distributed also by MySql Inc, <a href="http://www.sdn.sap.com/irj/scn/weblogs;jsessionid=%28J2EE3414800%29ID1243106650DB12715359355348892918End?blog=/pub/wlg/7514">now</a> again by SAP only -- and so named <a href="http://www.sdn.sap.com/irj/sdn/maxdb;jsessionid=%28J2EE3414800%29ID1243106650DB12715359355348892918End">SAP MaxDB</a>), it comes with several Python access modules, documented <a href="http://maxdb.sap.com/doc/7%5F7/46/71b2a516ae0284e10000000a1553f6/frameset.htm">here</a>.</p> <p>This is the only meaning I can attach to "SAP as the database engine" -- that you want to access SAP MaxDB. Other answers make different assumptions and (I believe) are also correct... under those different assumptions.</p>
5
2009-09-23T20:45:05Z
[ "python", "sap", "abap" ]
Can SAP work with Python?
1,466,917
<p>Can Python be used to query a SAP database?</p>
15
2009-09-23T15:55:23Z
1,524,563
<p>As stated above, when you just want to read tables or do RFC or BAPI calls, you can use CPython with the unmaintained Python SAP RFC module or Piers Harding's <a href="http://pypi.python.org/pypi/saprfc/" rel="nofollow">SAP RFC</a>. The RFC calls to just read a table are RFC_GET_TABLE_ENTRIES or RFC_READ_TABLE, where the former is preferred, but also not released to customers.</p> <p>For a more official way, you can use SAP's JCO connector with Jython or SAP's .Net Connector with Ironpython; both connectors can be downloaded from SAP's service marketplace and both allow to call the RFC functionality including the two calls listed above.</p> <p>As also stated above, the way proposed by SAP to access backend functionality is via SAP's vast SOA infrastructure. Here you can use Jython with e.g. the Axis library or Ironpython with Microsofts WCF. Note, that the services provided by SAP obviously won't allow you to access the plain tables, instead you just can call, what a service provides. SAP already delivers about 3.000 services (see the ES Wiki on SDN), and creating your own service is in fact dead simple, once you have your business logic in a remote-enabled function module.</p>
2
2009-10-06T09:35:18Z
[ "python", "sap", "abap" ]
Can SAP work with Python?
1,466,917
<p>Can Python be used to query a SAP database?</p>
15
2009-09-23T15:55:23Z
13,127,357
<p>Python RFC connector is now available as SAP open source <a href="https://github.com/SAP/PyRFC">https://github.com/SAP/PyRFC</a></p>
9
2012-10-29T18:14:39Z
[ "python", "sap", "abap" ]
Can SAP work with Python?
1,466,917
<p>Can Python be used to query a SAP database?</p>
15
2009-09-23T15:55:23Z
31,300,609
<p>SAP now has a Python RFC connector called pyrfc. This supersedes sapnwrfc.</p> <p>This can be found at: <a href="https://github.com/SAP/PyRFC" rel="nofollow">https://github.com/SAP/PyRFC</a></p> <p>"The pyrfc Python package provides Python bindings for SAP NetWeaver RFC Library, for a comfortable way of calling ABAP modules from Python and Python modules from ABAP, via SAP Remote Function Call (RFC) protocol."</p>
2
2015-07-08T18:19:44Z
[ "python", "sap", "abap" ]
Django models - pass additional information to manager
1,467,245
<p>I'm trying to implement row-based security checks for Django models. The idea is that when I access model manager I specify some additional info which is used in database queries so that only allowed instances are fetched from database.</p> <p>For example, we can have two models: Users and, say, Items. Each Item belongs to some User and User may be connected to many Items. And let there be some restrictions, according to which a user may see or may not see Items of another User. I want to separate this restrictions from other query elements and write something like:</p> <pre><code>items = Item.scoped.forceRule('user1').all() # all items visible for 'user1' </code></pre> <p>or</p> <pre><code># show all items of 'user2' visible by 'user1' items = Item.scoped.forceRule('user1').filter(author__username__exact = 'user2') </code></pre> <p>To acheive this I made following:</p> <pre><code>class SecurityManager(models.Manager): def forceRule(self, onBehalf) : modelSecurityScope = getattr(self.model, 'securityScope', None) if modelSecurityScope : return super(SecurityManager, self).get_query_set().filter(self.model.securityScope(onBehalf)) else : return super(SecurityManager, self).get_query_set() def get_query_set(self) : # # I need to know that 'onBehalf' parameter here # return super(SecurityManager, self).get_query_set() class User(models.Model) : username = models.CharField(max_length=32, unique=True) class Item(models.Model) : author = models.ForeignKey(User) private = models.BooleanField() name = models.CharField(max_length=32) scoped = SecurityManager() @staticmethod def securityScope(onBehalf) : return Q(author__username__exact = onBehalf) | Q(bookmark__private__exact = False) </code></pre> <p>For shown examples it works fine, but dies on following:</p> <pre><code>items = Item.scoped.forceRule('user1').filter(author__username__exact = 'user2') # (*) items2 = items[0].author.item_set.all() # (**) </code></pre> <p>Certainly, <code>items2</code> is populated by all items of 'user2', not only those which conform the rule. That is because when all() is executed <code>SecurityManager.get_query_set()</code> has no information about the restriction set. Though it could. For example, in forceRule() I could add a field for every instance and then, if I could access that field from manager, apply the rule needed.</p> <p>So, the question is - is there any way to pass an argument provided to <code>forceRule()</code> in statement <code>(*)</code> to manager, called in statement <code>(**)</code>.</p> <p>Or another question - am I doing strange things that I shouldn't do at all?</p> <p>Thank you.</p>
8
2009-09-23T16:44:07Z
1,471,512
<p>From my reading of the documentation I think there are two problems:</p> <ol> <li>The SecurityManager will not be used for the related objects (and instance of django.db.models.Manager will be used instead)</li> <li>You can fix the above, but the documentation goes to great <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#do-not-filter-away-any-results-in-this-type-of-manager-subclass" rel="nofollow">lengths</a> to specify that get_query_set() should not filter out any rows for related queries.</li> </ol> <p>I suggest creating a function that takes a QuerySet and applies the filter you need to it. This can then be used whenever you get to a QS of Items and want to process them further.</p>
4
2009-09-24T12:54:31Z
[ "python", "django", "django-models" ]
Are python modules first class citizens?
1,467,612
<p>I mean, can I create them dynamically?</p>
6
2009-09-23T17:56:19Z
1,467,633
<p>You can create them dynamically, with the <a href="http://docs.python.org/library/imp.html#imp.new%5Fmodule">imp.new_module</a> method.</p>
5
2009-09-23T17:59:11Z
[ "python", "module" ]
Are python modules first class citizens?
1,467,612
<p>I mean, can I create them dynamically?</p>
6
2009-09-23T17:56:19Z
1,467,635
<p>Yes:</p> <pre><code>&gt;&gt;&gt; import types &gt;&gt;&gt; m = types.ModuleType("mymod") &gt;&gt;&gt; m &lt;module 'mymod' (built-in)&gt; </code></pre>
9
2009-09-23T17:59:30Z
[ "python", "module" ]
django registration module
1,467,735
<p>i started to learn django using the official documentation tutorial and in turn created this registration form. i have the whole app setup but am stuck at how to process the data. i mean the documentation is a little tough to understand. if i can get some help, it would be great.</p> <p>this is how the models are setup:</p> <pre><code>class user (models.Model): username = models.CharField(max_length=20) name = models.CharField(max_length=25) collegename = models.CharField(max_length=50) event = models.CharField(max_length=30) col_roll = models.CharField(max_length=15) def __unicode__(self): return self.username </code></pre> <p>and this is the form in index.html:</p> <pre><code>&lt;form action="" method="post"&gt;&lt;/form&gt; &lt;input name="username" type="text" maxlength="40" /&gt; &lt;input name="name" type="text" maxlength="40" /&gt; &lt;input name="collegename" type="text" maxlength="40" /&gt; &lt;input name="event" type="text" maxlength="40" /&gt; &lt;input name="col_roll" type="text" maxlength="40" /&gt; &lt;input type="submit" value="Register" /&gt; &lt;/form&gt; </code></pre> <p>i do not follow how to create the view to process this registration of a new user. if anybody could help me, it would be great. The database (MySQL) is created with the name (register_user). I do not understand how to put the values from the above form in to the database. If it would have been regular python, it would have been easily done, but DJANGO i dont understand. </p> <p>Thanks a lot.</p>
0
2009-09-23T18:17:31Z
1,467,766
<p>You don't seem to have read the <a href="http://docs.djangoproject.com/en/dev/topics/forms/" rel="nofollow">documentation on forms</a>. It explains in detail how to create a form from your model, how to output it in a template (so you don't need to write the HTML input elements manually), and how to process it in a view.</p>
1
2009-09-23T18:23:20Z
[ "python", "mysql", "django" ]
django registration module
1,467,735
<p>i started to learn django using the official documentation tutorial and in turn created this registration form. i have the whole app setup but am stuck at how to process the data. i mean the documentation is a little tough to understand. if i can get some help, it would be great.</p> <p>this is how the models are setup:</p> <pre><code>class user (models.Model): username = models.CharField(max_length=20) name = models.CharField(max_length=25) collegename = models.CharField(max_length=50) event = models.CharField(max_length=30) col_roll = models.CharField(max_length=15) def __unicode__(self): return self.username </code></pre> <p>and this is the form in index.html:</p> <pre><code>&lt;form action="" method="post"&gt;&lt;/form&gt; &lt;input name="username" type="text" maxlength="40" /&gt; &lt;input name="name" type="text" maxlength="40" /&gt; &lt;input name="collegename" type="text" maxlength="40" /&gt; &lt;input name="event" type="text" maxlength="40" /&gt; &lt;input name="col_roll" type="text" maxlength="40" /&gt; &lt;input type="submit" value="Register" /&gt; &lt;/form&gt; </code></pre> <p>i do not follow how to create the view to process this registration of a new user. if anybody could help me, it would be great. The database (MySQL) is created with the name (register_user). I do not understand how to put the values from the above form in to the database. If it would have been regular python, it would have been easily done, but DJANGO i dont understand. </p> <p>Thanks a lot.</p>
0
2009-09-23T18:17:31Z
1,467,866
<p>It took me a bit of time to figure out the form processing bit when I started. The first thing you need before you get to the form part is to create a <a href="http://docs.djangoproject.com/en/dev/intro/tutorial03/#intro-tutorial03" rel="nofollow">view function</a>. The view will use your index.html file as a template. In that view you'll want to create a form (either from Daniel's link above or by <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/" rel="nofollow">creating a form from your model</a>). Once you have a form class, provide an instantiated copy of that in the view (e.g., form = MyRegistrationModelForm()) and then replace all of your input tags in index.html with {{ form }}. That will output a pre-formatted form, which may not be exactly what you want, but you can then view source and see what the form fields need to be named and then you can customize from there.</p> <p>One other thing. Not sure if you are, but you should be using <a href="http://bitbucket.org/ubernostrum/django-registration/wiki/Home" rel="nofollow">django-registration</a> for this. Rather than creating your own user class, use the built-in User class in django.contrib.auth.models and then use django-registration for the custom fields you need. You'll be able to plug in other modules much more easily if you use the defined User class.</p> <p>As for the database, assuming you have put the proper MySQL connection information into settings.py, running 'python manage.py syncdb' in the root of your project should create all the necessary tables. Make sure to re-run it as you add new models.</p>
0
2009-09-23T18:38:34Z
[ "python", "mysql", "django" ]
How do i make Pydev + jython to startup faster when running a script?
1,467,827
<p>i'm working with pydev + jython.great ide , but quite slow when i try to run a jython program. this is probably something due to libraries load time.</p> <p>What can i do to speed it up ?</p> <p>Thanks , yaniv</p>
3
2009-09-23T18:31:32Z
1,849,587
<p>If you have a machine with more than one processor you could try starting eclipse/pydev with the options <code>-vmargs -XX:+UseParallelGC</code> You could also try different JVMs to see if any of them give better performance.</p>
1
2009-12-04T20:51:30Z
[ "python", "jython", "pydev" ]
How do i make Pydev + jython to startup faster when running a script?
1,467,827
<p>i'm working with pydev + jython.great ide , but quite slow when i try to run a jython program. this is probably something due to libraries load time.</p> <p>What can i do to speed it up ?</p> <p>Thanks , yaniv</p>
3
2009-09-23T18:31:32Z
1,902,449
<p>Jython startup time is slow ... there's a lot to bootup!</p> <p>Everytime you run a Jython script from scratch, it will incur the same Jython startup time cost.</p> <p>Hence, the reason Jython, Java, and Python are not great for CGI invocations. Hence, the reason for mod_python in Apache.</p> <p>The key is to start-up Jython once and reuse it. But this is not always possible especially during development because your modules are always changing and Jython does not recognize these changes automatically.</p> <p>Jython needs a way to know which modules have changed for automatic reloads. This is not built into Jython and you'll have to rely on some other third party library to help with this. The concept is to remove from 'sys.modules' the modules which have changed. A simple solution is to just clear all the modules from sys.modules - which will cause all modules to be reloaded. This is obviously, not the most efficient solution.</p> <p>Another tip is to only import modules that your module needs at the time that it 'really' needs them. If you import every module at the top of your modules, that will increase your module import cost. So, refactor imports to within methods/functions where they are needed and where it 'makes sense'. Of course, if your method/function is computation heavy and is used frequently, it does not make sence to import modules within that method/function.</p> <p>Hopefully, that helps you out!</p>
2
2009-12-14T18:00:32Z
[ "python", "jython", "pydev" ]