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- Adding a specified width to strings | 8,459,364 | 3 | 2011-12-10T19:48:21Z | 8,459,440 | 8 | 2011-12-10T19:59:21Z | [
"python",
"file",
"textwrapping"
] | I want to write a string to a file but I want to have a specified length, for example, in the text file, I want to write "Atom", I want it to have a specified length from column 1 - 6, and the next phrase/word, from column 7-11, next from 13-16, and etc... I would want to write to a text file say, random\_text.txt, ple... | In Python2.6 or later, you could use the [str.format](http://docs.python.org/library/string.html#format-string-syntax) method:
```
with open('random_text.txt', 'w') as f:
f.write('{0:6}{1:6}{2:4}'.format('Atom','word','next'))
```
yields a file `random_text.txt` with contents
```
Atom word next
```
The number... |
python map string split list | 8,461,230 | 12 | 2011-12-11T01:19:11Z | 8,461,246 | 9 | 2011-12-11T01:22:34Z | [
"python",
"string",
"parsing",
"functional-programming"
] | I am trying to map the `str.split` function to an array of string. namely, I would like to split all the strings in a string array that follow the same format. Any idea how to do that with `map` in python? For example let's assume we have a list like this:
```
>>> a = ['2011-12-22 46:31:11','2011-12-20 20:19:17', '201... | `map(lambda x: x.split(), a)` but, using a list comprehension `[x.split() for x in a]` is much clearer in this case. |
python map string split list | 8,461,230 | 12 | 2011-12-11T01:19:11Z | 8,461,254 | 23 | 2011-12-11T01:24:20Z | [
"python",
"string",
"parsing",
"functional-programming"
] | I am trying to map the `str.split` function to an array of string. namely, I would like to split all the strings in a string array that follow the same format. Any idea how to do that with `map` in python? For example let's assume we have a list like this:
```
>>> a = ['2011-12-22 46:31:11','2011-12-20 20:19:17', '201... | Though it isn't well known, there is a function designed just for this purpose, [operator.methodcaller](http://docs.python.org/library/operator.html#operator.methodcaller):
```
>>> from operator import methodcaller
>>> a = ['2011-12-22 46:31:11','2011-12-20 20:19:17', '2011-12-20 01:09:21']
>>> map(methodcaller("split... |
How can I struct.unpack many numbers at once | 8,461,798 | 3 | 2011-12-11T03:38:16Z | 8,461,913 | 9 | 2011-12-11T04:13:31Z | [
"python",
"struct"
] | I want to put a bunch of packed integers into a file, e.g.:
```
for i in int_list:
fp.write(struct.pack('<I', i))
```
Now I'd like to read them out into int\_list. I could do this, but it seems inefficient:
```
data = fp.read()
int_list = []
for i in xrange(0, len(data), 4):
int_list.append(struct.unpack('<I... | You can do it more efficiently in both directions:
```
>>> import struct
>>> int_list = [0, 1, 258, 32768]
>>> fmt = "<%dI" % len(int_list)
>>> data = struct.pack(fmt, *int_list)
>>> data
'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x01\x00\x00\x00\x80\x00\x00'
>>> # f.write(data)
... # data = f.read()
...
>>> fmt = "<%dI" %... |
Python multiprocessing - Pipe vs Queue | 8,463,008 | 75 | 2011-12-11T09:28:37Z | 8,463,046 | 127 | 2011-12-11T09:36:37Z | [
"python",
"performance",
"queue",
"multiprocessing",
"pipe"
] | What are the fundamental differences between queues and pipes in [Python's multiprocessing package](http://docs.python.org/library/multiprocessing.html)?
In what scenarios should one choose one over the other? When is it advantageous to use `Pipe()`? When is it advantageous to use `Queue()`? | * A [`Pipe()`](http://docs.python.org/library/multiprocessing.html#multiprocessing.Pipe) can only have two endpoints.
* A [`Queue()`](http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue) can have multiple producers and consumers.
**When to use them**
If you need more than two points to communica... |
Transmit JSON data to Django website | 8,463,127 | 3 | 2011-12-11T09:54:46Z | 8,463,552 | 7 | 2011-12-11T11:22:47Z | [
"python",
"django",
"json"
] | I'm transmitting a `application/json` in java with a `HttpPost` to a server which use Django.
I am performing the transmission as described here: [JSON POST request parsing in PHP](http://stackoverflow.com/questions/8391302/json-post-request-parsing-in-php/8391451#8391451)
How can I create a page that receive this js... | You can receive json through `request.raw_post_data`
```
data=simplejson.loads( request.raw_post_data )
``` |
How to make a field conditionally optional in WTForms? | 8,463,209 | 12 | 2011-12-11T10:08:33Z | 8,464,478 | 41 | 2011-12-11T13:56:19Z | [
"python",
"google-app-engine",
"validation",
"wtforms"
] | My form validation is working nearly complete, I just have 2 cases I don't know exactly how to solve: 1) The password field should be required of course but I also provide the possibility to log in with google or facebook account via OAuth and then name gets prefilled but I remove the password field completely from the... | I'm not sure this quite fits your needs, but I've used a `RequiredIf` custom validator on fields before, which makes a field required if another field has a value in the form... for instance, in a datetime-and-timezone scenario, I can make the timezone field required to have a value if the user has entered a datetime.
... |
Assignment of objects and fundamental types | 8,463,907 | 5 | 2011-12-11T12:22:56Z | 8,464,011 | 9 | 2011-12-11T12:37:44Z | [
"python"
] | There is this code:
```
# assignment behaviour for integer
a = b = 0
print a, b # prints 0 0
a = 4
print a, b # prints 4 0 - different!
# assignment behaviour for class object
class Klasa:
def __init__(self, num):
self.num = num
a = Klasa(2)
b = a
print a.num, b.num # prints 2 2
a.num = 3
print a.num, b.... | This is a stumbling block for many Python users. The object reference semantics are different from what C programmers are used to.
Let's take the first case. When you say `a = b = 0`, a new `int` object is created with value `0` and two references to it are created (one is `a` and another is `b`). These two variables ... |
What should I do if socket.setdefaulttimeout() is not working? | 8,464,391 | 7 | 2011-12-11T13:42:57Z | 8,465,202 | 16 | 2011-12-11T15:39:34Z | [
"python",
"http",
"urllib2",
"mechanize",
"urllib"
] | I'm writing a script(multi-threaded) to retrieve contents from a website, and the site's not very stable so every now and then there's hanging http request which cannot even be time-outed by `socket.setdefaulttimeout()`. Since I have no control over that website, the only thing I can do is to improve my codes but I'm r... | While `socket.setsocketimeout` will set the default timeout for new sockets, if you're not using the sockets directly, the setting can be easily overwritten. In particular, if the library calls `socket.setblocking` on its socket, it'll reset the timeout.
`urllib2.open` has a timeout argument, hovewer, there is no time... |
How to convert a python set to a numpy array? | 8,466,014 | 13 | 2011-12-11T17:35:58Z | 8,466,028 | 17 | 2011-12-11T17:38:28Z | [
"python",
"arrays",
"numpy",
"set"
] | I am using a set operation in python to perform a symmetric difference between two numpy arrays. The result, however, is a set and I need to convert it back to a numpy array to move forward. Is there a way to do this? Here's what I tried:
```
a = numpy.array([1,2,3,4,5,6])
b = numpy.array([2,3,5])
c = set(a) ^ set(b)
... | Do:
```
>>> numpy.array(list(c))
array([1, 4, 6])
```
And dtype is int (int64 on my side.) |
How to convert a python set to a numpy array? | 8,466,014 | 13 | 2011-12-11T17:35:58Z | 8,466,040 | 18 | 2011-12-11T17:39:38Z | [
"python",
"arrays",
"numpy",
"set"
] | I am using a set operation in python to perform a symmetric difference between two numpy arrays. The result, however, is a set and I need to convert it back to a numpy array to move forward. Is there a way to do this? Here's what I tried:
```
a = numpy.array([1,2,3,4,5,6])
b = numpy.array([2,3,5])
c = set(a) ^ set(b)
... | Don't convert the numpy array to a set to perform exclusive-or. Use [setxor1d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.setxor1d.html#numpy.setxor1d) directly.
```
>>> import numpy
>>> a = numpy.array([1,2,3,4,5,6])
>>> b = numpy.array([2,3,5])
>>> numpy.setxor1d(a, b)
array([1, 4, 6])
``` |
how to read a file that can be saved as either ansi or unicode in python? | 8,466,460 | 2 | 2011-12-11T18:43:49Z | 8,468,126 | 7 | 2011-12-11T22:44:15Z | [
"python",
"unicode",
"utf-8",
"ansi"
] | I have to write a script that support reading of a file which can be saved as either Unicode or Ansi (using MS's notepad).
I don't have any indication of the encoding format in the file, how can I support both encoding formats? (kind of a generic way of reading files with out knowing the format in advanced). | MS Notepad gives the user a choice of 4 encodings, expressed in clumsy confusing terminology:
"Unicode" is UTF-16, written little-endian. "Unicode big endian" is UTF-16, written big-endian. In both UTF-16 cases, this means that the appropriate BOM will be written. Use `utf-16` to decode such a file.
"UTF-8" is UTF-8;... |
Django circular model reference | 8,466,726 | 10 | 2011-12-11T19:21:55Z | 8,466,752 | 19 | 2011-12-11T19:25:22Z | [
"python",
"django"
] | I'm starting to work on a small soccer league management website (mostly for learning purposes) and can't wrap my mind around a Django models relationship. For simplicity, let's say I have 2 types of objects - Player and Team. Naturally, a player belongs to one team so that's a ForeignKey(Team) in the Player model.
So ... | as you can see in [the docs](https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey), for exactly this reason it is possible to specify the foreign model as a string.
```
team = models.ForeignKey('Team')
``` |
Using request.user with Django ModelForm | 8,466,768 | 13 | 2011-12-11T19:27:23Z | 8,467,248 | 20 | 2011-12-11T20:34:18Z | [
"python",
"django",
"django-forms"
] | I'm having a problem with logged users and a Django `ModelForm`. I have a class named *Animal* that has a `ForeignKey` to `User` and some data related to the animal like age, race, and so on. A user can add Animals to the DB and I have to track the author of each animal, so I need to add the *request.user* that is logg... | You just need to exclude it from the form, then set it in the view.
```
class AnimalForm(ModelForm):
class Meta:
model = Animal
exclude = ('publisher',)
```
... and in the view:
```
form = AnimalForm(request.POST)
if form.is_valid():
animal = form.save(commit=false)
animal... |
Using request.user with Django ModelForm | 8,466,768 | 13 | 2011-12-11T19:27:23Z | 14,157,675 | 7 | 2013-01-04T13:00:06Z | [
"python",
"django",
"django-forms"
] | I'm having a problem with logged users and a Django `ModelForm`. I have a class named *Animal* that has a `ForeignKey` to `User` and some data related to the animal like age, race, and so on. A user can add Animals to the DB and I have to track the author of each animal, so I need to add the *request.user* that is logg... | Another way (slightly shorter):
You need to exclude the field as well:
```
class AnimalForm(ModelForm):
class Meta:
model = Animal
exclude = ('publisher',)
```
then in the view:
```
animal = Animal(publisher=request.user)
form = AnimalForm(request.POST, instance=animal)
if form.is_valid():
... |
What is the proper way to handle Redis connection in Tornado ? (Async - Pub/Sub) | 8,466,838 | 8 | 2011-12-11T19:35:33Z | 14,800,637 | 9 | 2013-02-10T17:44:36Z | [
"python",
"redis",
"tornado",
"publish-subscribe"
] | I am using Redis along with my Tornado application with asyc client Brukva, when I looked at the sample apps at Brukva site they are making new connection on "**init**" method in websocket
```
class MessagesCatcher(tornado.websocket.WebSocketHandler):
def __init__(self, *args, **kwargs):
super(MessagesCatc... | A little late but, I've been using [tornado-redis](https://github.com/leporo/tornado-redis). It works with tornado's ioloop and the `tornado.gen` module
**Install tornadoredis**
It can be installed from pip
```
pip install tornadoredis
```
or with setuptools
```
easy_install tornadoredis
```
but you really should... |
Python, want logging with log rotation and compression | 8,467,978 | 27 | 2011-12-11T22:18:50Z | 8,468,041 | 41 | 2011-12-11T22:30:37Z | [
"python",
"logging"
] | Can anyone suggest a way in python to do logging with:
* log rotation every day
* compression of logs when they're rotated
* optional - delete oldest log file to preserve X MB of free space
* optional - sftp log files to server
Thanks for any responses,
Fred | * **log rotation every day:** Use a [TimedRotatingFileHandler](http://docs.python.org/library/logging.handlers.html#timedrotatingfilehandler)
* **compression of logs**: Set the `encoding='bz2'` parameter. (Note this "trick" will only work for Python2. 'bz2' is no longer considered an encoding in Python3.)
* **optional ... |
Python, want logging with log rotation and compression | 8,467,978 | 27 | 2011-12-11T22:18:50Z | 9,587,563 | 8 | 2012-03-06T16:15:06Z | [
"python",
"logging"
] | Can anyone suggest a way in python to do logging with:
* log rotation every day
* compression of logs when they're rotated
* optional - delete oldest log file to preserve X MB of free space
* optional - sftp log files to server
Thanks for any responses,
Fred | In addition to unutbu's answer: here's how to modify the TimedRotatingFileHandler to compress using zip files.
```
import logging
import logging.handlers
import zipfile
import codecs
import sys
import os
import time
import glob
class TimedCompressedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
... |
Python, want logging with log rotation and compression | 8,467,978 | 27 | 2011-12-11T22:18:50Z | 16,461,440 | 7 | 2013-05-09T12:08:17Z | [
"python",
"logging"
] | Can anyone suggest a way in python to do logging with:
* log rotation every day
* compression of logs when they're rotated
* optional - delete oldest log file to preserve X MB of free space
* optional - sftp log files to server
Thanks for any responses,
Fred | The other way to compress logfile during rotate (new in python 3.3) is using BaseRotatingHandler (and all inherited) class attribute *rotator* for example:
```
import gzip
import os
import logging
import logging.handlers
class GZipRotator:
def __call__(self, source, dest):
os.rename(source, dest)
... |
converting QdateTime to normal python dateTime? | 8,468,756 | 11 | 2011-12-12T00:45:27Z | 8,468,934 | 15 | 2011-12-12T01:17:49Z | [
"python",
"datetime",
"pyqt",
"pyqt4",
"qdatetime"
] | I have a lot of existing code that just uses the normal `dateTime` class in python, however in upgrading my program I am using the `QtGui.QdateTimeEdit()` class, but that class returns a `QdateTime` object that seems to be incompatible with the normal `dateTime` object.
So, is there a sane way to convert `QdateTime` t... | `QDateTime` has a `toPyDateTime` method which will return regular `datetime` objects.
```
In : from PyQt4 import QtCore
In : QtCore.PYQT_VERSION_STR
Out: '4.8.6'
In : QtCore.QT_VERSION_STR
Out: '4.7.4'
In : now = QtCore.QDateTime.currentDateTime()
In : now
Out: PyQt4.QtCore.QDateTime(2011, 12, 11, 20, 12, 47, 55)
... |
converting QdateTime to normal python dateTime? | 8,468,756 | 11 | 2011-12-12T00:45:27Z | 8,468,984 | 7 | 2011-12-12T01:27:15Z | [
"python",
"datetime",
"pyqt",
"pyqt4",
"qdatetime"
] | I have a lot of existing code that just uses the normal `dateTime` class in python, however in upgrading my program I am using the `QtGui.QdateTimeEdit()` class, but that class returns a `QdateTime` object that seems to be incompatible with the normal `dateTime` object.
So, is there a sane way to convert `QdateTime` t... | **[PyQt - use `.toPyDateTime()` on QtCore.QDateTime object](http://pyqt.sourceforge.net/Docs/PyQt4/qdatetime.html#toPyDateTime)**
```
>>> from PyQt4.QtCore import QDateTime
>>> qdate = QDateTime(2012, 12, 20, 11, 59, 59)
>>> qdate
PyQt4.QtCore.QDateTime(2012, 12, 20, 11, 59, 59)
>>> date = qdate.toPyDateTime()
>>> dat... |
SWIG wrapping C++ for Python: translating a list of strings to an STL vector of STL strings | 8,469,138 | 5 | 2011-12-12T01:56:29Z | 8,752,983 | 10 | 2012-01-06T03:21:53Z | [
"c++",
"python",
"string",
"vector",
"swig"
] | I would like to wrap a C++ function with SWIG which accepts a vector of STL strings as an input argument:
```
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void print_function(vector<string> strs) {
for (unsigned int i=0; i < strs.size(); i++)
cout << strs[i] << endl;
}
```
I want... | You need to tell SWIG that you want a vector string typemap. It does not magically guess all the different vector types that can exist.
This is at the link provided by Schollii:
```
//To wrap with SWIG, you might write the following:
%module example
%{
#include "example.h"
%}
%include "std_vector.i"
%include "std_s... |
Saving openpyxl file via text and filestream | 8,469,665 | 10 | 2011-12-12T03:32:51Z | 8,470,729 | 7 | 2011-12-12T06:37:10Z | [
"python",
"excel",
"filestream",
"openpyxl"
] | I'm building OpenPyXL into an application that expects a string containing the content of the excel file, for it to write via file stream.
From my investigation into the OpenPyXL source code, it doesn't look like it supports this kind of output. Does anyone have any experience with modifying openpyxl to support this?
... | What about using a `StringIO` object to save the contents of the file:
```
from openpyxl.workbook import Workbook
from StringIO import StringIO
output = StringIO()
wb = Workbook()
wb.save(output)
print output.getvalue()
```
The string you're looking for is what is being printed in the last line of this example. |
Saving openpyxl file via text and filestream | 8,469,665 | 10 | 2011-12-12T03:32:51Z | 8,714,342 | 21 | 2012-01-03T15:13:19Z | [
"python",
"excel",
"filestream",
"openpyxl"
] | I'm building OpenPyXL into an application that expects a string containing the content of the excel file, for it to write via file stream.
From my investigation into the OpenPyXL source code, it doesn't look like it supports this kind of output. Does anyone have any experience with modifying openpyxl to support this?
... | jcollado's answer is actually valid, but there is also a function (sadly not documented yet) called "save\_virtual\_workbook" in openpyxl.writer.excel that will take your workbook and return the workbook as a string:
```
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import save_virtual_workbook
wb... |
Using mock patch to mock an instance method | 8,469,680 | 21 | 2011-12-12T03:36:14Z | 8,469,699 | 12 | 2011-12-12T03:40:53Z | [
"python",
"mocking"
] | I'm trying to mock something while testing a Django app using the imaginatively named [Mock testing library](http://www.voidspace.org.uk/python/mock/index.html). I can't seem to quite get it to work, I'm trying to do this:
```
models.py
from somelib import FooClass
class Promotion(models.Model):
foo = models.For... | Ah I was confused on where to apply that patch decorator. Fixed:
```
class ViewsDoSomething(TestCase):
view = 'my_app.views.do_something'
@patch.object(my_app.models.FooClass, 'bar')
def test_enter_promotion(self, mock_method):
self.client.get(reverse(view))
``` |
Using mock patch to mock an instance method | 8,469,680 | 21 | 2011-12-12T03:36:14Z | 34,534,635 | 9 | 2015-12-30T17:56:52Z | [
"python",
"mocking"
] | I'm trying to mock something while testing a Django app using the imaginatively named [Mock testing library](http://www.voidspace.org.uk/python/mock/index.html). I can't seem to quite get it to work, I'm trying to do this:
```
models.py
from somelib import FooClass
class Promotion(models.Model):
foo = models.For... | To add onto Kit's answer above, specifying a 3rd argument to patch.object() allows the mocked object/method to be specified, otherwise a default MagicMock object is used.
```
def fake_bar(self):
print "Do something I want!"
return True
@patch.object(my_app.models.FooClass, 'bar', fake_bar)
... |
Strange JQuery Error "code 501, message Unsupported method OPTIONS" | 8,470,414 | 5 | 2011-12-12T05:51:02Z | 8,480,578 | 9 | 2011-12-12T20:44:38Z | [
"javascript",
"jquery",
"python",
"http",
"httpserver"
] | I am learning the JQuery Get method. I start up a Python HTTP server:
(just typing command "**Python -m SimpleHTTPServer**").
It's fine to test this webserver by just visiting "http://localhost:80" on my web browser. However, when I write this very simple javascript to visit my webserver. I get an error message:
**"... | What I do is to write a customized **HTTPRequestHandler**. I add a **do-OPTIONS** method inside MyHandler to tell browser my server support CORS. This is done by sending headers **Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers**. Also, I add a "self.send\_header('Access-Contr... |
What is the best way to implement a forced page refresh using Flask? | 8,470,431 | 14 | 2011-12-12T05:53:04Z | 8,470,673 | 12 | 2011-12-12T06:28:33Z | [
"javascript",
"python",
"html",
"flask"
] | **Background**
I have a large number of fields that will be updating real time from an external process. I would like to update the Flask hosted pages periodically to show connected users any changes. Ideally the whole page would not refresh, this was a complaint of a similar system, but rather just update a number o... | To avoid refreshing the entire page you want to use what is called AJAX. It looks like this is easy to [implement in flask](http://flask.pocoo.org/docs/patterns/jquery/#the-html).
Since you want it to happen periodically you need to call your AJAX functions from a [timer](http://ejohn.org/blog/how-javascript-timers-wo... |
How to enable {% trans %} tag for jinja templates? | 8,471,455 | 11 | 2011-12-12T08:11:18Z | 8,811,462 | 8 | 2012-01-10T22:28:29Z | [
"python",
"google-app-engine",
"internationalization",
"jinja2"
] | I try to enable the `trans` tag and I've made a test template i18n.html:
`{% trans %}For sale{% endtrans %}--{{message}}--{{decimal_format}}`
Here is my python code according to the [manpages](http://webapp-improved.appspot.com/tutorials/i18n.html):
```
from webapp2_extras import i18n as multilingua
import jinja2
fro... | Take a look at Jinja2's [i18n Extension documentation](http://jinja.pocoo.org/docs/extensions/#i18n-extension). Calling `install_gettext_translations` basically sets the object through which Jinja2 will call gettext, ngettext, etc, in order to translate strings when it encounters a `{% trans %}` tag.
Since those funct... |
gcc-4.2 failed with exit status 1 | 8,473,066 | 16 | 2011-12-12T10:43:59Z | 8,780,323 | 9 | 2012-01-08T19:03:52Z | [
"python",
"python-2.7",
"osx-lion",
"gcc-4.2"
] | I've been looking for an answer to this issue but I couldn't find it, so here it is.
I'm trying to install [Uniconvertor](http://sk1project.org/modules.php?name=Products&product=uniconvertor) with a setup.py file into a MacOS X Lion (Python 2.7.2) using:
```
python setup.py install
```
Then I get the following error... | I was able to resolve this by downloading one of these: <https://github.com/kennethreitz/osx-gcc-installer/releases> |
gcc-4.2 failed with exit status 1 | 8,473,066 | 16 | 2011-12-12T10:43:59Z | 11,655,195 | 24 | 2012-07-25T17:21:43Z | [
"python",
"python-2.7",
"osx-lion",
"gcc-4.2"
] | I've been looking for an answer to this issue but I couldn't find it, so here it is.
I'm trying to install [Uniconvertor](http://sk1project.org/modules.php?name=Products&product=uniconvertor) with a setup.py file into a MacOS X Lion (Python 2.7.2) using:
```
python setup.py install
```
Then I get the following error... | Try the following:
1. Install the latest Xcode.
2. From Xcode's Preferences menu, install the
Command Line Tools (Downloads/Components tab). |
Regular expression: Match string between two slashes if the string itself contains escaped slashes | 8,473,853 | 5 | 2011-12-12T11:50:18Z | 8,473,924 | 15 | 2011-12-12T11:55:57Z | [
"python",
"regex"
] | I'm trying to build a regular expression that matches regular expressions between two forward slashes. My main problem is that regular expressions themselves can contain forward slashes, escaped by a backslash. I try to filter them out with a negative lookbehind assertion (only match the closing slash if there is no ba... | Try this:
```
pattern = re.compile(r"^/(?:\\.|[^/\\])*/")
```
**Explanation:**
```
^ # Start of string
/ # Match /
(?: # Match either...
\\. # an escaped character
| # or
[^/\\] # any character except slash/backslash
)* # any number of times.
/ # Match /
```
For your "real-worl... |
Pythonic way to add datetime.date and datetime.time objects | 8,474,670 | 84 | 2011-12-12T12:57:52Z | 8,474,692 | 150 | 2011-12-12T12:59:15Z | [
"datetime",
"python"
] | I have two objects that represent the same event instance --- one holds the date, the other the time of this event, and I want to create a datetime object.
Since one can't simply add date and time objects (following call fails):
```
datetime.date(2011, 01, 01) + datetime.time(10, 23)
``` | It's in the [python docs](http://docs.python.org/release/2.6/library/datetime.html#datetime.datetime.combine).
```
datetime.datetime.combine(datetime.date(2011, 01, 01), datetime.time(10, 23))
```
returns
```
datetime.datetime(2011, 1, 1, 10, 23)
``` |
how do i write to a python subprocess' stdin | 8,475,290 | 27 | 2011-12-12T13:46:55Z | 8,475,367 | 47 | 2011-12-12T13:52:56Z | [
"python",
"subprocess",
"stdin",
"nuke"
] | I'm trying to write a python script that starts a subprocess, and writes to the subprocess stdin. I'd also like to be able to determine an action to be taken if the subprocess crashes.
The process I'm trying to start is a program called nuke which has its own built in version of python which I'd like to be able to sub... | It might be better to use [`communicate`](http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate):
```
from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]
```
"Better", because of this warning:... |
fastest way to iterate in python | 8,475,807 | 4 | 2011-12-12T14:26:45Z | 8,475,998 | 12 | 2011-12-12T14:40:13Z | [
"python",
"numpy",
"pyopengl"
] | I've never had to concern myself with this problem so far but now I need to use some large number of vertices that need to be buffered by PyOpenGL and it seems like the python iteration is the bottleneck. Here is the situation. I have an array of 3D points `vertices`, and at each step I have to compute a 4D array of co... | To make this code fast, you need to "vectorise" it: replace all explicit Python loops by implicit loops, using NumPy's boradcasting rules. I can try and give a vectorised version of your loop:
```
if self.color_array is None:
self.color_array = numpy.empty((len(activity), 4))
diff_activity = (activity - self.min)... |
share data using Manager() in python multiprocessing module | 8,476,392 | 7 | 2011-12-12T15:08:50Z | 8,488,430 | 9 | 2011-12-13T11:30:03Z | [
"python",
"multiprocessing"
] | I tried to share data when using the `multiprocessing` module (python 2.7, Linux), I got different results when using slightly different code:
```
import os
import time
from multiprocessing import Process, Manager
def editDict(d):
d[1] = 10
d[2] = 20
d[3] = 30
pnum = 3
m = Manager()
```
**1st version:*... | It is because you access the variable by the list index the second time, while the first time you pass the actual variable. As stated in the [multiprocessing docs](http://docs.python.org/library/multiprocessing.html#multiprocessing.managers.SyncManager.list):
> *Modifications to mutable values or items in dict and lis... |
checking assertions in a lambda in python | 8,477,346 | 4 | 2011-12-12T16:19:50Z | 8,477,383 | 8 | 2011-12-12T16:22:55Z | [
"python"
] | I'm trying to use assertions to show some invariants (mostly in testing)
Thus i want to write something like the following:
```
values = [ range(10) ]
expected_values = [ range(10) ]
map (lambda x: assert x[0] == x[1] ,zip( [ run_function(i) for i in values ], expected_values))
```
If I use this with unittest.asser... | From the [documentation](http://docs.python.org/reference/expressions.html#lambda):
> Note that functions created with lambda forms cannot contain statements.
[`assert` is a statement.](http://docs.python.org/reference/simple_stmts.html#the-assert-statement)
So no, you cannot use the `assert` statement in a lambda e... |
checking assertions in a lambda in python | 8,477,346 | 4 | 2011-12-12T16:19:50Z | 8,477,459 | 7 | 2011-12-12T16:27:54Z | [
"python"
] | I'm trying to use assertions to show some invariants (mostly in testing)
Thus i want to write something like the following:
```
values = [ range(10) ]
expected_values = [ range(10) ]
map (lambda x: assert x[0] == x[1] ,zip( [ run_function(i) for i in values ], expected_values))
```
If I use this with unittest.asser... | Unfortunately, `assert` is a statement and Pythons limited lambdas don't allow that in them. They also restrict things like `print`.
You can use a generator expression here though.
```
assert all(x[0] == x[1] for x in zip( [run_function(i) for i in values ], expected_values))
```
I personally think that the followi... |
Flattening a list of dicts of lists of dicts (etc) of unknown depth in Python (nightmarish JSON structure) | 8,477,550 | 5 | 2011-12-12T16:35:27Z | 8,478,177 | 8 | 2011-12-12T17:19:56Z | [
"python",
"json",
"list",
"recursion",
"dictionary"
] | I'm dealing with a JSON structure which is output to me in structures like this:
```
[{u'item': u'something',
u'data': {
u'other': u'',
u'else':
[
{
u'more': u'even more',
u'argh':
{
... | Since the depth of your data is arbitrary, it is easier to resort to recursion to flatten it. This function creates a flat dictionary, with the path to each data item composed as the key, in order to avoid collisions.
You can retrieve its contents later with `for key in sorted(dic_.keys())`, for example.
I didn't tes... |
How redirect a shell command output to a Python script input ? | 8,478,137 | 11 | 2011-12-12T17:16:46Z | 8,478,633 | 14 | 2011-12-12T17:55:56Z | [
"python",
"shell",
"input",
"pipe"
] | This is probably something really basic, but I can not find a good solution for it.
I need to write a python script that can accept input from a pipe like this:
```
$ some-linux-command | my_script.py
```
something like this:
```
cat email.txt | script.py
```
Or it will just be piped by my .forward file directly fr... | Use sys.stdin to read the input . Example :
Example content of s.py :
```
import sys
data = sys.stdin.readlines()
print data
```
-- Running :
```
user@xxxxxxx:~$ cat t.txt
alpha
beta
gamma
user@xxxxxxx:~$ cat t.txt | python ./s.py
['alpha\n', 'beta\n', 'gamma\n']
```
You can also make the ... |
Flask doesn't locate template directory when running with twisted | 8,478,404 | 14 | 2011-12-12T17:37:59Z | 8,595,382 | 31 | 2011-12-21T19:43:23Z | [
"python",
"templates",
"twisted",
"flask"
] | Following some advice that I found [here](http://stackoverflow.com/questions/5248825/web-interface-for-a-twisted-application) I am trying to use Flask as a web interface for an application that runs with twisted.
As suggested in Flask documentation I created a "templates" directory which is at the same level as my scr... | Some frameworks will change directory from your current working directory when they are run in daemon mode, and this might very well be the case here.
Flask, since 0.7, has supported passing a template\_folder keyword argument when calling Flask, so you could try:
```
import os
tmpl_dir = os.path.join(os.path.dirname... |
Lambda function in sorting function | 8,478,958 | 3 | 2011-12-12T18:21:48Z | 8,478,988 | 17 | 2011-12-12T18:24:14Z | [
"python"
] | There is this code:
```
lista = [3,4,5,2,1,6,8,3]
print lista # [3, 4, 5, 2, 1, 6, 8, 3]
lista.sort(cmp=lambda x,y: cmp(y,x)) # sort descending
print lista # [8, 6, 5, 4, 3, 3, 2, 1] -- it is sorted
lista = [3,4,5,2,1,6,8,3]
print lista # [3, 4, 5, 2, 1, 6, 8, 3]
lista.sort(cmp=lambda x,y: y > x) # sort descending
pr... | The second example doesn't work because the function you're giving it isn't a valid comparator.
A valid comparator [is supposed to](http://docs.python.org/library/stdtypes.html#mutable-sequence-types)
> return a negative, zero or positive number depending on whether the
> first argument is considered smaller than, eq... |
using python urllib how to avoid non HTML content | 8,479,736 | 2 | 2011-12-12T19:30:42Z | 8,479,800 | 7 | 2011-12-12T19:34:33Z | [
"python",
"content-type",
"urllib",
"limits"
] | I am using urllib (note not urllib2) and getting title of pages from user supplied urls. Unfortunately sometimes the url is not an HTML but some huge file or some very long running process on the remote site.
I have checked the python docs but urllib is limited and looking at the source it seems I could change it but ... | [Here](http://docs.python.org/library/urllib.html#high-level-interface), it states that the `info()` method returns meta-information associated with the URL. You could use this to get the headers, and see what the Content-Type is (text/html), and if it's not what you want, discard the request.
```
>>> import urllib
>>... |
Best (most "pythonic") way to temporarily unzip a file | 8,479,827 | 6 | 2011-12-12T19:36:27Z | 8,479,923 | 16 | 2011-12-12T19:44:46Z | [
"gzip",
"python"
] | I need to temporarily create an unzipped version of some files. I've seen people do `zcat somefile.gz > /tmp/somefile` in bash, so I made this simple function in python:
```
from subprocess import check_call
def unzipto(zipfile, tmpfile):
with open(tmpfile, 'wb') as tf:
check_call(['zcat', zipfile], stdout... | `gzip.open(zipfile).read()` will give you the contents of the file in a single string.
```
with open(tmpfile, "wb") as tmp:
shutil.copyfileobj(gzip.open(zipfile), tmp)
```
will put the contents in a temporary file. |
using ctypes methods in python gives unexpected error | 8,480,376 | 8 | 2011-12-12T20:28:58Z | 8,480,476 | 8 | 2011-12-12T20:36:06Z | [
"python",
"ctypes"
] | I'm pretty new to python and ctypes. I'm trying to accomplish a seemingly easy task but am getting unexpected results. I'm trying to pass a string to a c function so I'm using the c\_char\_p type but it's giving me an error message. To simply it, this is whats happening:
```
>>>from ctypes import *
>>>c_char_p("hello ... | In Python 3.x, the `"text literal"` is really a unicode object. You want to use the byte-string literal like `b"byte-string literal"`
```
>>> from ctypes import *
>>> c_char_p('hello world')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string or integer address expected instead o... |
UnicodeDecodeError on join | 8,481,006 | 9 | 2011-12-12T21:18:58Z | 8,483,072 | 8 | 2011-12-13T00:57:51Z | [
"python",
"unicode",
"character-encoding"
] | So I have a list with some strings (which most of the strings I fetched from a sqlite3 db:
```
stats_list = ['Statistik \xc3\xb6ver s\xc3\xa5nger\n', 'Antal\tS\xc3\xa5ng', '1\tCarola - Betlehems Stj\xc3\xa4rna', '\n\nStatistik \xc3\xb6ver datak\xc3\xa4llor\n', 'K\xc3\xa4lla\tAntal', 'MANUAL\t1', '\n\nStatistik \xc3\xb... | Your problem is probably that you are mixing unicode strings with byte strings.
The code in "Edit 2" has several *unicode* strings being added to `stats_list`:
```
stats_list = [u'Statistik över sånger\n', u'Antal\tSång']
```
If you try to *decode* these unicode strings, you will get a `UnicodeEncodeError`. This ... |
Using "apt-get install xxx" inside Python script | 8,481,943 | 5 | 2011-12-12T22:40:28Z | 8,482,033 | 8 | 2011-12-12T22:47:18Z | [
"python",
"apt",
"apt-get"
] | currently I need to install some package using apt or rpm, according the OS.
I saw the lib "apt" to update or upgrade the system, but it is possible use it to install a single package?
I was trying to use too "subprocess":
```
subprocess.Popen('apt-get install -y filetoinstall', shell=True, stdin=None, stdout=None, s... | You can use `check_call` from the `subprocess` library.
```
from subprocess import STDOUT, check_call
import os
check_call(['apt-get', 'install', '-y', 'filetoinstall'],
stdout=open(os.devnull,'wb'), stderr=STDOUT)
```
Dump the `stdout` to `/dev/null`, or `os.devnull` in this case.
`os.devnull` is platform inde... |
Putting text in top left corner of matplotlib plot | 8,482,588 | 44 | 2011-12-12T23:48:54Z | 8,482,667 | 65 | 2011-12-12T23:59:33Z | [
"python",
"plot",
"matplotlib"
] | How can I put text in the top left (or top right) corner of a matplotlib figure, e.g. where a top left legend would be, or on top of the plot but in the top left corner? E.g. if it's a plt.scatter(), then something that would be within the square of the scatter, put in the top left most corner.
I'd like to do this wit... | You can use [`text`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text).
```
text(x, y, s, fontsize=12)
```
`text` coordinates can be given relative to the axis, so the position of your text will be independent of the size of the plot:
> The default transform specifies that text is in data coords,
> a... |
Putting text in top left corner of matplotlib plot | 8,482,588 | 44 | 2011-12-12T23:48:54Z | 8,482,798 | 7 | 2011-12-13T00:16:33Z | [
"python",
"plot",
"matplotlib"
] | How can I put text in the top left (or top right) corner of a matplotlib figure, e.g. where a top left legend would be, or on top of the plot but in the top left corner? E.g. if it's a plt.scatter(), then something that would be within the square of the scatter, put in the top left most corner.
I'd like to do this wit... | One solution would be to use the `plt.legend` function, even if you don't want an actual legend. You can specify the placement of the legend box by using the `loc` keyterm. More information can be found [at this website](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.legend) but I've also inclu... |
Making HTTP requests via Python Requests module not working via proxy where curl does? Why? | 8,482,896 | 11 | 2011-12-13T00:30:59Z | 8,816,739 | 8 | 2012-01-11T09:15:05Z | [
"python",
"proxy",
"get",
"http-request",
"python-requests"
] | Using this curl command I am able to get the response I am looking for from Bash
```
curl -v -u z:secret_key --proxy http://proxy.net:80 \
-H "Content-Type: application/json" https://service.com/data.json
```
[I have already seen this other post on proxies with the Requests module](http://stackoverflow.com/questions... | The problem actually lies with python's standard url access libraries - urllib/urllib2/httplib. I can't remember which library is the exact culprit, but for simplicity's sake, let's just call it urllib. Unfortunately, urllib doesn't implement the HTTP Connect method which is required for accessing an https site through... |
Python's trigonmetric function return unexpected values | 8,483,080 | 5 | 2011-12-13T00:59:11Z | 8,483,122 | 9 | 2011-12-13T01:04:02Z | [
"python",
"math",
"trigonometry"
] | ```
import math
print "python calculator"
print "calc or eval"
while 0 == 0:
check = raw_input() #(experimental evaluation or traditional calculator)
if check == "eval":
a = raw_input("operator\n") #operator
if a == "+":
b = input("arg1\n") #inarg1
c = input("arg2\n") #in... | You don't want o convert the return value of `sin()` to degrees -- the return value isn't an angle. You instead want to convert the argument to radians, since `math.sin()` expects radians:
```
>>> math.sin(math.radians(90))
1.0
``` |
django: return image data from a view | 8,483,348 | 9 | 2011-12-13T01:38:46Z | 8,483,796 | 11 | 2011-12-13T02:56:25Z | [
"python",
"django",
"binary",
"httpresponse"
] | I want a view to return image data. so something along the lines of
```
return HttpResponse(image_data, mimetype=âimage/pngâ)
```
I know I can do a `file.read()` to get the image data, but because the image is small (like 1x1 px) I want to just store it as a string object (or whatever object I can copy and paste ... | Here is a simple example from the [django-openid project](http://code.google.com/p/django-openid/)
```
def logo(request):
return HttpResponse(
OPENID_LOGO_BASE_64.decode('base64'), content_type='image/gif'
)
# Logo from http://openid.net/login-bg.gif
# Embedded here for convenience; you should serve this as a stat... |
defaultdict and tuples | 8,483,881 | 4 | 2011-12-13T03:09:16Z | 8,483,916 | 16 | 2011-12-13T03:15:57Z | [
"python"
] | I wanted to do the following:
```
d = defaultdict((int,float))
for z in range( lots_and_lots):
d['operation one'] += (1,5.67)
...
...
d['operation two'] += (1,4.56)
```
And then output the number of times each operation was called and the total of float value.
```
for k,v in d.items():
print k, 'Called', v... | You could do it with *[collections.Counter](http://docs.python.org/library/collections.html#collections.Counter)* to accumulate the results:
```
>>> from collections import Counter, defaultdict
>>> d = defaultdict(Counter)
>>> d['operation_one'].update(ival=1, fval=5.67)
>>> d['operation_two'].update(ival=1, fval=4.56... |
SQLAlchemy is Throwing an IntegrityError due to a DBSession.add() | 8,483,895 | 3 | 2011-12-13T03:12:05Z | 8,484,294 | 8 | 2011-12-13T04:22:32Z | [
"python",
"postgresql",
"sqlalchemy"
] | On the second time line 121 is called in this script <http://paste.pocoo.org/show/520040/>, I receive this error message:
```
*** IntegrityError: (IntegrityError) duplicate key value violates unique constraint "heroes_pkey"
DETAIL: Key (id)=(14) already exists.
'INSERT INTO heroes (id, name, description, image_name,... | The problem ended up being with Postgres. I had created the database by importing a sql file, and the sequence that kept track of the heroes primary key ended up not being accurate. This explained why the id was being incremented by one on each subsequent run, b/c Postgres was attempting to find an unused primary key. ... |
"unexpected indent" error when using notepad++ for creating django function | 8,483,969 | 7 | 2011-12-13T03:26:39Z | 8,484,868 | 16 | 2011-12-13T05:46:25Z | [
"python",
"django",
"notepad++",
"indentation"
] | I am following [this book](http://www.djangobook.com/en/2.0/chapter03/) to learn django using notepad++, something interesting happens, when I type the function using notepad++ for the following script:
```
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></h... | Settings->Preferences->Language Menu/Tab Settings->"Replace by space" |
"unexpected indent" error when using notepad++ for creating django function | 8,483,969 | 7 | 2011-12-13T03:26:39Z | 8,485,851 | 13 | 2011-12-13T07:48:43Z | [
"python",
"django",
"notepad++",
"indentation"
] | I am following [this book](http://www.djangobook.com/en/2.0/chapter03/) to learn django using notepad++, something interesting happens, when I type the function using notepad++ for the following script:
```
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></h... | Tell Notepad++ to show you all characters: go View > Show Symbol > Show All Characters. This will show tabs as `â` and spaces as `â`. Replace tabs with spaces where necessary to normalize the indentation. |
Django form/database error: value too long for type character varying(4) | 8,484,689 | 2 | 2011-12-13T05:22:49Z | 8,484,841 | 11 | 2011-12-13T05:42:04Z | [
"python",
"database",
"django",
"postgresql"
] | What I'm trying to do is save a stripe (the billing service) company id [around 200 characters or so] to my database in Django. How can I enable Django to allow for longer values?
The specific error is:
database error: value too long for type character varying(4)
I saw:
[value too long for type character varying(N)](... | Yes, make the column wider. The error message is quite clear: your 200 characters are too big to fit in a varchar(4).
First, update your model fields `max_length` attribute from 4 to a number that you expect will be long enough to contain the data you're feeding it.
Next up you have to update the database column itse... |
Construct a tree from list os file paths (Python) - Performance dependent | 8,484,943 | 7 | 2011-12-13T05:55:55Z | 8,496,834 | 9 | 2011-12-13T22:03:19Z | [
"python",
"recursion",
"path",
"tree"
] | Hey I am working on a very high performance file-managing/analyzing toolkit written in python.
I want to create a function that gives me a list or something like that in a tree format.
Something like in this [question (java-related)](http://stackoverflow.com/questions/1005551/construct-a-tree-structure-from-list-of-str... | Now that you clarified the question a bit more, I guess the following is what you want:
```
from collections import defaultdict
input_ = '''dir/file
dir/dir2/file2
dir/file3
dir2/alpha/beta/gamma/delta
dir2/alpha/beta/gamma/delta/
dir3/file4
dir3/file5'''
FILE_MARKER = '<files>'
def attach(branch, trunk):
'''
... |
python positional args and keyword args | 8,486,067 | 7 | 2011-12-13T08:13:26Z | 8,486,167 | 8 | 2011-12-13T08:23:35Z | [
"python",
"func",
"function"
] | I am reading the source codes of mercurial, and found such a func def in commands.py:
```
def import_(ui, repo, patch1=None, *patches, **opts):
...
```
in python, postional args must be put ahead of keyword args. But here, `patch1` is a keyword argument, followed by a positional argument `*patches`. why is this O... | Just have a look into the [PEP 3102](http://www.python.org/dev/peps/pep-3102/) also it seems its somehow related to [this](http://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python).
To summarize, patches and opts are there to accept variable arguments but the later is to accept keyword arguments. ... |
How to add an extra column to an numpy array | 8,486,294 | 81 | 2011-12-13T08:36:10Z | 8,486,342 | 17 | 2011-12-13T08:42:03Z | [
"python",
"numpy"
] | Lets say I have an numpy array a:
```
a = np.array([[1,2,3],[2,3,4]])
```
And I would like to add a column of zeros to get array b:
```
b = np.array([[1,2,3,0],[2,3,4,0]])
```
How can I do this easily in numpy? | While writing the question I came up with one way, using hstack
```
b = np.hstack((a, np.zeros((a.shape[0], 1), dtype=a.dtype)))
```
Any other (more elegant solutions) welcome! |
How to add an extra column to an numpy array | 8,486,294 | 81 | 2011-12-13T08:36:10Z | 8,489,498 | 52 | 2011-12-13T12:47:05Z | [
"python",
"numpy"
] | Lets say I have an numpy array a:
```
a = np.array([[1,2,3],[2,3,4]])
```
And I would like to add a column of zeros to get array b:
```
b = np.array([[1,2,3,0],[2,3,4,0]])
```
How can I do this easily in numpy? | I think a more straightforward solution and faster to boot is to do the following:
```
import numpy as np
N = 10
a = np.random.rand(N,N)
b = np.zeros((N,N+1))
b[:,:-1] = a
```
And timings:
```
In [23]: N = 10
In [24]: a = np.random.rand(N,N)
In [25]: %timeit b = np.hstack((a,np.zeros((a.shape[0],1))))
10000 loops,... |
How to add an extra column to an numpy array | 8,486,294 | 81 | 2011-12-13T08:36:10Z | 8,505,658 | 100 | 2011-12-14T13:56:43Z | [
"python",
"numpy"
] | Lets say I have an numpy array a:
```
a = np.array([[1,2,3],[2,3,4]])
```
And I would like to add a column of zeros to get array b:
```
b = np.array([[1,2,3,0],[2,3,4,0]])
```
How can I do this easily in numpy? | `np.r_[ ... ]` and `np.c_[ ... ]`
are useful alternatives to `vstack` and `hstack`,
with square brackets [] instead of round ().
A couple of examples:
```
: import numpy as np
: N = 3
: A = np.eye(N)
: np.c_[ A, np.ones(N) ] # add a column
array([[ 1., 0., 0., 1.],
[ 0., 1., 0., 1.],
... |
How to add an extra column to an numpy array | 8,486,294 | 81 | 2011-12-13T08:36:10Z | 18,207,544 | 12 | 2013-08-13T11:10:29Z | [
"python",
"numpy"
] | Lets say I have an numpy array a:
```
a = np.array([[1,2,3],[2,3,4]])
```
And I would like to add a column of zeros to get array b:
```
b = np.array([[1,2,3,0],[2,3,4,0]])
```
How can I do this easily in numpy? | What I find most elegant is the following:
```
b = np.insert(a, 3, values=0, axis=1) # insert values before column 3
```
An advantage of `insert` is that it also allows you to insert columns (or rows) at other places inside the array. Also instead of inserting a single value you can easily insert a whole vector, for ... |
How to add an extra column to an numpy array | 8,486,294 | 81 | 2011-12-13T08:36:10Z | 19,034,395 | 11 | 2013-09-26T17:09:28Z | [
"python",
"numpy"
] | Lets say I have an numpy array a:
```
a = np.array([[1,2,3],[2,3,4]])
```
And I would like to add a column of zeros to get array b:
```
b = np.array([[1,2,3,0],[2,3,4,0]])
```
How can I do this easily in numpy? | I think:
```
np.column_stack((a, zeros(shape(a)[0])))
```
is more elegant. |
How to add an extra column to an numpy array | 8,486,294 | 81 | 2011-12-13T08:36:10Z | 20,688,968 | 45 | 2013-12-19T18:23:39Z | [
"python",
"numpy"
] | Lets say I have an numpy array a:
```
a = np.array([[1,2,3],[2,3,4]])
```
And I would like to add a column of zeros to get array b:
```
b = np.array([[1,2,3,0],[2,3,4,0]])
```
How can I do this easily in numpy? | Use `numpy.append`:
```
>>> a = np.array([[1,2,3],[2,3,4]])
>>> a
array([[1, 2, 3],
[2, 3, 4]])
>>> z = np.zeros((2,1), dtype=int64)
>>> z
array([[0],
[0]])
>>> np.append(a, z, axis=1)
array([[1, 2, 3, 0],
[2, 3, 4, 0]])
``` |
How to add an extra column to an numpy array | 8,486,294 | 81 | 2011-12-13T08:36:10Z | 20,818,530 | 8 | 2013-12-28T19:35:55Z | [
"python",
"numpy"
] | Lets say I have an numpy array a:
```
a = np.array([[1,2,3],[2,3,4]])
```
And I would like to add a column of zeros to get array b:
```
b = np.array([[1,2,3,0],[2,3,4,0]])
```
How can I do this easily in numpy? | I like JoshAdel's answer because of the focus on performance. A minor performance improvement is to avoid the overhead of initializing with zeros, only to be overwritten. This has a measurable difference when N is large, empty is used instead of zeros, and the column of zeros is written as a separate step:
```
In [1]:... |
python subclassing multiprocessing.Process | 8,489,684 | 15 | 2011-12-13T13:00:34Z | 8,489,859 | 18 | 2011-12-13T13:14:40Z | [
"python",
"oop",
"concurrency",
"parallel-processing",
"multiprocessing"
] | I am new to python object oriented and i am rewriting my existing application as an object oriented version , because now developers are increases and my code become un-maintainable.
Normally i use multiprocessing ques but i found from this example <http://www.doughellmann.com/PyMOTW/multiprocessing/basics.html> that ... | Process needs a `Queue()` to receive the results... An example of how to do this follows...
```
from multiprocessing import Process, Queue
class Processor(Process):
def __init__(self, queue, idx):
super(Processor, self).__init__()
self.queue = queue
self.idx = idx
def return_name(self... |
pyserial for Python 2.7.2 | 8,491,111 | 3 | 2011-12-13T14:47:11Z | 8,491,164 | 9 | 2011-12-13T14:50:47Z | [
"python",
"python-module",
"pyserial",
"windows64"
] | *I'm new to Python.* According to the [internets](https://www.google.com/search?q=ImportError%3a%20No%20module%20named%20serial) I was looking for the module [pyserial](http://pyserial.sourceforge.net/) after receiving this error:
```
ImportError: No module named serial
```
I first tried to install [pywin32](http://s... | You could try it with pip. ([Here a question/answer about installing it](http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows))
Then type in your shell:
```
pip install pyserial
```
**Solution:**
The [installation of pip](http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows)... |
pyserial for Python 2.7.2 | 8,491,111 | 3 | 2011-12-13T14:47:11Z | 13,575,458 | 8 | 2012-11-27T00:21:42Z | [
"python",
"python-module",
"pyserial",
"windows64"
] | *I'm new to Python.* According to the [internets](https://www.google.com/search?q=ImportError%3a%20No%20module%20named%20serial) I was looking for the module [pyserial](http://pyserial.sourceforge.net/) after receiving this error:
```
ImportError: No module named serial
```
I first tried to install [pywin32](http://s... | From <http://www.instructables.com/id/The-Arduino-Internet-Gizmo/step19/Installing-the-software/>
Install pySerial as follows:
Download pySerial from <http://pypi.python.org/pypi/pyserial> - click on pyserial-2.6.tar.gz to download the library.
Run 7-Zip (Start -> All Programs -> 7-Zip -> 7-Zip File Manager).
Open ... |
Parsing msg/eml files with Python 2.7 | 8,491,152 | 4 | 2011-12-13T14:50:22Z | 9,041,532 | 7 | 2012-01-27T23:39:25Z | [
"python",
"parsing",
"eml",
"msg"
] | Is there a library that can parse msg or eml files? I wrote a script that parses an email once it is converted to a txt file, but i cannot find an email client that allows me to easily drag-n-drop emails from the gui into a folder as a txt file (if someone knows this i would love to know!)
Drag-n-dropping from Outlook... | For \*.eml files you can use [email module](http://docs.python.org/library/email.html) from standard library. You will need to use Parser from email.parser to create a message object. |
lift list of values to a list of lists of values | 8,491,618 | 2 | 2011-12-13T15:20:10Z | 8,491,647 | 9 | 2011-12-13T15:21:35Z | [
"python"
] | Here's a tricky one. I want to take a list of integers, and turn it into a list of lists containing that integer. This is so that I can later append to that list. Unfortunately `list()` does not take a single integer, so I can't `map` it to the list.
Here's a more concrete explanation:
Given,
```
>>> a = range(5)
>>... | I'd use a list comprehension for this:
```
In [1]: a = range(5)
In [2]: [[v] for v in a]
Out[2]: [[0], [1], [2], [3], [4]]
``` |
How to use Zeromq's inproc and ipc transports? | 8,492,377 | 11 | 2011-12-13T16:13:00Z | 8,492,567 | 9 | 2011-12-13T16:27:32Z | [
"python",
"ipc",
"zeromq",
"inproc"
] | Im a newbie to ZERMQ. ZeroMQ has TCP, INPROC and IPC transports. I'm looking for examples using python and inproc in Winx64 and python 2.7, which could also be used for linux.
Also, I have been looking for UDP methods of transport and cant find examples.
The only example I found is
```
import zmq
import zhelpers
co... | To the best of my knowledge, UDP is not supported by 0MQ. Also, IPC is only supported on OSes which have a POSIX-conforming implementation of named pipes; so, on Windows, you can really only use 'inproc', TCP, or PGM. However, above and beyond all this, one of 0MQ's major features is that your protocol is just part of ... |
python: convert year/month/day/hour/min/second to # seconds since Jan 1 1970 | 8,492,443 | 2 | 2011-12-13T16:18:09Z | 8,492,544 | 8 | 2011-12-13T16:24:48Z | [
"python",
"datetime",
"time",
"epoch"
] | I know how to do it in C and Java, but I don't know a quick way of converting year/month/day/hour/min/second to the # of seconds since the Jan 1 1970 epoch.
Can someone help me?
So far I've figured out how to create a [`datetime` object](http://docs.python.org/library/datetime.html) but I can't seem to get the elapse... | Use `timetuple` or `utctimetuple` method to get time tuple and convert it to timestamp using `time.mktime`
```
>>> import datetime
>>> dt = datetime.datetime(2011, 12, 13, 10, 23)
>>> import time
>>> time.mktime(dt.timetuple())
1323793380.0
```
There is a nice bug related to it <http://bugs.python.org/issue2736>, thi... |
Is Python code with classes slower? | 8,492,624 | 6 | 2011-12-13T16:31:22Z | 8,492,720 | 12 | 2011-12-13T16:36:43Z | [
"python",
"performance",
"class"
] | When I started learning Python I created a few applications without classes (only functions),
now I know classes and know that the code would be much readable (and easy to understand) when I would rewrite it with classes.
Will the code be much slower when I will use classes in general? | No.
In general you will not notice any difference in performance based on using classes or not. The different code structures implied may mean that one is faster than the other, but it's impossible to say which.
Always write code to be read, then if, and only if, it's not fast enough make it faster. Remember: [Premat... |
Is Python code with classes slower? | 8,492,624 | 6 | 2011-12-13T16:31:22Z | 8,493,947 | 8 | 2011-12-13T18:04:56Z | [
"python",
"performance",
"class"
] | When I started learning Python I created a few applications without classes (only functions),
now I know classes and know that the code would be much readable (and easy to understand) when I would rewrite it with classes.
Will the code be much slower when I will use classes in general? | To answer the question: yes, it is likely to be a little slower, all else being equal. Some things that used to be variables (including functions) are now going to be object attributes, and `self.foo` is always going to be slightly slower than `foo` regardless of whether `foo` was a global or local originally. (Local v... |
Python: exceptions in assignments | 8,493,071 | 10 | 2011-12-13T16:59:23Z | 8,493,882 | 11 | 2011-12-13T17:59:29Z | [
"python",
"exception",
"exception-handling"
] | If I try the following code (in Python 3.2.2),
```
def f():
raise Exception
x = f()
```
then it appears that `x` is untouched - it either remains undefined or keeps whatever value it had previously. Is this behaviour guaranteed whenever the right hand side of an assignment throws an exception? I realise this is ... | The Python language reference specifies this:
<http://docs.python.org/reference/expressions.html#evaluation-order>
> Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
The right side is evaluated, then the left side... |
Modulus % in Django template | 8,494,209 | 64 | 2011-12-13T18:23:57Z | 8,494,346 | 10 | 2011-12-13T18:36:16Z | [
"python",
"django",
"templates"
] | I'm looking for a way to use something like the modulus operator in django. What I am trying to do is to add a classname to every fourth element in a loop.
With modulus it would look like this:
```
{% for p in posts %}
<div class="post width1 height2 column {% if forloop.counter0 % 4 == 0 %}first{% endif %}}">
... | You can't use the modulus operator in Django template tags, but it would be easy enough to write a filter to do so. Something like this should work:
```
@register.filter
def modulo(num, val):
return num % val
```
And then:
```
{% ifequal forloop.counter0|modulo:4 0 %}
```
You could even do something like this, ... |
Modulus % in Django template | 8,494,209 | 64 | 2011-12-13T18:23:57Z | 8,494,410 | 8 | 2011-12-13T18:41:46Z | [
"python",
"django",
"templates"
] | I'm looking for a way to use something like the modulus operator in django. What I am trying to do is to add a classname to every fourth element in a loop.
With modulus it would look like this:
```
{% for p in posts %}
<div class="post width1 height2 column {% if forloop.counter0 % 4 == 0 %}first{% endif %}}">
... | It sounds like you should just use the cycle tag.
[Built-in template tags](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#cycle) |
Modulus % in Django template | 8,494,209 | 64 | 2011-12-13T18:23:57Z | 8,494,425 | 117 | 2011-12-13T18:42:38Z | [
"python",
"django",
"templates"
] | I'm looking for a way to use something like the modulus operator in django. What I am trying to do is to add a classname to every fourth element in a loop.
With modulus it would look like this:
```
{% for p in posts %}
<div class="post width1 height2 column {% if forloop.counter0 % 4 == 0 %}first{% endif %}}">
... | You need [divisibleby](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#divisibleby), a built-in django filter.
```
{% for p in posts %}
<div class="post width1 height2 column {% if forloop.counter0|divisibleby:4 %}first{% endif %}">
<div class="preview">
</div>
<... |
Defining __repr__ when subclassing set in Python | 8,494,358 | 4 | 2011-12-13T18:37:02Z | 8,495,271 | 7 | 2011-12-13T19:51:16Z | [
"python",
"set",
"subclassing"
] | I'm trying to subclass the `set` object in Python, using code similar to the below, but I can't work out a sensible definition of `__repr__` to use.
```
class Alpha(set):
def __init__(self, name, s=()):
super(Alpha, self).__init__(s)
self.name = name
```
I'd like to define `__repr__` in such a way... | I think I have something that gets you what you want, in addition to showing some benchmarks. They are almost all equivalent though I am sure there is a difference in memory usage.
```
#!/usr/bin/env python
import time
class Alpha(set):
def __init__(self, name, s=()):
super(Alpha, self).__init__(s)
... |
converting string to tuple | 8,494,514 | 8 | 2011-12-13T18:49:44Z | 8,494,624 | 8 | 2011-12-13T18:58:01Z | [
"python",
"string",
"tuples"
] | I need to write a function that takes a string '(1,2,3,4,5),(5,4,3,2,1)' and returns a list of tuples of the 1st and last element of each tuple, [(1,5),(5,1)].
I was thinking:
```
def f(givenstring):
a=givenstring.split(',')
for i in a[0:-1]:
tuple(int(i[0,-1]))
```
but here I'm stucked.. | You may use `eval`. I think it'll be the shortest one.
```
>>> s = '(1,2,3,4,5),(5,4,3,2,1)'
>>> ts = eval(s)
>>> ts
((1, 2, 3, 4, 5), (5, 4, 3, 2, 1))
>>> tsp = [(el[0],el[-1]) for el in ts]
>>> tsp
[(1, 5), (5, 1)]
```
Still, it's **not a good practice** to use `eval`.
Another option is to parse the string using `... |
converting string to tuple | 8,494,514 | 8 | 2011-12-13T18:49:44Z | 8,494,627 | 30 | 2011-12-13T18:58:30Z | [
"python",
"string",
"tuples"
] | I need to write a function that takes a string '(1,2,3,4,5),(5,4,3,2,1)' and returns a list of tuples of the 1st and last element of each tuple, [(1,5),(5,1)].
I was thinking:
```
def f(givenstring):
a=givenstring.split(',')
for i in a[0:-1]:
tuple(int(i[0,-1]))
```
but here I'm stucked.. | You can use [`ast.literal_eval()`](http://docs.python.org/library/ast.html#ast.literal_eval):
> Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and N... |
Using additional command line arguments with gunicorn | 8,495,367 | 9 | 2011-12-13T19:58:47Z | 8,496,666 | 15 | 2011-12-13T21:49:02Z | [
"python",
"flask",
"gunicorn"
] | Assuming I'm starting a Flask app under gunicorn as per <http://gunicorn.org/deploy.html#runit>, is there a way for me to include/parse/access additional command line arguments?
E.g., can I include and parse the `foo` option in my Flask application somehow?
`gunicorn mypackage:app --foo=bar`
Thanks, | You can't pass command line arguments directly but you can choose application configurations easily enough.
```
$ gunicorn 'mypackage:build_app(foo="bar")'
```
Will call the function "build\_app" passing the foo="bar" kwarg as expected. This function should then return the WSGI callable that'll be used. |
Controlling C++ Output from Python Script | 8,496,733 | 3 | 2011-12-13T21:55:16Z | 8,496,922 | 7 | 2011-12-13T22:09:19Z | [
"c++",
"python"
] | I have a bit of an issue here. I have a Python script which calls binaries compiled from C++. The Python script has its own set of outputs (to standard out and error), which are easily disable-able. The C++ binaries have their own set of outputs (to standard out and error, among others) as well; the source can be alter... | One way to do this is:
* Duplicate in python the file descriptors for `stdout` and `stderr` using `os.dup`.
* Redirect the original `stdout` and `stderr` using `reopen` (from C's `stdio`) to write to a file of your choice.
Note: `reopen` isn't available directly from python, but you should be able to call it as in th... |
Graceful Primary Key Error handling in Python/psycopg2 | 8,497,886 | 15 | 2011-12-13T23:48:01Z | 8,498,214 | 13 | 2011-12-14T00:34:58Z | [
"python",
"sql",
"postgresql",
"psycopg2"
] | Using Python 2.7 and
In [150]: psycopg2.**version**
Out[150]: '2.4.2 (dt dec pq3 ext)'
I have a simple python scripts that processing transactions and writes data to a database. Occasionally there is an insert that violates my primary key. This is fine, i just want it to ignore that record and continue on it merry wa... | You should rollback transaction on error.
I've added one more `try..except..else` construction in the code bellow to show the exact place where exception will occur.
```
try:
cur = conn.cursor()
try:
cur.execute("""insert into encounter_id_table (
encounter_id,current_date )
... |
Can i calculate exp(1+2j) in python? | 8,498,310 | 5 | 2011-12-14T00:50:44Z | 8,498,319 | 14 | 2011-12-14T00:52:49Z | [
"python",
"math"
] | Can i calculate exp(1+2j) in python?
```
exp(1+2j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
``` | You need a complex version of this function:
```
cmath.exp(1+2j)
```
See <http://docs.python.org/library/cmath.html> |
Can i calculate exp(1+2j) in python? | 8,498,310 | 5 | 2011-12-14T00:50:44Z | 8,498,322 | 7 | 2011-12-14T00:53:30Z | [
"python",
"math"
] | Can i calculate exp(1+2j) in python?
```
exp(1+2j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
``` | You may want to import `e` from the math module to do this.
For example:
```
>>> from math import e
>>> print e ** (1+2j)
(-1.1312043837568135+2.4717266720048188j)
``` |
How to write Python 2.x as much compatible with Python 3.x as possible? | 8,498,823 | 34 | 2011-12-14T02:18:20Z | 8,498,857 | 7 | 2011-12-14T02:24:05Z | [
"python",
"python-3.x",
"compatibility",
"python-2.x"
] | There are many ways to **include Python 3.x features in Python 2.x**, so code of Python 2.x scripts could be easily converted into Python 3.x in the future. One of these examples is replacing `print` statement with `print()` function:
```
>>> from __future__ import print_function
```
Is there any list or resource tha... | You should check out [Porting Python Code to 3.0](http://wiki.python.org/moin/PortingPythonToPy3k). While it's aimed at porting, it answers essentially the same question; you just won't be going all the way. |
How to write Python 2.x as much compatible with Python 3.x as possible? | 8,498,823 | 34 | 2011-12-14T02:18:20Z | 8,500,158 | 22 | 2011-12-14T06:08:34Z | [
"python",
"python-3.x",
"compatibility",
"python-2.x"
] | There are many ways to **include Python 3.x features in Python 2.x**, so code of Python 2.x scripts could be easily converted into Python 3.x in the future. One of these examples is replacing `print` statement with `print()` function:
```
>>> from __future__ import print_function
```
Is there any list or resource tha... | I'm putting the finishing touches on an approximately 5000 line, deduplicating backup program (<http://stromberg.dnsalias.org/~strombrg/backshift/>) that runs on CPython 2.[567], CPython 3.[0123] (3.3 is still alpha 0), Pypy 1.7 and Jython trunk. I also tried IronPython, but it was a pretty different thing - it had no ... |
How to write Python 2.x as much compatible with Python 3.x as possible? | 8,498,823 | 34 | 2011-12-14T02:18:20Z | 8,501,694 | 7 | 2011-12-14T08:55:58Z | [
"python",
"python-3.x",
"compatibility",
"python-2.x"
] | There are many ways to **include Python 3.x features in Python 2.x**, so code of Python 2.x scripts could be easily converted into Python 3.x in the future. One of these examples is replacing `print` statement with `print()` function:
```
>>> from __future__ import print_function
```
Is there any list or resource tha... | There is [a whole chapter](http://python3porting.com/noconv.html) on this in "[Porting to Python 3](http://python3porting.com/)". Also don't miss the appendixes, that list language differences with workarounds to support both languages.
You probably want to use the [six library](http://pypi.python.org/pypi/six), altho... |
Python statement of short 'if-else' | 8,500,374 | 12 | 2011-12-14T06:34:43Z | 8,500,408 | 12 | 2011-12-14T06:38:58Z | [
"python",
"if-statement"
] | Is there a Python version of the following `if`-`else` statement in C++ or similar statement like this:
```
int t = 0;
int m = t==0?100:5;
``` | The construct you are referring to is called the [ternary operator](https://en.wikipedia.org/wiki/%3F:). Python has a version of it (since version 2.5), like this:
```
x if a > b else y
``` |
Python statement of short 'if-else' | 8,500,374 | 12 | 2011-12-14T06:34:43Z | 8,500,430 | 28 | 2011-12-14T06:42:03Z | [
"python",
"if-statement"
] | Is there a Python version of the following `if`-`else` statement in C++ or similar statement like this:
```
int t = 0;
int m = t==0?100:5;
``` | ```
m = 100 if t == 0 else 5 # Requires Python version >= 2.5
m = (5, 100)[t == 0] # Or [5, 7][t == 0]
```
Both of the above lines will result in the same thing.
The first line makes use of Python's version of a "*ternary operator*" available since version 2.5, though the Python documentation refers to it as `Con... |
How to plot a gradient color line in matplotlib? | 8,500,700 | 19 | 2011-12-14T07:13:48Z | 8,505,774 | 15 | 2011-12-14T14:04:25Z | [
"python",
"matplotlib",
"gradient"
] | To state it in a general form, I'm looking for a way to join several points with a **gradient color line** using **matplotlib**, and I'm not finding it anywhere.
To be more specific, I'm plotting a 2D random walk with a one color line. But, as the points have a relevant sequence, I would like to look at the plot and se... | I recently answered a question with a similar request ( [creating over 20 unique legends using matplotlib](http://stackoverflow.com/questions/8389636/creating-over-20-unique-legends-using-matplotlib/8391452#8391452) ). There I showed that you can map the cycle of colors you need to plot your lines to a color map. You c... |
How to plot a gradient color line in matplotlib? | 8,500,700 | 19 | 2011-12-14T07:13:48Z | 25,941,474 | 9 | 2014-09-19T19:53:53Z | [
"python",
"matplotlib",
"gradient"
] | To state it in a general form, I'm looking for a way to join several points with a **gradient color line** using **matplotlib**, and I'm not finding it anywhere.
To be more specific, I'm plotting a 2D random walk with a one color line. But, as the points have a relevant sequence, I would like to look at the plot and se... | Note that if you have many points, calling `plt.plot` for each line segment can be quite slow. It's more efficient to use a LineCollection object.
Using the [`colorline` recipe](http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb) you could do the following:
```
import matplot... |
Flask JSON Custom Error Page | 8,503,238 | 5 | 2011-12-14T10:51:23Z | 8,996,580 | 26 | 2012-01-25T00:56:05Z | [
"python",
"flask"
] | is there any implementation exists on JSON as custom error page on Flask? | You can create a json response object using the "jsonify" helper from flask and then set the status\_code of the response before returning it like this:
```
def not_found(error):
response = jsonify({'code': 404,'message': 'No interface defined for URL'})
response.status_code = 404
return response
```
You ... |
Compiling django project with Pyrex | 8,505,059 | 2 | 2011-12-14T13:11:55Z | 8,505,859 | 7 | 2011-12-14T14:10:18Z | [
"python",
"django",
"cython",
"pyrex"
] | I was wondering if someone was able to compile Django based projects (into shared object libs for instance) with pyrex (or anything similar) and still maintain the flexibility using normal Django projects with python.
We have to be able to use the project with apache so it cannot be compiled into a standalone binary. ... | Pyrex and its sucessor - cython - are not fully python compatible - they are rather another language, although Python based.
Django is a very complex project, and would require strict Python compliance to run - i doubt it would be possible without some months of work to make Django work directly in cython or Pyrex - a... |
Is it possible to prefill a input() in Python 3's Command Line Interface? | 8,505,163 | 19 | 2011-12-14T13:19:42Z | 8,505,387 | 17 | 2011-12-14T13:36:21Z | [
"python",
"input",
"python-3.x",
"command-line-interface"
] | I'm using Python 3.2 on Ubuntu 11.10 (Linux). A piece of my new code looks like this:
`text = input("TEXT=")`
Is it possible to get some predefined string after the prompt, so I can adjust it if needed? It should be like this:
```
python3 file
TEXT=thepredefinedtextishere
```
Now I press `Backspace` 3 times
```
TE... | If your Python interpreter is linked against GNU readline, `input()` will use it. In this case, the following should work:
```
def input_with_prefill(prompt, text):
def hook():
readline.insert_text(text)
readline.redisplay()
readline.set_pre_input_hook(hook)
result = input(prompt)
readl... |
Var(x) and cov(x, x) don't give the same result in numpy | 8,506,325 | 14 | 2011-12-14T14:43:32Z | 8,506,655 | 16 | 2011-12-14T15:02:30Z | [
"python",
"numpy",
"covariance",
"variance"
] | A property of the covariance is, that cov(x, x) = var(x)
However, in numpy I don't get the same result.
```
from numpy import var, cov
x = range(10)
y = var(x)
z = cov(x, x)[0][1]
print y, z
```
Am I doing something wrong here? How can I obtain the correct result? | You must use z=cov(x,bias=1) in order to normalize by N ,because var is also norm by N
(according to [this](http://www.scipy.org/Numpy_Example_List#head-614d18fe6fcdeb848a222177b2bb5404502bf85f) |
Var(x) and cov(x, x) don't give the same result in numpy | 8,506,325 | 14 | 2011-12-14T14:43:32Z | 8,506,657 | 7 | 2011-12-14T15:02:35Z | [
"python",
"numpy",
"covariance",
"variance"
] | A property of the covariance is, that cov(x, x) = var(x)
However, in numpy I don't get the same result.
```
from numpy import var, cov
x = range(10)
y = var(x)
z = cov(x, x)[0][1]
print y, z
```
Am I doing something wrong here? How can I obtain the correct result? | The default ddof of `cov` (None) and `var` (0) are different. Try specifying the ddof (or bias):
```
>>> cov(x, x, ddof=0)
array([[ 8.25, 8.25],
[ 8.25, 8.25]])
>>> var(x)
8.25
``` |
Detect whether Celery is Available/Running | 8,506,914 | 27 | 2011-12-14T15:17:22Z | 8,522,470 | 34 | 2011-12-15T15:28:29Z | [
"python",
"django",
"celery",
"django-celery"
] | I'm using [Celery](http://celeryproject.org/) to manage asynchronous tasks. Occasionally, however, the celery process goes down which causes none of the tasks to get executed. I would like to be able to check the status of celery and make sure everything is working fine, and if I detect any problems display an error me... | Here's the code I've been using. `celery.task.control.Inspect.stats()` returns a dict containing lots of details about the currently available workers, None if there are no workers running, or raises an `IOError` if it can't connect to the message broker. I'm using RabbitMQ - it's possible that other messaging systems ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.