title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python element-wise tuple operations like sum | 497,885 | 52 | 2009-01-31T00:51:48Z | 497,931 | 18 | 2009-01-31T01:10:18Z | [
"python",
"tuples"
] | Is there anyway to get tuple operations in Python to work like this:
```
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
```
instead of:
```
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
```
I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only ... | Sort of combined the first two answers, with a tweak to ironfroggy's code so that it returns a tuple:
```
import operator
class stuple(tuple):
def __add__(self, other):
return self.__class__(map(operator.add, self, other))
# obviously leaving out checking lengths
>>> a = stuple([1,2,3])
>>> b = s... |
Python element-wise tuple operations like sum | 497,885 | 52 | 2009-01-31T00:51:48Z | 498,103 | 58 | 2009-01-31T02:49:16Z | [
"python",
"tuples"
] | Is there anyway to get tuple operations in Python to work like this:
```
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
```
instead of:
```
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
```
I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only ... | Using all built-ins..
```
tuple(map(sum, zip(a, b))
``` |
Python element-wise tuple operations like sum | 497,885 | 52 | 2009-01-31T00:51:48Z | 499,696 | 13 | 2009-01-31T22:25:06Z | [
"python",
"tuples"
] | Is there anyway to get tuple operations in Python to work like this:
```
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
```
instead of:
```
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
```
I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only ... | ```
from numpy import *
a = array( [1,2,3] )
b = array( [3,2,1] )
print a + b
```
gives `array([4,4,4])`.
See <http://www.scipy.org/Tentative_NumPy_Tutorial> |
Python element-wise tuple operations like sum | 497,885 | 52 | 2009-01-31T00:51:48Z | 12,702,871 | 23 | 2012-10-03T06:20:20Z | [
"python",
"tuples"
] | Is there anyway to get tuple operations in Python to work like this:
```
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
```
instead of:
```
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
```
I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only ... | This solution doesn't require an import:
```
tuple(map(lambda x, y: x + y, tuple1, tuple2))
``` |
How to make python gracefully fail? | 497,952 | 13 | 2009-01-31T01:22:08Z | 497,960 | 8 | 2009-01-31T01:26:01Z | [
"python"
] | I was just wondering how do you make python fail in a user defined way in all possible errors.
For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the ... | The ugly error message means that an exception is raised. You need to catch the exception.
A good place to start is the [Python tutorial's section on exceptions.](http://docs.python.org/tutorial/errors.html)
Basically you need to wrap your code in a `try...except` block like this:
```
try:
do_something_dangerous... |
How to make python gracefully fail? | 497,952 | 13 | 2009-01-31T01:22:08Z | 498,038 | 23 | 2009-01-31T02:01:10Z | [
"python"
] | I was just wondering how do you make python fail in a user defined way in all possible errors.
For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the ... | The following are a few basic strategies I regularly use in my more-than-trivial scripts and medium-size applications.
Tip 1: Trap the error at every level where it makes sense to continue processing. In your case it may be in the inside the loop. You don't have to protect every single line or every single function ca... |
How do I compile a Visual Studio project from the command-line? | 498,106 | 76 | 2009-01-31T02:52:25Z | 498,118 | 32 | 2009-01-31T02:58:27Z | [
"c++",
"python",
"visual-studio-2008",
"command-line"
] | I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using [Monotone](http://en.wikipedia.org/wiki/Monotone_%28software%29), [CMake](http://en.wikipedia.org/wiki/CMake), Visual Studio Express 2008, and custom tests.
All of the other parts seem pretty straight-forward... | MSBuild usually works, but I've run into difficulties before. You may have better luck with
```
devenv YourSolution.sln /Build
``` |
How do I compile a Visual Studio project from the command-line? | 498,106 | 76 | 2009-01-31T02:52:25Z | 498,130 | 77 | 2009-01-31T03:04:10Z | [
"c++",
"python",
"visual-studio-2008",
"command-line"
] | I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using [Monotone](http://en.wikipedia.org/wiki/Monotone_%28software%29), [CMake](http://en.wikipedia.org/wiki/CMake), Visual Studio Express 2008, and custom tests.
All of the other parts seem pretty straight-forward... | I know of two ways to do it.
**Method 1**
The first method (which I prefer) is to use [msbuild](http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx):
```
msbuild project.sln /Flags...
```
**Method 2**
You can also run:
```
vcexpress project.sln /build /Flags...
```
The vcexpress option returns immediately an... |
How do I compile a Visual Studio project from the command-line? | 498,106 | 76 | 2009-01-31T02:52:25Z | 17,867,663 | 11 | 2013-07-25T20:01:03Z | [
"c++",
"python",
"visual-studio-2008",
"command-line"
] | I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using [Monotone](http://en.wikipedia.org/wiki/Monotone_%28software%29), [CMake](http://en.wikipedia.org/wiki/CMake), Visual Studio Express 2008, and custom tests.
All of the other parts seem pretty straight-forward... | To be honest I have to add my 2 cents.
You can do it with **msbuild.exe**. There are many version of the **msbuild.exe**.
> C:\Windows\Microsoft.NET\Framework64\v2.0.50727\msbuild.exe
> C:\Windows\Microsoft.NET\Framework64\v3.5\msbuild.exe
> C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
> C:\Windows\M... |
Valid use case for django admin? | 498,199 | 11 | 2009-01-31T03:56:54Z | 498,288 | 17 | 2009-01-31T04:48:35Z | [
"python",
"django",
"django-admin"
] | I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django ... | No, the Django admin is not suited for individual user profiles, each user would be able to see, and edit, all other user profiles. This is suited more to an administrator who has to manage all the users at once.
What you need to build is a user profile page. Django already has a nice login system courtesy of the djan... |
Is Django a good choice for a security critical application? | 498,630 | 22 | 2009-01-31T10:46:37Z | 498,707 | 17 | 2009-01-31T11:56:17Z | [
"python",
"django",
"security"
] | Is Django a good choice for a security critical application?
I am asking this because most of the online banking software is built using Java. Is there any real reason for this? | Probably the reason behind Java is not in the in the security. I think Java is more used in large development companies and banks usually resort to them for their development needs (which probably are not only related to the web site but creep deeper in the backend).
So, I see no security reasons, mostly cultural ones... |
Is Django a good choice for a security critical application? | 498,630 | 22 | 2009-01-31T10:46:37Z | 498,798 | 30 | 2009-01-31T13:08:04Z | [
"python",
"django",
"security"
] | Is Django a good choice for a security critical application?
I am asking this because most of the online banking software is built using Java. Is there any real reason for this? | Actually, the security in Java and Python is the same. Digest-only password handling, cookies that timeout rapidly, careful deletion of sessions, multi-factor authentication. None of this is unique to a Java framework or a Python framework like Django.
Django, indeed, has a security backend architecture that allows yo... |
Is Django a good choice for a security critical application? | 498,630 | 22 | 2009-01-31T10:46:37Z | 499,599 | 8 | 2009-01-31T21:18:49Z | [
"python",
"django",
"security"
] | Is Django a good choice for a security critical application?
I am asking this because most of the online banking software is built using Java. Is there any real reason for this? | The reasons for building banking apps in Java are not related to security, at least IMHO. They are related to:
1. Java is the COBOL of the 21st century, so there is a lot of legacy code that would have to be rewritten and that takes time. Basically banking apps are old apps, they were built in java some ten years ago ... |
Regular expression to extract URL from an HTML link | 499,345 | 22 | 2009-01-31T19:02:34Z | 499,364 | 13 | 2009-01-31T19:13:16Z | [
"python",
"regex"
] | Iâm a newbie in Python. Iâm learning regexes, but I need help here.
Here comes the HTML source:
```
<a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
```
Iâm trying to code a tool that only prints out `http://ptop.se`. Can you help me please? | Don't use regexes, use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). That, or be so crufty as to spawn it out to, say, w3m/lynx and pull back in what w3m/lynx renders. First is more elegant probably, second just worked a heck of a lot faster on some unoptimized code I wrote a while back. |
Regular expression to extract URL from an HTML link | 499,345 | 22 | 2009-01-31T19:02:34Z | 499,366 | 10 | 2009-01-31T19:16:03Z | [
"python",
"regex"
] | Iâm a newbie in Python. Iâm learning regexes, but I need help here.
Here comes the HTML source:
```
<a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
```
Iâm trying to code a tool that only prints out `http://ptop.se`. Can you help me please? | this should work, although there might be more elegant ways.
```
import re
url='<a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>'
r = re.compile('(?<=href=").*?(?=")')
r.findall(url)
``` |
Regular expression to extract URL from an HTML link | 499,345 | 22 | 2009-01-31T19:02:34Z | 499,371 | 50 | 2009-01-31T19:17:06Z | [
"python",
"regex"
] | Iâm a newbie in Python. Iâm learning regexes, but I need help here.
Here comes the HTML source:
```
<a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
```
Iâm trying to code a tool that only prints out `http://ptop.se`. Can you help me please? | If you're only looking for one:
```
import re
match = re.search(r'href=[\'"]?([^\'" >]+)', s)
if match:
print match.group(0)
```
If you have a long string, and want every instance of the pattern in it:
```
import re
urls = re.findall(r'href=[\'"]?([^\'" >]+)', s)
print ', '.join(urls)
```
Where `s` is the strin... |
Regular expression to extract URL from an HTML link | 499,345 | 22 | 2009-01-31T19:02:34Z | 1,811,011 | 8 | 2009-11-27T23:37:54Z | [
"python",
"regex"
] | Iâm a newbie in Python. Iâm learning regexes, but I need help here.
Here comes the HTML source:
```
<a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
```
Iâm trying to code a tool that only prints out `http://ptop.se`. Can you help me please? | John Gruber (who wrote Markdown, which is made of regular expressions and is used right here on Stack Overflow) had a go at producing a regular expression that recognises URLs in text:
[http://daringfireball.net/2009/11/liberal\_regex\_for\_matching\_urls](http://daringfireball.net/2009/11/liberal%5Fregex%5Ffor%5Fmatc... |
What's the best serialization method for objects in memcached? | 499,593 | 23 | 2009-01-31T21:17:24Z | 600,483 | 7 | 2009-03-01T20:47:27Z | [
"python",
"serialization",
"xml-serialization",
"memcached",
"protocol-buffers"
] | My Python application currently uses the [python-memcached API](http://www.tummy.com/Community/software/python-memcached/) to set and get objects in memcached. This API uses Python's native [pickle module](http://docs.python.org/library/pickle.html) to serialize and de-serialize Python objects.
This API makes it simpl... | I tried several methods and settled on compressed JSON as the best balance between speed and memory footprint. Python's native Pickle function is slightly faster, but the resulting objects can't be used with non-Python clients.
I'm seeing 3:1 compression so all the data fits in memcache and the app gets sub-10ms respo... |
Can I use IPython in an embedded interactive Python console? | 499,705 | 7 | 2009-01-31T22:29:21Z | 19,891,856 | 13 | 2013-11-10T16:04:12Z | [
"python",
"console"
] | I use the following snippet to drop into a Python shell mid-program. This works fine, but I only get the standard console. Is there a way to do the same but using the [IPython](http://ipython.scipy.org/) shell?
```
import code
class EmbeddedConsole(code.InteractiveConsole):
def start(self):
try:
... | The answer by f3lix is no longer valid it seems, I was able to find this however:
At the top of your python script:
```
from IPython import embed
```
Wherever you want to spin up a console:
```
embed()
``` |
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference? | 500,168 | 14 | 2009-02-01T03:59:27Z | 500,195 | 15 | 2009-02-01T04:17:58Z | [
"python",
"datetime",
"timedelta"
] | I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post.
Looks like, according to the docs, I have to use the days attribute AND the seconds ... | You can compute the difference in seconds.
```
total_seconds = delta.days * 86400 + delta.seconds
```
No, you're no "missing something". It doesn't provide deltas in seconds. |
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference? | 500,168 | 14 | 2009-02-01T03:59:27Z | 3,471,718 | 21 | 2010-08-12T20:22:47Z | [
"python",
"datetime",
"timedelta"
] | I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post.
Looks like, according to the docs, I have to use the days attribute AND the seconds ... | It seems that Python 2.7 has introduced a [total\_seconds()](http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds) method, which is what you were looking for, I believe! |
Identifying numeric and array types in numpy | 500,328 | 11 | 2009-02-01T06:17:38Z | 500,908 | 16 | 2009-02-01T14:22:55Z | [
"python",
"numpy"
] | Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard... | As others have answered, there could be other numeric types besides the ones you mention.
One approach would be to check explicitly for the capabilities you want, with something like
```
# Python 2
def is_numeric(obj):
attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__']
return all(hasattr(obj, attr... |
How to vertically align Paragraphs within a Table using Reportlab? | 500,406 | 3 | 2009-02-01T07:55:43Z | 516,531 | 8 | 2009-02-05T16:01:15Z | [
"python",
"pdf",
"alignment",
"reportlab"
] | I'm using Reportlab to generate report cards. The report cards are basically one big Table object. Some of the content in the table cells needs to wrap, specifically titles and comments, and I also need to bold certain elements.
To accomplish both the wrapping and ability to bold, I'm using Paragraph objects within th... | I have to ask: have you tried the tablestyle VALIGN:MIDDLE?
something like:
```
t=Table(data)
t.setStyle(TableStyle([('VALIGN',(-1,-1),(-1,-1),'MIDDLE')]))
```
(more details in section 7.2 of the ReportLab user guide)
If that doesn't do it, then your paragraph object must be the full height of the cell, and intern... |
using django-rest-interface with http put | 500,434 | 9 | 2009-02-01T08:29:44Z | 501,337 | 13 | 2009-02-01T18:41:22Z | [
"python",
"django"
] | I'm trying to figure out how to implement my first RESTful interface using Django and django-rest-interface. I'm having problems with the HTTP PUT requests.
How do I access the parameters of the PUT request?
I thought they would be in the request.POST array, as PUT is somewhat similar to POST in my understanding, but ... | request.POST processes form-encoded data into a dictionary, which only makes sense for web browser form submissions. There is no equivalent for PUT, as web browsers don't PUT forms; the data submitted could have any content type. You'll need to get the raw data out of request.raw\_post\_data, possibly check the content... |
In Python - how to execute system command with no output | 500,477 | 8 | 2009-02-01T09:20:45Z | 500,512 | 17 | 2009-02-01T09:50:37Z | [
"python"
] | Is there a built-in method in Python to execute a system command without displaying the output? I only want to grab the return value.
It is important that it be cross-platform, so just redirecting the output to /dev/null won't work on Windows, and the other way around. I know I can just check os.platform and build the... | ```
import os
import subprocess
subprocess.call(["ls", "-l"], stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT)
``` |
is there an alternative way of calling next on python generators? | 500,578 | 3 | 2009-02-01T10:48:46Z | 500,609 | 15 | 2009-02-01T11:12:53Z | [
"python",
"language-features"
] | I have a generator and I would like to know if I can use it without having to worry about StopIteration , and I would like to use it without the **`for item in generator`** . I would like to use it with a while statement for example ( or other constructs ). How could I do that ? | built-in function
> next(iterator[, default])
> Retrieve the next item from the iterator by calling its `__next__()` method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
In Python 2.5 and older:
```
raiseStopIteration = object()
def next(iterator, default=ra... |
How do Django model fields work? | 500,650 | 9 | 2009-02-01T11:43:27Z | 501,362 | 19 | 2009-02-01T18:56:40Z | [
"python",
"django",
"django-models"
] | First of all,I'm not into web programming. I bumped into django and read a bit about models. I was intrigued by the following code ( from djangoproject.com ) :
```
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __str__(self):
... | The essence of your question is "how come these class variables (which I assign Field objects to) suddenly become instance variables (which I assign data to) in Django's ORM"? The answer to that is the magic of Python [metaclasses](http://docs.python.org/reference/datamodel.html).
A metaclass allows you to hook into a... |
Case insensitive Python regular expression without re.compile | 500,864 | 132 | 2009-02-01T13:56:14Z | 500,870 | 206 | 2009-02-01T14:01:10Z | [
"python",
"regex",
"case-sensitive",
"case-insensitive"
] | In Python, I can compile a regular expression to be case-insensitive using `re.compile`:
```
>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>>
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>
```
Is th... | Pass `re.IGNORECASE` to the `flags` param of [`search`](https://docs.python.org/library/re.html#re.search), [`match`](https://docs.python.org/library/re.html#re.match), or [`sub`](https://docs.python.org/library/re.html#re.sub):
```
re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.su... |
Case insensitive Python regular expression without re.compile | 500,864 | 132 | 2009-02-01T13:56:14Z | 10,444,271 | 31 | 2012-05-04T07:05:38Z | [
"python",
"regex",
"case-sensitive",
"case-insensitive"
] | In Python, I can compile a regular expression to be case-insensitive using `re.compile`:
```
>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>>
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>
```
Is th... | You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3):
```
re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
``` |
Problem in understanding Python list comprehensions | 501,308 | 4 | 2009-02-01T18:22:26Z | 501,323 | 18 | 2009-02-01T18:34:33Z | [
"python",
"list-comprehension"
] | What does the last line mean in the following code?
```
import pickle, urllib
handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p")
data = pickle... | Maybe best explained with an example:
```
print "".join([e[1] * e[0] for e in elt])
```
is the short form of
```
x = []
for e in elt:
x.append(e[1] * e[0])
print "".join(x)
```
List comprehensions are simply syntactic sugar for `for` loops, which make an expression out of a sequence of statements.
`elt` can be a... |
How can you use Python in Vim? | 501,585 | 50 | 2009-02-01T21:10:02Z | 501,698 | 155 | 2009-02-01T22:17:12Z | [
"python",
"vim"
] | I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:
> %!python for i in xrange(25); print 6\*i \n
How can you do such tweaks direcly in Vim? **[Solved]**
**[Clarification]** I need things to Vim, like printing sequences,... | In any of your vim windows, type something like this:
```
for x in range(1,10):
print '-> %d' % x
```
Visually select both of those lines (V to start visual mode), and type the following:
```
:!python
```
Because you pressed ':' in visual mode, that will end up looking like:
```
:'<,'>!python
```
Hit enter an... |
Both Python 2 and 3 in Emacs | 501,626 | 16 | 2009-02-01T21:32:47Z | 502,422 | 10 | 2009-02-02T07:14:45Z | [
"python",
"emacs",
"python-3.x"
] | I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well.
Here is how the different versions are set up in /usr/bin:
```
python -> python2.6*
python2 -> python2.6*
python2.6*
python3 -> python3.0*
python3.0*
```
Is there any... | If you are using python-mode.el you can try to change `py-which-shell`. In order to do this on a per-file basis you can put
```
# -*- py-which-shell: "python3"; -*-
```
at the first line of your file - or at the second line if the first line starts with `#!`.
Another choice is to put
```
# Local Variables:
# py-whic... |
Simple simulations for Physics in Python? | 501,940 | 7 | 2009-02-02T00:55:03Z | 502,627 | 10 | 2009-02-02T09:06:01Z | [
"python",
"modeling",
"simulation"
] | I would like to know similar, concrete simulations, as the simulation about watering a field [here](http://stackoverflow.com/questions/494184/simulation-problem-with-mouse-in-pygame).
What is your favorite library/internet page for such simulations in Python?
I know little Simpy, Numpy and Pygame. I would like to get... | If you are looking for some *game* physics (collisions, deformations, gravity, etc.) which *looks* real and is reasonably *fast* consider re-using some *physics engine* libraries.
As a first reference, you may want to look into [pymunk](http://www.pymunk.org/), a Python wrapper of [Chipmunk](http://wiki.slembcke.net/m... |
How to modularize a Python application | 501,945 | 5 | 2009-02-02T00:59:26Z | 502,014 | 8 | 2009-02-02T02:00:33Z | [
"python"
] | I've got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have an arbitrary number of versions concurrently running and it must work without superuser rights. Solutions I've come up... | Adding to sys.path (usually using site.addsitedir) is quite common and not particularly frowned upon. Certainly you will want your common working shared stuff to be in modules somewhere convenient.
If you are using Python 2.6+ there's already a user-level modules folder you can use without having to add to sys.path or... |
Finding the workspace size (screen size less the taskbar) using GTK | 502,282 | 5 | 2009-02-02T05:38:09Z | 508,251 | 9 | 2009-02-03T18:09:21Z | [
"python",
"gtk",
"pygtk"
] | How do you create a main window that fills the entire desktop **without covering (or being covered by) the task bar** and **without being maximized**? I can find the entire screen size with and set the main window accordingly with this:
```
window = gtk.Window()
screen = window.get_screen()
window.resize(screen.get_wi... | You are totally at the mercy of your window manager for this, and the key issue here is:
> **without being maximized**
So we are left with a number of hacks, because basically maximization and resizing are two separate things, in order that you might be able to remember where it was when it is unmaximized.
So before... |
Converting date between DD/MM/YYYY and YYYY-MM-DD? | 502,726 | 12 | 2009-02-02T10:01:49Z | 502,737 | 8 | 2009-02-02T10:07:57Z | [
"python",
"date"
] | Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.
This almost works, but fails because I don't provide time:
```
from datetime import datetime
lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d")
... | you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:
```
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')
``` |
Converting date between DD/MM/YYYY and YYYY-MM-DD? | 502,726 | 12 | 2009-02-02T10:01:49Z | 502,738 | 33 | 2009-02-02T10:09:22Z | [
"python",
"date"
] | Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.
This almost works, but fails because I don't provide time:
```
from datetime import datetime
lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d")
... | Your example code is wrong. This works:
```
import datetime
datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
```
The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result int... |
Django: How to create a model dynamically just for testing | 502,916 | 41 | 2009-02-02T11:35:52Z | 503,435 | 39 | 2009-02-02T14:49:31Z | [
"python",
"django",
"unit-testing",
"django-models",
"mocking"
] | I have a Django app that requires a `settings` attribute in the form of:
```
RELATED_MODELS = ('appname1.modelname1.attribute1',
'appname1.modelname2.attribute2',
'appname2.modelname3.attribute3', ...)
```
Then hooks their post\_save signal to update some other fixed model dependi... | You can put your tests in a `tests/` subdirectory of the app (rather than a `tests.py` file), and include a `tests/models.py` with the test-only models.
Then provide a test-running script ([example](https://github.com/carljm/django-model-utils/blob/master/runtests.py)) that includes your `tests/` "app" in `INSTALLED_A... |
Django: How to create a model dynamically just for testing | 502,916 | 41 | 2009-02-02T11:35:52Z | 1,827,272 | 10 | 2009-12-01T16:24:59Z | [
"python",
"django",
"unit-testing",
"django-models",
"mocking"
] | I have a Django app that requires a `settings` attribute in the form of:
```
RELATED_MODELS = ('appname1.modelname1.attribute1',
'appname1.modelname2.attribute2',
'appname2.modelname3.attribute3', ...)
```
Then hooks their post\_save signal to update some other fixed model dependi... | This solution works only for earlier versions of `django` (before `1.7`). You can check your version easily:
```
import django
django.VERSION < (1, 7)
```
Original response:
It's quite strange but form me works very simple pattern:
1. add tests.py to app which you are going to test,
2. in this file just define test... |
Django: How to create a model dynamically just for testing | 502,916 | 41 | 2009-02-02T11:35:52Z | 2,672,444 | 17 | 2010-04-20T04:00:49Z | [
"python",
"django",
"unit-testing",
"django-models",
"mocking"
] | I have a Django app that requires a `settings` attribute in the form of:
```
RELATED_MODELS = ('appname1.modelname1.attribute1',
'appname1.modelname2.attribute2',
'appname2.modelname3.attribute3', ...)
```
Then hooks their post\_save signal to update some other fixed model dependi... | @paluh's answer requires adding unwanted code to a non-test file and in my experience, @carl's solution does not work with django.test.TestCase which is needed to use fixtures. If you want to use django.test.TestCase, you need to make sure you call syncdb before the fixtures get loaded. This requires overriding the \_p... |
Django: How to create a model dynamically just for testing | 502,916 | 41 | 2009-02-02T11:35:52Z | 15,460,736 | 8 | 2013-03-17T12:34:18Z | [
"python",
"django",
"unit-testing",
"django-models",
"mocking"
] | I have a Django app that requires a `settings` attribute in the form of:
```
RELATED_MODELS = ('appname1.modelname1.attribute1',
'appname1.modelname2.attribute2',
'appname2.modelname3.attribute3', ...)
```
Then hooks their post\_save signal to update some other fixed model dependi... | Quoting from [a related answer](http://stackoverflow.com/a/6960879/2179211):
> If you want models defined for testing only then you should check out
> [Django ticket #7835](https://code.djangoproject.com/ticket/7835) in particular [comment #24](https://code.djangoproject.com/ticket/7835#comment:24) part of which
> is ... |
How to parse nagios status.dat file? | 503,148 | 4 | 2009-02-02T13:11:09Z | 2,570,062 | 9 | 2010-04-03T02:46:05Z | [
"python",
"parsing",
"nagios"
] | I'd like to parse status.dat file for nagios3 and output as xml with a python script.
The xml part is the easy one but how do I go about parsing the file? Use multi line regex?
It's possible the file will be large as many hosts and services are monitored, will loading the whole file in memory be wise?
I only need to ... | Pfft, get yerself mk\_livestatus. <http://mathias-kettner.de/checkmk_livestatus.html> |
Why is IronPython faster than the Official Python Interpreter | 504,716 | 8 | 2009-02-02T20:21:28Z | 504,725 | 37 | 2009-02-02T20:23:27Z | [
"python",
"performance",
"ironpython"
] | According to this:
<http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&referringTitle=IronPython%20Performance>
IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytec... | Python code doesn't get compiled to C, Python itself is written in C and interprets Python bytecode. CIL gets compiled to machine code, which is why you see better performance when using IronPython. |
Why is IronPython faster than the Official Python Interpreter | 504,716 | 8 | 2009-02-02T20:21:28Z | 506,956 | 8 | 2009-02-03T12:49:08Z | [
"python",
"performance",
"ironpython"
] | According to this:
<http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&referringTitle=IronPython%20Performance>
IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytec... | You're right, C is a lot faster. That's why in those results CPython is twice as fast when it comes to dictionaries, which are almost pure C. On the other hand, Python code is not compiled, it's interpreted. Function calls in CPython are terribly slow.
But on the other hand:
```
TryRaiseExcept: +4478.9%
```
Now, the... |
Py2exe for Python 3.0 | 505,230 | 28 | 2009-02-02T22:28:40Z | 506,005 | 7 | 2009-02-03T04:24:49Z | [
"python",
"python-3.x",
"py2exe"
] | I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.
Any ideas? | The `py2exe` and `2to3` programs serve completely different purposes, so I'm not sure what your ultimate goal is.
If you want to build an executable from a working Python program, use the version of `py2exe` that is suitable for whichever Python you are using (version 2 or version 3).
If you want to convert an existi... |
Py2exe for Python 3.0 | 505,230 | 28 | 2009-02-02T22:28:40Z | 633,648 | 27 | 2009-03-11T07:33:42Z | [
"python",
"python-3.x",
"py2exe"
] | I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.
Any ideas? | ### Update 2014-05-15
py2exe for Python 3.x is now released! [Get it on PyPI](https://pypi.python.org/pypi/py2exe).
### Old information
Have a look at the py2exe SourceForge project SVN repository at:
<http://py2exe.svn.sourceforge.net/>
The last I looked at it, it said the last update was August 2009. But keep an... |
Py2exe for Python 3.0 | 505,230 | 28 | 2009-02-02T22:28:40Z | 1,263,200 | 27 | 2009-08-11T22:00:16Z | [
"python",
"python-3.x",
"py2exe"
] | I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.
Any ideas? | Did you check out [cx\_Freeze](http://cx-freeze.sourceforge.net/)? It seems to create standalone executables from your Python scripts, including support for Python 3.0 and 3.1 |
Py2exe for Python 3.0 | 505,230 | 28 | 2009-02-02T22:28:40Z | 23,638,686 | 8 | 2014-05-13T18:15:48Z | [
"python",
"python-3.x",
"py2exe"
] | I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.
Any ideas? | # py2exe for Python3 is out!
Here is the original bug report:
<http://sourceforge.net/projects/py2exe/>
Here is the comment mentioning the release:
<http://sourceforge.net/projects/py2exe/>
Here is the package on pypi:
<https://pypi.python.org/pypi/py2exe/0.9.2.0>
**Note that py2exe for Python 3 only supports... |
Closures in Python | 505,559 | 6 | 2009-02-03T00:13:06Z | 505,596 | 7 | 2009-02-03T00:26:25Z | [
"python",
"closures",
"lexical-scope"
] | I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly:
```
def memoize(fn):
def get(key):
return (False,)
def vset(key, value):
global get
oldget = get
def newget(ky):
... | The problem is in your scoping, not in your closures. If you're up for some heavy reading, then you can try <http://www.python.org/dev/peps/pep-3104/>.
If that's not the case, here's the simple explanation:
The problem is in the statement `global get` . `global` refers to the outermost scope, and since there isn't an... |
Closures in Python | 505,559 | 6 | 2009-02-03T00:13:06Z | 505,663 | 7 | 2009-02-03T00:57:24Z | [
"python",
"closures",
"lexical-scope"
] | I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly:
```
def memoize(fn):
def get(key):
return (False,)
def vset(key, value):
global get
oldget = get
def newget(ky):
... | ```
def memoize(fn):
get = [lambda key: (False, None)]
def vset(args):
value = fn(*args)
oldget = get[0]
def newget(key):
if args == key:
return (True, value)
return oldget(key)
get[0] = newget
return value
def mfun(*args):
found, value = get[0](args)
if found:
... |
Is there a widely used STOMP adapter for Twisted? | 506,594 | 2 | 2009-02-03T10:12:30Z | 561,901 | 7 | 2009-02-18T16:45:59Z | [
"python",
"twisted",
"activemq",
"stomp"
] | I checked out stomper and it didn't look complete. (I'm very new to Python) Is anybody out there using stomper in a production environment?
If not, I guess I'll have to roll out my own Twisted Stomp adapter.
Thanks in advance! | There is a python library called [stomper](https://github.com/oisinmulvihill/stomper) which I've used in the past with twisted (it comes with twisted example code). Disclaimer, I've worked on the code for stomper so I like it :)
These days I've moved away from stomp/ActiveMQ towards AMQP + [RabbitMQ](http://www.rabbit... |
Python xml minidom. generate <text>Some text</text> element | 507,405 | 10 | 2009-02-03T14:59:17Z | 507,555 | 8 | 2009-02-03T15:30:32Z | [
"python",
"xml",
"minidom"
] | I have the following code.
```
from xml.dom.minidom import Document
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
main = doc.createElement('Text')
root.appendChild(main)
text = doc.createTextNode('Some text here')
main.appendChild(text)
print doc.toprettyxml(indent='\t')
```
The result i... | > Can this easily be done?
It depends what exact rule you want, but generally no, you get little control over pretty-printing. If you want a specific format you'll usually have to write your own walker.
The DOM Level 3 LS parameter format-pretty-print in [pxdom](http://www.doxdesk.com/software/py/pxdom.html) comes pr... |
How do i install pyCurl? | 507,927 | 22 | 2009-02-03T16:50:24Z | 507,955 | 7 | 2009-02-03T16:56:48Z | [
"python",
"libcurl",
"pycurl",
"installation"
] | I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.
i'... | Depends on platform. Here on ubuntu it's as simple as:
```
sudo aptitude install python-pycurl
```
It's common enough a package to think that most major Linux distributions will have it in their sources.
If you're on windows, you'll need [cURL](http://curl.haxx.se/download.html) too. Then you can install [pycurl](ht... |
How do i install pyCurl? | 507,927 | 22 | 2009-02-03T16:50:24Z | 508,143 | 7 | 2009-02-03T17:42:26Z | [
"python",
"libcurl",
"pycurl",
"installation"
] | I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.
i'... | As it has been said already, it depends on the platform.
In general, I prefer to use only the Python interpreter itself that is packaged for my OS and install everything else in a [virtual environment](http://pypi.python.org/pypi/virtualenv), but this is a whole different story...
If you've got [setuptools](http://pyp... |
How do i install pyCurl? | 507,927 | 22 | 2009-02-03T16:50:24Z | 551,418 | 11 | 2009-02-15T19:07:16Z | [
"python",
"libcurl",
"pycurl",
"installation"
] | I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.
i'... | According to <http://bazaar-vcs.org/PyCurl>
> Since Windows does not come with
> neither cURL or pycURL, Windows users
> will have to install both.
>
> cURL downloads:
> <http://curl.haxx.se/download.html>.
>
> pycURL downloads:
> <http://pycurl.sourceforge.net/download/>.
>
> Both links contain Linux (and other
> \*N... |
How do i install pyCurl? | 507,927 | 22 | 2009-02-03T16:50:24Z | 5,385,014 | 12 | 2011-03-21T23:35:40Z | [
"python",
"libcurl",
"pycurl",
"installation"
] | I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.
i'... | You can try to download pycurl from here
<http://www.lfd.uci.edu/~gohlke/pythonlibs/>
> PycURL is a interface to the libcurl library.
> pycurl-7.19.0.win-amd64-py2.6.âexe [863 KB] [Python 2.6] [64 bit] [Dec 09, 2010]
> pycurl-7.19.0.win-amd64-py2.7.âexe [863 KB] [Python 2.7] [64 bit] [Dec 09, 2010]
> pycurl... |
How do i install pyCurl? | 507,927 | 22 | 2009-02-03T16:50:24Z | 10,699,666 | 14 | 2012-05-22T09:52:55Z | [
"python",
"libcurl",
"pycurl",
"installation"
] | I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.
i'... | **TL,DR**
Get a binary from this website: <http://www.lfd.uci.edu/~gohlke/pythonlibs/>
Direct links: [`2.6 32bit`](http://www.lfd.uci.edu/~gohlke/pythonlibs/qjbh48zu/pycurl-7.19.0.win32-py2.6.exe),
[`2.7 32bit`](http://www.lfd.uci.edu/~gohlke/pythonlibs/qjbh48zu/pycurl-7.19.0.win32-py2.7.exe),[`2.6 64bit`](http://www... |
Is there a good dependency analysis tool for Python? | 508,277 | 23 | 2009-02-03T18:18:07Z | 509,194 | 24 | 2009-02-03T22:26:13Z | [
"python",
"dependencies"
] | Dependency analysis programs help us organize code by controlling the dependencies between modules in our code. When one module is a circular dependency of another module, it is a clue to find a way to turn that into a unidirectional dependency or merge two modules into one module.
What is the best dependency analysis... | I recommend using [snakefood](http://furius.ca/snakefood/) for creating graphical dependency graphs of Python projects. It detects dependencies nicely enough to immediately see areas for refactorisation. Its usage is pretty straightforward if you read a little bit of documentation.
Of course, you can omit the graph-cr... |
AUTO_INCREMENT in sqlite problem with python | 508,627 | 8 | 2009-02-03T19:49:59Z | 508,664 | 34 | 2009-02-03T19:56:53Z | [
"python",
"sqlite"
] | I am using sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page <http://www.sqlite.org/syntaxdiagrams.html#column-constraint> but that did not work either. Without AUTO\_INCREMENT my table can be created.
```
An error occurred: near "AUTO_INCREMENT": sy... | This is addressed in the [SQLite FAQ](http://www.sqlite.org/faq.html). [Question #1](http://www.sqlite.org/faq.html#q1).
Which states:
> How do I create an AUTOINCREMENT
> field?
>
> Short answer: A column declared
> INTEGER PRIMARY KEY will
> autoincrement.
>
> Here is the long answer: If you
> declare a column of a... |
AUTO_INCREMENT in sqlite problem with python | 508,627 | 8 | 2009-02-03T19:49:59Z | 508,667 | 10 | 2009-02-03T19:57:06Z | [
"python",
"sqlite"
] | I am using sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page <http://www.sqlite.org/syntaxdiagrams.html#column-constraint> but that did not work either. Without AUTO\_INCREMENT my table can be created.
```
An error occurred: near "AUTO_INCREMENT": sy... | It looks like AUTO\_INCREMENT should be AUTOINCREMENT see <http://www.sqlite.org/syntaxdiagrams.html#column-constraint> |
Multidimensional array in Python | 508,657 | 8 | 2009-02-03T19:54:37Z | 261,084 | 18 | 2008-11-04T06:37:50Z | [
"java",
"python",
"arrays"
] | I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:
```
double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
```
Further values will be created bei loops... | If you restrict yourself to the Python standard library, then a list of lists is the closest construct:
```
arr = [[1,2],[3,4]]
```
gives a 2d-like array. The rows can be accessed as `arr[i]` for `i` in `{0,..,len(arr}`, but column access is difficult.
If you are willing to add a library dependency, the [NumPy](http... |
Multidimensional array in Python | 508,657 | 8 | 2009-02-03T19:54:37Z | 261,340 | 13 | 2008-11-04T09:34:25Z | [
"java",
"python",
"arrays"
] | I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:
```
double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
```
Further values will be created bei loops... | To create a standard python array of arrays of arbitrary size:
```
a = [[0]*cols for _ in [0]*rows]
```
It is accessed like this:
```
a[0][1] = 5 # set cell at row 0, col 1 to 5
```
A small python gotcha that's worth mentioning: It is tempting to just type
```
a = [[0]*cols]*rows
```
but that'll copy the *same* c... |
Multidimensional array in Python | 508,657 | 8 | 2009-02-03T19:54:37Z | 261,656 | 10 | 2008-11-04T12:04:00Z | [
"java",
"python",
"arrays"
] | I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:
```
double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
```
Further values will be created bei loops... | Multidimensional arrays are a little murky. There are few reasons for using them and many reasons for thinking twice and using something else that more properly reflects what you're doing. [Hint. your question was thin on context ;-) ]
If you're doing matrix math, then use `numpy`.
However, some folks have worked wit... |
Multidimensional array in Python | 508,657 | 8 | 2009-02-03T19:54:37Z | 508,677 | 11 | 2009-02-03T19:59:02Z | [
"java",
"python",
"arrays"
] | I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:
```
double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
```
Further values will be created bei loops... | You can create it using nested lists:
```
matrix = [[a,b],[c,d],[e,f]]
```
If it has to be dynamic it's more complicated, why not write a small class yourself?
```
class Matrix(object):
def __init__(self, rows, columns, default=0):
self.m = []
for i in range(rows):
self.m.append([defa... |
Multidimensional array in Python | 508,657 | 8 | 2009-02-03T19:54:37Z | 508,679 | 11 | 2009-02-03T20:00:21Z | [
"java",
"python",
"arrays"
] | I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:
```
double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
```
Further values will be created bei loops... | Take a look at [numpy](http://numpy.scipy.org//)
here's a code snippet for you
```
import numpy as npy
d = npy.zeros((len(x)+1, len(y)+1, len(x)+len(y)+3))
d[0][0][0] = 0 # although this is unnecessary since zeros initialises to zero
d[i][j][k] = npy.inf
```
I don't think you need to be implementing a scientific ap... |
Python time to age | 508,727 | 2 | 2009-02-03T20:12:06Z | 508,742 | 16 | 2009-02-03T20:16:48Z | [
"python",
"datetime"
] | I'm trying to convert a date string into an age.
The string is like: "Mon, 17 Nov 2008 01:45:32 +0200" and I need to work out how many days old it is.
I have sucessfully converted the date using:
```
>>> time.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
(2008, 11, 17, 1, 45, 32, 0, 322, ... | You need to use the module `datetime` and the object [`datetime.timedelta`](http://docs.python.org/library/datetime.html#datetime.timedelta)
```
from datetime import datetime
t1 = datetime.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
t2 = datetime.now()
tdelta = t2 - t1 # actually a date... |
A replacement for python's httplib? | 508,817 | 9 | 2009-02-03T20:36:21Z | 508,840 | 21 | 2009-02-03T20:44:37Z | [
"python",
"http",
"curl",
"twisted"
] | I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.
Could I improve performance by replacing httplib with something else?
I've seen that twisted offers ... | Often when I've had performance problems with httplib, the problem hasn't been with the httplib itself, but with how I'm using it. Here are a few common pitfalls:
(1) Don't make a new TCP connection for every web request. If you are making lots of request to the same server, instead of this pattern:
```
conn = ht... |
A replacement for python's httplib? | 508,817 | 9 | 2009-02-03T20:36:21Z | 508,858 | 18 | 2009-02-03T20:53:12Z | [
"python",
"http",
"curl",
"twisted"
] | I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.
Could I improve performance by replacing httplib with something else?
I've seen that twisted offers ... | > Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.
>
> Could I improve performance by replacing httplib with something else?
Do you *suspect* it or are you *sure* that that it's `httplib`? Profile before you do anything to improve the performance... |
How to overwrite some bytes in the middle of a file with Python? | 508,983 | 11 | 2009-02-03T21:31:53Z | 509,014 | 18 | 2009-02-03T21:39:57Z | [
"python",
"file",
"patching"
] | I'd like to be able to overwrite some bytes at a given offset in a file using Python.
My attempts have failed miserably and resulted in:
* overwriting the bytes at the offset but also truncating the file just after (file mode = "w" or "w+")
* appending the bytes at the end of the file (file mode = "a" or "a+")
Is it... | Try this:
```
fh = open("filename.ext", "r+b")
fh.seek(offset)
fh.write(bytes)
fh.close()
``` |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 509,295 | 1,891 | 2009-02-03T22:48:24Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | It's pretty simple really:
```
a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
```
There is also the `step` value, which can be used with any of the above:
```
a[start:end:... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 509,297 | 245 | 2009-02-03T22:49:04Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | The tutorial talks about it:
<http://docs.python.org/tutorial/introduction.html#strings>
(Scroll down a bit until you get to the part about slicing.)
The ASCII art diagram is helpful too for remembering how slices work:
```
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 509,377 | 180 | 2009-02-03T23:08:22Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | Enumerating the possibilities allowed by the grammar:
```
>>> seq[:] # [seq[0], seq[1], ..., seq[-1] ]
>>> seq[low:] # [seq[low], seq[low+1], ..., seq[-1] ]
>>> seq[:high] # [seq[0], seq[1], ..., seq[high-1]]
>>> seq[low:high] # [seq[low], ... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 509,415 | 82 | 2009-02-03T23:15:02Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | And a couple of things that weren't immediately obvious to me when I first saw the slicing syntax:
```
>>> x = [1,2,3,4,5,6]
>>> x[::-1]
[6,5,4,3,2,1]
```
Easy way to reverse sequences!
And if you wanted, for some reason, every second item in the reversed sequence:
```
>>> x = [1,2,3,4,5,6]
>>> x[::-2]
[6,4,2]
``` |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 522,212 | 20 | 2009-02-06T21:16:28Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | I use the "an index points between elements" method of thinking about it myself, but one way of describing it which sometimes helps others get it is this:
```
mylist[X:Y]
```
X is the index of the first element you want.
Y is the index of the first element you *don't* want. |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 567,094 | 33 | 2009-02-19T20:52:44Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | After using it a bit I realise that the simplest description is that it is exactly the same as the arguments in a for loop...
```
(from:to:step)
```
any of them are optional
```
(:to:step)
(from::step)
(from:to)
```
then the negative indexing just needs you to add the length of the string to the negative indices to... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 4,729,334 | 119 | 2011-01-18T21:37:57Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | The answers above don't discuss slice assignment:
```
>>> r=[1,2,3,4]
>>> r[1:1]
[]
>>> r[1:1]=[9,8]
>>> r
[1, 9, 8, 2, 3, 4]
>>> r[1:1]=['blah']
>>> r
[1, 'blah', 9, 8, 2, 3, 4]
```
This may also clarify the difference between slicing and indexing. |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 7,315,935 | 64 | 2011-09-06T06:50:08Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | Found this great table at <http://wiki.python.org/moin/MovingToPythonFromOtherLanguages>
```
Python indexes and slices for a six-element list.
Indexes enumerate the elements, slices enumerate the spaces between the elements.
Index from rear: -6 -5 -4 -3 -2 -1 a=[0,1,2,3,4,5] a[1:]==[1,2,3,4,5]
Index f... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 9,827,284 | 16 | 2012-03-22T17:20:59Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | This is just for some extra info...
Consider the list below
```
>>> l=[12,23,345,456,67,7,945,467]
```
Few other tricks for reversing the list:
```
>>> l[len(l):-len(l)-1:-1]
[467, 945, 7, 67, 456, 345, 23, 12]
>>> l[:-len(l)-1:-1]
[467, 945, 7, 67, 456, 345, 23, 12]
>>> l[len(l)::-1]
[467, 945, 7, 67, 456, 345, 2... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 9,923,354 | 21 | 2012-03-29T10:15:12Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | I find it easier to remember how it's works, then I can figure out any specific start/stop/step combination.
It's instructive to understand `range()` first:
```
def range(start=0, stop, step=1): # illegal syntax, but that's the effect
i = start
while (i < stop if step > 0 else i > stop):
yield i
... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 13,005,464 | 51 | 2012-10-22T05:33:39Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | In python 2.7
Slicing in python
```
[a:b:c]
len = length of string, tuple or list
c -- default is +1. sign of c indicates forward or backward, absolute value of c indicates steps. Default is forward with step size 1. Positive means forward, negative means backward.
a -- when c is positive or blank, default is 0... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 14,682,039 | 13 | 2013-02-04T07:20:03Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | ```
index:
------------>
0 1 2 3 4
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
0 -4 -3 -2 -1
<------------
slice:
<---------------|
|--------------->
: 1 2 3 4 :
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
: -4 -3 -2 -1 :
|-... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 15,824,717 | 16 | 2013-04-05T01:59:41Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | You can also use slice assignment to remove one or more elements from a list:
```
r = [1, 'blah', 9, 8, 2, 3, 4]
>>> r[1:4] = []
>>> r
[1, 2, 3, 4]
``` |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 16,267,103 | 19 | 2013-04-28T19:49:39Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | Python slicing notation:
```
a[start:end:step]
```
* For `start` and `end`, negative values are interpreted as being relative to the end of the sequence.
* Positive indices for `end` indicate the position *after* the last element to be included.
* Blank values are defaulted as follows: `[+0:-0:1]`.
* Using a negative... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 20,443,928 | 15 | 2013-12-07T16:52:45Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | As a general rule, writing code with a lot of hardcoded index values leads to a readability
and maintenance mess. For example, if you come back to the code a year later, youâll
look at it and wonder what you were thinking when you wrote it. The solution shown
is simply a way of more clearly stating what your code is ... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 24,713,353 | 62 | 2014-07-12T13:19:03Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | > # Explain Python's slice notation
In short, the colons (`:`) in subscript notation (`subscriptable[subscriptarg]`) make slice notation - which has the optional arguments, `start`, `stop`, `step`:
```
sliceable[start:stop:step]
```
Python slicing is a computationally fast way to methodically access parts of your da... |
Explain Python's slice notation | 509,211 | 1,331 | 2009-02-03T22:31:02Z | 29,237,560 | 11 | 2015-03-24T16:08:36Z | [
"python",
"list",
"slice"
] | I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it. | This is how I teach slices to newbies:
**Understanding difference between indexing and slicing:**
Wiki Python has this amazing picture which clearly distinguishes indexing and slicing.

It is a list with 6 elements in it. To understand slicing bette... |
python reading lines w/o \n? | 509,446 | 3 | 2009-02-03T23:23:57Z | 509,482 | 13 | 2009-02-03T23:34:39Z | [
"python",
"file",
"newline"
] | Would this work on all platforms? i know windows does \r\n, and remember hearing mac does \r while linux did \n. I ran this code on windows so it seems fine, but do any of you know if its cross platform?
```
while 1:
line = f.readline()
if line == "":
break
line = line[:-1]
print "\"" + line + ... | First of all, there is [universal newline support](https://www.python.org/dev/peps/pep-0278/)
Second: just use `line.strip()`. Use `line.rstrip('\r\n')`, if you want to preserve any whitespace at the beginning or end of the line.
Oh, and
```
print '"%s"' % line
```
or at least
```
print '"' + line + '"'
```
might... |
Python M2Crypto - generating a DSA key pair and separating public/private components | 509,449 | 2 | 2009-02-03T23:25:04Z | 509,633 | 7 | 2009-02-04T00:35:25Z | [
"python",
"cryptography",
"rsa",
"m2crypto"
] | Could anybody explain what is the cause of the following:
```
>>> from M2Crypto import DSA, BIO
>>> dsa = DSA.gen_params(1024)
..+........+++++++++++++++++++++++++++++++++++++++++++++++++++*
............+.+.+..+.........+.............+.....................+.
...+.............+...........+................................. | Call dsa.gen\_key(), then save. You aren't actually generating the public key.
```
>>> from M2Crypto import DSA, BIO
>>> dsa = DSA.gen_params(1024)
..+..etc
>>> mem = BIO.MemoryBuffer()
>>> dsa.gen_key()
>>> dsa.save_key_bio(mem, cipher=None)
1
>>> dsa.save_pub_key_bio(mem)
1
>>> print mem.getvalue()
-----BEGIN DSA PR... |
Change directory to the directory of a Python script | 509,742 | 4 | 2009-02-04T01:24:43Z | 509,754 | 14 | 2009-02-04T01:30:18Z | [
"python",
"scripting",
"directory"
] | How do i change directory to the directory with my python script in? So far I figured out I should use `os.chdir` and `sys.argv[0]`. I'm sure there is a better way then to write my own function to parse argv[0]. | ```
os.chdir(os.path.dirname(__file__))
``` |
Best way to write a Python function that integrates a gaussian? | 509,994 | 6 | 2009-02-04T03:49:20Z | 510,040 | 12 | 2009-02-04T04:11:03Z | [
"python",
"scipy",
"gaussian",
"integral"
] | In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function?... | scipy ships with the "error function", aka Gaussian integral:
```
import scipy.special
help(scipy.special.erf)
``` |
Best way to write a Python function that integrates a gaussian? | 509,994 | 6 | 2009-02-04T03:49:20Z | 511,155 | 27 | 2009-02-04T12:32:51Z | [
"python",
"scipy",
"gaussian",
"integral"
] | In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function?... | Okay, you appear to be pretty confused about several things. Let's start at the beginning: you mentioned a "multidimensional function", but then go on to discuss the usual one-variable Gaussian curve. This is *not* a multidimensional function: when you integrate it, you only integrate one variable (x). The distinction ... |
creating blank field and receving the INTEGER PRIMARY KEY with sqlite, python | 510,135 | 3 | 2009-02-04T05:06:34Z | 510,182 | 7 | 2009-02-04T05:34:27Z | [
"python",
"sqlite"
] | I am using sqlite with python. When i insert into table A i need to feed it an ID from table B. So what i wanted to do is insert default data into B, grab the id (which is auto increment) and use it in table A. Whats the best way receive the key from the table i just inserted into? | As Christian said, `sqlite3_last_insert_rowid()` is what you want... but that's the C level API, and you're using the Python DB-API bindings for SQLite.
It looks like the cursor method `lastrowid` will do what you want [(search for 'lastrowid' in the documentation for more information)](http://docs.python.org/library/... |
How can I make a time delay in Python? | 510,348 | 1,061 | 2009-02-04T07:04:09Z | 64,486 | 330 | 2008-09-15T16:34:29Z | [
"python",
"sleep",
"timedelay"
] | I would like to know how to put a time delay in a Python script. | You can use the sleep() function in the time module. It can take a float argument for sub second resolution.
```
from time import sleep
sleep(0.1) # Time in seconds.
``` |
How can I make a time delay in Python? | 510,348 | 1,061 | 2009-02-04T07:04:09Z | 510,351 | 1,176 | 2009-02-04T07:05:59Z | [
"python",
"sleep",
"timedelay"
] | I would like to know how to put a time delay in a Python script. | ```
import time
time.sleep(5) # delays for 5 seconds
```
Here is another example where something is run once a minute:
```
import time
while True:
print "This prints once a minute."
time.sleep(60) # Delay for 1 minute (60 seconds)
``` |
How can I make a time delay in Python? | 510,348 | 1,061 | 2009-02-04T07:04:09Z | 510,356 | 40 | 2009-02-04T07:07:32Z | [
"python",
"sleep",
"timedelay"
] | I would like to know how to put a time delay in a Python script. | Please read <http://www.faqts.com/knowledge_base/view.phtml/aid/2609/fid/378>, which can help you further:
> Try the sleep function in the time module.
>
> ```
> import time
> time.sleep(60)
> ```
>
> And put this in a while loop and a statement will only execute on the
> minute... That allows you to run a statement a... |
How can I make a time delay in Python? | 510,348 | 1,061 | 2009-02-04T07:04:09Z | 6,234,820 | 57 | 2011-06-04T05:03:16Z | [
"python",
"sleep",
"timedelay"
] | I would like to know how to put a time delay in a Python script. | What You Need Is
`time.sleep(sec)`
where sec is how many seconds delay you add there
you also need to
`import time` |
How can I make a time delay in Python? | 510,348 | 1,061 | 2009-02-04T07:04:09Z | 22,583,596 | 153 | 2014-03-22T21:06:10Z | [
"python",
"sleep",
"timedelay"
] | I would like to know how to put a time delay in a Python script. | There is a built-in Python module called `time`. Use it like this:
```
import time
time.sleep(5)
```
This will make the script wait for 5 seconds. |
How can I make a time delay in Python? | 510,348 | 1,061 | 2009-02-04T07:04:09Z | 23,131,522 | 19 | 2014-04-17T11:08:36Z | [
"python",
"sleep",
"timedelay"
] | I would like to know how to put a time delay in a Python script. | There is a built in python module named time.
The 2 examples are identical but differ only in the way the method is imported from the module:
1 Use This:
```
import time
time.sleep(Num of seconds to sleep)
```
2 Use this:
```
from time import sleep
sleep(Num of seconds to sleep)
``` |
How can I make a time delay in Python? | 510,348 | 1,061 | 2009-02-04T07:04:09Z | 23,665,492 | 18 | 2014-05-14T21:30:35Z | [
"python",
"sleep",
"timedelay"
] | I would like to know how to put a time delay in a Python script. | A bit of fun with sleepy generator.
The question is about time delay. It can be fixed time, but in some cases we might need a delay measured since last time. Here is one possible solutions:
# Delay measured since last time (waking up regularly)
The situation can be, we want to do something as regularly as possible a... |
How can I make a time delay in Python? | 510,348 | 1,061 | 2009-02-04T07:04:09Z | 28,965,832 | 18 | 2015-03-10T14:04:40Z | [
"python",
"sleep",
"timedelay"
] | I would like to know how to put a time delay in a Python script. | to halt further execution for defined time, sleep method is available in time package.
it easy all you have to do is at the top of your code type in
`from time import sleep`
then use sleep in your desired code let say 5 seconds:
`sleep(5)`
alternatively you can import time and then use time.sleep(5)
`import time... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.