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: How to catch a flask except like this? | 17,787,023 | 6 | 2013-07-22T11:59:13Z | 18,993,072 | 7 | 2013-09-24T22:18:12Z | [
"python",
"flask",
"try-catch"
] | I run a simple flask app like this:
```
from flask import Flask
app = Flask(__name__)
@app.route('/')
def welcome():
return "OK"
app.config.update(
DEBUG = True
)
if __name__ == '__main__':
app.run(use_reloader = False)
```
when I run it and visit it, sometimes(not always) it could't response the re... | I recently ran into this error message while trying to use Flask to serve audio files. I get this error message whenever the client closes the stream before the end of the stream.
This error message doesn't originate from your Flask application, but rather from the underlying SocketServer used to dispatch request data... |
scikit-learn how to know documents in the cluster? | 17,788,431 | 2 | 2013-07-22T13:07:05Z | 17,790,635 | 8 | 2013-07-22T14:49:25Z | [
"python",
"cluster-analysis",
"scikit-learn",
"k-means"
] | I am new to both python and scikit-learn so please bear with me.
I took this source code for k means clustering algorithm from [k means clustering.](http://scikit-learn.org/stable/_downloads/document_clustering.py)
I then modified to run on my local set by using load\_file function.
Although the algorithm terminates... | Forget about the `Bunch` object. It's just an implementation detail to load the toy datasets that are bundled with scikit-learn.
In real life, with you real data you just have to call directly:
```
km = KMeans(n_clusters).fit(my_document_features)
```
then collect cluster assignments from:
```
km.labels_
```
`my_d... |
Python saving multiple figures into one PDF file | 17,788,685 | 7 | 2013-07-22T13:19:47Z | 17,788,764 | 12 | 2013-07-22T13:23:35Z | [
"python",
"matplotlib"
] | In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using:
```
plt.savefig(filename1 + '.pdf')
```
or
```
plt.savefig(filename1 + '.jpg')
```
Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can a... | Use [`PdfPages`](http://matplotlib.org/api/backend_pdf_api.html#matplotlib.backends.backend_pdf.PdfPages) to solve your problem. Pass your `figure` object to the `savefig` method.
For example, if you have a whole pile of `figure` objects open and you want to save them into a multi-page PDF, you might do:
```
import m... |
Python saving multiple figures into one PDF file | 17,788,685 | 7 | 2013-07-22T13:19:47Z | 17,789,014 | 10 | 2013-07-22T13:35:45Z | [
"python",
"matplotlib"
] | In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using:
```
plt.savefig(filename1 + '.pdf')
```
or
```
plt.savefig(filename1 + '.jpg')
```
Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can a... | Do you mean save multiple figures *into* one file, or save multiple figures using *one script*?
Here's how you can save two different figures using one *script*.
```
>>> from matplotlib import pyplot as plt
>>> fig1 = plt.figure()
>>> plt.plot(range(10))
[<matplotlib.lines.Line2D object at 0x10261bd90>]
>>> fig2 = pl... |
How to install ipython notebook locally? | 17,790,558 | 3 | 2013-07-22T14:46:28Z | 19,207,870 | 7 | 2013-10-06T10:35:54Z | [
"python",
"ubuntu",
"virtualenv",
"ipython",
"ipython-notebook"
] | I would like to use ipython notebook. When I type `ipython notebook` in the command line, I get:
```
Could not start notebook. Please install ipython-notebook
```
The problem is that I do not have root privileges on the system (I use Ubuntu). I think that there is a work around with virtual environment but I do not k... | ```
sudo apt-get install ipython-notebook
``` |
How to install ipython notebook locally? | 17,790,558 | 3 | 2013-07-22T14:46:28Z | 26,533,096 | 7 | 2014-10-23T16:42:24Z | [
"python",
"ubuntu",
"virtualenv",
"ipython",
"ipython-notebook"
] | I would like to use ipython notebook. When I type `ipython notebook` in the command line, I get:
```
Could not start notebook. Please install ipython-notebook
```
The problem is that I do not have root privileges on the system (I use Ubuntu). I think that there is a work around with virtual environment but I do not k... | After running `pip install ipython[notebook]`, you need to deactivate the virtualenv and then activate it again.
In other words:
```
$ deactivate
$ workon my-virtualenv
(my-virtualenv)$ ipython notebook &
``` |
testing flask sql alchemy | 17,791,571 | 8 | 2013-07-22T15:29:52Z | 17,792,475 | 7 | 2013-07-22T16:14:32Z | [
"python",
"session",
"sqlalchemy",
"flask"
] | I have a working web application on Flask with SqlAlchemy for moderation of news, it has some api methods to handle moderation requests, such as approve, deny currently selected news, list them, etc. I want to write unit tests to this methods, and I made them work, but I don't understand, how to implement executing all... | I suggest you use the [Flask-Testing](http://pythonhosted.org/Flask-Testing/) extension. This is an approved extension which lets you do the unit testing as you desire. It has a specific section for SQLAlchemy as well.
**Testing with SQLAlchemy**
This covers a couple of points if you are using Flask-Testing with SQLA... |
Python Iterate Dictionary by Index | 17,793,364 | 11 | 2013-07-22T17:07:25Z | 17,793,421 | 35 | 2013-07-22T17:10:41Z | [
"python",
"dictionary"
] | I wanna iterate through a dictionary in python by their index no.
Example :
```
dict = {'apple':'red','mango':'green','orange':'orange'}
```
I wanna iterate through the dictionary from first to last , so that I can access the dictionary items by their indexes . For example 1st item will be apple ,2nd item will be m... | You can iterate over keys and get values by keys:
```
for key in dict.iterkeys():
print key, dict[key]
```
You can iterate over keys and corresponding values:
```
for key, value in dict.iteritems():
print key, value
```
You can use `enumerate` if you want indexes (remember that dictionaries don't have an or... |
How do I convert only specific parts of a string to uppercase in Python? | 17,794,241 | 5 | 2013-07-22T17:59:23Z | 17,794,356 | 16 | 2013-07-22T18:05:24Z | [
"python",
"string"
] | So I am writing a function that takes in a string input (ex: abcdefg) and a shorter portion of that input (ex: cde) and searches for it within the first longer string.
How do I make it so that only that second portion is capitalized in the first string?
Ex:
> > > Input 1: abcdefg
> > >
> > > Input 2: cde
> > >
> > >... | ```
def foo(str1, str2):
return str1.replace(str2, str2.upper())
``` |
How to get the highest element in absolute value in a numpy matrix? | 17,794,266 | 11 | 2013-07-22T18:00:49Z | 27,903,986 | 7 | 2015-01-12T14:14:50Z | [
"python",
"numpy"
] | Here is what I am currently doing, it works but it's a little cumbersome:
```
x = np.matrix([[1, 1], [2, -3]])
xmax = x.flat[abs(x).argmax()]
``` | The value you're looking for has to be either x.max() or x.min() so you could try
```
max(x.min(), x.max(), key=abs)
```
which is similar to aestrivex's solution but perhaps more readable? Note this will return the minimum in the case where `x.min()` and `x.max()` have the same absolute value e.g. -5 and 5. If you ha... |
Create a list of 2 variables | 17,794,557 | 4 | 2013-07-22T18:17:12Z | 17,794,596 | 10 | 2013-07-22T18:19:37Z | [
"python",
"string",
"list"
] | If I have variables `x` and `y`, such that:
* `x` is always a string
* `y` can either be a string or a list of strings
How can I create a list `z == [x, <all elements of y>]`?
For instance:
```
x = 'x'
y = 'y'
# create z
assert z == ['x', 'y']
```
```
x = 'x'
y = ['y', 'y2']
# create z
assert z == ['x', 'y', 'y2']... | ```
z = [x] + (y if isinstance(y, list) else [y])
```
Generally I'd avoid having a `y` that could be either a string or a list, though: it seems unnecessary. |
Is short-circuiting in assignment statements considered good style? | 17,794,948 | 4 | 2013-07-22T18:38:39Z | 17,794,972 | 13 | 2013-07-22T18:40:03Z | [
"python"
] | If I understand correctly
```
myvar = a and b or c
```
gives the same result as
```
if a:
if b:
myvar = b
else:
myvar = c
else:
myvar = c
```
so I guess it's more elegant.
I seem to remember seeing this kind of short-circuit assignment statement in JavaScript code. But is it considered good style in ... | Most of the time, you then want to use a [conditional expression](http://docs.python.org/2/reference/expressions.html#conditional-expressions) instead:
```
myvar = b if a else c
```
Short-circuiting is very Pythonic however, just be aware of the pitfalls where `b` is false-y; using short-circuiting will result in *di... |
How to append an element of a sublist in python | 17,795,613 | 4 | 2013-07-22T19:16:52Z | 17,795,644 | 10 | 2013-07-22T19:18:57Z | [
"python",
"list"
] | I have a list of lists in the form:
```
list = [[3, 1], [3, 2], [3, 3]]
```
And I want to split it into two lists, one with the x values of each sublist and one with the y values of each sublist.
I currently have this:
```
x = y = []
for sublist in list:
x.append(sublist[0])
y.append(sublist[1])
```
But th... | By doing `x = y = []` you are creating `x` and `y` and referencing them to the same list, hence the erroneous output. (The Object IDs are same below)
```
>>> x = y = []
>>> id(x)
43842656
>>> id(y)
43842656
```
If you fix that, you get the correct result.
```
>>> x = []
>>> y = []
>>> for sublist in lst:
x.a... |
Pycharm completion not working | 17,796,423 | 3 | 2013-07-22T20:05:23Z | 17,797,500 | 11 | 2013-07-22T21:11:35Z | [
"python",
"osx",
"pycharm"
] | I am using 2.7.3, registered with a key and everything. I am using Python 2.7.2 that came with my mac, my poor old mac.
Code completion and Intention Actions are not showing up.
I have not touched either one of those settings since installation.
It may be unrelated but completion on eclipse didn't work either.
How do I... | Turns out there is a power save feature in the file menu. I had it turned on. |
Convert a list to a string and back | 17,796,446 | 8 | 2013-07-22T20:06:46Z | 17,796,475 | 17 | 2013-07-22T20:08:07Z | [
"python",
"python-2.7"
] | I have a virtual machine which reads instructions from tuples nested within a list like so:
```
[(0,4738),(0,36),
(0,6376),(0,0)]
```
When storing this kind of machine code program, a text file is easiest, and has to be written as a string. Which is obviously quite hard to convert back.
Is there any module which ca... | Use the [`json` module](http://docs.python.org/2/library/json.html):
```
string = json.dumps(lst)
lst = json.loads(string)
```
Demo:
```
>>> import json
>>> lst = [(0,4738),(0,36),
... (0,6376),(0,0)]
>>> string = json.dumps(lst)
>>> string
'[[0, 4738], [0, 36], [0, 6376], [0, 0]]'
>>> lst = json.loads(string)
>>> ... |
Convert a list to a string and back | 17,796,446 | 8 | 2013-07-22T20:06:46Z | 17,796,490 | 7 | 2013-07-22T20:08:51Z | [
"python",
"python-2.7"
] | I have a virtual machine which reads instructions from tuples nested within a list like so:
```
[(0,4738),(0,36),
(0,6376),(0,0)]
```
When storing this kind of machine code program, a text file is easiest, and has to be written as a string. Which is obviously quite hard to convert back.
Is there any module which ca... | [JSON!](http://docs.python.org/2/library/json.html)
```
import json
with open(data_file, 'wb') as dump:
dump.write(json.dumps(arbitrary_data))
```
and similarly:
```
source = open(data_file, 'rb').read()
data = json.loads(source)
``` |
Calling an instance variable from a class that is inside of that class | 17,797,044 | 3 | 2013-07-22T20:43:10Z | 17,797,270 | 7 | 2013-07-22T20:56:28Z | [
"python",
"class"
] | I have a class that has a logger instance variable, and I am creating another class inside of that and I want to use the logger instance variable inside of that class, but not sure how to call it.
Example Code:
```
class A():
def __init__(self):
self.logger = Logger.get() #this works fine didn't include t... | As the Zen of Python states, *"Flat is better than nested."* You could un-nest `B`, and pass the logger as an argument to `B.__init__`.
By doing so,
* You make clear what variables `B` depends on.
* `B` becomes easier to unit test
* `B` may be reused in other situations.
---
```
class A():
def __init__(self):
... |
repetitive arithmetic in Python | 17,799,659 | 4 | 2013-07-23T00:34:29Z | 17,799,820 | 7 | 2013-07-23T00:56:35Z | [
"python"
] | From a purely performance standpoint, is it generally the best practice to assign the result of a repetitive arithmetic operation to a variable and use that variable throughout the code? Or does Python have some internal way of caching the result and using it whenever it encounters the repeated statement.
For example ... | I don't know of any Python implementation that caches the intermediate results. Binding a local variable is pretty cheap, so after a couple of calculations, it will come out faster.
In the special cases where only constants are used, the peephole optimiser can reduce those to constants
eg.
```
$ python3.3
Python 3.3... |
Why are these two functions different? | 17,799,958 | 25 | 2013-07-23T01:11:26Z | 17,800,134 | 8 | 2013-07-23T01:32:04Z | [
"python",
"python-2.7",
"bytecode",
"cpython"
] | Take a look at this:
```
>>> def f():
... return (2+3)*4
...
>>> dis(f)
2 0 LOAD_CONST 5 (20)
3 RETURN_VALUE
```
Evidently, the compiler has pre-evaluated `(2+3)*4`, which makes sense.
Now, if I simply change the order of the operands of `*`:
```
>>> def f():
... ret... | In the first case the unoptimized code is `LOAD 2 LOAD 3 ADD LOAD 4 MULTIPLY` and in the second case it's `LOAD 4 LOAD 2 LOAD 3 ADD MULTIPLY`. The pattern matcher in `fold_binops_on_constants()` must handle the first `ADD` ok (replacing `LOAD LOAD ADD` with `LOAD`) and then follows on to do the same thing to `MULTIPLY`... |
How to run a method before all tests in all classes? | 17,801,300 | 7 | 2013-07-23T04:04:09Z | 17,844,938 | 15 | 2013-07-24T21:14:51Z | [
"python",
"selenium",
"py.test"
] | I'm writing selenium tests, with a set of classes, each class containing several tests. Each class currently opens and then closes Firefox, which has two consequences:
* super slow, opening firefox takes longer than running the test in a class...
* crashes, because after firefox has been closed, trying to reopen it re... | You might want to use a session-scoped "autouse" fixture:
```
# content of conftest.py or a tests file (e.g. in your tests or root directory)
@pytest.fixture(scope="session", autouse=True)
def do_something(request):
# prepare something ahead of all tests
request.addfinalizer(finalizer_function)
```
This will... |
e Multiple file upload with flask built in uplaoder | 17,801,717 | 4 | 2013-07-23T04:52:15Z | 17,802,252 | 7 | 2013-07-23T05:42:11Z | [
"python",
"flask"
] | [Uploading Files in flask](http://flask.pocoo.org/docs/patterns/fileuploads/) has been explained in the docs properly. But I was wondering if the same built-in flask file upload can be used for multiple uploads.
I went through [this answer](http://stackoverflow.com/questions/11817182/uploading-multiple-files-with-flask... | You'll want to call the [`getlist`](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict.getlist) method of [`request.files`](http://flask.pocoo.org/docs/api/#flask.Request.files) (which is an instance of [`werkzeug.datastructures.MultiDict`](http://werkzeug.pocoo.org/docs/datastructures/#we... |
Flask-SQLAlchemy join across 3 models and a Table construct | 17,801,747 | 6 | 2013-07-23T04:54:23Z | 17,803,626 | 7 | 2013-07-23T07:12:56Z | [
"python",
"sqlalchemy",
"flask"
] | I have 3 models:
```
class Customer(Model):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
statemented_branch_id = Column(Integer, ForeignKey('branch'))
...
class Branch(Model):
__tablename__ = 'branch'
id = Column(Integer, primary_key=True)
...
class SalesManager(Mod... | I needed to add a `backref` to my `SalesManager` model that allows SQLAlchemy to figure out how to get from `SalesManager` to branch.
```
class SalesManager(Model):
__tablename__ = 'sales_manager'
id = Column(Integer, primary_key=True)
branches = relationship(
'Branch', secondary=sales_manager_bra... |
why should we use Exception as a superclass, why not BaseException | 17,802,242 | 4 | 2013-07-23T05:41:13Z | 17,802,352 | 7 | 2013-07-23T05:50:19Z | [
"python",
"exception",
"python-2.7",
"superclass"
] | In python, whenever we are writing User-defined exception, we have to extend it from class `Exception`.
my question is why can't we extend it from `BaseException` which is super-class of exception hierarchy and `Exception` is also subclass of `BaseException`. | `BaseException` includes things like `KeyboardInterrupt` and `SystemExit`, which use the exception mechanism, but which most people shouldn't be catching. It's analogous to `Throwable` in Java, if you're familiar with that. Things that derive directly from `BaseException` are generally intended to shut down the system ... |
Python: using an if statement on an argument which may or may not be there | 17,802,492 | 2 | 2013-07-23T06:00:57Z | 17,802,532 | 7 | 2013-07-23T06:03:55Z | [
"python",
"if-statement",
"argv"
] | I've been trying to make a small script (I'm brand new to Python, by the way), which will return a a scrabble score for a given word (argv[1], and to prompt me to type a word if I dont give it one. After fiddling around with if statements and many index errors later, I settled on this:
```
try:
do something with s... | Part of Python's philosophy is "It is better to ask forgiveness than permission" - and as this is an error case, there is no harm to the `try`, `except`. That said, if you want to avoid it, you could just check the number of arguments:
```
def main():
if len(argv) < 2:
print "We need at least one argument"... |
Django User Sessions, Cookies and Timeout | 17,803,329 | 3 | 2013-07-23T06:55:12Z | 17,803,861 | 7 | 2013-07-23T07:24:43Z | [
"python",
"django",
"session",
"cookies",
"django-models"
] | I'm working with a Django application and my current goal is to keep track of the user session with cookies. I have a feeling that, as always, my understanding is a bit off with regards to how I do this.
For starters, I would like to manage *how long* it has been since a user has logged in, that way I can successfully... | You can configure the [session](https://docs.djangoproject.com/en/dev/ref/settings/#std%3asetting-SESSION_COOKIE_AGE) middleware for logging out the user automatically,
configure the `SESSION_COOKIE_AGE`, to some low value, and provide the `SESSION_SAVE_EVERY_REQUEST`, as `True`.
This will automatically logout the use... |
How to customize a requirements.txt for multiple environments? | 17,803,829 | 31 | 2013-07-23T07:23:06Z | 20,720,019 | 62 | 2013-12-21T14:30:24Z | [
"python",
"deployment",
"heroku",
"requirements.txt"
] | I have two branches, Development and Production. Each has dependencies, some of which are different. Development points to dependencies that are themselves in development. Likewise for Production. I need to deploy to Heroku which expects each branch's dependencies in a single file called 'requirements.txt'.
What is th... | You can cascade your requirements files and use the "-r" flag to tell pip to include the contents of one file inside another. You can break out your requirements into a modular folder hierarchy like this:
```
`-- django_project_root
|-- requirements
| |-- common.txt
| |-- dev.txt
| `-- prod.txt
`-- requirements.... |
Django admin.py Unknown command: 'collectstatic' | 17,804,743 | 8 | 2013-07-23T08:10:03Z | 21,526,634 | 30 | 2014-02-03T11:49:41Z | [
"python",
"django"
] | I have upgraded from django 1.2.7 to django 1.5.1
I am using python 2.6.6
When i try to run `python manage.py collectstatic` i get
> Unknown command: 'collectstatic'
from my settings.py
```
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finde... | Had a similar error message, but despite my suspicions it had nothing to do with Django update. If you have an error in settings (I had an empty SECRET\_KEY value), then "django" will be the only app that gets loaded. I found the root of the problem by running "manage.py shell" and that quickly told me what's wrong wit... |
How to get the symbolic path instead of real path? | 17,805,312 | 6 | 2013-07-23T08:39:38Z | 17,806,123 | 12 | 2013-07-23T09:17:58Z | [
"python",
"symlink"
] | Suppose I have a path named:
```
/this/is/a/real/path
```
Now, I create a symbolic link for it:
```
/this/is/a/link -> /this/is/a/real/path
```
and then, I put a file into this path:
```
/this/is/a/real/path/file.txt
```
and cd it with symbolic path name:
```
cd /this/is/a/link
```
now, pwd command will return... | The difference between `os.path.abspath` and `os.path.realpath` is that `os.path.abspath` does not resolve symbolic links, so it should be exactly what you are looking for. I do:
```
/home/user$ mkdir test
/home/user$ mkdir test/real
/home/user$ mkdir test/link
/home/user$ touch test/real/file
/home/user$ ln -s /home/... |
Some QLineEdit questions | 17,805,791 | 3 | 2013-07-23T09:02:22Z | 17,806,007 | 7 | 2013-07-23T09:12:33Z | [
"python",
"pyqt",
"qlineedit"
] | I'm using Python with PyQt and I have a few problems with my `QLineEdits`.
1. First of all, I want to put text on them, but not the regular one, I mean the transparent text that disappears when you click on the `QLineEdit`.
2. How can I disable clicking on my `QLineEdit`? | Pretty much like this:
```
linedit = QtGui.QlineEdit()
linedit.setPlaceholderText("My grey text which disappear when I click on it")
linedit.setEnabled(False)
```
with Qt minimum version 4.7 and latest PyQt 4. |
Execute a Python script post install using distutils / setuptools | 17,806,485 | 21 | 2013-07-23T09:33:05Z | 18,159,969 | 28 | 2013-08-10T08:07:49Z | [
"python",
"install",
"setuptools",
"distutils",
"post-install"
] | I'm trying to add a post-install task to Python distutils as described in [How to extend distutils with a simple post install script?](http://stackoverflow.com/questions/1321270/how-to-extend-distutils-with-a-simple-post-install-script/1321345). The task is supposed to execute a Python script *in the installed lib dire... | The way to address these deficiences is:
1. Get the full path to the Python interpreter executing `setup.py` from `sys.executable`.
2. Classes inheriting from `distutils.cmd.Command` (such as `distutils.command.install.install` which we use here) implement the `execute` method, which executes a given function in a "sa... |
How to convert a stat output to a unix permissions string | 17,809,386 | 7 | 2013-07-23T11:49:33Z | 17,810,089 | 10 | 2013-07-23T12:22:12Z | [
"python"
] | If you run `os.stat(path)` on a file and then take its `st_mode` parameter, how do you get from there to a string like this: `rw-r--r--` as known from the Unix world? | Since Python 3.3 you could use [`stat.filemode`](http://docs.python.org/3/library/stat.html#stat.filemode):
```
In [7]: import os, stat
In [8]: print(stat.filemode(os.stat('/home/soon/foo').st_mode))
-rw-r--r--
In [9]: ls -l ~/foo
-rw-r--r-- 1 soon users 0 Jul 23 18:15 /home/soon/foo
``` |
Syntax Error: Not a Chance | 17,811,855 | 16 | 2013-07-23T13:38:26Z | 17,811,862 | 34 | 2013-07-23T13:38:41Z | [
"python",
"syntax-error",
"curly-braces"
] | I tried executed the following code in the python IDLE
```
from __future__ import braces
```
And I got the following error:
```
SyntaxError: not a chance
```
What does the above error mean? | You have found an easter egg in Python. It is a joke.
It means that delimiting blocks by braces instead of indentation will never be implemented.
*Normally*, imports from the [special `__future__` module](http://docs.python.org/2/library/__future__.html) enable features that are backwards-incompatible, such as the `p... |
Syntax Error: Not a Chance | 17,811,855 | 16 | 2013-07-23T13:38:26Z | 17,811,937 | 12 | 2013-07-23T13:41:34Z | [
"python",
"syntax-error",
"curly-braces"
] | I tried executed the following code in the python IDLE
```
from __future__ import braces
```
And I got the following error:
```
SyntaxError: not a chance
```
What does the above error mean? | The `__future__` module is normally used to provide features from future versions of Python.
This is an easter egg that summarizes its developers' feelings on this issue.
There are several more:
`import this` will display the zen of Python.
`import __hello__` will display `Hello World...`.
In Python 2.7 and 3.0, `... |
How to plot two columns of a pandas data frame using points? | 17,812,978 | 19 | 2013-07-23T14:23:42Z | 17,813,222 | 21 | 2013-07-23T14:33:45Z | [
"python",
"matplotlib",
"plot",
"pandas",
"dataframe"
] | I have a pandas data frame and would like to plot values from one column versus the values from another column. Fortunately, there is `plot` method associated with the data-frames that seems to do what I need:
```
df.plot(x='col_name_1', y='col_name_2')
```
Unfortunately, it looks like among the plot styles (listed [... | You can specify the `style` of the plotted line when calling [`df.plot`](http://pandas.pydata.org/pandas-docs/version/0.15.0/generated/pandas.DataFrame.plot.html?highlight=plot#pandas-dataframe-plot):
```
df.plot(x='col_name_1', y='col_name_2', style='o')
```
The `style` argument can also be a `dict` or `list`, e.g.:... |
How to plot two columns of a pandas data frame using points? | 17,812,978 | 19 | 2013-07-23T14:23:42Z | 17,813,277 | 13 | 2013-07-23T14:36:04Z | [
"python",
"matplotlib",
"plot",
"pandas",
"dataframe"
] | I have a pandas data frame and would like to plot values from one column versus the values from another column. Fortunately, there is `plot` method associated with the data-frames that seems to do what I need:
```
df.plot(x='col_name_1', y='col_name_2')
```
Unfortunately, it looks like among the plot styles (listed [... | For this (and most plotting) I would not rely on the Pandas wrappers to matplotlib. Instead, just use matplotlib directly:
```
import matplotlib.pyplot as plt
plt.scatter(df['col_name_1'], df['col_name_2'])
plt.show() # Depending on whether you use IPython or interactive mode, etc.
```
and remember that you can acces... |
Maximize a function with many parameters (python) | 17,814,169 | 8 | 2013-07-23T15:12:55Z | 17,814,310 | 7 | 2013-07-23T15:19:06Z | [
"python",
"function",
"math",
"mcmc"
] | first, let me say that I lack experiences with scientific math or statistics - so this might be a very well-known problem, but I don't know where to start.
I have a function `f(x1, x2, ..., xn)` where I need to guess the x'ses and find the highest value for `f`. The function has the following properties:
* the total ... | I think you want to take a look at scipy.optimize (<http://docs.scipy.org/doc/scipy-0.10.0/reference/tutorial/optimize.html>). A maximization is the minimization of the -1\*function. |
Detect key input in Python | 17,815,686 | 11 | 2013-07-23T16:22:07Z | 17,815,891 | 14 | 2013-07-23T16:31:22Z | [
"python",
"input",
"tkinter",
"keyboard"
] | I don't know why Python is that weird, you can't find this by searching in google very easily, but it's quite simple.
How can I detect 'SPACE' or actually any key?
How can I do this:
```
print('You pressed %s' % key)
```
This should be included in python core, so please do not link modules not related for core pytho... | You could make a little Tkinter app:
```
import Tkinter as tk
def onKeyPress(event):
text.insert('end', 'You pressed %s\n' % (event.char, ))
root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPr... |
Convert generator object to a dictionary | 17,815,945 | 7 | 2013-07-23T16:34:00Z | 17,815,964 | 8 | 2013-07-23T16:34:52Z | [
"python"
] | Here is my code:
```
# library to extract cookies in a http message
cj = cookielib.CookieJar()
... do connect to httpserver etc
cdict = ((c.name,c.value) for c in cj)
```
The problem with this code is cdict is a generator. But I want to simply create a dictionary. How can I change the last line to assign to a dicti... | Use a dictionary comprehension. (Introduced in Python 2.7)
`cdict = {c.name:c.value for c in cj}`
For example,
```
>>> {i:i*2 for i in range(10)}
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
```
Here is the [PEP](http://www.python.org/dev/peps/pep-0274/) which introduced Dictionary Comprehensio... |
How to open IPython interpreter in emacs? | 17,817,019 | 9 | 2013-07-23T17:27:12Z | 17,822,336 | 16 | 2013-07-23T22:48:43Z | [
"python",
"emacs",
"ipython"
] | In order to use IPython during Python development in Emacs, I have been opening up a terminal, and typing `ipython`. This doesn't seem like the right way to do it.
For one thing, my buffer lists this buffer as `*ansi-term*`, which is confusing, as I often end up with multiple terminals, one of which is dedicated to Py... | I don't know what Prelude is, but if you can install the latest Emacs (i.e, Emacs with Fabian's python-mode included), then you can use the following to let Python mode know your preferred choice of interpreter. Then you just need to call `M-x run-python`.
```
(when (executable-find "ipython")
(setq python-shell-int... |
NLTK SVM Classifier Terminates | 17,817,183 | 2 | 2013-07-23T17:35:49Z | 19,868,470 | 7 | 2013-11-08T21:04:09Z | [
"python",
"python-2.7",
"nltk",
"svm"
] | I am using the SVM classifier built in NLTK and after training the model, when I try to classify a document, the program terminates with `Error during execution, QProcess error: 1 Execution Interrupted`
I am using the following code:-
```
classifier = nltk.classify.svm.SvmClassifier.train(train_features)
for test_rec... | `nltk.classify.svm` was deprecated. For classification based
on support vector machines SVMs use `nltk.classify.scikitlearn`
(or [scikit-learn](http://scikit-learn.org) directly).For more details [NLTK 3.0 documentation](http://nltk.org/api/nltk.classify.html#module-nltk.classify.svm)
You can use `nltk.classify.scikit... |
Receiving error: Reverse for with arguments '()' and keyword arguments not found | 17,818,034 | 3 | 2013-07-23T18:21:27Z | 17,821,292 | 9 | 2013-07-23T21:18:59Z | [
"python",
"django",
"django-templates",
"django-urls"
] | I am getting an error creating a link in my Django template.
My template looks like this:
```
<a href="{% url 'location_detail' pk=location.id %}">{{ location.name }}</a>
```
My urls.py looks like:
```
url(r'^location(?P<pk>\d+)/$', views.location_detail, name="location_detail"),
```
My view looks like:
```
def l... | The problem was that I had a name space on the primary project urls.py:
```
url(r'^com/', include('com.urls', namespace="com")),
```
Changing the url to:
```
{% url 'com:location_detail' pk=location.id %}
```
That did the trick |
Is it possible to have an alias for sys.stdout in python? | 17,818,502 | 6 | 2013-07-23T18:44:58Z | 17,818,521 | 10 | 2013-07-23T18:46:12Z | [
"python"
] | Consider this sample python code. It reads from stdin and writes to a file.
```
import sys
arg1 = sys.argv[1]
f = open(arg1,'w')
f.write('<html><head><title></title></head><body>')
for line in sys.stdin:
f.write("<p>")
f.write(line)
f.write("</p>")
f.write("</body></html>")
f.close()
```
Suppose I wan... | Just do
```
>>> import sys
>>> f = sys.stdout
>>> f.write('abc')
abc
```
Now you just need to do `f = sys.stdout` instead of `f = open(fileName)`. (And remove `f.close()`)
**Also**, Please consider using the following syntax for files.
```
with open(fileName, 'r') as f:
# Do Something
```
The file automaticall... |
Is it possible to have an alias for sys.stdout in python? | 17,818,502 | 6 | 2013-07-23T18:44:58Z | 17,818,616 | 13 | 2013-07-23T18:50:18Z | [
"python"
] | Consider this sample python code. It reads from stdin and writes to a file.
```
import sys
arg1 = sys.argv[1]
f = open(arg1,'w')
f.write('<html><head><title></title></head><body>')
for line in sys.stdin:
f.write("<p>")
f.write(line)
f.write("</p>")
f.write("</body></html>")
f.close()
```
Suppose I wan... | Names in Python are just bindings. Therefore:
```
f = sys.stdout
```
Just binds the name `f` to *the object* that's *also bound* to `sys.stdout`...
Note that since they're both the same object, any changes you make to `f` or `sys.stdout` at this point will affect *both*... So don't do `f.close()` as you normally wou... |
Populate a Pandas SparseDataFrame from a SciPy Sparse Matrix | 17,818,783 | 19 | 2013-07-23T18:58:05Z | 17,819,427 | 19 | 2013-07-23T19:32:57Z | [
"python",
"numpy",
"scipy",
"pandas",
"sparse-matrix"
] | I noticed Pandas now has [support for Sparse Matrices and Arrays](http://pandas.pydata.org/pandas-docs/dev/sparse.html). Currently, I create `DataFrame()`s like this:
```
return DataFrame(matrix.toarray(), columns=features, index=observations)
```
Is there a way to create a `SparseDataFrame()` with a `scipy.sparse.cs... | A direct conversion is not supported ATM. Contributions are welcome!
Try this, should be ok on memory as the SpareSeries is much like a csc\_matrix (for 1 column)
and pretty space efficient
```
In [37]: col = np.array([0,0,1,2,2,2])
In [38]: data = np.array([1,2,3,4,5,6],dtype='float64')
In [39]: m = csc_matrix( (d... |
Coverting Index into MultiIndex (hierachical index) in Pandas | 17,819,119 | 7 | 2013-07-23T19:16:08Z | 17,819,120 | 7 | 2013-07-23T19:16:08Z | [
"python",
"pandas"
] | In the data I am working with the index is compound - i.e. it has both item name and a timestamp, e.g. `[email protected]|2013-05-07 05:52:51 +0200`.
I want to do hierarchical indexing, so that the same e-mails are grouped together, so I need to convert a DataFrame Index into a MultiIndex (e.g. for the entry above - `(n... | Once we have a DataFrame
```
import pandas as pd
df = pd.read_csv("input.csv", index_col=0) # or from another source
```
and a function mapping each index to a tuple (below, it is for the example from this question)
```
def process_index(k):
return tuple(k.split("|"))
```
we can create a hierarchical index in ... |
Jinja2 and Flask: Pass variable into parent template without passing it into children | 17,819,178 | 4 | 2013-07-23T19:19:11Z | 17,819,870 | 8 | 2013-07-23T19:57:33Z | [
"python",
"templates",
"variables",
"flask",
"jinja2"
] | Let's say I have a base template with a header in it, and the content of that header needs to be passed into the template.
```
<header>
You are logged in as {{ name }}
</header>
```
This base template gets extended by many pages. How can I pass in that variable without passing it to each individual child? For examp... | May I suggest you use the global variable 'g' in flask. This is by default available in the jinja templates. So you don't need to worry about passing it anywhere in the base template or children. Just make sure you set it first when you login
```
g.username = user.name
```
then in templates, just do this:
```
You ar... |
XML (.xsd) feed validation against a schema | 17,819,884 | 15 | 2013-07-23T19:58:26Z | 17,819,981 | 20 | 2013-07-23T20:03:23Z | [
"python",
"xml",
"python-2.7",
"xsd",
"xml-validation"
] | I have a XML file and I have a XML schema. I want to validate the file against that schema and check if it adheres to that. I am using python but am open to any language for that matter if there is no such useful library in python.
What would be my best options here? I would worry about the how fast I can get this up ... | Definitely [`lxml`](http://lxml.de/).
Define an [`XMLParser`](http://lxml.de/api/index.html) with a predefined schema, load the the file `fromstring()` and catch any XML Schema errors:
```
from lxml import etree
def validate(xmlparser, xmlfilename):
try:
with open(xmlfilename, 'r') as f:
etre... |
Storing Pandas objects along with regular Python objects in HDF5 | 17,820,071 | 7 | 2013-07-23T20:08:37Z | 17,820,256 | 8 | 2013-07-23T20:19:33Z | [
"python",
"pandas",
"hdf5"
] | Pandas has a [nice interface](http://pandas.pydata.org/pandas-docs/dev/io.html) that facilitates storing things like Dataframes and Series in an HDF5:
```
random_matrix = np.random.random_integers(0,10, m_size)
my_dataframe = pd.DataFrame(random_matrix)
store = pd.HDFStore('some_file.h5',complevel=9, complib='bzip2... | Here's the example from the cookbook: <http://pandas.pydata.org/pandas-docs/stable/cookbook.html#hdfstore>
You can store arbitrary objects as the attributes of a node. I belive there is a 64kb limit (I think its total attribute data for that node). The objects are pickled
```
In [1]: df = DataFrame(np.random.randn(8,... |
How to exit pdb and allow program to continue? | 17,820,618 | 16 | 2013-07-23T20:40:44Z | 17,820,890 | 40 | 2013-07-23T20:55:23Z | [
"python"
] | I'm using the pdb module to debug a program. I'd like to understand how I can exit pdb and allow the program to continue onward to completion. The program is computationally expensive to run, so I don't want to exit without the script attempting to complete. `continue` doesn't seems to work. How can I exit pdb and cont... | `continue` should "Continue execution, only stop when a breakpoint is encountered", so you've got a breakpoint set somewhere. To remove the breakpoint (if you inserted it manually):
```
(Pdb) break
Num Type Disp Enb Where
1 breakpoint keep yes at /path/to/test.py:5
(Pdb) clear 1
Deleted breakpoint 1
(P... |
a cleaner way to approach try except in python | 17,821,212 | 3 | 2013-07-23T21:14:24Z | 17,821,312 | 8 | 2013-07-23T21:20:34Z | [
"python",
"exception",
"try-catch"
] | So, let say I have 3 different calls called `something`, `something1` and `something2`.
and right now, im calling it like
```
try:
something
something1
something2
except Keyerror as e:
print e
```
Note that in the above code, if something fails, something1 and something2 will not get executed and so on.
... | You could try this, assuming you wrap things in functions:
```
for func in (something, something1, something2):
try:
func()
except Keyerror as e:
print e
``` |
Regex Match for Domain Name in Django Model | 17,821,400 | 3 | 2013-07-23T21:27:45Z | 17,822,192 | 8 | 2013-07-23T22:36:40Z | [
"python",
"regex",
"django",
"model"
] | I have one table, which looks like:
```
class Tld(models.Model):
domainNm = models.CharField(validators=[ RegexValidator('^[0-9]^[a-z]','yourdomain.com only','Invalid Entry')], max_length=40)
dtCreated = models.DateField()
```
for domainNm - I want to validate on any entry that looks like:
* domain.com
* 1do... | If you want to validate HTTP URL's, forget the regex and use the [builtin validator](https://docs.djangoproject.com/en/dev/ref/validators/#django.core.validators.URLValidator).
If you want only domains without any protocol, try:
```
def full_domain_validator(hostname):
"""
Fully validates a domain name as com... |
Random Number from Histogram | 17,821,458 | 10 | 2013-07-23T21:32:48Z | 17,822,210 | 14 | 2013-07-23T22:37:48Z | [
"python",
"numpy",
"scipy",
"montecarlo"
] | Suppose I create a histogram using scipy/numpy, so I have two arrays: one for the bin counts, and one for the bin edges. If I use the histogram to represent a probability distribution function, how can I efficiently generate random numbers from that distribution? | It's probably what `np.random.choice` does in @Ophion's answer, but you can construct a normalized cumulative density function, then choose based on a uniform random number:
```
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
data = np.random.normal(size=1000)
hist, bins = np.histog... |
Clunky arg check in Python | 17,821,792 | 2 | 2013-07-23T22:00:35Z | 17,821,852 | 10 | 2013-07-23T22:06:11Z | [
"python",
"kwargs"
] | I have a function:
```
def check_user(self, **args):
allowed = ['name', 'screen_name', 'url', 'description', 'location']
arg_check = [val for val in args if val not in allowed]
if arg_check:
raise ValueError('Invalid args: ' + ' '.join(arg_check))
```
And it works, but it feels very unpythonic. Is... | I think a more pythonic version would explicitly declare the allowed arguments in the function definition. Just replace `None` with your default values.
```
def check_user(self, name=None, screen_name=None, url=None,
description=None, location=None):
# Do something here
# ...
``` |
How to get an UTC date string in Python? | 17,822,158 | 10 | 2013-07-23T22:33:49Z | 17,822,273 | 21 | 2013-07-23T22:44:04Z | [
"python",
"datetime",
"utc"
] | I am trying to get utc date string as "YYYYMMDD"
For now I do the following,
```
nowTime = time.gmtime();
nowDate = date(nowTime.tm_year, nowTime.tm_mon, nowTime.tm_mday)
print nowDate.strftime('%Y%m%d')
```
I used to do:
```
datetime.date.today().strftime()
```
but this gives me date string in local TZ
How can ... | ```
from datetime import datetime, timezone
datetime.now(timezone.utc).strftime("%Y%m%d")
```
Or as Davidism pointed out, this would also work:
```
from datetime import datetime
datetime.utcnow().strftime("%Y%m%d")
```
I prefer the first approach, as it gets you in the habit of using timezone aware datetimes - but a... |
Python: adding two dicts together | 17,823,801 | 3 | 2013-07-24T01:35:34Z | 17,823,824 | 11 | 2013-07-24T01:37:54Z | [
"python"
] | Alrigt, lets say I have these two dictionaries:
```
A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
B = {(3,'y'):4, (6,'y'):6}
```
I am trying to add them together such that I get a dict similar to this:
```
C = {(3,'x'):-2,(3,'y'):4, (6,'y'):9, (8, 'b'):9}
```
I have tried making a comprehension that does this for dicts o... | I would use a [collections.Counter](http://docs.python.org/2/library/collections.html#collections.Counter) for this:
```
>>> A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
>>> B = {(3,'y'):4, (6,'y'):6}
>>> import collections
>>> C = collections.Counter(A)
>>> C.update(B)
>>> dict(C)
{(3, 'y'): 4, (8, 'b'): 9, (3, 'x'): -2, ... |
bufsize must be an integer error while grepping a message | 17,824,096 | 3 | 2013-07-24T02:09:54Z | 17,824,147 | 10 | 2013-07-24T02:14:57Z | [
"python",
"subprocess"
] | I am running into following error while trying to grep for a message consisting of multipe lines in a log...can anyone provide inputs on how to overcome this error?
CODE:-
```
print gerrit_commitmsg
gerritlog = Popen('git','log','--grep','gerrit_commitmsg', stdout=PIPE, stderr=PIPE)
print gerritlog
```
E... | The `subprocess.Popen` class expects an argument list like this:
```
Popen(args, bufsize=0, ...)
```
So you're passing it:
* `args` = `git`
* `bufsize` = `log`
Hence the error (`bufsize` expects an integer value). The command vector needs to be a list, like this:
```
gerritlog = Popen(['git','log','--grep','gerrit... |
python-like string indexing in C++ | 17,824,210 | 3 | 2013-07-24T02:24:20Z | 17,824,410 | 17 | 2013-07-24T02:51:42Z | [
"c++",
"python",
"string"
] | Is there any (possibly, using a macros) way to get a substring of a string using python-like expression f(i:j)? Or, more specifically, resolve i:j expression into pair of indices i and j? Any ideas?
EDIT: Yes, I need :. Or ;. Basically, something that simple function or macros can't do.
Just want to see if it is possi... | I hate myself for answering, but ...
```
#include <iostream>
#include <string>
#define f(x) substr(true?x, false?x)
int main () {
std::string s = "Hello, world";
std::string y = s.f(1:4);
std::cout << y << "\n";
}
```
Warning: I am a hiring manager. If I ever discover that you use this technique, I will **nev... |
How to specify that a parameter is a list of specific objects in Python docstrings | 17,824,280 | 17 | 2013-07-24T02:34:39Z | 19,524,180 | 23 | 2013-10-22T17:09:05Z | [
"python",
"pycharm"
] | I really like using docstrings in Python to specify type parameters when projects get beyond a certain size.
I'm having trouble finding a standard to use to specify that a parameter is a list of specific objects, e.g. in Haskell types I'd use [String] or [A].
Current standard (recognisable by PyCharm editor):
```
de... | In comments section of [PyCharm's manual](http://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html) there's a nice hint from developer:
```
#: :type: dict of (str, C)
#: :type: list of str
```
It works for me pretty well. Now it makes me wonder what's the best way to document parametrized classes in Pyth... |
Pyqtgraph with anaconda python on MAC gives nib error | 17,824,693 | 3 | 2013-07-24T03:25:44Z | 17,861,162 | 8 | 2013-07-25T14:39:22Z | [
"python",
"osx",
"qt",
"nib",
"anaconda"
] | I'm trying to use the [pyqtgraph](http://pyqtgraph.org/) with anaconda python on Mac os
```
Python 2.7.5 |Anaconda 1.6.1 (x86_64)| (default, Jun 28 2013, 22:20:13)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
```
I installed pyqtgraph with `pip install pyqtgraph`, which seemed to work fine. However, if I run any co... | The solution is to use `python.app` (or the equivalent `pythonw`) to run the program, instead of just `python`. If `pyqtgraph` installed any commands, you'll need to edit them so that their shebang line calls `#!/path/to/anaconda/bin/python.app/Contents/MacOS/python`. |
Why does readline.read_history_file give me 'IOError: [Errno 2] No such file or directory' | 17,824,898 | 3 | 2013-07-24T03:50:03Z | 17,824,899 | 14 | 2013-07-24T03:50:03Z | [
"python",
"python-2.7",
"readline"
] | My Python history file exists at ~/.pyhistory and contains the following:
```
from project.stuff import *
quit()
from project.stuff import *
my_thing = Thing.objects.get(id=21025)
my_thing
my_thing.child_set.all()
my_thing.current_state
my_thing.summary_set
my_thing.summary_set.all()
[ x.type for x in my_thing.child_s... | Your history file appears to be an older version. Try converting it to the format expected by later versions of readline, most notably the first line should be literally '\_HiStOrY\_V2\_' and all spaces should be replaced with '\040':
```
_HiStOrY_V2_
from\040project.stuff\040import\040*
quit()
from\040project.stuff\0... |
How to set value of a ManyToMany field in Django? | 17,826,629 | 2 | 2013-07-24T06:23:54Z | 17,829,433 | 11 | 2013-07-24T08:58:35Z | [
"python",
"django",
"models"
] | while learning Django to do web programming,I faced this problem.
I searched Google and Django's official website biut could not find any answer. Please help me.
System environment:
1. Fedora 18
2. Python 2.7
3. Django 1.5.1
4. Eclipse + PyDev
Runtime: Django's development server
I have a models includes ManyToMany... | It looks like the problem here is that you're trying to add something to the M2M table before it's actually created in the database.
When you run `post = Postsï¼ï¼` you create an object in memory, but **not** in the database. So when you then try to add a new entry to the M2M table there is nothing to reference. (Re... |
Python: xlrd discerning dates from floats | 17,827,471 | 8 | 2013-07-24T07:14:00Z | 17,850,954 | 8 | 2013-07-25T06:50:26Z | [
"python",
"excel",
"date",
"xlrd"
] | I wanted to import a file containing text, numbers and dates using xlrd on Python.
I tried something like:
```
if "/" in worksheet.cell_value:
do_this
else:
do_that
```
But that was of no use as I latter discovered dates are stored as floats, not strings. To convert them to datetime type I did:
```
try:
... | Well, never mind, I found a solution and here it is!
```
try:
cell = worksheet.cell(row - 1, i)
if cell.ctype == xlrd.XL_CELL_DATE:
date = datetime.datetime(1899, 12, 30)
get_ = datetime.timedelta(int(worksheet.cell_value(row - 1, i)))
get_col2 = str(date + get_)[:10]
d = dateti... |
Python: xlrd discerning dates from floats | 17,827,471 | 8 | 2013-07-24T07:14:00Z | 18,016,189 | 9 | 2013-08-02T11:48:59Z | [
"python",
"excel",
"date",
"xlrd"
] | I wanted to import a file containing text, numbers and dates using xlrd on Python.
I tried something like:
```
if "/" in worksheet.cell_value:
do_this
else:
do_that
```
But that was of no use as I latter discovered dates are stored as floats, not strings. To convert them to datetime type I did:
```
try:
... | I think you could make this much simpler by making more use of the tools available in xlrd:
```
cell_type = worksheet.cell_type(row - 1, i)
cell_value = worksheet.cell_value(row - 1, i)
if cell_type == xlrd.XL_CELL_DATE:
# Returns a tuple.
dt_tuple = xlrd.xldate_as_tuple(cell_value, workbook.datemode)
# C... |
python: number range to regex matching string | 17,829,875 | 7 | 2013-07-24T09:18:35Z | 17,840,228 | 13 | 2013-07-24T16:51:09Z | [
"python",
"regex"
] | This may be a problem that has already been solved, but I can't figure it out. I have two largish integers, lets call them `start_number` and `end_number` (they represent a contiguous block of telephone numbers). Other numbers (represented as strings) will be input into my system and I need to use regex to match this a... | [assuming you need this because it's some weird 3rd party system that requires regexp]
**New Approach**
the more i think about Frederik's comment, the more i agree. the regexp engine should be able to compile this down to a compact DFA, even if the input string is long. for many cases, the following is a sensible sol... |
Convert user input strings to raw string literal to construct regular expression | 17,830,198 | 7 | 2013-07-24T09:32:48Z | 17,830,394 | 12 | 2013-07-24T09:42:19Z | [
"python",
"regex"
] | I know there are some posts about convert string to raw string literal, but none of them help my situation.
My problem is:
Say, for example, I want to know whether the pattern "\section" is in the text "abcd\sectiondefghi". Of course, I can do this:
```
import re
motif = r"\\section"
txt = r"abcd\sectiondefghi"
pat... | Use [`re.escape()`](http://docs.python.org/2/library/re.html#re.escape) to make sure input text is treated as literal text in a regular expression:
```
pattern = re.compile(re.escape(motif))
```
Demo:
```
>>> import re
>>> motif = r"\section"
>>> txt = r"abcd\sectiondefghi"
>>> pattern = re.compile(re.escape(motif))... |
ValueError: too many values to unpack in Python Dictionary | 17,830,778 | 4 | 2013-07-24T10:01:03Z | 17,830,802 | 10 | 2013-07-24T10:02:36Z | [
"python",
"dictionary"
] | I have a function that accepts a string, list and a dictionary
```
def superDynaParams(myname, *likes, **relatives): # *n is a list and **n is dictionary
print '--------------------------'
print 'my name is ' + myname
print 'I like the following'
for like in likes:
print like
print 'and ... | You are looping over a dictionary:
```
for key, role in relatives:
```
but that only yields *keys*, so one single object at a time. If you want to loop over keys and values, use the `dict.items()` method:
```
for key, role in relatives.items():
```
On Python 2, use the `dict.iteritems()` method for efficiency:
```... |
stack trace from manage.py runserver not appearing | 17,833,195 | 9 | 2013-07-24T11:50:32Z | 23,818,289 | 17 | 2014-05-22T22:46:32Z | [
"python",
"django"
] | Django's `runserver` command doesn't output a stack trace when I append `--traceback --verbosity 2`:
```
â« python manage.py runserver --traceback --verbosity 2
Validating models...
0 errors found
July 24, 2013 - 11:45:12
Django version 1.5.1, using settings 'base.settings'
Development server is running at http://12... | Agreed that this is convenient, especially for MVVM-centric app development (e.g. Angular/Ember front-end). Also this is helpful when others are testing out the front-end.
As you mentioned, this isn't provided by `DEBUG=True`. You can add a stacktrace when running `./manage.py runserver` by adding the following to the... |
Is this the best way to add an extra dimension to a numpy array in one line of code? | 17,835,121 | 8 | 2013-07-24T13:14:34Z | 17,835,184 | 12 | 2013-07-24T13:17:11Z | [
"python",
"arrays",
"python-3.x",
"numpy",
"reshape"
] | If k is an numpy array of an arbitrary shape, so `k.shape = (s1, s2, s3, ..., sn)`, and I want to reshape it so that `k.shape` becomes `(s1, s2, ..., sn, 1)`, is this the best way to do it in one line?
```
k.reshape(*(list(k.shape) + [1])
``` | It's easier like this:
```
k.reshape(k.shape + (1,))
```
But if all you want is to add an empty dimension at the end, you should use `numpy.newaxis`:
```
import numpy as np
k = k[..., np.newaxis]
```
or
```
k = k[..., None]
```
(See the [documentation on slicing](http://docs.scipy.org/doc/numpy/reference/arrays.i... |
How to update matplotlib's imshow() window interactively? | 17,835,302 | 9 | 2013-07-24T13:21:45Z | 17,837,600 | 15 | 2013-07-24T14:53:34Z | [
"python",
"numpy",
"matplotlib",
"spyder"
] | I'm working on some computer vision algorithm and I'd like to show how a numpy array changes in each step.
What works now is that if I have a simple `imshow( array )` at the end of my code, the window displays and shows the final image.
However what I'd like to do is to update and display the imshow window as the ima... | You don't need to call `imshow` all the time. It is much faster to use the object's `set_data` method:
```
myobj = imshow(first_image)
for pixel in pixels:
addpixel(pixel)
myobj.set_data(segmentedimg)
draw()
```
The `draw()` should make sure that the backend updates the image.
**UPDATE:** your question w... |
Count rows which do not contain some string-Pandas DataFrames | 17,836,237 | 7 | 2013-07-24T14:00:20Z | 17,836,285 | 12 | 2013-07-24T14:02:38Z | [
"python",
"pandas",
"dataframe"
] | I want to count the rows where the dataframe do not contain some string. Eg:
```
df = pd.DataFrame([[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3], list('AAABBBBABCBDDD'), ['x/y/z','x/y','x/y/z/n','x/u','x','x/u/v','x/y/z','x','x/u/v/b','-','x/y','x/y/z','x','x/u/v/w']]).T
df.columns = ['col1','col2','... | Try:
```
~df.col3.str.contains('u|z')
```
## Update
To Count, use
```
(~df.col3.str.contains('u|z')).sum()
``` |
Add "django-admin.py" path to command line on Windows 7 | 17,836,416 | 3 | 2013-07-24T14:08:18Z | 17,836,439 | 7 | 2013-07-24T14:09:06Z | [
"python",
"django",
"windows",
"windows-7",
"cmd"
] | I've been trying to add the `django-admin.py` path to command line on Windows 7.
I have tried to do it this way:
```
C:\>set django-admin.py = C:\Python27\Scripts\django-admin.py
```
But `cmd` told me that:
```
'django-admin.py' is not recognized as an internal or external command.
```
So how can I add `django-adm... | Try following command.
```
set path=%path%;c:\python27\scripts
```
`PATH` is set only for the cmd.exe in which you run the above command.
**UPDATE**
To permanently set PATH:
1. Right click **My computer** in the desktop.
2. Click **Advanced System Settings** on the left.
3. Click **Environmental Variable**.
4. Add... |
orthogonal projection with numpy | 17,836,880 | 6 | 2013-07-24T14:26:30Z | 17,838,396 | 9 | 2013-07-24T15:25:05Z | [
"python",
"arrays",
"numpy"
] | I have a list of 3D-points for which I calculate a plane by numpy.linalg.lstsq - method. But Now I want to do a orthogonal projection for each point into this plane, but I can't find my mistake:
```
from numpy.linalg import lstsq
def VecProduct(vek1, vek2):
return (vek1[0]*vek2[0] + vek1[1]*vek2[1] + vek1[2]*vek2... | You are doing a very poor use of `np.lstsq`, since you are feeding it a precomputed 3x3 matrix, instead of letting it do the job. I would do it like this:
```
import numpy as np
def calc_plane(x, y, z):
a = np.column_stack((x, y, np.ones_like(x)))
return np.linalg.lstsq(a, z)[0]
>>> x = np.random.rand(1000)
... |
Mocking __init__() for unittesting | 17,836,939 | 11 | 2013-07-24T14:28:37Z | 17,950,141 | 16 | 2013-07-30T14:42:37Z | [
"python",
"sqlite",
"unit-testing",
"mocking"
] | I have a class:
```
class DatabaseThing():
def __init__(self, dbName, user, password):
self.connection = ibm_db_dbi.connect(dbName, user, password)
```
I want to test this class but with a test database. So in my test class I am something like this:
```
import sqlite3 as lite
import unittest
from Data... | Instead of mocking, you could simply subclass the database class and test against that:
```
class TestingDatabaseThing(DatabaseThing):
def __init__(self, connection):
self.connection = connection
```
and instantiate **that** class instead of `DatabaseThing` for your tests. The methods are still the sam... |
How do I skip a few iterations in a for loop | 17,837,316 | 11 | 2013-07-24T14:42:18Z | 17,837,346 | 7 | 2013-07-24T14:43:27Z | [
"python",
"loops"
] | In python I usually loop through ranges simply by
```
for i in range(100):
#do something
```
but now I want to skip a few steps in the loop. More specifically, I want something like `continue(10)` so that it would skip the whole loop and increase the counter by 10. If I were using a for loop in C I'd just sum 10... | You cannot alter the target list (`i` in this case) of a `for` loop. Use a `while` loop instead:
```
while i < 10:
i += 1
if i == 2:
i += 3
```
Alternatively, use an iterable and increment that:
```
from itertools import islice
numbers = iter(range(10))
for i in numbers:
if i == 2:
next(... |
How do I skip a few iterations in a for loop | 17,837,316 | 11 | 2013-07-24T14:42:18Z | 17,837,409 | 18 | 2013-07-24T14:46:20Z | [
"python",
"loops"
] | In python I usually loop through ranges simply by
```
for i in range(100):
#do something
```
but now I want to skip a few steps in the loop. More specifically, I want something like `continue(10)` so that it would skip the whole loop and increase the counter by 10. If I were using a for loop in C I'd just sum 10... | The best way is to assign the iterator a name - it is common have an iterable as opposed to an iterator (the difference being an iterable - for example a list - starts from the beginning each time you iterate over it). In this case, just use [the `iter()` built-in function](http://docs.python.org/3.3/library/functions.... |
Django virtualenv layout | 17,837,723 | 13 | 2013-07-24T14:57:58Z | 17,838,508 | 20 | 2013-07-24T15:29:23Z | [
"python",
"django",
"virtualenv"
] | I am very new to django. I just have a very basic question about project layout using virtualenv. When we create virtualenv and install all the dependencies-django etc, do I need to switch my directory to the virtualenv and then create a project there? Or do I need to create my project outside of virtualenv. I apologiz... | No, the directory where you create the virtual environment is completely separate and is not where you would go and create your django project.
In fact, you would usually put all your virtual environments in a separate directory; for me I put them in `$HOME/work/.envs` (note the `.`, this makes the directory hidden by... |
How to achieve python's any() with a custom predicate? | 17,839,574 | 10 | 2013-07-24T16:19:43Z | 17,839,581 | 17 | 2013-07-24T16:20:21Z | [
"python",
"python-2.7",
"functional-programming",
"any",
"filterfunction"
] | ```
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> if filter(lambda x: x > 10, l):
... print "foo"
... else: # the list will be empty, so bar will be printed
... print "bar"
...
bar
```
I'd like to use [`any()`](http://docs.python.org/2/library/functions.html#any) for thi... | Use a [generator expression](http://docs.python.org/2/reference/expressions.html#generator-expressions) as that one argument:
```
any(x > 10 for x in l)
```
Here the predicate is in the expression side of the generator expression, but you can use any expression there, including using functions.
Demo:
```
>>> l = ra... |
construct pandas DataFrame from values in variables | 17,839,973 | 30 | 2013-07-24T16:40:24Z | 17,840,195 | 58 | 2013-07-24T16:49:48Z | [
"python",
"pandas",
"dataframe"
] | This may be a simple question, but I can not figure out how to do this. Lets say that I have two variables as follows.
```
a = 2
b = 3
```
I want to construct a DataFrame from this:
```
df2 = pd.DataFrame({'A':a,'B':b})
```
This generates an error:
> ValueError: If using all scalar values, you must pass an index
... | The error message says that if you're passing scalar values, you have to pass an index. So you can either not use scalar values for the columns -- e.g. use a list:
```
>>> df = pd.DataFrame({'A': [a], 'B': [b]})
>>> df
A B
0 2 3
```
or use scalar values and pass an index:
```
>>> df = pd.DataFrame({'A': a, 'B'... |
Is there a way to make numpy.argmin() as fast as min()? | 17,840,661 | 18 | 2013-07-24T17:12:48Z | 17,841,486 | 12 | 2013-07-24T18:00:47Z | [
"python",
"arrays",
"numpy",
"min"
] | I'm trying to find the minimum array indices along one dimension of a very large 2D numpy array. I'm finding that this is very slow (already tried speeding it up with bottleneck, which was only a minimal improvement). However, taking the straight minimum appears to be an order of magnitude faster:
```
import numpy as ... | ```
In [1]: import numpy as np
In [2]: a = np.random.rand(3000, 16000)
In [3]: %timeit a.min(axis=0)
1 loops, best of 3: 421 ms per loop
In [4]: %timeit a.argmin(axis=0)
1 loops, best of 3: 1.95 s per loop
In [5]: %timeit a.min(axis=1)
1 loops, best of 3: 302 ms per loop
In [6]: %timeit a.argmin(axis=1)
1 loops, b... |
Is there a way to make numpy.argmin() as fast as min()? | 17,840,661 | 18 | 2013-07-24T17:12:48Z | 17,842,841 | 8 | 2013-07-24T19:11:31Z | [
"python",
"arrays",
"numpy",
"min"
] | I'm trying to find the minimum array indices along one dimension of a very large 2D numpy array. I'm finding that this is very slow (already tried speeding it up with bottleneck, which was only a minimal improvement). However, taking the straight minimum appears to be an order of magnitude faster:
```
import numpy as ... | I just took a look at [the source code](https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/calculation.c#L153), and while I don't fully understand why things are being done the way they are, this is what happens:
1. `np.min` is basically a call to `np.minimum.reduce`.
2. `np.argmin` first moves the a... |
Pandas groupby: How to get a union of strings | 17,841,149 | 23 | 2013-07-24T17:43:24Z | 17,841,294 | 45 | 2013-07-24T17:51:18Z | [
"python",
"pandas"
] | I have a dataframe like this:
```
A B C
0 1 0.749065 This
1 2 0.301084 is
2 3 0.463468 a
3 4 0.643961 random
4 1 0.866521 string
5 2 0.120737 !
```
Calling
```
In [10]: print df.groupby("A")["B"].sum()
```
will return
```
A
1 1.615586
2 0.421821
3 0.46346... | ```
In [4]: df = read_csv(StringIO(data),sep='\s+')
In [5]: df
Out[5]:
A B C
0 1 0.749065 This
1 2 0.301084 is
2 3 0.463468 a
3 4 0.643961 random
4 1 0.866521 string
5 2 0.120737 !
In [6]: df.dtypes
Out[6]:
A int64
B float64
C object
dtype: object
```
... |
Pandas groupby: How to get a union of strings | 17,841,149 | 23 | 2013-07-24T17:43:24Z | 17,841,308 | 15 | 2013-07-24T17:51:56Z | [
"python",
"pandas"
] | I have a dataframe like this:
```
A B C
0 1 0.749065 This
1 2 0.301084 is
2 3 0.463468 a
3 4 0.643961 random
4 1 0.866521 string
5 2 0.120737 !
```
Calling
```
In [10]: print df.groupby("A")["B"].sum()
```
will return
```
A
1 1.615586
2 0.421821
3 0.46346... | You can use the `apply` method to apply an arbitrary function to the grouped data. So if you want a set, apply `set`. If you want a list, apply `list`.
```
>>> d
A B
0 1 This
1 2 is
2 3 a
3 4 random
4 1 string
5 2 !
>>> d.groupby('A')['B'].apply(list)
A
1 [This, string]
2 ... |
Is it possible to do fancy formatting for page footers with weasyprint? | 17,843,147 | 6 | 2013-07-24T19:27:55Z | 21,272,283 | 9 | 2014-01-22T01:07:43Z | [
"python",
"pdf",
"formatting",
"weasyprint"
] | weasyprint understands certain custom css directives, such as:
```
@bottom-right {
content: "Page " counter(page) " of " counter(pages) "
}
```
which places a "Page 1 of 4" style counter at the bottom right of each pdf page weasyprint generates.
I'd like to produce slightly fancier formatting for my footers - f... | "Page **1** *of* **4**" is not doable at the moment. If youâre interested, please send comments to [[email protected]](http://lists.w3.org/Archives/Public/www-style/) about what a new CSS feature could look like to do this kind of thing.
What works is:
* Page-margin rules like `@bottom-right`, with the `content` pro... |
Difference between tkinter and Tkinter | 17,843,596 | 11 | 2013-07-24T19:51:15Z | 17,843,652 | 23 | 2013-07-24T19:55:00Z | [
"python",
"import",
"tkinter"
] | When I answer Tkinter questions I usually try and run the code myself, but sometimes I get this error:
```
Traceback (most recent call last):
File "C:\Python27\pygame2.py", line 1, in <module>
from tkinter import *
ImportError: No module named tkinter
```
When I look at the question I see they import `tkinter` ... | It's simple.
For python2 it is:
```
from Tkinter import *
```
For python3 it is:
```
from tkinter import *
```
Here's the way how can you forget about this confusion once and for all:
```
try:
from Tkinter import *
except ImportError:
from tkinter import *
``` |
Python Recursion within Class | 17,843,785 | 4 | 2013-07-24T20:02:29Z | 17,843,819 | 8 | 2013-07-24T20:04:51Z | [
"python"
] | I just learn python today, and so am thinking about writing a code about recursion, naively.
So how can we achieve the following in python?
```
class mine:
def inclass(self):
self = mine();
def recur(num):
print(num, end="")
if num > 1:
print(" * ",end="")
return... | Each method of a class has to have `self` as a first parameter, i.e. do this:
```
def recur(self, num):
```
and it should work now.
Basically what happens behind the scene is when you do
```
instance.method(arg1, arg2, arg3, ...)
```
Python does
```
method(instance, arg1, arg2, arg3, ....)
``` |
Clean python return assignment | 17,844,778 | 3 | 2013-07-24T21:04:20Z | 17,844,820 | 10 | 2013-07-24T21:06:43Z | [
"python"
] | I have a method that returns multiple items.
```
def multiReturn():
return 1,2,3,4
```
and Im assigning it on one line
```
one, two, three, four = multiReturn()
```
Is there a way to cleanup the above line
Something like:
```
one,
two,
three,
four = multiReturn()
```
because I have some variable names that ha... | You can use parentheses:
```
(
one,
two,
three,
four
) = range(4)
``` |
Clean python return assignment | 17,844,778 | 3 | 2013-07-24T21:04:20Z | 17,844,832 | 8 | 2013-07-24T21:07:25Z | [
"python"
] | I have a method that returns multiple items.
```
def multiReturn():
return 1,2,3,4
```
and Im assigning it on one line
```
one, two, three, four = multiReturn()
```
Is there a way to cleanup the above line
Something like:
```
one,
two,
three,
four = multiReturn()
```
because I have some variable names that ha... | If you're returning so many items already, consider creating a data structure of some sort. A class should be fine, but if you consider it overkill, you can use a dict or even a [namedtuple](http://docs.python.org/2/library/collections.html#collections.namedtuple).
```
# First define the structure
myStruct = namedtupl... |
ImportError: cannot import name | 17,845,366 | 10 | 2013-07-24T21:46:20Z | 17,845,428 | 19 | 2013-07-24T21:51:56Z | [
"python",
"flask"
] | I have two files `app.py` and `mod_login.py`
app.py
```
from flask import Flask
from mod_login import mod_login
app = Flask(__name__)
app.config.update(
USERNAME='admin',
PASSWORD='default'
)
```
mod\_login.py
```
# coding: utf8
from flask import Blueprint, render_template, redirect, session, url_for, req... | The problem is that you have a circular import:
in app.py
```
from mod_login import mod_login
```
in mod\_login.py
```
from app import app
```
This is not permitted in Python. See [Circular import dependency in Python](http://stackoverflow.com/questions/1556387/circular-import-dependency-in-python) for more info. I... |
Django - Display ImageField | 17,846,290 | 6 | 2013-07-24T23:03:38Z | 17,846,328 | 9 | 2013-07-24T23:07:23Z | [
"python",
"django",
"imagefield"
] | i just start to use django and i haven't found a lot of info on how to display an imageField, so i made this:
models.py
```
class Car(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=5, decimal_places=2)
photo = models.ImageField(upload_to='site_media')
```
vi... | An `ImageField` contains a `url` attribute, which you can use in your templates to render the proper HTML.
```
{% block content %}
<img src="{{ carx.photo.url }}">
{% endblock %}
``` |
Python: comprehension to compose two dictionaries | 17,846,545 | 6 | 2013-07-24T23:27:38Z | 17,846,568 | 8 | 2013-07-24T23:30:10Z | [
"python"
] | I'm trying to write a comprehension that will compose two dictionaries in the following way:
```
d1 = {1:'a',2:'b',3:'c'}
d2 = {'a':'A','b':'B','c':'C'}
result = {1:'A',2:'B',3:'C'}
```
That is, the resulting dictionary is formed from the keys of the first one and the values of the second one for each pair where the ... | One way to do it is:
```
result = {k: d2.get(v) for k, v in d1.items()}
```
What behavior did you want for keys that have a value that is not in d2? |
Proper shebang for Python script | 17,846,908 | 22 | 2013-07-25T00:08:34Z | 17,846,946 | 37 | 2013-07-25T00:14:00Z | [
"python",
"portability",
"shebang"
] | I'm usually using the following shebang declaration in my Python scripts:
```
#!/usr/bin/python
```
Recently, I've came across this shebang declaration:
```
#!/usr/bin/env python
```
In the script documentation, it was noted that using this form is "more portable".
What does this declaration mean? How come there's... | ```
#!/usr/bin/env python
```
is more portable because in general the program `/usr/bin/env` can be used to "activate" the desired command without full path.
Otherwise, you would have to specify the full path of the Python interpreter, which can vary.
So no matter if the Python interpreter was in `/usr/bin/python` o... |
mysql-connector python 'IN' operator stored as list | 17,847,297 | 3 | 2013-07-25T01:04:55Z | 17,847,395 | 7 | 2013-07-25T01:16:39Z | [
"python",
"mysql",
"mysql-connector"
] | I am using mysql-connector with python and have a query like this:
```
SELECT avg(downloadtime) FROM tb_npp where date(date) between %s and %s and host like %s",(s_date,e_date,"%" + dc + "%")
```
NOw, if my variable 'dc' is a list like this:
```
dc = ['sjc','iad','las']
```
Then I have a mysql query like below:
`... | I'm not familiar with mysql-connector, but its behavior appears to be [similar to MySQLdb](http://stackoverflow.com/q/4574609/190597) in this regard. If that's true, you need to use a bit of string formatting:
```
sql = """SELECT avg(downloadtime) FROM tb_npp where date(date) = %s
and substring(host,6,3) in ... |
May someone explain this decorator code to me? | 17,847,733 | 6 | 2013-07-25T01:55:50Z | 17,847,809 | 7 | 2013-07-25T02:03:19Z | [
"python"
] | *The code has been taken from Learning Python 4th Edition by Mark Lutz*
```
class tracer:
def __init__(self, func):
self.calls = 0
self.func = func
def __call__(self, *args):
self.calls += 1
print('call %s to %s' % (self.calls, self.fu... | What's happening here is the body of the function is being replaced. A decorator like so
```
@tracer
def spam(...)
...
```
Is the equivalent of:
```
def spam(...)
...
spam = tracer(spam)
```
Now, `tracer(spam)` returns an instance of the `tracer` class where the original definition of `spam` is stored in `sel... |
What is the difference between sympy and sage? | 17,847,902 | 18 | 2013-07-25T02:14:21Z | 17,865,186 | 26 | 2013-07-25T17:47:03Z | [
"python",
"math",
"algebra",
"sympy",
"sage"
] | What do you guys recommend for extensive mathematics/physics/chemistry solving systems.
Sympy or sage based on the latest versions?
I also heard about mathics using both of them, w
hat would be the best option if there is another option? | (Full disclosure: I am the lead developer of SymPy)
The first thing you should understand is that SymPy and Sage are not quite the same thing. SymPy is a pure Python library, that does computer algebra. Sage is a collection of open source mathematical software. Sage tries to gather together all the major open source m... |
What is the difference between sympy and sage? | 17,847,902 | 18 | 2013-07-25T02:14:21Z | 17,893,720 | 7 | 2013-07-27T02:39:00Z | [
"python",
"math",
"algebra",
"sympy",
"sage"
] | What do you guys recommend for extensive mathematics/physics/chemistry solving systems.
Sympy or sage based on the latest versions?
I also heard about mathics using both of them, w
hat would be the best option if there is another option? | I completely forgot that we have a writeup of the difference between SymPy and Sage on the SymPy wiki: <https://github.com/sympy/sympy/wiki/SymPy-vs.-Sage>. There are also pages for SymPy vs. other CASs there too. |
Text-Replace in docx and save the changed file with python-docx | 17,850,227 | 7 | 2013-07-25T06:03:19Z | 30,556,079 | 7 | 2015-05-31T09:53:26Z | [
"python",
"replace",
"ms-word",
"docx"
] | I'm trying to use the [python-docx module](https://github.com/mikemaccana/python-docx) to replace a word in a file and save the new file with the caveat that the new file must have exactly the same formatting as the old file, but with the word replaced. How am I supposed to do this?
The docx module has a savedocx that... | this worked for me:
```
def docx_replace(old_file,new_file,rep):
zin = zipfile.ZipFile (old_file, 'r')
zout = zipfile.ZipFile (new_file, 'w')
for item in zin.infolist():
buffer = zin.read(item.filename)
if (item.filename == 'word/document.xml'):
res = buffer.decode("utf-8")
... |
Animation using matplotlib with subplots and ArtistAnimation | 17,853,680 | 4 | 2013-07-25T09:09:56Z | 17,863,659 | 11 | 2013-07-25T16:26:53Z | [
"python",
"animation",
"matplotlib"
] | I am working on an image analysis and I want to create an animation of the final results that includes the time-sequence of 2D data and a plot of the time sequences at a single pixel such that the 1D plot updates as the 2D animation progresses. Then set them up in a subplot side by side The link below has an image of t... | `plot` returns a list of artists (hence why the error is referring to a list). This is so you can call `plot` like `lines = plot(x1, y1, x2, y2,...)`.
Change
```
im2 = ax2.plot(image[0:time,5,5])
```
to
```
im2, = ax2.plot(image[0:time,5,5])
```
Adding the comma un-packs the length one list into `im2`
As for yo... |
error: [Errno 10053] | 17,854,713 | 13 | 2013-07-25T09:55:00Z | 17,854,758 | 12 | 2013-07-25T09:57:03Z | [
"python",
"flask"
] | If I am coding on Flask, then I sometimes get this error:
```
Traceback (most recent call last):
File "C:\Python27\lib\SocketServer.py", line 284, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Python27\lib\SocketServer.py", line 310, in process_request
self.finish_reques... | From the [Windows Sockets Error Codes](http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668%28v=vs.85%29.aspx) list:
> **WSAECONNABORTED** 10053
> Software caused connection abort.
> An established connection was aborted by the software in your host computer, possibly due to a data transmission time-ou... |
Passing and returning numpy arrays to C++ methods via Cython | 17,855,032 | 20 | 2013-07-25T10:10:13Z | 18,176,741 | 13 | 2013-08-11T21:12:48Z | [
"python",
"arrays",
"numpy",
"cython"
] | There are lots of questions about using numpy in cython on this site, a particularly useful one being [Simple wrapping of C code with cython](http://stackoverflow.com/questions/3046305/simple-wrapping-of-c-code-with-cython).
However, the cython/numpy interface api [seems to have changed a bit](http://docs.cython.org/s... | You've basically got it right. First, hopefully optimization shouldn't be a big deal. Ideally, most of the time is spent inside your C++ kernel, not in the cythnon wrapper code.
There are a few stylistic changes you can make that will simplify your code. (1) Reshaping between 1D and 2D arrays is not necessary. When yo... |
Convert string to image in python | 17,856,242 | 5 | 2013-07-25T11:04:33Z | 17,856,617 | 8 | 2013-07-25T11:23:47Z | [
"python",
"python-imaging-library"
] | I started to learn python a week ago and want to write a small programm that converts a email to a image (.png) so that it can be shared on forums without risking to get lots of spam mails.
It seems like the python standard libary doesn't contain a module that can do that but i`ve found out that there's a PIL module f... | 1. use `ImageDraw.text` - but it doesn't do any formating, it just prints string at the given location
```
img = Image.new('RGB', (200, 100))
d = ImageDraw.Draw(img)
d.text((20, 20), 'Hello', fill=(255, 0, 0))
```
to find out the text size:
```
text_width, text_height = d.textsize('Hello')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.