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 |
|---|---|---|---|---|---|---|---|---|---|
reverse a string in Python | 766,141 | 25 | 2009-04-19T21:35:54Z | 766,163 | 59 | 2009-04-19T21:43:46Z | [
"python",
"string",
"slice"
] | I was looking for a way to print a string backwards, and after a quick search on google, I found this method:
Suppose 'a' is a string variable. This will return the 'a' string backwards:
```
a[::-1]
```
Can anyone explain how that works? | Sure, the `[::]` is the [extended slice](https://docs.python.org/whatsnew/2.3.html#extended-slices) operator. It allows you to take substrings. Basically, it works by specifying which elements you want as [begin:end:step], and it works for all sequences. Two neat things about it:
* You can omit one or more of the elem... |
Python speed testing - Time Difference - milliseconds | 766,335 | 63 | 2009-04-19T23:08:27Z | 766,382 | 94 | 2009-04-19T23:31:01Z | [
"python",
"datetime",
"time",
"time-measurement"
] | What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.
So far I have this code:
```
from datetime import datetime
tstart = datetime.now()
print t1
# code to speed test
tend = datetime.now()
print t2
... | [`datetime.timedelta`](http://docs.python.org/3.2/library/datetime.html#timedelta-objects) is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds
```
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a
>>> c
datetime.timedelta(0, 4, 3... |
Python speed testing - Time Difference - milliseconds | 766,335 | 63 | 2009-04-19T23:08:27Z | 766,402 | 18 | 2009-04-19T23:38:06Z | [
"python",
"datetime",
"time",
"time-measurement"
] | What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.
So far I have this code:
```
from datetime import datetime
tstart = datetime.now()
print t1
# code to speed test
tend = datetime.now()
print t2
... | You could also use:
```
import time
start = time.clock()
do_something()
end = time.clock()
print "%.2gs" % (end-start)
```
Or you could use the [python profilers](http://docs.python.org/library/profile.html). |
Python speed testing - Time Difference - milliseconds | 766,335 | 63 | 2009-04-19T23:08:27Z | 766,473 | 31 | 2009-04-20T00:18:10Z | [
"python",
"datetime",
"time",
"time-measurement"
] | What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.
So far I have this code:
```
from datetime import datetime
tstart = datetime.now()
print t1
# code to speed test
tend = datetime.now()
print t2
... | You might want to use [the timeit module](http://docs.python.org/library/timeit.html) instead. |
Python speed testing - Time Difference - milliseconds | 766,335 | 63 | 2009-04-19T23:08:27Z | 24,274,452 | 19 | 2014-06-17T22:38:54Z | [
"python",
"datetime",
"time",
"time-measurement"
] | What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.
So far I have this code:
```
from datetime import datetime
tstart = datetime.now()
print t1
# code to speed test
tend = datetime.now()
print t2
... | Since Python 2.7 there's the timedelta.total\_seconds() method. So, to get the elapsed milliseconds:
```
>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> delta = b - a
>>> print delta
0:00:05.077263
>>> int(delta.total_seconds() * 1000) # milliseconds
5077
``` |
Python non-greedy regexes | 766,372 | 54 | 2009-04-19T23:24:03Z | 766,377 | 59 | 2009-04-19T23:27:21Z | [
"python",
"regex",
"regex-greedy"
] | How do I make a python regex like "(.\*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?
I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"? | You seek the all-powerful '\*?'
<http://docs.python.org/2/howto/regex.html#greedy-versus-non-greedy> |
Python non-greedy regexes | 766,372 | 54 | 2009-04-19T23:24:03Z | 766,379 | 9 | 2009-04-19T23:28:04Z | [
"python",
"regex",
"regex-greedy"
] | How do I make a python regex like "(.\*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?
I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"? | Would not `\\(.*?\\)` work ? That is the non-greedy syntax. |
Python non-greedy regexes | 766,372 | 54 | 2009-04-19T23:24:03Z | 766,384 | 41 | 2009-04-19T23:31:33Z | [
"python",
"regex",
"regex-greedy"
] | How do I make a python regex like "(.\*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?
I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"? | ```
>>> x = "a (b) c (d) e"
>>> re.search(r"\(.*\)", x).group()
'(b) c (d)'
>>> re.search(r"\(.*?\)", x).group()
'(b)'
```
[According to the docs](http://docs.python.org/library/re.html#regular-expression-syntax):
> The '`*`', '`+`', and '`?`' qualifiers are all greedy; they match as much text as possible. Sometimes ... |
mod_wsgi force reload modules | 766,601 | 5 | 2009-04-20T02:04:53Z | 1,037,909 | 9 | 2009-06-24T11:59:02Z | [
"python",
"module",
"mod-wsgi",
"reload"
] | Is there a way to have mod\_wsgi reload all modules (maybe in a particular directory) on each load?
While working on the code, it's very annoying to restart apache every time something is changed. The only option I've found so far is to put `modname = reload(modname)` below every import.. but that's also really annoyi... | The link:
<http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode>
should be emphasised. It also should be emphaised that on UNIX systems daemon mode of mod\_wsgi must be used and you must implement the code monitor described in the documentation. The whole process reloading option will not work for embedded mode ... |
Some internals of Django auth middleware | 766,733 | 4 | 2009-04-20T03:02:36Z | 767,299 | 9 | 2009-04-20T07:52:51Z | [
"python",
"django"
] | In the django.contrib.auth middleware
I see the code:
```
class AuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), "requires session middleware"
request.__class__.user = LazyUser()
return None
```
Please avdise me why such a form
reque... | `LazyUser` is descriptor-class. According to [documentation](http://docs.python.org/reference/datamodel.html#invoking-descriptors) it can be only class attribute not instance one:
> For instance, `a.x` has a lookup chain starting with `a.__dict__['x']`, then `type(a).__dict__['x']`, and continuing through the base cla... |
nice html reports for pyunit | 767,377 | 8 | 2009-04-20T08:24:39Z | 767,442 | 9 | 2009-04-20T08:44:49Z | [
"python",
"html",
"pyunit"
] | Do you know a tool for creating nice html reports for pyunit? | I suggest the following:
1. Run your tests using [nose](http://somethingaboutorange.com/mrl/projects/nose/)
2. Create a nose plugin that outputs results as HTML. The nose example code has a simple HTML output plugin (<https://raw.github.com/nose-devs/nose/master/examples/html_plugin/htmlplug.py>). You can probably use... |
Blocks of code in python | 767,519 | 8 | 2009-04-20T09:14:23Z | 767,529 | 9 | 2009-04-20T09:21:31Z | [
"python",
"ruby",
"lambda",
"codeblocks"
] | Can you elaborate on the current state of "blocks" (in the Ruby sense) in Python?
What are the language constructs that exist in python? How do they compare to other languages (like Ruby, Smalltalk, [insert more])? Or does python lack of such constructs?
I have so far understood the `lambda` thing; it is only one-lin... | functions are the first-class members in python
```
def add(x, y):
return x + y
a = add # bind
b = a(34, 1) # call
```
so you can pass functions around all you want. you can do the same with any callable object in python. |
Estimating zip size/creation time | 767,684 | 7 | 2009-04-20T10:23:56Z | 767,704 | 14 | 2009-04-20T10:32:27Z | [
"python",
"zip",
"time-estimation",
"size-estimation"
] | I need to create ZIP archives on demand, using either Python zipfile module or unix command line utilities.
Resources to be zipped are often > 1GB and not necessarily compression-friendly.
How do I efficiently estimate its creation time / size? | Extract a bunch of small parts from the big file. Maybe 64 chunks of 64k each. Randomly selected.
Concatenate the data, compress it, measure the time and the compression ratio. Since you've randomly selected parts of the file chances are that you have compressed a representative subset of the data.
Now all you have t... |
Riddle: The Square Puzzle | 767,912 | 21 | 2009-04-20T11:41:59Z | 767,984 | 15 | 2009-04-20T12:06:28Z | [
"python",
"puzzle"
] | Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle:
---
There is this 10\*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traver... | This is very similar to the [Knight's Tour](http://en.wikipedia.org/wiki/Knight%27s%5Ftour) problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".
The key optimisation I remember from tackling the Knights Tour ... |
Riddle: The Square Puzzle | 767,912 | 21 | 2009-04-20T11:41:59Z | 769,302 | 10 | 2009-04-20T17:33:38Z | [
"python",
"puzzle"
] | Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle:
---
There is this 10\*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traver... | I decided to look at the problem and see if I could break it into 5x5 solutions with the ending of a solution one jump away from the corner of another.
First assumption was that 5x5 is solvable. It is and fast.
So I ran solve(0,5) and looked at the results. I drew a 10x10 numbered grid in Excel with a 5x5 numbered gr... |
Riddle: The Square Puzzle | 767,912 | 21 | 2009-04-20T11:41:59Z | 772,644 | 8 | 2009-04-21T13:40:39Z | [
"python",
"puzzle"
] | Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle:
---
There is this 10\*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traver... | Eventually, I have come up with the modified Python code to overcome the problem. I've tun the code for a couple of hours and it has already found half a million solutions in a couple of hours.
The full set of solutions still require a total exhaustive search, i.e. to let the program run until it finishes with all co... |
What is the most Pythonic way to provide a fall-back value in an assignment? | 768,175 | 14 | 2009-04-20T13:10:00Z | 768,190 | 26 | 2009-04-20T13:13:49Z | [
"python"
] | In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:
```
my $x = undef;
my $y = 2;
my $a = $x || $y;
```
After this,
```
$a == 2
```
Is there a concise way to achieve this in Python if the value x is None, or would a ... | Since 2.5:
If you want to fall back **only** on None:
```
a = x if x is not None else y
```
If you want to fall back also on empty string, `false`, `0` etc.:
```
a = x if x else y
```
or
```
a = x or y
```
---
As for undefined (as never defined, a.k.a. not bound):
```
try:
a = x
except NameError:
a = y
``... |
Common ways to connect to odbc from python on windows? | 768,312 | 20 | 2009-04-20T13:41:50Z | 768,330 | 14 | 2009-04-20T13:47:27Z | [
"python",
"windows",
"odbc",
"pywin32",
"pyodbc"
] | What library should I use to connect to odbc from python on windows? Is there a good alternative for pywin32 when it comes to odbc?
I'm looking for something well-documented, robust, actively maintained, etc. [`pyodbc`](http://code.google.com/p/pyodbc/) looks good -- are there any others? | I use [SQLAlchemy](http://www.sqlalchemy.org) for all python database access. I highly recommend SQLAlchemy.
SA uses pyodbc under the hood when connecting to SQL server databases. It uses other DBAPI libraries to connect to other database, for instance cx\_Oracle.
A simplistic example, using SQLAlchemy like you would... |
Common ways to connect to odbc from python on windows? | 768,312 | 20 | 2009-04-20T13:41:50Z | 768,500 | 24 | 2009-04-20T14:26:37Z | [
"python",
"windows",
"odbc",
"pywin32",
"pyodbc"
] | What library should I use to connect to odbc from python on windows? Is there a good alternative for pywin32 when it comes to odbc?
I'm looking for something well-documented, robust, actively maintained, etc. [`pyodbc`](http://code.google.com/p/pyodbc/) looks good -- are there any others? | You already suggested **pyodbc**, and I am going to agree with you.
It has given me the least amount of issues in my experience; I've used [pymssql](http://pymssql.sourceforge.net/) and [adodbapi](http://adodbapi.sourceforge.net/), and when those threw exceptions/created issues, I swapped out the code and replaced it ... |
Test for Python module dependencies being installed | 768,504 | 7 | 2009-04-20T14:27:40Z | 768,597 | 8 | 2009-04-20T14:43:12Z | [
"python",
"reflection",
"import",
"module",
"python-module"
] | How could one test whether a set of modules is installed, given the names of the modules. E.g.
```
modules = set(["sys", "os", "jinja"])
for module in modules:
# if test(module exists):
# do something
```
While it's possible to write out the tests as:
```
try:
import sys
except ImportError:
print "No sys!... | You can use the [`__import__()`](http://docs.python.org/library/functions.html) function like this::
```
for module in modules:
try:
__import__(module)
except ImportError:
do_something()
```
You can also use [`imp.find_module`](http://docs.python.org/library/imp.html) to determine whether a mo... |
Parse a .py file, read the AST, modify it, then write back the modified source code | 768,634 | 100 | 2009-04-20T14:51:55Z | 769,113 | 19 | 2009-04-20T16:44:53Z | [
"python",
"compiler-construction",
"abstract-syntax-tree"
] | I want to programmatically edit python source code. Basically I want to read a `.py` file, generate the [AST](http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree), and then write back the modified python source code (i.e. another `.py` file).
There are ways to parse/compile python source code using standard python m... | You might not need to re-generate source code. That's a bit dangerous for me to say, of course, since you have not actually explained why you think you need to generate a .py file full of code; but:
* If you want to generate a .py file that people will actually use, maybe so that they can fill out a form and get a use... |
Parse a .py file, read the AST, modify it, then write back the modified source code | 768,634 | 100 | 2009-04-20T14:51:55Z | 769,199 | 48 | 2009-04-20T17:04:21Z | [
"python",
"compiler-construction",
"abstract-syntax-tree"
] | I want to programmatically edit python source code. Basically I want to read a `.py` file, generate the [AST](http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree), and then write back the modified python source code (i.e. another `.py` file).
There are ways to parse/compile python source code using standard python m... | [Pythoscope](http://pythoscope.org/) does this to the test cases it automatically generates as does the [2to3](http://docs.python.org/library/2to3.html) tool for python 2.6 (it converts python 2.x source into python 3.x source).
Both these tools uses the [lib2to3](http://svn.python.org/projects/python/trunk/Lib/lib2to... |
Parse a .py file, read the AST, modify it, then write back the modified source code | 768,634 | 100 | 2009-04-20T14:51:55Z | 769,202 | 43 | 2009-04-20T17:05:41Z | [
"python",
"compiler-construction",
"abstract-syntax-tree"
] | I want to programmatically edit python source code. Basically I want to read a `.py` file, generate the [AST](http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree), and then write back the modified python source code (i.e. another `.py` file).
There are ways to parse/compile python source code using standard python m... | The builtin ast module doesn't seem to have a method to convert back to source. However, the [codegen](https://pypi.python.org/pypi/codegen/1.0) module here provides a pretty printer for the ast that would enable you do do so.
eg.
```
import ast
import codegen
expr="""
def foo():
print("hello world")
"""
p=ast.par... |
How do I prevent execution of arbitrary commands from a Django app making system calls? | 768,677 | 5 | 2009-04-20T15:03:41Z | 768,720 | 10 | 2009-04-20T15:14:47Z | [
"python",
"django",
"security"
] | I have a Django application I'm developing that must make a system call to an external program on the server. In creating the command for the system call, the application takes values from a form and uses them as parameters for the call. I suppose this means that one can essentially use bogus parameters and write arbit... | Based on my understanding of the question, I'm assuming you aren't letting the users specify commands to run on the shell, but just arguments to those commands. In this case, you can avoid [shell injection](http://en.wikipedia.org/wiki/Code%5Finjection#Shell%5FInjection) attacks by using the [`subprocess`](http://docs.... |
Dynamic Loading of Python Modules | 769,534 | 3 | 2009-04-20T18:34:04Z | 769,610 | 10 | 2009-04-20T18:50:01Z | [
"python",
"dynamic",
"module",
"loading"
] | I'm trying to dynamically load modules I've created.
Right now this works properly:
```
import structures.index
```
But if I try the same thing by importing it dynamically, it fails.
```
struct = __import__("structures.index")
```
Error supplied is:
```
Error ('No module named structures.index',)
```
Any ideas w... | I'm not sure what "it fails" means, so I'll just mention that `__import__('structures.index')` should, in fact, work, but it doesn't assign the module name in the current scope. To do that (and then use a class in the dynamically imported module), you'll have to use:
```
structures = __import__('structures.index')
str... |
Multiple projects from one setup.py? | 769,793 | 6 | 2009-04-20T19:35:26Z | 770,247 | 7 | 2009-04-20T21:45:32Z | [
"python",
"setuptools"
] | My current [setup.py](http://github.com/dbr/tvdb%5Fapi/blob/fa55575e26b188de9b9b9f0c41d52c2a45400796/setup.py) (using setuptools) installs two things, one is `tvdb_api` (an API wrapper), the other is `tvnamer` (a command line script)
I wish to make the two available separately, so a user can do..
```
easy_install tvd... | `setup.py` is just a regular Python file, which by convention sets up packages. By convention, `setup.py` contains a call to the setuptools or distutils `setup()` function. If you want to use one `setup.py` for two packages, you can call a different `setup()` function based on a command-line argument:
```
import sys
i... |
How do I use AND in a Django filter? | 769,843 | 16 | 2009-04-20T19:55:11Z | 769,849 | 34 | 2009-04-20T19:57:38Z | [
"python",
"django"
] | How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.
For example the following SQL query does exactly that when I run it on mysql database:
```
select * from myapp_question
where ((question like '%software%') and (que... | ```
mymodel.objects.filter(first_name__icontains="Foo", first_name__icontains="Bar")
``` |
How do I use AND in a Django filter? | 769,843 | 16 | 2009-04-20T19:55:11Z | 769,862 | 8 | 2009-04-20T20:01:38Z | [
"python",
"django"
] | How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.
For example the following SQL query does exactly that when I run it on mysql database:
```
select * from myapp_question
where ((question like '%software%') and (que... | You can chain filter expressions in Django:
```
q = Question.objects.filter(question__contains='software').filter(question__contains='java')
```
You can find more info in the Django docs at "[Chaining Filters](http://docs.djangoproject.com/en/dev/topics/db/queries/#id1)". |
How do I use AND in a Django filter? | 769,843 | 16 | 2009-04-20T19:55:11Z | 770,078 | 37 | 2009-04-20T21:04:52Z | [
"python",
"django"
] | How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.
For example the following SQL query does exactly that when I run it on mysql database:
```
select * from myapp_question
where ((question like '%software%') and (que... | For thoroughness sake, let's just mention the [`Q`](http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects) object method:
```
from django.db.models import Q
criterion1 = Q(question__contains="software")
criterion2 = Q(question__contains="java")
q = Question.objects.filter(criterion1 & ... |
Python Cmd module, subclassing issue | 770,134 | 5 | 2009-04-20T21:18:36Z | 770,183 | 9 | 2009-04-20T21:30:39Z | [
"python"
] | I'm trying to work out what's not working in this code:
```
#!/usr/bin/python
import cmd
class My_class (cmd.Cmd):
"""docstring for Twitter_handler"""
def __init__(self):
super(My_class, self).__init__()
if __name__ == '__main__':
my_handler = My_class()
```
Here's the error I get
```
Traceback (... | [super()](http://docs.python.org/library/functions.html#super) only works for [new-style classes](http://docs.python.org/reference/datamodel.html#newstyle) |
Python Cmd module, subclassing issue | 770,134 | 5 | 2009-04-20T21:18:36Z | 770,189 | 7 | 2009-04-20T21:32:19Z | [
"python"
] | I'm trying to work out what's not working in this code:
```
#!/usr/bin/python
import cmd
class My_class (cmd.Cmd):
"""docstring for Twitter_handler"""
def __init__(self):
super(My_class, self).__init__()
if __name__ == '__main__':
my_handler = My_class()
```
Here's the error I get
```
Traceback (... | cmd.Cmd is not a new style class in Python 2.5, 2.6, 2.7.
Note that your code does *not* raise an exception in Python 3.0. |
Python - Overridding print() | 770,657 | 4 | 2009-04-21T00:53:23Z | 770,665 | 13 | 2009-04-21T00:56:16Z | [
"python",
"python-3.x",
"mod-wsgi",
"wsgi"
] | I'm using mod\_wsgi and was wondering if it's possible to over-write the print() command (since it's useless).
Doing this doesn't work:
```
print = myPrintFunction
```
Since it's a syntax error. :( | Print is not a function in Python 2.x, so this is not directly possible.
You can, however, [override sys.stdout](http://code.activestate.com/recipes/119404/).
If you are on Python 3.0 in which [print is now a function](http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function) what you have would then work, as... |
What does python3 do with the methods passed to the "key" argument of sorted()? | 770,845 | 4 | 2009-04-21T02:37:47Z | 770,875 | 8 | 2009-04-21T02:55:17Z | [
"python",
"python-3.x",
"sorted"
] | I have a question about how python treats the methods passed to sorted(). Consider the following small script:
```
#!/usr/bin/env python3
import random
class SortClass:
def __init__(self):
self.x = random.choice(range(10))
self.y = random.choice(range(10))
def getX(self):
return self.... | Methods on classes are just functions.
```
class MyClass(object):
... def my_method(self): pass
...
>>> MyClass.my_method
<function my_method at 0x661c38>
```
When you fetch a method from an instance of a class, Python uses some magic (called descriptors) to return a bound method. Bound methods automatically inse... |
Running python code from standard Cocoa application | 772,112 | 8 | 2009-04-21T11:18:44Z | 772,220 | 7 | 2009-04-21T11:57:55Z | [
"python",
"cocoa",
"osx",
"pyobjc"
] | I have an XCode project built as a Cocoa single document application (it's not a Python-Cocoa application, that is not what I want).
All the documentation I found assumes I want to create a Cocoa application with code written in Python and this is not the case - I want a standard Cocoa application that calls a method ... | A google search for [embed python objective C](http://www.google.com/search?q=embed%2Bpython%2Bobjective%2BC), returns a few links that might be of interest, in particular:
* <http://blog.alienoverlord.com/?p=14>
* <http://blog.tlensing.org/2008/11/04/embedding-python-in-a-cocoa-application/> |
What does the Python Ellipsis object do? | 772,124 | 196 | 2009-04-21T11:21:12Z | 772,134 | 8 | 2009-04-21T11:24:33Z | [
"python",
"ellipsis"
] | While idly surfing the namespace I noticed an odd looking object called "**Ellipsis**", it does not seem to be or do anything special, but it's a globally available builtin.
After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else.
Was this obj... | You can use Ellipsis yourself, in custom slicing situations like numpy has done, but it has no usage in any builtin class.
I don't know if it was added specifically for use in numpy, but I certainly haven't seen it used elsewhere.
See also: <http://stackoverflow.com/questions/118370/how-do-you-use-the-ellipsis-slicin... |
What does the Python Ellipsis object do? | 772,124 | 196 | 2009-04-21T11:21:12Z | 772,148 | 27 | 2009-04-21T11:30:30Z | [
"python",
"ellipsis"
] | While idly surfing the namespace I noticed an odd looking object called "**Ellipsis**", it does not seem to be or do anything special, but it's a globally available builtin.
After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else.
Was this obj... | From the [Python documentation](http://www.python.org/doc/2.5.2/lib/bltin-ellipsis-object.html):
> This object is used by extended slice
> notation (see the *[Python Reference
> Manual](http://www.python.org/doc/2.5.2/ref/ref.html)*). It supports no special
> operations. There is exactly one
> ellipsis object, named `... |
What does the Python Ellipsis object do? | 772,124 | 196 | 2009-04-21T11:21:12Z | 773,472 | 242 | 2009-04-21T16:26:07Z | [
"python",
"ellipsis"
] | While idly surfing the namespace I noticed an odd looking object called "**Ellipsis**", it does not seem to be or do anything special, but it's a globally available builtin.
After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else.
Was this obj... | This came up in another [question](http://stackoverflow.com/questions/752602/slicing-in-python-expressions-documentation) recently. I'll elaborate on my [answer](http://stackoverflow.com/questions/752602/slicing-in-python-expressions-documentation/753260#753260) from there:
[Ellipsis](http://docs.python.org/dev/librar... |
What does the Python Ellipsis object do? | 772,124 | 196 | 2009-04-21T11:21:12Z | 6,189,281 | 73 | 2011-05-31T14:39:41Z | [
"python",
"ellipsis"
] | While idly surfing the namespace I noticed an odd looking object called "**Ellipsis**", it does not seem to be or do anything special, but it's a globally available builtin.
After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else.
Was this obj... | In Python 3, you can use the Ellipsis literal `...` as a ânopâ placeholder for code:
```
def will_do_something():
...
```
This is **not** magic; any expression can be used instead of `...`, e.g.:
```
def will_do_something():
1
```
(Can't use the word âsanctionedâ, but I can say that this use was [*n... |
What does the Python Ellipsis object do? | 772,124 | 196 | 2009-04-21T11:21:12Z | 6,189,379 | 33 | 2011-05-31T14:47:58Z | [
"python",
"ellipsis"
] | While idly surfing the namespace I noticed an odd looking object called "**Ellipsis**", it does not seem to be or do anything special, but it's a globally available builtin.
After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else.
Was this obj... | You can also use the Ellipsis when specifying expected [doctest](http://docs.python.org/library/doctest.html#doctest.ELLIPSIS) output:
```
class MyClass(object):
"""Example of a doctest Ellipsis
>>> thing = MyClass()
>>> # Match <class '__main__.MyClass'> and <class '%(module).MyClass'>
>>> type(thing... |
Django payment proccessing | 772,240 | 22 | 2009-04-21T12:05:31Z | 772,320 | 18 | 2009-04-21T12:28:12Z | [
"python",
"django"
] | Can anyone suggest any good payment processing libraries for python/django? | The most developed Django solution is [Satchmo](http://www.satchmoproject.com/docs/svn/) with support for Authorize.Net, TrustCommerce, CyberSource, PayPal, Google Checkout, and Protx.
The new kid on the Django block is [django-lfs](http://code.google.com/p/django-lfs/) which looks like only support for PayPal at the ... |
Why are 0d arrays in Numpy not considered scalar? | 773,030 | 41 | 2009-04-21T15:02:51Z | 794,812 | 76 | 2009-04-27T18:55:32Z | [
"python",
"numpy"
] | Surely a 0d array is scalar, but Numpy does not seem to think so... am I missing something or am I just misunderstanding the concept?
```
>>> foo = numpy.array(1.11111111111, numpy.float64)
>>> numpy.ndim(foo)
0
>>> numpy.isscalar(foo)
False
>>> foo.item()
1.11111111111
``` | One should not think too hard about it. It's ultimately better for the mental health and longevity of the individual.
The curious situation with Numpy scalar-types was bore out of the fact that there is no graceful and consistent way to degrade the 1x1 matrix to scalar types. Even though mathematically they are the sa... |
Plot logarithmic axes with matplotlib in python | 773,814 | 188 | 2009-04-21T18:00:26Z | 773,850 | 48 | 2009-04-21T18:07:42Z | [
"python",
"matplotlib",
"scale",
"logarithm"
] | I want to plot a graph with one logarithmic axis using matplotlib.
I've been reading the docs, but can't figure out the syntax. I know that it's probably something simple like 'scale=linear' in the plot arguments, but I can't seem to get it right
Sample program:
```
from pylab import *
import matplotlib.pyplot as p... | You simply need to use [semilogy](http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.semilogy) instead of plot:
```
from pylab import *
import matplotlib.pyplot as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)
line, = ax.semilogy(a, color='blue',... |
Plot logarithmic axes with matplotlib in python | 773,814 | 188 | 2009-04-21T18:00:26Z | 1,183,415 | 201 | 2009-07-26T00:14:42Z | [
"python",
"matplotlib",
"scale",
"logarithm"
] | I want to plot a graph with one logarithmic axis using matplotlib.
I've been reading the docs, but can't figure out the syntax. I know that it's probably something simple like 'scale=linear' in the plot arguments, but I can't seem to get it right
Sample program:
```
from pylab import *
import matplotlib.pyplot as p... | You can use the [Axes.set\_yscale](http://matplotlib.sourceforge.net/api/axes%5Fapi.html#matplotlib.axes.Axes.set%5Fyscale) method. That allows you to change the scale after the Axes object is created. That would also allow you to build a control to let the user pick the scale if you needed to.
The relevant line to ad... |
Plot logarithmic axes with matplotlib in python | 773,814 | 188 | 2009-04-21T18:00:26Z | 3,513,577 | 175 | 2010-08-18T15:10:32Z | [
"python",
"matplotlib",
"scale",
"logarithm"
] | I want to plot a graph with one logarithmic axis using matplotlib.
I've been reading the docs, but can't figure out the syntax. I know that it's probably something simple like 'scale=linear' in the plot arguments, but I can't seem to get it right
Sample program:
```
from pylab import *
import matplotlib.pyplot as p... | First of all, it's not very tidy to mix `pylab` and `pyplot` code. What's more, [pyplot style is preferred over using pylab](http://matplotlib.org/faq/usage_faq.html#matplotlib-pyplot-and-pylab-how-are-they-related).
Here is a slightly cleaned up code, using only `pyplot` functions:
```
from matplotlib import pyplot
... |
Python +sockets | 773,869 | 5 | 2009-04-21T18:12:19Z | 773,920 | 7 | 2009-04-21T18:21:56Z | [
"python",
"sockets",
"ports"
] | i have to create connecting server<=>client. I use this code:
Server:
```
import socket
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: b... | The question is a little confusing, but I will try to help out. Basically, if the port (50007) is blocked on the server machine by a firewall, you will NOT be able to make a tcp connection to it from the client. That is the purpose of the firewall. A lot of protocols (SIP and bittorrent for example) do use firewall and... |
Python difflib: highlighting differences inline? | 774,316 | 15 | 2009-04-21T19:57:32Z | 788,780 | 28 | 2009-04-25T12:05:12Z | [
"python",
"diff"
] | When comparing similar lines, I want to highlight the differences on the same line:
```
a) lorem ipsum dolor sit amet
b) lorem foo ipsum dolor amet
lorem <ins>foo</ins> ipsum dolor <del>sit</del> amet
```
While difflib.HtmlDiff appears to do this sort of inline highlighting, it produces very verbose markup.
Unfortu... | For your simple example:
```
import difflib
def show_diff(seqm):
"""Unify operations between two compared strings
seqm is a difflib.SequenceMatcher instance whose a & b are strings"""
output= []
for opcode, a0, a1, b0, b1 in seqm.get_opcodes():
if opcode == 'equal':
output.append(seqm.a... |
Explain Python entry points? | 774,824 | 107 | 2009-04-21T21:59:55Z | 774,859 | 16 | 2009-04-21T22:10:16Z | [
"python",
"setuptools"
] | I've read the documentation on egg entry points in Pylons and on the Peak pages, and I still don't really understand. Could someone explain them to me, or point me at an article or book that does? | From abstract point of view, entry points are used to create a system-wide registry of Python callables that implement certain interfaces. There are APIs in pkg\_resources to see which entry points are advertised by a given package as well as APIs to determine which packages advertise a certain entry point.
Entry poin... |
Explain Python entry points? | 774,824 | 107 | 2009-04-21T21:59:55Z | 782,984 | 90 | 2009-04-23T18:37:08Z | [
"python",
"setuptools"
] | I've read the documentation on egg entry points in Pylons and on the Peak pages, and I still don't really understand. Could someone explain them to me, or point me at an article or book that does? | An "entry point" is typically a function (or other callable function-like object) that a developer or user of your Python package might want to use, though a non-callable object can be supplied as an entry point as well (as correctly pointed out in the comments!).
The most popular kind of entry point is the "console\_... |
Explain Python entry points? | 774,824 | 107 | 2009-04-21T21:59:55Z | 9,615,473 | 115 | 2012-03-08T09:39:04Z | [
"python",
"setuptools"
] | I've read the documentation on egg entry points in Pylons and on the Peak pages, and I still don't really understand. Could someone explain them to me, or point me at an article or book that does? | [EntryPoints](https://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points) provide a persistent, filesystem-based object name registration and name-based direct object import mechanism (implemented by the [setuptools](http://pypi.python.org/pypi/setuptools) package).
They associate names of Python obje... |
Multiple statements in list compherensions in Python? | 774,876 | 6 | 2009-04-21T22:14:48Z | 774,987 | 18 | 2009-04-21T22:45:01Z | [
"python",
"list-comprehension"
] | Is it possible to have something like:
```
list1 = ...
currentValue = 0
list2 = [currentValue += i, i for i in list1]
```
I tried that but didn't work? What's the proper syntax to write those?
EDIT: the print statement was an example. Actually I am incrementing a value outside the loop. | Statements *cannot* go inside of expressions in Python; it was a complication that was deliberately designed out of the language. For this problem, try using a complication that **did** make it into the language: generators. Watch:
```
def total_and_item(sequence):
total = 0
for i in sequence:
total +=... |
Python Time Seconds to h:m:s | 775,049 | 178 | 2009-04-21T23:08:16Z | 775,075 | 284 | 2009-04-21T23:15:54Z | [
"python"
] | I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python? | By using the [`divmod()`](http://docs.python.org/library/functions.html#divmod) function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:
```
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
print "%d:%02d:%02d... |
Python Time Seconds to h:m:s | 775,049 | 178 | 2009-04-21T23:08:16Z | 775,095 | 344 | 2009-04-21T23:22:15Z | [
"python"
] | I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python? | or you can do
```
>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
``` |
Python Time Seconds to h:m:s | 775,049 | 178 | 2009-04-21T23:08:16Z | 24,507,708 | 22 | 2014-07-01T10:13:42Z | [
"python"
] | I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python? | I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use [time.strftime](https://docs.python.org/2/library/time.html#time.strftime), which gives more control over formatting:
```
>>> import time
>>> time.strftime("%H:%M:%S", time.gmtime(666))
'00:11:06'
```
[gmtime](https:/... |
Python Time Seconds to h:m:s | 775,049 | 178 | 2009-04-21T23:08:16Z | 31,946,730 | 8 | 2015-08-11T16:06:05Z | [
"python"
] | I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python? | ```
>>> "{:0>8}".format(datetime.timedelta(seconds=66))
>>> '00:01:06' # good
```
and:
```
>>> "{:0>8}".format(datetime.timedelta(seconds=666777)
>>> '7 days, 17:12:57' # nice
```
without ':0>8':
```
>>> "{}".format(datetime.timedelta(seconds=66))
>>> '0:01:06' # not HH:MM:SS
```
and:
```
>>> time.strftime("%H:%M... |
Efficiently determining if a business is open or not based on store hours | 775,161 | 6 | 2009-04-21T23:48:14Z | 775,247 | 8 | 2009-04-22T00:25:59Z | [
"python",
"mysql",
"performance",
"solr"
] | Given a time (eg. currently 4:24pm on Tuesday), I'd like to be able to select all businesses that are currently open out of a set of businesses.
* I have the open and close times for every business for every day of the week
* Let's assume a business can open/close only on 00, 15, 30, 45 minute marks of each hour
* I'm... | If you are willing to just look at single week at a time, you can canonicalize all opening/closing times to be set numbers of minutes since the start of the week, say Sunday 0 hrs. For each store, you create a number of tuples of the form [startTime, endTime, storeId]. (For hours that spanned Sunday midnight, you'd hav... |
Directory Walker for Python | 775,231 | 4 | 2009-04-22T00:19:13Z | 778,377 | 12 | 2009-04-22T17:40:32Z | [
"python",
"directory-listing"
] | I am currently using the directory walker from [Here](http://effbot.org/librarybook/os-path-walk-example-3.py)
```
import os
class DirectoryWalker:
# a forward iterator that traverses a directory tree
def __init__(self, directory):
self.stack = [directory]
self.files = []
self.index = 0
def __getitem__(s... | Why do you want to do such boring thing yourself?
```
for path, directories, files in os.walk('.'):
print 'ls %r' % path
for directory in directories:
print ' d%r' % directory
for filename in files:
print ' -%r' % filename
```
Output:
```
'.'
d'finction'
d'.hg'
-'setup.p... |
Python MySQL Parameterized Queries | 775,296 | 44 | 2009-04-22T00:43:21Z | 775,320 | 10 | 2009-04-22T00:53:31Z | [
"python",
"mysql"
] | I am having a hard time using the MySQLdb module to insert information into my database. I need to insert 6 variables into the table.
```
cursor.execute ("""
INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
VALUES
(var1, var2, var3, var4, var5, var6)
""")
```
C... | The linked docs give the following example:
```
cursor.execute ("""
UPDATE animal SET name = %s
WHERE name = %s
""", ("snake", "turtle"))
print "Number of rows updated: %d" % cursor.rowcount
```
So you just need to adapt this to your own code - example:
```
cursor.execute ("""
... |
Python MySQL Parameterized Queries | 775,296 | 44 | 2009-04-22T00:43:21Z | 775,344 | 21 | 2009-04-22T01:04:31Z | [
"python",
"mysql"
] | I am having a hard time using the MySQLdb module to insert information into my database. I need to insert 6 variables into the table.
```
cursor.execute ("""
INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
VALUES
(var1, var2, var3, var4, var5, var6)
""")
```
C... | You have a few options available. You'll want to get comfortable with python's string iterpolation. Which is a term you might have more success searching for in the future when you want to know stuff like this.
Better for queries:
```
some_dictionary_with_the_data = {
'name': 'awesome song',
'artist': 'some b... |
Python MySQL Parameterized Queries | 775,296 | 44 | 2009-04-22T00:43:21Z | 775,399 | 167 | 2009-04-22T01:35:26Z | [
"python",
"mysql"
] | I am having a hard time using the MySQLdb module to insert information into my database. I need to insert 6 variables into the table.
```
cursor.execute ("""
INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
VALUES
(var1, var2, var3, var4, var5, var6)
""")
```
C... | Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. **The difference might seem trivial, but in reality it's huge**.
### Incorrect (with security issues)
```
c.execute("SELECT * FROM foo WHERE... |
os.path.exists() for files in your Path? | 775,351 | 11 | 2009-04-22T01:09:31Z | 775,360 | 12 | 2009-04-22T01:16:08Z | [
"python",
"windows"
] | I commonly use os.path.exists() to check if a file is there before doing anything with it.
I've run across a situation where I'm calling a executable that's in the configured env path, so it can be called without specifying the abspath.
Is there something that can be done to check if the file exists before calling it... | You could get the PATH environment variable, and try "exists()" for the .exe in each dir in the path. But that could perform horribly.
example for finding notepad.exe:
```
import os
for p in os.environ["PATH"].split(os.pathsep):
print os.path.exists(os.path.join(p, 'notepad.exe'))
```
more clever example:
```
i... |
What is "generator object" in django? | 776,060 | 4 | 2009-04-22T07:41:35Z | 776,089 | 19 | 2009-04-22T07:55:01Z | [
"python",
"generator"
] | Am using Django voting package and when i use the method get\_top() in the shell, it returns something like **"generator object at 0x022f7AD0**, i've never seen anything like this before, how do you access it and what is it?
my code:
```
v=Vote.objects.get_top(myModel, limit=10, reversed=False)
print v
<generator obj... | If you want a list, just call list() on your generator object.
A generator object in python is something like a lazy list. The elements are only evaluated as soon as you iterate over them. (Thus calling list on it evaluates all of them.)
For example you can do:
```
>>> def f(x):
... print "yay!"
... return 2 * x
>... |
What is "generator object" in django? | 776,060 | 4 | 2009-04-22T07:41:35Z | 776,143 | 7 | 2009-04-22T08:11:20Z | [
"python",
"generator"
] | Am using Django voting package and when i use the method get\_top() in the shell, it returns something like **"generator object at 0x022f7AD0**, i've never seen anything like this before, how do you access it and what is it?
my code:
```
v=Vote.objects.get_top(myModel, limit=10, reversed=False)
print v
<generator obj... | A generator is a kind of iterator. An iterator is a kind of iterable object, and like any other iterable,
You can iterate over every item using a for loop:
```
for vote in Vote.objects.get_top(myModel, limit=10, reversed=False):
print v.name, vote
```
If you need to access items by index, you can convert it to a... |
Multiple simultaneous network connections - Telnet server, Python | 776,120 | 16 | 2009-04-22T08:03:44Z | 776,845 | 16 | 2009-04-22T11:54:36Z | [
"python",
"sockets",
"telnet"
] | I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.
My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one.
... | Implemented in [twisted](http://twistedmatrix.com/):
```
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
class SendContent(Protocol):
def connectionMade(self):
self.transport.write(self.factory.text)
self.transport.loseConnection()
class SendContentFac... |
Appengine - Possible to get an entity using only key string without model name? | 776,324 | 3 | 2009-04-22T09:15:04Z | 918,507 | 11 | 2009-05-27T23:34:25Z | [
"python",
"google-app-engine"
] | I want to be able to have a view that will act upon a number of different types of objects
all the view will get is the key string eg:
agpwb2xsdGhyZWFkchULEg9wb2xsY29yZV9hbnN3ZXIYAww
without knowing the model type, is it possible to retrieve the entity from just that key string?
thanks | No superclassing required, just use db.get():
```
from google.appengine.ext import db
key_str = 'agpwb2xsdGhyZWFkchULEg9wb2xsY29yZV9hbnN3ZXIYAww'
entity = db.get(key_str)
``` |
Using Twisted's twisted.web classes, how do I flush my outgoing buffers? | 776,631 | 9 | 2009-04-22T10:57:50Z | 802,632 | 9 | 2009-04-29T14:30:35Z | [
"python",
"twisted",
"multipart-mixed-replace"
] | I've made a simple http server using Twisted, which sends the Content-Type: multipart/x-mixed-replace header. I'm using this to test an http client which I want to set up to accept a long-term stream.
The problem that has arisen is that my client request hangs until the *http.Request* calls self.finish(), then it rece... | Using `time.sleep()` prevents twisted from doing its job. To make it work you can't use `time.sleep()`, you must return control to twisted instead. The easiest way to modify your existing code to do that is by using [`twisted.internet.defer.inlineCallbacks`](http://twistedmatrix.com/documents/8.2.0/api/twisted.internet... |
Python reflection - Can I use this to get the source code of a method definition | 777,371 | 8 | 2009-04-22T14:05:23Z | 777,875 | 16 | 2009-04-22T15:37:27Z | [
"python",
"reflection"
] | **Duplicate of..**
* [How can I get the code of python function?](http://stackoverflow.com/questions/427453/how-can-i-get-the-code-of-python-function)
* [print the code which defined a lambda function](http://stackoverflow.com/questions/334851/print-the-code-which-defined-a-lambda-function)
* [Python: How do you get P... | Use the inspect module:
```
import inspect
import mymodule
print inspect.getsource(mymodule.sayHello)
```
The function must be defined in a module that you import. |
Django Form values without HTML escape | 777,458 | 2 | 2009-04-22T14:22:14Z | 777,528 | 7 | 2009-04-22T14:36:34Z | [
"python",
"django-forms",
"currency",
"symbols"
] | I need to set the Django forms.ChoiceField to display the currency symbols. Since django forms escape all the HTML ASCII characters, I can't get the $ ( **€** ) or the £ ( **£** ) to display the currency symbol.
```
<select id="id_currency" name="currency">
<option value="&#36;">$</option>
<o... | You can use "[safe](http://docs.djangoproject.com/en/dev/topics/templates/#how-to-turn-it-off)" in the template or "[mark\_safe](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#filters-and-auto-escaping)" in the view
**update**
```
from django.utils.safestring import mark_safe
currencies = ((mark_sa... |
Python subprocess "object has no attribute 'fileno'" error | 777,996 | 6 | 2009-04-22T16:05:06Z | 778,059 | 9 | 2009-04-22T16:15:09Z | [
"python",
"pipe",
"subprocess"
] | This code generates "AttributeError: 'Popen' object has no attribute 'fileno'" when run with Python 2.5.1
Code:
```
def get_blame(filename):
proc = []
proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE))
proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE)
proc.... | Three things
First, your ()'s are wrong.
Second, the result of `subprocess.Popen()` is a process object, not a file.
```
proc = []
proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE))
proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE)
```
The value of `proc[-1]` isn't the fi... |
smtplib and gmail - python script problems | 778,202 | 19 | 2009-04-22T16:52:17Z | 780,516 | 7 | 2009-04-23T06:33:55Z | [
"python",
"smtp",
"gmail",
"smtplib"
] | Here's my script:
```
#!/usr/bin/python
import smtplib
msg = 'Hello world.'
server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587
server.ehlo()
server.starttls()
server.ehlo()
server.login('[email protected]','mypass')
server.sendmail('[email protected]','[email protected]',msg)
server.close()
```
I'm jus... | Have you tried constructing a valid message?
```
from email.MIMEText import MIMEText
msg = MIMEText('body')
msg['Subject'] = 'subject'
msg['From'] = "..."
msg['Reply-to'] = "..."
msg['To'] = "..."
``` |
Accepting email address as username in Django | 778,382 | 68 | 2009-04-22T17:42:20Z | 778,399 | 25 | 2009-04-22T17:46:39Z | [
"python",
"django",
"authentication"
] | Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.
Please advise, thank you. | Here's what we do. It isn't a "complete" solution, but it does much of what you're looking for.
```
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
class Meta:
model = Use... |
Accepting email address as username in Django | 778,382 | 68 | 2009-04-22T17:42:20Z | 9,134,982 | 32 | 2012-02-03T20:20:55Z | [
"python",
"django",
"authentication"
] | Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.
Please advise, thank you. | For anyone else wanting to do this, I'd recommend taking a look at [django-email-as-username](https://github.com/dabapps/django-email-as-username) which is a pretty comprehensive solution, that includes patching up the admin and the `createsuperuser` management commands, amongst other bits and pieces.
**Edit**: As of ... |
Accepting email address as username in Django | 778,382 | 68 | 2009-04-22T17:42:20Z | 25,278,186 | 15 | 2014-08-13T04:39:42Z | [
"python",
"django",
"authentication"
] | Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.
Please advise, thank you. | Here is one way to do it so that both username and email are accepted:
```
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.forms import ValidationError
class EmailAuthenticationForm(AuthenticationFor... |
Accepting email address as username in Django | 778,382 | 68 | 2009-04-22T17:42:20Z | 26,336,203 | 7 | 2014-10-13T08:57:09Z | [
"python",
"django",
"authentication"
] | Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.
Please advise, thank you. | Django now provides a full example of an extended authentication system with admin and form: <https://docs.djangoproject.com/en/dev/topics/auth/customizing/#a-full-example>
You can basically copy/paste it and adapt (I didn't need the `date_of_birth` in my case).
It is actually available since Django 1.5 and is still ... |
Generating unique and opaque user IDs in Google App Engine | 778,965 | 9 | 2009-04-22T20:06:21Z | 780,623 | 7 | 2009-04-23T07:15:00Z | [
"python",
"google-app-engine",
"guid",
"uniqueidentifier"
] | I'm working on an application that lets registered users create or upload content, and allows anonymous users to view that content and browse registered users' pages to find that content - this is very similar to how a site like Flickr, for example, allows people to browse its users' pages.
To do this, I need a way to... | Your timing is impeccable: Just yesterday, a new release of the SDK came out, with support for [unique, permanent user IDs](http://code.google.com/appengine/docs/python/users/userclass.html#User%5Fuser%5Fid). They meet all the criteria you specified. |
regex for parsing SQL statements | 778,969 | 6 | 2009-04-22T20:07:38Z | 779,084 | 8 | 2009-04-22T20:31:40Z | [
"python",
"regex"
] | I've got an IronPython script that executes a bunch of SQL statements against a SQL Server database. the statements are large strings that actually contain multiple statements, separated by the "GO" keyword. That works when they're run from sql management studio and some other tools, but not in ADO. So I split up the s... | Is "GO" always on a line by itself? You could just split on "^GO$". |
How to upload a pristine Python package to PyPI? | 778,980 | 10 | 2009-04-22T20:10:03Z | 779,790 | 16 | 2009-04-23T00:15:17Z | [
"python",
"packaging",
"pypi"
] | What's the magic "`python setup.py some_incantation_here`" command to upload a package to PyPI, in a form that can be downloaded to get the original package in its original form?
I have a package with some source and a few image files (as package\_data). If I do "`setup.py sdist register upload`", the .tar.gz has the ... | When you perform an "sdist" command, then what controls the list of included files is your "MANIFEST.in" file sitting next to "setup.py", not whatever you have listed in "package\_data". This has something to do with the schizophrenic nature of the Python packaging solutions today; "sdist" is powered by the [distutils]... |
Python Multiprocessing: Sending data to a process | 779,384 | 2 | 2009-04-22T21:47:29Z | 781,749 | 8 | 2009-04-23T13:37:03Z | [
"python",
"multiprocessing"
] | I have subclassed `Process` like so:
```
class EdgeRenderer(Process):
def __init__(self,starter,*args,**kwargs):
Process.__init__(self,*args,**kwargs)
self.starter=starter
```
Then I define a `run` method which uses `self.starter`.
That `starter` object is of a class `State` that I define.
Is it... | On unix systems, multiprocessing uses os.fork() to create the children, on windows, it uses some subprocess trickery and serialization to share the data. So to be cross platform, yes - it must be serializable. The child will get a new copy.
That being said, here's an example:
```
from multiprocessing import Process
i... |
Python Access Data in Package Subdirectory | 779,495 | 41 | 2009-04-22T22:17:52Z | 779,552 | 19 | 2009-04-22T22:37:04Z | [
"python",
"packages"
] | I am writing a python package with modules that need to open data files in a `./data/` subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system.
I've tr... | You can use underscore-underscore-file-underscore-underscore (`__file__`) to get the path to the package, like this:
```
import os
this_dir, this_filename = os.path.split(__file__)
DATA_PATH = os.path.join(this_dir, "data", "data.txt")
print open(DATA_PATH).read()
``` |
Python Access Data in Package Subdirectory | 779,495 | 41 | 2009-04-22T22:17:52Z | 5,601,839 | 47 | 2011-04-08T23:42:39Z | [
"python",
"packages"
] | I am writing a python package with modules that need to open data files in a `./data/` subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system.
I've tr... | The standard way to do this is with setuptools packages and pkg\_resources.
You can lay out your package according to the following hierarchy, and configure the package setup file to point it your data resources, as per this link:
<http://docs.python.org/distutils/setupscript.html#installing-package-data>
You can th... |
Python Access Data in Package Subdirectory | 779,495 | 41 | 2009-04-22T22:17:52Z | 26,278,544 | 9 | 2014-10-09T12:33:03Z | [
"python",
"packages"
] | I am writing a python package with modules that need to open data files in a `./data/` subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system.
I've tr... | To provide a solution working today. Definitely use this API to not reinvent all those wheels.
A true filesystem filename is needed. Zipped eggs will be extracted to a cache directory:
```
from pkg_resources import resource_filename, Requirement
path_to_vik_logo = resource_filename(Requirement.parse("enb.portals"), ... |
Stop python from closing on error | 779,675 | 10 | 2009-04-22T23:31:27Z | 779,686 | 13 | 2009-04-22T23:37:20Z | [
"python",
"debugging"
] | In python when running scripts is there a way to stop the console window from closing after spitting out the traceback? | ```
try:
#do some stuff
1/0 #stuff that generated the exception
except Exception as ex:
print ex
raw_input()
``` |
Stop python from closing on error | 779,675 | 10 | 2009-04-22T23:31:27Z | 779,693 | 13 | 2009-04-22T23:39:11Z | [
"python",
"debugging"
] | In python when running scripts is there a way to stop the console window from closing after spitting out the traceback? | If you doing this on a Windows OS, you can prefix the target of your shortcut with:
```
C:\WINDOWS\system32\cmd.exe /K <command>
```
This will prevent the window from closing when the command exits. |
Stop python from closing on error | 779,675 | 10 | 2009-04-22T23:31:27Z | 781,074 | 8 | 2009-04-23T10:03:04Z | [
"python",
"debugging"
] | In python when running scripts is there a way to stop the console window from closing after spitting out the traceback? | You can register a top-level exception handler that keeps the application alive when an unhandled exception occurs:
```
def show_exception_and_exit(exc_type, exc_value, tb):
import traceback
traceback.print_exception(exc_type, exc_value, tb)
raw_input("Press key to exit.")
sys.exit(-1)
import sys
sy... |
What to write into log file? | 779,989 | 10 | 2009-04-23T01:41:25Z | 779,995 | 9 | 2009-04-23T01:44:15Z | [
"python",
"logging",
"methodology"
] | My question is simple: what to write into a log.
Are there any conventions?
What do I have to put in?
Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is.
I already have some ideas, like a timestamp, a unique identifier for each function/method... | **Here are some suggestions for content:**
* timestamp
* message
* log message type (such as error, warning, trace, debug)
* thread id ( so you can make sense of the log file from a multi threaded application)
**Best practices for implementation:**
* Put a mutex around the write method so that you can be sure that e... |
What to write into log file? | 779,989 | 10 | 2009-04-23T01:41:25Z | 780,005 | 18 | 2009-04-23T01:47:54Z | [
"python",
"logging",
"methodology"
] | My question is simple: what to write into a log.
Are there any conventions?
What do I have to put in?
Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is.
I already have some ideas, like a timestamp, a unique identifier for each function/method... | It's quite pleasant, and already implemented.
Read this: <http://docs.python.org/library/logging.html>
---
**Edit**
"easy to parse, read," are generally contradictory features. English -- easy to read, hard to parse. XML -- easy to parse, hard to read. There is no format that achieves easy-to-read and easy-to-parse... |
How do I create collision detections for my bouncing balls? | 780,169 | 6 | 2009-04-23T03:13:56Z | 780,201 | 9 | 2009-04-23T03:29:34Z | [
"python",
"collision-detection"
] | I have coded an animation (in python) for three beach balls to bounce around a screen. I now wish to have them all collide and be able to bounce off each other. I would really appreciate any help that can be offered.
```
import pygame
import random
import sys
class Ball:
def __init__(self,X,Y):
self.vel... | Collision detection for arbitrary shapes is usually quite tricky since you have to figure out if any pixel collides.
This is actually easier with circles. If you have two circles of radius r1 and r2, a collision has occurred if the distance between the centers is less than r1+r2.
The distance between the two centers ... |
Unescape Python Strings From HTTP | 780,334 | 14 | 2009-04-23T04:36:55Z | 780,344 | 33 | 2009-04-23T04:41:14Z | [
"python",
"http",
"header",
"urllib2",
"mod-wsgi"
] | I've got a string from an HTTP header, but it's been escaped.. what function can I use to unescape it?
```
myemail%40gmail.com -> [email protected]
```
Would urllib.unquote() be the way to go? | I am pretty sure that urllib's [`unquote`](http://docs.python.org/library/urllib.html#urllib.unquote) is the common way of doing this.
```
>>> import urllib
>>> urllib.unquote("myemail%40gmail.com")
'[email protected]'
```
There's also [`unquote_plus`](http://docs.python.org/library/urllib.html#urllib.unquote%5Fplus)... |
Convert a number to a list of integers | 780,390 | 13 | 2009-04-23T05:14:20Z | 780,403 | 47 | 2009-04-23T05:22:12Z | [
"python",
"list",
"integer"
] | How do I write the `magic` function below?
```
>>> num = 123
>>> lst = magic(num)
>>>
>>> print lst, type(lst)
[1, 2, 3], <type 'list'>
``` | You mean this?
```
num = 1234
lst = [int(i) for i in str(num)]
``` |
Convert a number to a list of integers | 780,390 | 13 | 2009-04-23T05:14:20Z | 780,407 | 10 | 2009-04-23T05:23:15Z | [
"python",
"list",
"integer"
] | How do I write the `magic` function below?
```
>>> num = 123
>>> lst = magic(num)
>>>
>>> print lst, type(lst)
[1, 2, 3], <type 'list'>
``` | You could do this:
```
>>> num = 123
>>> lst = map(int, str(num))
>>> lst, type(lst)
([1, 2, 3], <type 'list'>)
``` |
Python base class method call: unexpected behavior | 780,670 | 5 | 2009-04-23T07:31:02Z | 780,728 | 9 | 2009-04-23T07:58:52Z | [
"python",
"inheritance",
"dictionary"
] | Why does `str(A())` seemingly call `A.__repr__()` and not `dict.__str__()` in the example below?
```
class A(dict):
def __repr__(self):
return 'repr(A)'
def __str__(self):
return dict.__str__(self)
class B(dict):
def __str__(self):
return dict.__str__(self)
print 'call: repr(A) e... | `str(A())` does call `__str__`, in turn calling `dict.__str__()`.
It is `dict.__str__()` that returns the value repr(A). |
SQLAlchemy - Dictionary of tags | 780,774 | 14 | 2009-04-23T08:19:36Z | 784,095 | 21 | 2009-04-24T00:21:28Z | [
"python",
"sqlalchemy"
] | I have question regarding the SQLAlchemy. How can I add into my mapped class the dictionary-like attribute, which maps the string keys into string values and which will be stored in the database (in the same or another table as original mapped object). I want this add support for arbitrary tags of my objects.
I found ... | The simple answer is **yes**.
Just use an association proxy:
```
from sqlalchemy import Column, Integer, String, Table, create_engine
from sqlalchemy import orm, MetaData, Column, ForeignKey
from sqlalchemy.orm import relation, mapper, sessionmaker
from sqlalchemy.orm.collections import column_mapped_collection
from ... |
How to set correct value for Django ROOT_URLCONF setting in different branches | 781,211 | 7 | 2009-04-23T10:54:32Z | 781,404 | 13 | 2009-04-23T12:01:26Z | [
"python",
"django",
"mercurial"
] | I've put site directory created by `django-admin startproject` under version control (Mercurial). Let's say, the site is called `frobnicator`.
Now I want to make some serious refactoring, so I clone the site using command
```
hg clone frobnicator frobnicator-refactoring`
```
but `ROOT_URLCONF` in `settings.py` still... | Simply remove project name form `ROOT_URLCONF` definition - it is optional. Then you can have project folder with different names. |
Python3 Http Web Server: virtual hosts | 781,466 | 2 | 2009-04-23T12:20:12Z | 781,474 | 10 | 2009-04-23T12:22:59Z | [
"python",
"http",
"python-3.x",
"virtualhost"
] | I am writing an rather simple http web server in python3. The web server needs to be simple - only basic reading from config files, etc. I am using only standard libraries and for now it works rather ok.
There is only one requirement for this project, which I can't implement on my own - virtual hosts. I need to have a... | Virtual hosts work by obeying the Host: header in the HTTP request.
Just read the headers of the request, and take action based on the value of the Host: header |
Qt and context menu | 782,255 | 14 | 2009-04-23T15:26:41Z | 782,462 | 39 | 2009-04-23T16:14:44Z | [
"python",
"qt",
"pyqt",
"menu"
] | i need to create a context menu on right clicking at my window. But i really don't know what should i do. Are there any widgets or i must make it by my hands?
Programming language: Python
Graphical lib: Qt (PyQt). | I can't speak for python, but it's fairly easy in C++.
first after creating the widget you set the policy:
```
w->setContextMenuPolicy(Qt::CustomContextMenu);
```
then you connect the context menu event to a slot:
```
connect(w, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &))... |
Qt and context menu | 782,255 | 14 | 2009-04-23T15:26:41Z | 958,969 | 14 | 2009-06-06T04:07:47Z | [
"python",
"qt",
"pyqt",
"menu"
] | i need to create a context menu on right clicking at my window. But i really don't know what should i do. Are there any widgets or i must make it by my hands?
Programming language: Python
Graphical lib: Qt (PyQt). | Another example which shows how to use actions in a toolbar and context menu.
```
class Foo( QtGui.QWidget ):
def __init__(self):
QtGui.QWidget.__init__(self, None)
mainLayout = QtGui.QVBoxLayout()
self.setLayout(mainLayout)
# Toolbar
toolbar = QtGui.QToolBar()
mai... |
Emacs function to message the python function I'm in | 782,357 | 10 | 2009-04-23T15:50:22Z | 782,413 | 21 | 2009-04-23T16:01:39Z | [
"python",
"emacs",
"elisp"
] | I'm editing some Python code with rather long functions and decided it would be useful to quickly get the function name without scrolling up. I put this bit of code together to do it. Is there something built in to emacs in general, or the standard python mode in particular, which I can use instead?
```
(defun python-... | You may find decent results with [which-function-mode](http://www.gnu.org/software/emacs/manual/html%5Fnode/emacs/Which-Function.html):
> Which Function mode is a minor mode
> that displays the current function
> name in the mode line, updating it as
> you move around in a buffer.
>
> To either enable or disable Which... |
how to run a python script in the background? | 783,531 | 10 | 2009-04-23T21:07:49Z | 783,555 | 37 | 2009-04-23T21:15:11Z | [
"python",
"windows",
"backgrounding"
] | I have a script which checking something on my pc every 5 min and I dont want python to show on my tasktray
is there any way to make python run in the background and force him not to show in my task tray ?
thanks
im using windows by the way | If you run a console script using `pythonw.exe`, it will neither display a window nor appear in the task bar. For example, I use the following command to launch [ntlmaps](http://ntlmaps.sourceforge.net/) on startup:
```
C:\BenBlank\Python2.6\pythonw.exe scripts/ntlmaps
```
Be aware, however, that there is no way to i... |
Python equivalent of PHP's compact() and extract() | 783,781 | 7 | 2009-04-23T22:21:29Z | 783,839 | 8 | 2009-04-23T22:40:07Z | [
"php",
"python",
"dictionary"
] | [compact](http://www.php.net/compact)() and [extract](http://www.php.net/extract)() are functions in PHP I find tremendously handy. compact() takes a list of names in the symbol table and creates a hashtable with just their values. extract does the opposite. e.g.,
```
$foo = 'what';
$bar = 'ever';
$a = compact('foo', ... | I'm afraid there are no equivalents in Python. To some extent, you can simulate their effect using (and passing) `locals`:
```
>>> def compact(locals, *keys):
... return dict((k, locals[k]) for k in keys)
...
>>> a = 10
>>> b = 2
>>> compact(locals(), 'a', 'b')
{'a': 10, 'b': 2}
>>> def extract(locals, d):
... ... |
Python equivalent of PHP's compact() and extract() | 783,781 | 7 | 2009-04-23T22:21:29Z | 783,867 | 9 | 2009-04-23T22:47:46Z | [
"php",
"python",
"dictionary"
] | [compact](http://www.php.net/compact)() and [extract](http://www.php.net/extract)() are functions in PHP I find tremendously handy. compact() takes a list of names in the symbol table and creates a hashtable with just their values. extract does the opposite. e.g.,
```
$foo = 'what';
$bar = 'ever';
$a = compact('foo', ... | It's not very Pythonic, but if you really must:
```
import inspect
def compact(*names):
caller = inspect.stack()[1][0] # caller of compact()
vars = {}
for n in names:
if n in caller.f_locals:
vars[n] = caller.f_locals[n]
elif n in caller.f_globals:
vars[n] = caller.... |
Truncating floats in Python | 783,897 | 46 | 2009-04-23T22:56:44Z | 783,900 | 94 | 2009-04-23T22:59:15Z | [
"python",
"floating-point"
] | I want to remove digits from a float to have a fixed number of digits after the dot, like:
```
1.923328437452 -> 1.923
```
I need to output as a string to another function, not print.
Also I want to ignore the lost digits, not round them. | ```
round(1.923328437452, 3)
```
See [Python's documentation on the standard types](http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex). You'll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.