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 C extension: Use extension PYD or DLL? | 8,262,884 | 17 | 2011-11-24T22:03:18Z | 8,471,102 | 13 | 2011-12-12T07:23:03Z | [
"python",
"python-c-extension",
"pyd"
] | I have a Python extension written in C and I wonder if I should use the file extension DLL or PYD under Windows. (And what would I use in Linux?)
Are there any differences (besides the filename)?
I found [an unofficial article](http://pyfaq.infogami.com/is-a-pyd-file-the-same-as-a-dll). Is this the secret of pyc?
Why... | pyd files are just dll files ready for python importing.
To distinguish them from normal dlls, I suggest, use pyd not dll in windows.
There is the official doc about this issue:
<http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll> |
Python on Linux: get host name in /etc/hostname | 8,263,192 | 8 | 2011-11-24T22:49:48Z | 8,263,238 | 9 | 2011-11-24T22:56:04Z | [
"python",
"linux",
"ip"
] | From within a Python script I am trying to get the host name in a Linux box. It is a Debian GNU/Linux Amazon EC2 instance. I have set the correct name in `/etc/hostname`. The recommended solution `socket.gethostname()` is not working: it shows the ip- plus the IP tuple.
I have searched on StackOverflow and nothing is ... | Try `os.uname()`. According to [the doc](http://docs.python.org/library/os.html#os.uname), it is the second position in the tuple returned.
But, as the doc itself states, the "better way to get the hostname is `socket.gethostname()` or even `socket.gethostbyaddr(socket.gethostname())`." |
Read into a bytearray at an offset? | 8,263,899 | 5 | 2011-11-25T00:59:17Z | 8,264,275 | 11 | 2011-11-25T02:25:47Z | [
"python",
"io",
"python-3.x",
"buffer"
] | How can I use the [`readinto()`](http://docs.python.org/py3k/library/io.html#io.RawIOBase.readinto) method call to an offset inside a [`bytearray`](http://docs.python.org/py3k/library/functions.html#bytearray), in the same way that [`struct.unpack_from`](http://docs.python.org/py3k/library/struct.html#struct.unpack_fro... | You can use a [`memoryview`](http://docs.python.org/library/stdtypes.html#memoryview) to do the job. For example:
```
dest = bytearray(10) # all zero bytes
v = memoryview(dest)
ioObject.readinto(v[3:])
print(repr(dest))
```
Assuming that `iObject.readinto(...)` reads the bytes 1, 2, 3, 4, and 5 then this code prints:... |
How to get priorly-unkown array as the output of a function in Fortran | 8,264,336 | 12 | 2011-11-25T02:36:03Z | 8,265,857 | 12 | 2011-11-25T07:19:05Z | [
"python",
"arrays",
"fortran",
"dynamic-arrays"
] | In **Python**:
```
def select(x):
y = []
for e in x:
if e!=0:
y.append(e)
return y
```
that works as:
```
x = [1,0,2,0,0,3]
select(x)
[1,2,3]
```
to be translated into **Fortran**:
```
function select(x,n) result(y)
implicit none
integer:: x(n),n,i,j,y(?)
j = 0
do i=... | I hope a real Fortran programmer comes along, but in the absence of better advice, I would only specify the shape and not the size of `x(:)`, use a temporary array `temp(size(x))`, and make the output y `allocatable`. Then after the first pass, `allocate(y(j))` and copy the values from the temporary array. But I can't ... |
How to get priorly-unkown array as the output of a function in Fortran | 8,264,336 | 12 | 2011-11-25T02:36:03Z | 8,265,903 | 10 | 2011-11-25T07:26:27Z | [
"python",
"arrays",
"fortran",
"dynamic-arrays"
] | In **Python**:
```
def select(x):
y = []
for e in x:
if e!=0:
y.append(e)
return y
```
that works as:
```
x = [1,0,2,0,0,3]
select(x)
[1,2,3]
```
to be translated into **Fortran**:
```
function select(x,n) result(y)
implicit none
integer:: x(n),n,i,j,y(?)
j = 0
do i=... | Here is an example of a Fortran function returning a variable length array. This is a feature of Fortran 2003. Also used in the test driver is automatic allocation on assignment, another Fortran 2003 feature.
```
module my_subs
contains
function select(x) result(y)
implicit none
integer, dimension (:), inten... |
Dividing Python module in to multiple regions | 8,265,583 | 10 | 2011-11-25T06:42:57Z | 20,225,477 | 7 | 2013-11-26T18:50:30Z | [
"c#",
"python",
"formatting"
] | Like in C# We can create regions by using `#region`some methods `#endregion`.
Is there any way to format python code in similar fashion ?
So that i can keep all my relevant methods in one block. | Looks like PyCharm has it, check here: ~~<http://www.jetbrains.com/pycharm/webhelp/folding-custom-regions-with-line-comments.html>~~
**Update**: <https://www.jetbrains.com/help/pycharm/2016.1/code-folding.html#using_folding_comments> |
Why is python's dict implemented as hash table whereas std::map is tree-based? | 8,265,608 | 9 | 2011-11-25T06:47:39Z | 8,265,627 | 18 | 2011-11-25T06:50:02Z | [
"c++",
"python",
"map",
"hashtable"
] | Why one languages uses tree and another uses hash table for seemingly similar data structure?
c++'s map vs python's dict
A related question is about performance of hash table.
Please comment on my understanding of hash table below.
A tree is guaranteed to have O(log n).
Whereas hash table has no guarantee unless... | The new C++ standard has the `std::unordered_map` type [which is a hash table](http://en.wikipedia.org/wiki/Unordered_map_%28C++%29). IIRC they wanted it to get into the previous standard as well, but there was not enough time during the discussions so it was left out. However, most popular compilers provided it in one... |
Why is python's dict implemented as hash table whereas std::map is tree-based? | 8,265,608 | 9 | 2011-11-25T06:47:39Z | 8,266,263 | 12 | 2011-11-25T08:12:50Z | [
"c++",
"python",
"map",
"hashtable"
] | Why one languages uses tree and another uses hash table for seemingly similar data structure?
c++'s map vs python's dict
A related question is about performance of hash table.
Please comment on my understanding of hash table below.
A tree is guaranteed to have O(log n).
Whereas hash table has no guarantee unless... | Your understanding of hash tables (and who use them) is flawed.
The problem is, hash table is a rather vague term. Under the hood there are many implementations... but first let's talk about the use of BST (Binary Search Trees).
---
> Why does C++ uses a Binary Search Tree ?
C++ is designed by commitee, there are m... |
Using the lowercase function with CSV rows | 8,265,648 | 4 | 2011-11-25T06:52:13Z | 8,265,675 | 7 | 2011-11-25T06:54:58Z | [
"python",
"csv",
"lowercase"
] | I'm trying to print all data from a csv in lowercase, but I'm not having any luck.
Here's what I have so far:
```
import csv
books = csv.reader(open("books.csv","rb"))
for row in books:
print row
```
This prints all the content of the csv, but when I add the `.lower()` function, I get errors.
What am I doing w... | Try
```
print [r.lower() for r in row]
``` |
Python regex negating metacharacters | 8,266,052 | 4 | 2011-11-25T07:45:23Z | 8,266,142 | 9 | 2011-11-25T07:57:59Z | [
"python",
"regex",
"regex-negation"
] | Python metacharacter negation.
After scouring the net and writing a few different syntaxes I'm out of ideas.
Trying to rename some files. They have a year in the title e.g. [2002].
Some don't have the brackets, which I want to rectify.
So I'm trying to find a regex (that I can compile preferably) that in my mind loo... | If you want to check for things around a pattern you can use *lookahead* and *lookbehind* assertions. These don't form part of the match but say what you expect to find (or not find) around it.
As we don't want brackets we'll need use a *negative* lookbehind and lookahead.
A negative lookahead looks like this `(?!...... |
How to install Python with Wampserver | 8,266,153 | 11 | 2011-11-25T07:59:43Z | 11,245,120 | 10 | 2012-06-28T12:54:19Z | [
"python"
] | I want install Python with Wamp or Appserv on windows, how to install ? can it run together ? | Here is my answer:
1. First you need to install python version from the python official website.
2. Now install it on yuor hard disk as i installed it in my C drive. It will be installed like (C:/Python27)
3. Now make any python file (for example lets make a file python.py in which we write)
```
#!C:/Python27/p... |
How to install Python with Wampserver | 8,266,153 | 11 | 2011-11-25T07:59:43Z | 20,128,269 | 19 | 2013-11-21T17:47:44Z | [
"python"
] | I want install Python with Wamp or Appserv on windows, how to install ? can it run together ? | Python support can be added to WampServer fairly easily, similar to adding any Apache module that doesn't ship with the base package. You need to take a few extra steps to make sure you can continue to use WampServer console to manage your application stack.
## Download mod\_wsgi Apache Module
You'll need to get an a... |
Python 2.7: replace method of string object deprecated | 8,267,219 | 4 | 2011-11-25T09:50:22Z | 8,267,285 | 17 | 2011-11-25T09:55:43Z | [
"python"
] | My "workmates" just told me that the replace method of the string object was deprecated and will be removed in 3.xx.
May I ask you if it's true, why, and if so, how to replace it (with examples)?
Thank you very much. | The [documentation](http://docs.python.org/py3k/library/stdtypes.html) of 3.2 says nothing about that the replace method of the str type should be removed. I also see no reason why someone should do that.
What was removed is the replace function in the [string](http://docs.python.org/library/string.html) module.
An e... |
Error: No such file or directory | 8,268,150 | 2 | 2011-11-25T11:03:55Z | 8,268,253 | 7 | 2011-11-25T11:12:36Z | [
"python",
"file-io"
] | I am trying to extract data from a XML file with python. I tried the following code.
```
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse("data_v2.xml")
```
Error message:
```
IOError: [Errno 2] No such file or directory: 'data_v2.xml'.
``` | This is not XML error. This means that `data_v2.xml` does not exist -- system (operation system) cannot find it. Maybe this name is wrong, maybe you need to provide full path. |
How to ignore directories when running Django collectstatic? | 8,269,883 | 18 | 2011-11-25T13:31:37Z | 8,441,824 | 17 | 2011-12-09T06:22:34Z | [
"python",
"django",
"deployment"
] | I am running a small test project with Django 1.3, Ubuntu 11.10, gunicorn and Nginx, everything in a virtualenv, and now I'm running collectstatic to get my static files into the directory that Nginx serves from.
For simplicity's sake let's say my static directory is something like /home/user/static and my project is ... | Don't write full path of directories. For example usage:
```
python manage.py collectstatic --noinput -i admin
```
This command won't copy the admin/ directory to STATIC\_ROOT path. |
Python remove all whitespace in a string | 8,270,092 | 292 | 2011-11-25T13:51:21Z | 8,270,124 | 133 | 2011-11-25T13:54:45Z | [
"python",
"trim",
"removing-whitespace"
] | I want to eliminate all the whitespace from a string, on both ends, and in between words.
I have this Python code:
```
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
```
But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace? | To remove *only spaces* use [`str.replace`](http://docs.python.org/2/library/stdtypes.html#str.replace):
```
sentence = sentence.replace(' ', '')
```
To remove *all whitespace characters* (space, tab, newline, and so on) you can use [`split`](http://docs.python.org/2/library/stdtypes.html#str.split) then [`join`](htt... |
Python remove all whitespace in a string | 8,270,092 | 292 | 2011-11-25T13:51:21Z | 8,270,145 | 12 | 2011-11-25T13:56:22Z | [
"python",
"trim",
"removing-whitespace"
] | I want to eliminate all the whitespace from a string, on both ends, and in between words.
I have this Python code:
```
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
```
But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace? | For removing whitespace from beginning and end, use `strip`.
```
>> " foo bar ".strip()
"foo bar"
``` |
Python remove all whitespace in a string | 8,270,092 | 292 | 2011-11-25T13:51:21Z | 8,270,146 | 625 | 2011-11-25T13:56:30Z | [
"python",
"trim",
"removing-whitespace"
] | I want to eliminate all the whitespace from a string, on both ends, and in between words.
I have this Python code:
```
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
```
But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace? | If you want to remove leading and ending spaces, use [`str.strip()`](http://docs.python.org/2/library/stdtypes.html#str.strip):
```
sentence = ' hello apple'
sentence.strip()
>>> 'hello apple'
```
If you want to remove all spaces, use [`str.replace()`](http://docs.python.org/2/library/stdtypes.html#str.replace):
`... |
Python remove all whitespace in a string | 8,270,092 | 292 | 2011-11-25T13:51:21Z | 28,607,213 | 19 | 2015-02-19T13:05:41Z | [
"python",
"trim",
"removing-whitespace"
] | I want to eliminate all the whitespace from a string, on both ends, and in between words.
I have this Python code:
```
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
```
But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace? | If you also want to remove all the other strange whitespace characters that exist in unicode you can use re.sub with the re.UNICODE arguement:
```
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)
```
... because do you really want to keep [these strange unicode characters](http://en.wikipedia.org/wiki/Whites... |
Python remove all whitespace in a string | 8,270,092 | 292 | 2011-11-25T13:51:21Z | 33,967,378 | 11 | 2015-11-28T03:36:53Z | [
"python",
"trim",
"removing-whitespace"
] | I want to eliminate all the whitespace from a string, on both ends, and in between words.
I have this Python code:
```
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
```
But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace? | Whitespace includes **space, tabs and CRLF**. So an elegant and **one-liner** string function we can use is **translate**.(Surprised no one mentioned it!)
`' hello apple'.translate(None, ' \n\t\r')`
**OR** if you want to be thorough
```
import string
' hello apple'.translate(None, string.whitespace)
``` |
In a matplotlib plot, can I highlight specific x-value ranges? | 8,270,981 | 21 | 2011-11-25T15:09:21Z | 8,271,438 | 29 | 2011-11-25T15:49:05Z | [
"python",
"statistics",
"matplotlib"
] | I'm making a visualization of historical stock data for a project, and I'd like to highlight regions of drops. For instance, when the stock is experiencing significant drawdown, I would like to highlight it with a red region.
Can I do this automatically, or will I have to draw a rectangle or something? | Have a look at [`axvspan`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.axvspan) (and axhspan for highlighting a region of the y-axis).
```
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.axvspan(3, 6, color='red', alpha=0.5)
plt.show()
```
. **Edit:** it seems that the OP of that question already used the code I posted to him to ask [the same question](http://stackoverflow.com/q/8203696/146792), but I was unaware of it. Apologies. The answers prov... | This is a pure guess, and I haven't figured out an easy way to check whether it is right, but I have a theory for you.
I tried your code and get the same of results, `without_else()` is repeatedly slightly slower than `with_else()`:
```
>>> T(lambda : without_else()).repeat()
[0.42015745017874906, 0.3188967452567226,... |
Matplotlib : Comma separated number format for axis | 8,271,564 | 12 | 2011-11-25T16:02:37Z | 8,272,640 | 11 | 2011-11-25T17:48:36Z | [
"python",
"matplotlib"
] | I am attempting to change the format of my axis to be comma seperated in Matplotlib running under Python 2.7 but am unable to do so.
I suspect that I need to use a FuncFormatter but I am at a bit of a loss.
Can anyone help? | Yes, you can use `matplotlib.ticker.FuncFormatter` to do this.
Here is the example:
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
def func(x, pos): # formatter function takes tick label and tick position
s = str(x)
ind = s.index('.')
return s[:ind] + ',' + s[ind+... |
Matplotlib : Comma separated number format for axis | 8,271,564 | 12 | 2011-11-25T16:02:37Z | 12,400,853 | 7 | 2012-09-13T06:47:49Z | [
"python",
"matplotlib"
] | I am attempting to change the format of my axis to be comma seperated in Matplotlib running under Python 2.7 but am unable to do so.
I suspect that I need to use a FuncFormatter but I am at a bit of a loss.
Can anyone help? | I know the question is old, but as I currently am searching for similar solutions, I decided to leave a comment for future reference if others need this.
For an alternative solution, use the `locale` module and activate locale-formatting in matplotlib.
E.g., in major parts of Europe, comma is the desired separator. Y... |
JavaScript function similar to Python range() | 8,273,047 | 35 | 2011-11-25T18:33:19Z | 8,273,091 | 42 | 2011-11-25T18:38:58Z | [
"javascript",
"python"
] | Is there a function in JavaScript similar to Python's `range()`?
I think there should be a better way than to write the following lines every time:
```
array = new Array();
for (i = 0; i < specified_len; i++) {
array[i] = i;
}
``` | **No**, there is none, but **you can make one**.
## JavaScript's implementation of Python's `range()`
Trying to **emulate how it works in Python**, I would create function similar to this:
```
function range(start, stop, step) {
if (typeof stop == 'undefined') {
// one param defined
stop = start;... |
JavaScript function similar to Python range() | 8,273,047 | 35 | 2011-11-25T18:33:19Z | 8,273,165 | 7 | 2011-11-25T18:48:10Z | [
"javascript",
"python"
] | Is there a function in JavaScript similar to Python's `range()`?
I think there should be a better way than to write the following lines every time:
```
array = new Array();
for (i = 0; i < specified_len; i++) {
array[i] = i;
}
``` | Here you go.
This will write (or overwrite) the value of each index with the index number.
```
Array.prototype.writeIndices = function( n ) {
for( var i = 0; i < (n || this.length); ++i ) this[i] = i;
return this;
};
```
If you don't provide a number, it will use the current length of the Array.
Use it like... |
JavaScript function similar to Python range() | 8,273,047 | 35 | 2011-11-25T18:33:19Z | 8,275,011 | 17 | 2011-11-25T23:10:52Z | [
"javascript",
"python"
] | Is there a function in JavaScript similar to Python's `range()`?
I think there should be a better way than to write the following lines every time:
```
array = new Array();
for (i = 0; i < specified_len; i++) {
array[i] = i;
}
``` | In addition to what's already said, Javascript 1.7+ provides support for [iterators and generators](https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators) which can be used to create a lazy, memory-efficient version of `range`, simlar to `xrange` in Python2:
```
function range(low, high) {
r... |
JavaScript function similar to Python range() | 8,273,047 | 35 | 2011-11-25T18:33:19Z | 37,980,601 | 12 | 2016-06-23T00:59:17Z | [
"javascript",
"python"
] | Is there a function in JavaScript similar to Python's `range()`?
I think there should be a better way than to write the following lines every time:
```
array = new Array();
for (i = 0; i < specified_len; i++) {
array[i] = i;
}
``` | For a very simple range in ES6:
```
let range = n => Array.from(Array(n).keys())
``` |
saving an 'lxml.etree._ElementTree' object | 8,274,438 | 9 | 2011-11-25T21:37:29Z | 8,274,474 | 12 | 2011-11-25T21:43:01Z | [
"python",
"lxml",
"pickle"
] | I've spent the last couple of days getting to grips with the basics of lxml; in particular using lxml.html to parse websites and create an ElementTree of the content. Ideally, I want to save the returned ElementTree so that I can load it up and experiment with it, without having to parse the website every time I modify... | lxml is a C library - libxml to be precise - and the object probably don't support python pickling or any other kind of serialization - except serializing them to XML.
So you'll either have to keep them in memory, or re-parse the XML fragments you need, I assume. |
saving an 'lxml.etree._ElementTree' object | 8,274,438 | 9 | 2011-11-25T21:37:29Z | 8,274,904 | 12 | 2011-11-25T22:52:33Z | [
"python",
"lxml",
"pickle"
] | I've spent the last couple of days getting to grips with the basics of lxml; in particular using lxml.html to parse websites and create an ElementTree of the content. Ideally, I want to save the returned ElementTree so that I can load it up and experiment with it, without having to parse the website every time I modify... | You are already dealing with XML, and `lxml` is great at parsing XML. So I think
the simplest thing to do would be to serialize to XML:
To write to file:
```
import lxml.etree as ET
filename = '/tmp/test.xml'
with open(filename,'w') as f:
f.write(ET.tostring(myobject))
```
To parse from file:
```
with open(fil... |
Check substring match of a word in a list of words | 8,275,417 | 2 | 2011-11-26T00:31:20Z | 8,275,543 | 8 | 2011-11-26T01:04:16Z | [
"python",
"substring",
"string-matching"
] | I want to check if a word is in a list of words.
```
word = "with"
word_list = ["without", "bla", "foo", "bar"]
```
I tried `if word in set(list)`, but it is not yielding the wanted result due to the fact `in` is matching string rather than item. That is to say, `"with"` is a match in any of the words in the `word_li... | You could do:
```
found = any(word in item for item in wordlist)
```
It checks each word for a match and returns true if any are matches |
Installing Pygame for Mac OS X 10.6.8 | 8,275,808 | 12 | 2011-11-26T02:12:36Z | 10,714,442 | 27 | 2012-05-23T06:13:59Z | [
"python",
"osx"
] | Using Python 2.7.2. When I try to import pygame I get this error message:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in <module>
from pygame.base import *
ImportErro... | The Python 2.7.3 .dmg Mac OS installer installs both 64-bit and 32-bit binaries in:
`/Library/Frameworks/Python.framework/Versions/2.7/bin/`
There is a 32-bit binary called `python2.7-32` in that folder.
To use it in the Terminal simply type $ `python2.7-32` instead of `python`
To use it in IDLE simply rename the 6... |
Statically Typed Metaprogramming? | 8,276,387 | 20 | 2011-11-26T04:55:51Z | 8,276,724 | 10 | 2011-11-26T06:23:08Z | [
"python",
"scala",
"f#",
"metaprogramming"
] | I've been thinking about what I would miss in porting some Python code to a statically typed language such as F# or Scala; the libraries can be substituted, the conciseness is comparable, but I have lots of python code which is as follows:
```
@specialclass
class Thing(object):
@specialFunc
def method1(arg1, a... | Very interesting question.
Some points regarding metaprogramming in Scala:
* In scala 2.10 there will be developments in [scala reflection](http://days2011.scala-lang.org/sites/days2011/files/01.%20Martin%20Odersky.pdf)
* There is work in source to source transformation (macros) which is something you are looking for... |
Wondering About GeoDjango and Mapping Services | 8,276,740 | 4 | 2011-11-26T06:28:54Z | 8,311,346 | 8 | 2011-11-29T13:15:18Z | [
"python",
"database",
"django",
"google-maps",
"geodjango"
] | I'm trying to build my first GIS app with GeoDjango and I have a few questions before I begin:
First: What exactly is GeoDjango for in relation to Google Maps? Is it simply for processing the information, which is then passed to a service like Google Maps?
If this is true, what's the advantage of using GeoDjango vs s... | As said in [documentation](https://docs.djangoproject.com/en/dev/ref/contrib/gis/tutorial/#introduction):
> GeoDjango is an add-on for Django that turns it into a world-class
> geographic Web framework. GeoDjango strives to make it as simple as
> possible to create geographic Web applications, like location-based
> se... |
python multiprocessing lock issue | 8,276,933 | 4 | 2011-11-26T07:16:25Z | 8,277,123 | 11 | 2011-11-26T08:02:47Z | [
"python",
"locking",
"multiprocessing"
] | I want to add a list of dicts together with python multiprocessing module.
Here is a simplified version of my code:
```
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
import multiprocessing
import functools
import time
def merge(lock, d1, d2):
time.sleep(5) # some time consuming stuffs
with lock:
for ... | The following should run cross-platform (i.e. on Windows, too) in both Python 2 and 3. It uses a process pool initializer to set the manager dict as a global in each child process.
FYI:
* Using a lock is unnecessary with a manager dict.
* The number of processes in a `Pool` defaults to the CPU count.
* If you're not ... |
python 2 and python 3 __cmp__ | 8,276,983 | 15 | 2011-11-26T07:27:29Z | 8,277,011 | 7 | 2011-11-26T07:36:23Z | [
"python"
] | When I use the code in Python 2 it works fine while Python 3 it gives me the error
```
class point:
def __init__(self,x,y):
self.x=x
self.y=y
def dispc(self):
return ('(' +str(self.x)+','+str(self.y)+')')
def __cmp__(self,other):
return ((self... | This was a major and deliberate change in Python 3. See [here](http://docs.python.org/py3k/whatsnew/3.0.html#ordering-comparisons) for more details. |
python 2 and python 3 __cmp__ | 8,276,983 | 15 | 2011-11-26T07:27:29Z | 8,277,028 | 19 | 2011-11-26T07:41:21Z | [
"python"
] | When I use the code in Python 2 it works fine while Python 3 it gives me the error
```
class point:
def __init__(self,x,y):
self.x=x
self.y=y
def dispc(self):
return ('(' +str(self.x)+','+str(self.y)+')')
def __cmp__(self,other):
return ((self... | You need to provide `__lt__` and `__eq__` method for ordering in Python 3. `__cmp__` is no longer used.
**Updated to respond to questions/comments below**
`__lt__` takes `self` and `other` as arguments, and needs to return whether `self` is less than `other`. For example:
```
class Point(object):
...
def __l... |
Multiprocessing in a pipeline done right | 8,277,715 | 8 | 2011-11-26T10:13:54Z | 16,343,709 | 7 | 2013-05-02T17:00:59Z | [
"python",
"multiprocessing"
] | I'd like to know how multiprocessing is done right. Assuming I have a list `[1,2,3,4,5]` generated by function `f1` which is written to a `Queue` (left green circle). Now I start two processes pulling from that queue (by executing `f2` in the processes). They process the data, say: doubling the value, and write it to t... | With [MPipe](http://vmlaker.github.io/mpipe) module, simply do this:
```
from mpipe import OrderedStage, Pipeline
def f2(value):
return value * 2
def f3(value):
print(value)
s1 = OrderedStage(f2, size=2)
s2 = OrderedStage(f3)
p = Pipeline(s1.link(s2))
def f1():
for task in [1,2,3,4,5,None]:
p.p... |
Python 3 - From list to exact string (like list) | 8,280,061 | 2 | 2011-11-26T17:01:17Z | 8,280,073 | 8 | 2011-11-26T17:03:17Z | [
"python"
] | I have:
```
list = [1, 2, 3, 4, 5]
```
And I want the exact string:
```
string = "[1, 2, 3, 4, 5]"
```
Any help? | Represent it:
```
>>> repr([1, 2, 3, 4, 5])
'[1, 2, 3, 4, 5]'
``` |
curve fitting with python | 8,280,871 | 13 | 2011-11-26T19:08:02Z | 8,280,903 | 28 | 2011-11-26T19:14:18Z | [
"python",
"numpy",
"curve-fitting"
] | I'm trying to fit some data and stuff, I know there is a simple command to do this with python/numpy/matplotlib, but I can't find it. I think it is something like
```
popt,popc = numpy.curvefit(f,x)
```
where `popt` is the paramters of `f`, `popc` is the fit quality and `f` is a predefined function of f. Does any of ... | Take a look at [scipy.optimize.curve\_fit](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html):
> scipy.optimize.curve\_fit(f, xdata, ydata, p0=None, sigma=None, \*\*kw)
>
> Use non-linear least squares to fit a function, f, to data. |
10*10 fold cross validation in scikit-learn? | 8,281,034 | 5 | 2011-11-26T19:36:33Z | 8,281,241 | 8 | 2011-11-26T20:05:39Z | [
"python",
"machine-learning",
"scikits",
"scikit-learn"
] | Is `class sklearn.cross_validation.ShuffleSplit(n, n_iterations=10, test_fraction=0.10000000000000001, indices=True, random_state=None)` the right way for 10\*10fold CV in scikit-learn? (By changing the random\_state to 10 different numbers)
Because I didn't find any random\_state parameter in `Stratified K-Fold` or `... | I am not sure what you mean by 10\*10 cross validation. The ShuffleSplit configuration you give will make you call the fit method of the estimator 10 times. If you call this 10 times by explicitly using an outer loop or directly call it 100 times with 10% of the data reserved for testing in a single loop if you use ins... |
How to get current Linux process ID (pid) from cmdline (in shell- and language-independent fashion)? | 8,281,345 | 5 | 2011-11-26T20:20:52Z | 16,136,863 | 12 | 2013-04-21T22:26:32Z | [
"python",
"linux",
"shell",
"command-line",
"fabric"
] | How to get one's current process ID (pid) from Linux cmdline (in shell- and language-independent fashion)? [pidof(8)](http://linux.die.net/man/8/pidof) appears to have no option to get the calling-processes pid. bash of course has `$$` but for my generic usage, can't rely on a shell (bash or otherwise). And in some cas... | From python:
```
$ python
>>> import os
>>> os.getpid()
12252
``` |
Python, How to get all external ip addresses with multiple NICs | 8,281,371 | 4 | 2011-11-26T20:25:20Z | 8,287,065 | 9 | 2011-11-27T16:31:28Z | [
"python",
"networking",
"ip",
"nic"
] | What is the most efficient way to get all of the external ip address of a machine with multiple nics, using python? I understand that an external server is neeeded (I have one available) but am un able to find a way to find a good way to specify the nic to use for the connection (So I can use a for loop to iterate thro... | You should use [netifaces](http://pypi.python.org/pypi/netifaces/). It is designed to be cross-platform on Mac OS X, Linux, and Windows.
```
>>> import netifaces as ni
>>> ni.interfaces()
['lo', 'eth0', 'eth1', 'vboxnet0', 'dummy1']
>>> ni.ifaddresses('eth0')
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:02:55:... |
Python: how to use variables as a string? | 8,281,455 | 3 | 2011-11-26T20:40:05Z | 8,281,478 | 8 | 2011-11-26T20:44:15Z | [
"python",
"django"
] | Supose I have such variables: var1, var2, var3, var4, var 5, ..., var100 (lists and dictionaries are not suitable in my case, because all these vars are class objects).
I must process all them in similar way, for example:
```
if var1:
print 'var1 is not None'
if var2:
print 'var2 is not None'
if var3:
pri... | `locals()` returns a dictionary of local variables. Similarly, `globals()` returns a dictionary of global variables. You can find the variable and its value in one of those, depending on where it was defined.
```
for i in range(1,101):
if ('var%s' % i) in locals():
print 'var%s is not None' % i
pri... |
two lists into a dictionary | 8,281,739 | 4 | 2011-11-26T21:26:23Z | 8,281,755 | 7 | 2011-11-26T21:28:16Z | [
"python",
"dictionary",
"zip"
] | I have two lists created in python like so:
```
list1 = [2, 3, 3, 4, 4, 5]
list2 = [-4, 8, -4, 8, -1, 2]
```
Now I zipped these two lists into a dictionary like so:
```
d = dict(zip(list1, list2))
```
which gives me:
```
{2: -4, 3: -4, 4: -1, 5: 2}
```
What I want to get is a result like this:
```
{2: -4, 3: 4, ... | Try using a [`defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict):
```
from collections import defaultdict
d = defaultdict(int)
for k, v in zip(list1, list2):
d[k] += v
```
Result:
```
defaultdict(<type 'int'>, {2: -4, 3: 4, 4: 7, 5: 2})
```
See it working online: [ideone](ht... |
two lists into a dictionary | 8,281,739 | 4 | 2011-11-26T21:26:23Z | 8,281,760 | 10 | 2011-11-26T21:29:26Z | [
"python",
"dictionary",
"zip"
] | I have two lists created in python like so:
```
list1 = [2, 3, 3, 4, 4, 5]
list2 = [-4, 8, -4, 8, -1, 2]
```
Now I zipped these two lists into a dictionary like so:
```
d = dict(zip(list1, list2))
```
which gives me:
```
{2: -4, 3: -4, 4: -1, 5: 2}
```
What I want to get is a result like this:
```
{2: -4, 3: 4, ... | I think you want something like this:
```
>>> list1 = [2, 3, 3, 4, 4, 5]
>>> list2 = [-4, 8, -4, 8, -1, 2]
>>> d = {}
>>> for k, v in zip(list1, list2):
d[k] = d.get(k, 0) + v
>>> d
{2: -4, 3: 4, 4: 7, 5: 2}
``` |
In laymans terms, what does the Python string format "g" actually mean? | 8,282,130 | 4 | 2011-11-26T22:30:42Z | 8,282,210 | 8 | 2011-11-26T22:45:51Z | [
"python",
"floating-point",
"number-formatting",
"exponent"
] | I feel a bit silly for asking what I'm sure is a rather basic question, but I've been learning Python and I'm having difficulty understanding what exactly the "g" and "G" string formats actually do.
The documentation has this to say:
> Floating point format. Uses lowercase exponential format if exponent is less than ... | These examples are probably illustrative:
```
>>> numbers = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001]
>>> for number in numbers:
... print "%%e=%e, %%f=%f, %%g=%g" % (number, number, number)
...
%e=1.000000e+02, %f=100.000000, %g=100
%e=1.000000e+01, %f=10.000000, %g=10
%e=1.000000e+00, %f=1.000000, %g=1
%e... |
I have Python on my Ubuntu system, but gcc cant find Python.h | 8,282,231 | 34 | 2011-11-26T22:49:51Z | 8,282,257 | 30 | 2011-11-26T22:53:46Z | [
"python",
"c",
"ubuntu",
"header"
] | I am on a school computer, so I can't install anything.
I am trying to create C code which can be run in Python. It seems all the articles I am finding on it require you to use
```
#include <Python.h>
```
I do this, but when I compile it complains that *there is no such file or directory.*
The computer has Python (... | You need the `python-dev` package which contains `Python.h` |
I have Python on my Ubuntu system, but gcc cant find Python.h | 8,282,231 | 34 | 2011-11-26T22:49:51Z | 8,282,261 | 38 | 2011-11-26T22:54:45Z | [
"python",
"c",
"ubuntu",
"header"
] | I am on a school computer, so I can't install anything.
I am trying to create C code which can be run in Python. It seems all the articles I am finding on it require you to use
```
#include <Python.h>
```
I do this, but when I compile it complains that *there is no such file or directory.*
The computer has Python (... | On Ubuntu, you would need to install a package called `python-dev`. Since this package doesn't seem to be installed (`locate Python.h` didn't find anything) and you can't install it system-wide yourself, we need a different solution.
You can install Python in your home directory -- you don't need any special permissio... |
I have Python on my Ubuntu system, but gcc cant find Python.h | 8,282,231 | 34 | 2011-11-26T22:49:51Z | 14,773,082 | 13 | 2013-02-08T12:56:17Z | [
"python",
"c",
"ubuntu",
"header"
] | I am on a school computer, so I can't install anything.
I am trying to create C code which can be run in Python. It seems all the articles I am finding on it require you to use
```
#include <Python.h>
```
I do this, but when I compile it complains that *there is no such file or directory.*
The computer has Python (... | On ubuntu you can just type `sudo apt-get install python-dev -y` in terminal to install the python-dev package. |
I have Python on my Ubuntu system, but gcc cant find Python.h | 8,282,231 | 34 | 2011-11-26T22:49:51Z | 19,344,978 | 12 | 2013-10-13T12:03:28Z | [
"python",
"c",
"ubuntu",
"header"
] | I am on a school computer, so I can't install anything.
I am trying to create C code which can be run in Python. It seems all the articles I am finding on it require you to use
```
#include <Python.h>
```
I do this, but when I compile it complains that *there is no such file or directory.*
The computer has Python (... | You have to use *#include "python2.7/Python.h"* instead of *#include "Python.h"*. |
Removing character in list of strings | 8,282,553 | 12 | 2011-11-26T23:54:24Z | 8,282,563 | 20 | 2011-11-26T23:56:58Z | [
"python"
] | If I have a list of strings such as:
```
[("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]
```
What should I do in order to get rid of all the `8`s in each string? I tried using `strip` or `replace` in a for loop but it doesn't work like it would in a normal string (that not in a list). Does anyone have a suggestion? | Try this:
```
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
print([s.strip('8') for s in lst]) # remove the 8 from the string borders
print([s.replace('8', '') for s in lst]) # remove all the 8s
``` |
Removing character in list of strings | 8,282,553 | 12 | 2011-11-26T23:54:24Z | 8,282,631 | 8 | 2011-11-27T00:09:53Z | [
"python"
] | If I have a list of strings such as:
```
[("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]
```
What should I do in order to get rid of all the `8`s in each string? I tried using `strip` or `replace` in a for loop but it doesn't work like it would in a normal string (that not in a list). Does anyone have a suggestion? | Beside using loop and for comprehension, you could also use map
```
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst
``` |
cProfile saving data to file causes jumbles of characters | 8,283,112 | 14 | 2011-11-27T02:04:47Z | 8,283,329 | 19 | 2011-11-27T03:03:29Z | [
"python",
"file",
"command-line",
"profiling",
"cprofile"
] | I am using cProfile on a module named bot4CA.py so in the console I type:
```
python -m cProfile -o thing.txt bot4CA.py
```
After the module runs and exits, it creates a file named thing.txt and when I open it, there is some information there, and the rest is a jumble of characters instead of a neatly organized file ... | You should use the `pstats` module to parse this file and extract information in user-friendly format from it. For example:
```
import pstats
p = pstats.Stats('thing.txt')
p.sort_stats('cumulative').print_stats(10)
```
It's all [in the documentation](http://docs.python.org/library/profile.html), of course. Go over th... |
Call Javascript function from Python | 8,284,765 | 23 | 2011-11-27T10:02:44Z | 8,284,932 | 9 | 2011-11-27T10:31:35Z | [
"javascript",
"python",
"screen-scraping",
"web-scraping"
] | I am working on a web-scraping project. One of the website, I am working has the data coming from Javascript.
There was a suggestion in one of my earlier question, that I can directly call the Javascript from Python.
Any idea how to do it? I was not able to figure out how to call the Javascript function for instance ... | Find a JavaScript interpreter that has Python bindings. (Try Rhino? V8? SeaMonkey?). When you have found one, it should come with examples of how to use it from python.
Python itself, however, does not include a *JavaScript interpreter*. |
Pass the user-agent through webdriver in Selenium | 8,286,127 | 7 | 2011-11-27T14:06:26Z | 10,581,973 | 21 | 2012-05-14T10:55:52Z | [
"python",
"selenium",
"screen-scraping",
"web-scraping",
"user-agent"
] | I am working on a website scraping project using Selenium in Python. When I open the homepage through a browser, it opens properly.
But, when I try to open the webpage through `webdriver()` in Selenium, it opens a completely different page.
I think, it is able to detect the `user-agent`( not sure what it is called) a... | Changing the user agent in the python version of webdriver is done by altering your browser's profile. I have only done this for `webdriver.Firefox()` by passing a profile parameter. You need to do the following:
```
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.us... |
How to save an image locally using Python whose URL address I already know? | 8,286,352 | 51 | 2011-11-27T14:46:37Z | 8,286,397 | 11 | 2011-11-27T14:51:16Z | [
"python",
"web-scraping"
] | I know the URL of an image on Internet.
e.g. <http://www.digimouth.com/news/media/2011/09/google-logo.jpg>, which contains the logo of Google.
Now, how can I download this image using Python without actually opening the URL in a browser and saving the file manually. | ```
import urllib
resource = urllib.urlopen("http://www.digimouth.com/news/media/2011/09/google-logo.jpg")
output = open("file01.jpg","wb")
output.write(resource.read())
output.close()
```
`file01.jpg` will contain your image. |
How to save an image locally using Python whose URL address I already know? | 8,286,352 | 51 | 2011-11-27T14:46:37Z | 8,286,449 | 122 | 2011-11-27T15:01:14Z | [
"python",
"web-scraping"
] | I know the URL of an image on Internet.
e.g. <http://www.digimouth.com/news/media/2011/09/google-logo.jpg>, which contains the logo of Google.
Now, how can I download this image using Python without actually opening the URL in a browser and saving the file manually. | Here is a more straightforward way if all you want to do is save it as a file:
```
import urllib
urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
```
The second argument is the local path where the file should be saved. |
How to save an image locally using Python whose URL address I already know? | 8,286,352 | 51 | 2011-11-27T14:46:37Z | 23,159,190 | 7 | 2014-04-18T17:36:59Z | [
"python",
"web-scraping"
] | I know the URL of an image on Internet.
e.g. <http://www.digimouth.com/news/media/2011/09/google-logo.jpg>, which contains the logo of Google.
Now, how can I download this image using Python without actually opening the URL in a browser and saving the file manually. | I wrote [a script that does just this](https://github.com/nateberman/Python-WebImageScraper), and it is available on my github for your use.
I utilized BeautifulSoup to allow me to parse any website for images. If you will be doing much web scraping (or intend to use my tool) I suggest you `sudo pip install BeautifulS... |
Find anagrams for a list of words | 8,286,554 | 5 | 2011-11-27T15:17:38Z | 8,286,606 | 9 | 2011-11-27T15:25:26Z | [
"python"
] | If I have a list of strings for example:
```
["car", "tree", "boy", "girl", "arc"....]
```
What should I do in order to find anagrams in that list? For example `(car, arc)`.
I tried using for loop for each string and I used `if` in order to ignore strings in different lengths but I can't get the right result.
How ca... | Create a dictionary of (sorted word, list of word). All the words that are in the same list are anagrams of each other.
```
from collections import defaultdict
def load_words(filename='/usr/share/dict/american-english'):
with open(filename) as f:
for word in f:
yield word.rstrip()
def get_ana... |
Find anagrams for a list of words | 8,286,554 | 5 | 2011-11-27T15:17:38Z | 8,286,639 | 12 | 2011-11-27T15:29:01Z | [
"python"
] | If I have a list of strings for example:
```
["car", "tree", "boy", "girl", "arc"....]
```
What should I do in order to find anagrams in that list? For example `(car, arc)`.
I tried using for loop for each string and I used `if` in order to ignore strings in different lengths but I can't get the right result.
How ca... | In order to do this for 2 strings you can do this:
```
def isAnagram(str1, str2):
str1_list = list(str1)
str1_list.sort()
str2_list = list(str2)
str2_list.sort()
return (str1_list == str2_list)
```
As for the iteration on the list, it is pretty straight forward |
Get first N key pairs from an Ordered Dictionary to another one in python | 8,287,000 | 4 | 2011-11-27T16:22:04Z | 8,300,222 | 11 | 2011-11-28T18:04:51Z | [
"python",
"dictionary",
"ordereddictionary"
] | I have an ordered dictionary (OrderedDict) sorted by value. How can I get the top (say 25) key values and add them to a new dictionary?
For example: I have something like this
```
dictionary={'a':10,'b':20,'c':30,'d':5}
ordered=OrderedDict(sorted(dictionary.items(), key=lambda x: x[1],reverse=True))
```
Now ordered i... | The primary purpose of OrderedDict is retaining the order in which the elements were created.
What you want here is [`collections.Counter`](http://docs.python.org/library/collections.html#collections.Counter), which has the n-most-frequent functionality built-in:
```
>>> dictionary={'a':10,'b':20,'c':30,'d':5}
>>> imp... |
IPython won't start | 8,287,422 | 15 | 2011-11-27T17:21:29Z | 8,287,474 | 18 | 2011-11-27T17:28:37Z | [
"python",
"ipython"
] | I'm running Windows 7 x64. I installed the 32x verson of Python 2.7.2 and IPython 0.11 using the Windows Installers. They installed all right. I added C:\Python27 and C:\Python27\Scripts to the system envorment variables.
When I type ipython in the command prompt I get this message:
> Traceback (most recent call last... | Solution. Also need to install `setuptools` from <http://pypi.python.org/pypi/setuptools> |
Proxies with Python 'Requests' module | 8,287,628 | 53 | 2011-11-27T17:50:23Z | 8,287,752 | 93 | 2011-11-27T18:08:32Z | [
"python",
"http-request",
"python-requests"
] | Just a short, simple one about the excellent [Requests](http://docs.python-requests.org/en/latest/index.html) module for Python.
I can't seem to find in the documentation what the variable 'proxies' should contain. When I send it a dict with a standard "IP:PORT" value it rejected it asking for 2 values.
So, I guess (b... | The `proxies`' dict syntax is `{"protocol":"ip:port", ...}`. With it you can specify different (or the same) proxie(s) for requests using *http*, *https*, and *ftp* protocols:
```
http_proxy = "http://10.10.1.10:3128"
https_proxy = "https://10.10.1.11:1080"
ftp_proxy = "ftp://10.10.1.10:3128"
proxyDict = {
... |
Proxies with Python 'Requests' module | 8,287,628 | 53 | 2011-11-27T17:50:23Z | 16,311,657 | 12 | 2013-05-01T01:54:46Z | [
"python",
"http-request",
"python-requests"
] | Just a short, simple one about the excellent [Requests](http://docs.python-requests.org/en/latest/index.html) module for Python.
I can't seem to find in the documentation what the variable 'proxies' should contain. When I send it a dict with a standard "IP:PORT" value it rejected it asking for 2 values.
So, I guess (b... | I have found that urllib has some really good code to pick up the system's proxy settings and they happen to be in the correct form to use directly. You can use this like:
```
import urllib
...
r = requests.get('http://example.org', proxies=urllib.getproxies())
```
It works really well and urllib knows about getting... |
Proxies with Python 'Requests' module | 8,287,628 | 53 | 2011-11-27T17:50:23Z | 21,529,910 | 11 | 2014-02-03T14:28:29Z | [
"python",
"http-request",
"python-requests"
] | Just a short, simple one about the excellent [Requests](http://docs.python-requests.org/en/latest/index.html) module for Python.
I can't seem to find in the documentation what the variable 'proxies' should contain. When I send it a dict with a standard "IP:PORT" value it rejected it asking for 2 values.
So, I guess (b... | The accepted answer was a good start for me, but I kept getting the following error:
```
AssertionError: Not supported proxy scheme None
```
Fix to this was to specify the http:// in the proxy url thus:
```
http_proxy = "http://194.62.145.248:8080"
https_proxy = "https://194.62.145.248:8080"
ftp_proxy = "10.10.1... |
Django: how to get format date in views? | 8,287,883 | 20 | 2011-11-27T18:23:39Z | 8,288,298 | 53 | 2011-11-27T19:21:17Z | [
"python",
"django",
"date"
] | I need to use SHORT\_DATETIME\_FORMAT in view.
```
def manage_list(request):
user = User.objects.filter().order_by('date_joined')
usrs = []
for usr in user:
usrs.append({
_('First name'): usr.first_name,
_('Last name'): usr.last_name,
_('Email'): us... | The `django.utils.formats` module is what you're looking for. The only reference I could find in the docs was in the [Django 1.2 release notes](https://docs.djangoproject.com/en/dev/releases/1.2/#date-format-helper-functions).
Remember that the localisation will only work if the [`USE_L10N`](https://docs.djangoproject... |
Django: how to get format date in views? | 8,287,883 | 20 | 2011-11-27T18:23:39Z | 16,163,428 | 15 | 2013-04-23T07:28:08Z | [
"python",
"django",
"date"
] | I need to use SHORT\_DATETIME\_FORMAT in view.
```
def manage_list(request):
user = User.objects.filter().order_by('date_joined')
usrs = []
for usr in user:
usrs.append({
_('First name'): usr.first_name,
_('Last name'): usr.last_name,
_('Email'): us... | You might want to try using django.utils.dateformat.DateFormat
```
>>> from datetime import datetime
>>> dt = datetime.now()
>>> from django.utils.dateformat import DateFormat
>>> from django.utils.formats import get_format
>>> df = DateFormat(dt)
>>> df.format(get_format('DATE_FORMAT'))
u'April 23, 2013'
>>> df.forma... |
Django: how to get format date in views? | 8,287,883 | 20 | 2011-11-27T18:23:39Z | 18,706,531 | 11 | 2013-09-09T20:30:31Z | [
"python",
"django",
"date"
] | I need to use SHORT\_DATETIME\_FORMAT in view.
```
def manage_list(request):
user = User.objects.filter().order_by('date_joined')
usrs = []
for usr in user:
usrs.append({
_('First name'): usr.first_name,
_('Last name'): usr.last_name,
_('Email'): us... | To use the Django **date** filter in a view use `defaultfilters`, e.g.:
```
from django.template import defaultfilters
formatted_date = defaultfilters.date(usr.date_joined, "SHORT_DATETIME_FORMAT")
``` |
What's the relationship between environments and projects in virtualenvwrapper? | 8,288,297 | 10 | 2011-11-27T19:21:08Z | 9,425,560 | 12 | 2012-02-24T04:48:19Z | [
"python",
"virtualenv",
"pip",
"virtualenvwrapper"
] | In other words, what's the difference between the `mkvirtualenv` and `mkproject` commands?
I have a workflow that looks like this:
```
/dev
projectA
appA
appB
projectB
appA
appB
```
All of the apps share some resources (like South, pep8, etc.), but other resources are specific... | From my understanding of the [documentation](http://www.doughellmann.com/docs/virtualenvwrapper/command_ref.html#project-directory-management), `mkvirtualenv projectenv` simply creates a new virtual environment named `projectenv` in `$WORKON_HOME`, while `mkproject projectenv` creates a new virtual environment named `p... |
Python `print` passing extra text to sys.stdout? | 8,288,717 | 4 | 2011-11-27T20:19:15Z | 8,288,724 | 7 | 2011-11-27T20:20:56Z | [
"python",
"stdout",
"stderr",
"sys"
] | This is probably something stupid I am missing but it has really got me hung up on a larger project (`c` extension) that I am writing.
Why is `print "Hello, World!"` passing `None` and an extra `\n` to `sys.stdout` here?
```
>>> import sys
>>> class StdOutHook:
... def write(self, text):
... sys.__stdout_... | `print x()` prints the return value of `x()` which is implicitly `None`
Either replace `print "Hello world"` with `return "Hello world"` or replace `print x()` with `x()` |
Efficient strings containing each other | 8,288,960 | 12 | 2011-11-27T20:55:19Z | 8,288,991 | 9 | 2011-11-27T20:59:22Z | [
"python",
"regex",
"string"
] | I have two sets of strings (`A` and `B`), and I want to know all pairs of strings `a in A` and `b in B` where `a` is a substring of `b`.
The first step of coding this was the following:
```
for a in A:
for b in B:
if a in b:
print (a,b)
```
However, I wanted to know-- is there a more efficien... | Of course you can easily write this as a list comprehension:
```
[(a, b) for a in A for b in B if a in b]
```
This might slightly speed up the loop, but don't expect too much. I doubt using regular expressions will help in any way with this one.
**Edit**: Here are some timings:
```
import itertools
import timeit
im... |
Efficient strings containing each other | 8,288,960 | 12 | 2011-11-27T20:55:19Z | 8,289,119 | 7 | 2011-11-27T21:18:14Z | [
"python",
"regex",
"string"
] | I have two sets of strings (`A` and `B`), and I want to know all pairs of strings `a in A` and `b in B` where `a` is a substring of `b`.
The first step of coding this was the following:
```
for a in A:
for b in B:
if a in b:
print (a,b)
```
However, I wanted to know-- is there a more efficien... | Let's assume your words are bounded at a reasonable size (let's say 10 letters). Do the following to achieve linear(!) time complexity, that is, `O(A+B)`:
* Initialize a hashtable or trie
* For each string b in B:
+ For every substring of that string
- Add the substring to the hashtable/trie (this is no worse th... |
Python 2.7 32-bit install on Win 7: No registry keys? | 8,289,859 | 6 | 2011-11-27T23:09:51Z | 8,290,228 | 7 | 2011-11-28T00:15:35Z | [
"python",
"windows",
"registry",
"install"
] | I have downloaded the Python 2.7.2 Windows x86 32-bit MSI from python.org and installed it on a 64-bit Windows 7 system. Everything works (at least the command-line interpreter starts and runs), but the install process does not create any `Python` entries under HKEY\_LOCAL\_MACHINE/SOFTWARE in the Windows registry.
Va... | 32-bit applications installed on 64-bit OSes store their registry values in:
HKEY\_LOCAL\_MACHINE\SOFTWARE\Wow6432Node. If you look there, you should see the settings you are looking for. |
Python 2.7 Beautiful Soup Img Src Extract | 8,289,957 | 7 | 2011-11-27T23:29:10Z | 8,290,064 | 21 | 2011-11-27T23:48:58Z | [
"python",
"beautifulsoup"
] | ```
for imgsrc in Soup.findAll('img', {'class': 'sizedProdImage'}):
if imgsrc:
imgsrc = imgsrc
else:
imgsrc = "ERROR"
patImgSrc = re.compile('src="(.*)".*/>')
findPatImgSrc = re.findall(patImgSrc, imgsrc)
print findPatImgSrc
'''
<img height="72" name="proimg" id="image" class="sizedProdImage"... | You're passing beautifulsoup node to re.findall. You have to convert it to string. Try:
```
findPatImgSrc = re.findall(patImgSrc, str(imgsrc))
```
Better yet, use the tools beautifulsoup provides:
```
[x['src'] for x in soup.findAll('img', {'class': 'sizedProdImage'})]
```
gives you a list of all src attributes of ... |
Python 2.7 Beautiful Soup Img Src Extract | 8,289,957 | 7 | 2011-11-27T23:29:10Z | 17,558,599 | 17 | 2013-07-09T21:29:37Z | [
"python",
"beautifulsoup"
] | ```
for imgsrc in Soup.findAll('img', {'class': 'sizedProdImage'}):
if imgsrc:
imgsrc = imgsrc
else:
imgsrc = "ERROR"
patImgSrc = re.compile('src="(.*)".*/>')
findPatImgSrc = re.findall(patImgSrc, imgsrc)
print findPatImgSrc
'''
<img height="72" name="proimg" id="image" class="sizedProdImage"... | There is more simple solution:
```
soup.find('img')['src']
``` |
Python : UnicodeEncodeError: 'latin-1' codec can't encode character | 8,290,206 | 8 | 2011-11-28T00:12:05Z | 8,290,307 | 9 | 2011-11-28T00:32:37Z | [
"python",
"unicode",
"encode"
] | I am at a scenario where I call api and based on the results from api I call database for each record that I in api. My api call return strings and when I make the database call for the items return by api, for some elements I get the following error.
```
Traceback (most recent call last):
File "TopLevelCategories.p... | If you need Latin-1 encoding, you have several options to get rid of the en-dash or other code points above 255 (characters not included in Latin-1):
```
>>> u = u'hello\u2013world'
>>> u.encode('latin-1', 'replace') # replace it with a question mark
'hello?world'
>>> u.encode('latin-1', 'ignore') # ignore it
'... |
python subclasses | 8,290,323 | 6 | 2011-11-28T00:36:23Z | 8,290,331 | 10 | 2011-11-28T00:39:13Z | [
"python",
"inheritance",
"subclass",
"quadratic"
] | I currently have a class called Polynomial, The initialization looks like this:
```
def __init__(self, *termpairs):
self.termdict = dict(termpairs)
```
I'm creating a polynomial by making the keys the exponents and
the associated values are the coefficients. To create an instance of this class, you enter as follo... | You probably want
```
class Quadratic(Polynomial):
def __init__(self, quadratic, linear, constant):
Polynomial.__init__(self, (2, quadratic), (1, linear), (0, constant))
``` |
python subclasses | 8,290,323 | 6 | 2011-11-28T00:36:23Z | 8,290,351 | 15 | 2011-11-28T00:43:43Z | [
"python",
"inheritance",
"subclass",
"quadratic"
] | I currently have a class called Polynomial, The initialization looks like this:
```
def __init__(self, *termpairs):
self.termdict = dict(termpairs)
```
I'm creating a polynomial by making the keys the exponents and
the associated values are the coefficients. To create an instance of this class, you enter as follo... | You should also use [`super()`](http://docs.python.org/library/functions.html#super) instead of using the constructor directly.
```
class Quadratic(Polynomial):
def __init__(self, quadratic, linear, constant):
super(Quadratic, self).__init__(quadratic[2], linear[1], constant[0])
``` |
Using "from __future__ import division" in my program, but it isn't loaded with my program | 8,290,636 | 12 | 2011-11-28T01:36:10Z | 8,290,910 | 9 | 2011-11-28T02:31:54Z | [
"python",
"sympy"
] | I wrote the following program in Python 2 to do Newton's method computations for my math problem set, and while it works perfectly, for reasons unbeknownst to me, when I initially load it in ipython with `%run -i NewtonsMethodMultivariate.py`, the Python 3 division is not imported. I know this because after I load my P... | Both `ipython -i` command and `run -i` in `ipython` interpreter ignore `from __future__ import division` in `print05.py` script.
```
$ cat print05.py
from __future__ import division
print(1/2)
```
In `ipython` console:
```
In [1]: print 1/2
0
In [2]: run -i print05.py
0.5
In [3]: division
Out[3]: _Feature((2, 2, 0,... |
Simple, versatile and re-usable entry dialog (sometimes referred to as input dialog) in PyGTK | 8,290,740 | 5 | 2011-11-28T01:54:53Z | 8,303,883 | 10 | 2011-11-28T23:28:48Z | [
"python",
"user-interface",
"gtk",
"pygtk"
] | I am searching for a simple dialog with a text entry widget asking the user for some input. The dialog should be easy to run (like the `gtk.MessageDialog` variants) and as flexible.
There are of course some examples but they are either not flexible enough or too complicated to construct for my taste.
I hate re-invent... | Based on an [example](http://ardoris.wordpress.com/2008/07/05/pygtk-text-entry-dialog/) I found (thanks [Ardoris](http://ardoris.wordpress.com/)!), I came up with a dialog subclass... hope it helps someone out there!
```
#!/usr/bin/env python
import gtk
class EntryDialog(gtk.MessageDialog):
def __init__(self, *arg... |
How to get Fabric to automatically (instead of user-interactively) interact with shell commands? Combine with pexpect? | 8,291,380 | 18 | 2011-11-28T03:55:30Z | 8,430,698 | 14 | 2011-12-08T11:59:14Z | [
"python",
"deployment",
"command-prompt",
"fabric",
"pexpect"
] | Seeking means to get [Fabric](http://fabfile.org) to automatically (instead of user-interactively) interact with shell commands (and not just requests for passwords, but also requested user input when no "stdin/interactive override" like `apt-get install -y` is available).
[This question](http://stackoverflow.com/ques... | It's not either/or. You just need to run the fab command through pexpect:
```
child = pexpect.spawn('fab <task>')
child.expect('prompt:')
child.send('reponse to prompt')
... etc
```
The fab command is just like any other command, so it can be scripted through pexpect. |
How to get Fabric to automatically (instead of user-interactively) interact with shell commands? Combine with pexpect? | 8,291,380 | 18 | 2011-11-28T03:55:30Z | 10,007,635 | 18 | 2012-04-04T08:39:29Z | [
"python",
"deployment",
"command-prompt",
"fabric",
"pexpect"
] | Seeking means to get [Fabric](http://fabfile.org) to automatically (instead of user-interactively) interact with shell commands (and not just requests for passwords, but also requested user input when no "stdin/interactive override" like `apt-get install -y` is available).
[This question](http://stackoverflow.com/ques... | As Glenn, I would say use pexpect; in addition,
have a look at this wrapper I wrote to script the pexpect behaviour from fabric:
```
from ilogue.fexpect import expect, expecting, run
prompts = []
prompts += expect('What is your name?','John')
prompts += expect('Where do you live?','New York')
with expecting(prompt... |
python how to convert from string.template object to string | 8,292,555 | 4 | 2011-11-28T07:16:26Z | 8,292,613 | 8 | 2011-11-28T07:24:25Z | [
"python",
"string",
"templates"
] | This is very simple.I am sure I am missing something silly.
```
fp = open(r'D:\UserManagement\invitationTemplate.html', 'rb')
html = Template(fp.read())
fp.close()
html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
print html
```
When i run this code in intepreter directly,I get the proper outpu... | `safe_substitute` **returns** the template with the substitutions made. This way, you can reuse the same template for multiple substitutions. So your code has to be
```
print html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
``` |
Python: continue iteration of for loop on exception | 8,293,086 | 11 | 2011-11-28T08:18:46Z | 8,293,371 | 7 | 2011-11-28T08:45:31Z | [
"python",
"exception",
"for-loop"
] | I have a simple `for` loop in Python that is exiting on exceptions even though the exception block contains a `continue`. There are still about 10 lines left to read when it hits an `IndexError` and exits the `for` loop. What am I missing here?
```
for row in hkx: ##'hkx' are rows being read in from 'csv.open'
tr... | It does exactly as it should and continues with the next line. If an exception is terminating your code early then it must either not be IndexError, or it must be being thrown from some code outside the `try:` block.
```
>>> hkx = [ range(5), range(4), range(4), range(5) ]
>>> for row in hkx: ##'hkx' are rows being r... |
Why I can't use urlencode to encode json format data? | 8,293,113 | 6 | 2011-11-28T08:20:37Z | 8,293,164 | 9 | 2011-11-28T08:26:43Z | [
"python",
"json",
"urlencode",
"python-2.7"
] | I have a problem about urlencode in python 2.7:
```
>>> import urllib
>>> import json
>>> urllib.urlencode(json.dumps({'title':"hello worldï¼",'anonymous':False,'needautocategory':True}))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/urllib.py", line 1280, i... | Because `urllib.urlencode` ["converts a mapping object or a sequence of two-element tuples to a âpercent-encodedâ string..."](http://docs.python.org/library/urllib.html#urllib.urlencode). Your string is neither of these.
I think you need `urllib.quote` or `urllib.quote_plus`. |
Why I can't use urlencode to encode json format data? | 8,293,113 | 6 | 2011-11-28T08:20:37Z | 8,293,170 | 10 | 2011-11-28T08:27:29Z | [
"python",
"json",
"urlencode",
"python-2.7"
] | I have a problem about urlencode in python 2.7:
```
>>> import urllib
>>> import json
>>> urllib.urlencode(json.dumps({'title':"hello worldï¼",'anonymous':False,'needautocategory':True}))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/urllib.py", line 1280, i... | [`urlencode`](http://docs.python.org/library/urllib.html#urllib.urlencode) can encode a dict, but not a string. The output of `json.dumps` is a string.
Depending on what output you want, either don't encode the dict in JSON:
```
>>> urllib.urlencode({'title':"hello worldï¼",'anonymous':False,'needautocategory':True}... |
Is it bad form to raise ArgumentError by hand? | 8,293,325 | 12 | 2011-11-28T08:40:42Z | 8,293,394 | 15 | 2011-11-28T08:48:06Z | [
"python",
"exception-handling",
"argparse"
] | If you want to add an extra check not provided by `argparse`, such as:
```
if variable a == b then c should be not None
```
...is it permissible to raise `ArgumentError` yourself?
Or, should you raise `Exception` instead?
Also what is common practice for this kind of situation? Say that you add a piece of code that... | There's nothing inherently wrong with raising an ArgumentError. You can use it anytime the arguments you receive are not what you expected them to be, including checking range of numbers.
Also, yes, in general it's alright for you to use the same exceptions provided by a given library if you are writing an extension t... |
Python dictionary with variables as keys | 8,293,617 | 6 | 2011-11-28T09:10:16Z | 8,293,869 | 9 | 2011-11-28T09:34:06Z | [
"python"
] | I'm a Python newbie trying to parse a file to make a table of memory allocations. My input file is in the following format:
```
48 bytes allocated at 0x8bb970a0
24 bytes allocated at 0x8bb950c0
48 bytes allocated at 0x958bd0e0
48 bytes allocated at 0x8bb9b060
96 bytes allocated at 0x8bb9afe0
24 bytes allocated at 0x8b... | Learning a language is as much about the syntax and basic types as it is about the standard library. Python already has a class that makes your task very easy: [`collections.Counter`](http://docs.python.org/py3k/library/collections.html#collections.Counter).
```
from collections import Counter
with open("allocFile.tx... |
Define a lambda expression that raises an Exception | 8,294,618 | 48 | 2011-11-28T10:41:32Z | 8,294,654 | 75 | 2011-11-28T10:45:29Z | [
"python"
] | How can I write a lambda expression that's equivalent to:
```
def x():
raise Exception()
```
The following is not allowed:
```
y = lambda : raise Exception()
``` | **UPDATE 2:** I was wrong! It turns out there's more than one way to skin a Python:
```
y = lambda: (_ for _ in ()).throw(Exception('foobar'))
```
---
~~No. Lambdas only accept expressions.~~ `raise ex` is a statement. Of course, you could write a general purpose raiser:
```
def raise_(ex):
raise ex
y = lambda... |
Define a lambda expression that raises an Exception | 8,294,618 | 48 | 2011-11-28T10:41:32Z | 9,547,687 | 21 | 2012-03-03T16:29:24Z | [
"python"
] | How can I write a lambda expression that's equivalent to:
```
def x():
raise Exception()
```
The following is not allowed:
```
y = lambda : raise Exception()
``` | How about:
```
lambda x: exec('raise(Exception(x))')
``` |
Define a lambda expression that raises an Exception | 8,294,618 | 48 | 2011-11-28T10:41:32Z | 13,070,076 | 14 | 2012-10-25T13:49:05Z | [
"python"
] | How can I write a lambda expression that's equivalent to:
```
def x():
raise Exception()
```
The following is not allowed:
```
y = lambda : raise Exception()
``` | Actually, there is a way, but it's very contrived.
You can create a code object using the `compile()` built-in function. This allows you to use the `raise` statement (or any other statement, for that matter), but it raises another challenge: executing the code object. The usual way would be to use the `exec` statement... |
Define a lambda expression that raises an Exception | 8,294,618 | 48 | 2011-11-28T10:41:32Z | 13,595,553 | 9 | 2012-11-28T00:09:38Z | [
"python"
] | How can I write a lambda expression that's equivalent to:
```
def x():
raise Exception()
```
The following is not allowed:
```
y = lambda : raise Exception()
``` | If all you want is a lambda expression that raises an arbitrary exception, you can accomplish this with an illegal expression. For instance, `lambda x: [][0]` will attempt to access the first element in an empty list, which will raise an IndexError.
**PLEASE NOTE**: This is a hack, not a feature. **Do not** use this i... |
pypi UserWarning: Unknown distribution option: 'install_requires' | 8,295,644 | 50 | 2011-11-28T12:13:17Z | 10,682,922 | 9 | 2012-05-21T09:44:46Z | [
"python",
"distutils",
"pypi"
] | Does anybody encounter this warning when executing `python setup.py install` of a PyPI package?
`install_requires` defines what the package requires. A lot of PyPI packages have this option. How can it be an "unknown distribution option"? | **ATTENTION**! **ATTENTION**! Imperfect answer ahead. To get the "latest memo" on the state of packaging in the Python universe, read [this fairly detailed essay](http://python-notes.boredomandlaziness.org/en/latest/pep_ideas/core_packaging_api.html).
I have just ran into this problem when trying to build/install ansi... |
pypi UserWarning: Unknown distribution option: 'install_requires' | 8,295,644 | 50 | 2011-11-28T12:13:17Z | 10,686,196 | 42 | 2012-05-21T13:28:57Z | [
"python",
"distutils",
"pypi"
] | Does anybody encounter this warning when executing `python setup.py install` of a PyPI package?
`install_requires` defines what the package requires. A lot of PyPI packages have this option. How can it be an "unknown distribution option"? | `python setup.py` uses distutils which doesn't support install\_requires. setuptools does, also distribute (its successor), and pip (which uses either) do. But you actually have to use them. I.e. call setuptools through the `easy_install` command or `pip install`.
Another way is to import setup from setuptools in your... |
how to plot streamlines , when i know u and v components of velocity(numpy 2d arrays), using a plotting program in python? | 8,296,617 | 14 | 2011-11-28T13:39:29Z | 8,313,754 | 20 | 2011-11-29T15:56:45Z | [
"python",
"numpy",
"matplotlib",
"scipy",
"velocity"
] | i hope the title itself was quite clear , i am solving 2D lid-driven cavity(square domain) problem using fractional step method , finite difference formulation (Navier-Stokes primitive variable form) , i have got u and v components of velocity over the entire domain , without manually calculating streamlines , is there... | Have a look at [Tom Flannaghan's `streamplot` function](http://www.atm.damtp.cam.ac.uk/people/tjf37/streamplot.py). The [relevant thread on the user's list is here](http://old.nabble.com/Any-update-on-streamline-plot-td30902670.html), and there's also another [similar code snippet by Ray Speth](http://web.mit.edu/speth... |
python: which file is newer & by how much time | 8,297,003 | 4 | 2011-11-28T14:07:16Z | 8,297,062 | 7 | 2011-11-28T14:11:08Z | [
"python",
"comparison",
"timedelta"
] | I am trying to create a filedate comparison routine. I suspect that the following is a rather clunky approach.
I had some difficulty finding info about timedelta's attributes or methods, or whatever they are called; hence, I measured the datetime difference below only in terms of days, minutes and seconds, and there i... | There is a solution for that already:
```
import os
modified_time = os.stat(path).st_mtime # time of most recent content modification
diff_time = os.stat(path_1).st_mtime - os.stat(path_2).st_mtime
```
Now you have the time in seconds since Epoch. why are you creating a new representation, you can create a deltatime ... |
Proper exception to raise if None encountered as argument | 8,297,526 | 9 | 2011-11-28T14:45:50Z | 8,297,651 | 17 | 2011-11-28T14:53:59Z | [
"python",
"exception"
] | What is the "proper" exception class to raise when one of my functions detects `None` passed where an argument value is required? For instance:
```
def MyFunction(MyArg1, MyArg2):
if not MyArg2:
raise ?Error?
```
I think I've seen `TypeError` used here (and it's true that I'm receiving a `NoneType` w... | There is no "invalid argument" or "null pointer" built-in exception in Python. Instead, most functions raise `TypeError` (invalid type such as `NoneType`) or `ValueError` (correct type, but the value is outside of the accepted domain).
If your function requires an object of a particular class and gets `None` instead, ... |
Inserting a row at a specific location in a 2d array in numpy? | 8,298,797 | 14 | 2011-11-28T16:17:44Z | 8,298,873 | 25 | 2011-11-28T16:21:41Z | [
"python",
"numpy"
] | I have a 2d array in numpy where I want to insert a new row. Following question [Numpy - add row to array](http://stackoverflow.com/questions/3881453/numpy-add-row-to-array) can help. We can use `numpy.vstack`, but it stacks at the start or at the end. Can anyone please help in this regard. | You are probably looking for [`numpy.insert`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html#numpy.insert)
```
>>> import numpy as np
>>> a = np.zeros((2, 2))
>>> a
array([[ 0., 0.],
[ 0., 0.]])
# In the following line 1 is the index before which to insert, 0 is the axis.
>>> np.insert(... |
Ultimate answer to relative python imports | 8,299,270 | 9 | 2011-11-28T16:49:20Z | 8,300,343 | 15 | 2011-11-28T18:15:05Z | [
"python",
"import",
"relative-path",
"python-2.5"
] | I know that there are lots of questions about the same import issues in Python but it seems that nobody managed to provide a clear example of correct usage.
Let's say that we have a package `mypackage` with two modules `foo` and `bar`. Inside `foo` we need to be able to access `bar`.
Because we are still developing i... | Take a look at the following info from [PEP 328](http://www.python.org/dev/peps/pep-0328/#relative-imports-and-name):
> Relative imports use a module's `__name__` attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to `'_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.