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 evaluate commands in form of strings | 18,241,565 | 2 | 2013-08-14T20:23:18Z | 18,241,624 | 8 | 2013-08-14T20:26:21Z | [
"python",
"functional-programming",
"symbols",
"evaluation"
] | In Python I am trying to figure out how to evaluate commands given as strings in a program. For example, consider the built in math functions `sin`, `cos` and `tan`
Say I am given these functions as a list;
```
li = ['sin', 'cos', 'tan']
```
Now, I want to iterate over each element in the list and apply each functio... | Just use the functions themselves:
```
from math import sin, cos, tan
li = [sin, cos, tan]
```
If you really need to use strings, create a dict:
```
funcs = {'sin': sin, 'cos': cos, 'tan': tan}
func = funcs[string]
func(x)
``` |
Issue with dict() in Python, TypeError:'tuple' object is not callable | 18,241,967 | 2 | 2013-08-14T20:45:33Z | 18,242,005 | 8 | 2013-08-14T20:47:52Z | [
"python",
"function",
"dictionary",
"tuples",
"typeerror"
] | I'm trying to make a function that will take an arbritrary number of dictionary inputs and create a new dictionary with all inputs included. If two keys are the same, the value should be a list with both values in it. I've succeded in doing this-- however, I'm having problems with the dict() function. If I manually per... | A typical example of why keywords should not be used as variable names. Here `dict(newtlist)` is trying to call the `dict()` builtin python, but there is a conflicting local variable `dict`. Rename that variable to fix the issue.
Something like this:
```
def dictcomb(*dct): #changed the local variable dict to dct and... |
Python3 subprocess output | 18,244,126 | 6 | 2013-08-14T23:43:40Z | 18,244,485 | 12 | 2013-08-15T00:27:39Z | [
"python",
"python-3.x",
"subprocess",
"bytestring"
] | I'm wanting to run the Linux word count utility wc to determine the number of lines currently in the /var/log/syslog, so I can detect that it's growing. I've tried various test, and while I get the results back from wc, it includes both the line count as well as the command (e.g., var/log/syslog).
So it's returning:
1... | I suggest that you use `subprocess.getoutput()` as it does exactly what you wantârun a command in a shell and get its [string output](http://docs.python.org/3.1/library/subprocess.html#subprocess.getoutput) (as opposed to [byte string](http://docs.python.org/3.1/library/subprocess.html#subprocess.check_output) output... |
How can I use executemany to instert into mysql a list of dictionaries in python | 18,244,565 | 8 | 2013-08-15T00:35:35Z | 18,245,311 | 8 | 2013-08-15T02:14:52Z | [
"python",
"mysql",
"mysql-python"
] | I'm currently using MySQL and Python to scrape data from the web. Specifically, I am scraping table data and inserting it into my database. My current solution works, but I feel it is extremely inefficient and will most likely lock up my database if I don't rewrite the code. Here is what I currently use (partial code):... | ```
itemBank = []
for row in rows:
itemBank.append((
tempRow2['Item_Name'],
tempRow1['Item_Price'],
tempRow3['Item_In_Stock'],
tempRow4['Item_Max'],
getTimeExtra
)) #append data
q = """ insert ignore into TABLE1 (
Item_Name, Item_Price, Item_In_Stock, Item... |
Python: finding leftmost non-zero in list of lists | 18,245,681 | 2 | 2013-08-15T03:02:07Z | 18,245,758 | 8 | 2013-08-15T03:10:54Z | [
"python",
"python-3.x"
] | say I have this list of list
```
listlist = [[0,0,0,1],[0,0,1,1],[1,0,1,1]]
```
and a empty dict()
```
answer = dict()
```
and say I want to find the leftmost non-zero in each list such that I can save the index of that non-zero number into a dictionary like:
```
for list in listlist: #(this is how the first itera... | If it's only ever `0`s and `1`s just do something like,
```
>>> answer = {i: lst.index(1) for i, lst in enumerate(listlist)}
>>> answer
{0: 3, 1: 2, 2: 0}
```
Also, don't use `list` as a variable name since it will mask `list` built-in. |
Django datetimefield time in template | 18,246,123 | 5 | 2013-08-15T04:01:44Z | 18,246,203 | 14 | 2013-08-15T04:12:21Z | [
"python",
"django",
"django-templates"
] | I have a `DateTimeField` in one of my models
If I display `{{ model.datetime }}` in the template, I see:
```
Aug. 13, 2013, 7:57 p.m.
```
If I display `{{ model.datetime.time }}` in the template , I see:
```
2:57 am
```
I want it to just display `7:57 p.m.` How can I get it to use the correct timezone. I have trie... | Try
```
{{ model.datetime|date:"g:i a" }}
```
If you want a different format, [refer to the documentation here](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date) |
Conditional expressions in Python Dictionary comprehensions | 18,246,827 | 4 | 2013-08-15T05:28:21Z | 18,246,830 | 11 | 2013-08-15T05:28:55Z | [
"python",
"dictionary-comprehension"
] | ```
a = {"hello" : "world", "cat":"bat"}
//Trying to achieve this
//Form a new dictionary only with keys with "hello" and their values
b = {"hello" : "world"}
//This didn't work
b = dict( (key, value) if key == "hello" for (key, value) in a.items())
```
Any suggestions on how to include a conditional expression in ... | Move the `if` at the end:
```
b = dict( (key, value) for (key, value) in a.items() if key == "hello" )
```
You can even use *dict-comprehension* (`dict(...)` is not one, you are just using the `dict` factory over a generator expression):
```
b = { key: value for key, value in a.items() if key == "hello" }
``` |
how to flip a bit at a specific position in an integer in any language | 18,247,126 | 4 | 2013-08-15T05:59:02Z | 18,247,143 | 10 | 2013-08-15T06:01:25Z | [
"java",
"python",
"c"
] | I have an integer `n`, and I want to flip its `k`th bit (from the lowest) in its binary representation. How can I do it?
For example, if I have `n=0b01101` and `k=2`, then the result is `0b01001=9`
Any language is fine. Thank you. | To flip one or more bits, use [binary XOR](http://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation). In your case, the appropriate XOR mask is `1` [shifted](http://stackoverflow.com/questions/141525/absolute-beginners-guide-to-bit-shifting) `k` bits to the left.
In Python:
```
In [58]: 0b01101 ^ (1 << 2)
Out[58]:... |
Print python os.urandom output on terminal | 18,247,971 | 6 | 2013-08-15T07:18:23Z | 18,248,014 | 7 | 2013-08-15T07:22:01Z | [
"python"
] | how can i print the output of `os.urandom(n)` in terminal?
I try to generate a SECRET\_KEY with fabfile and will output the 24 bytes.
Example how i implement both variants in the python shell:
```
>>> import os
>>> out = os.urandom(24)
>>> out
'oS\xf8\xf4\xe2\xc8\xda\xe3\x7f\xc75*\x83\xb1\x06\x8c\x85\xa4\xa7piE\xd6I... | If what you want is hex-encoded string, use [`binascii.a2b_hex`](http://docs.python.org/2/library/binascii.html#binascii.b2a_hex) (or `hexlify`):
```
>>> out = 'oS\xf8\xf4\xe2\xc8\xda\xe3\x7f\xc75*\x83\xb1\x06\x8c\x85\xa4\xa7piE\xd6I'
>>> import binascii
>>> print binascii.hexlify(out)
6f53f8f4e2c8dae37fc7352a83b1068c... |
What can I use to go one line break back in a terminal in Python? | 18,248,142 | 7 | 2013-08-15T07:31:39Z | 18,270,789 | 8 | 2013-08-16T10:04:57Z | [
"python",
"line-breaks"
] | I can go one caracter back using `\b` :
```
>>> print("123#456")
123#456
>>> print("123#\b456")
123456
```
But it doesn't work if a line break is involved :
```
>>> print("123#\n456")
123#
456
>>> print("123#\n\b456")
123#
456
```
Is there a way to go line break back ?
I'm asking this because I have a progress at ... | One possible (a bit hacky) solution is to use '\033[1A' to go back one line. Replace 1 with number of lines to jump back. There are several other escape sequences you can use to manipulate the cursor. Check out the complete list at: <http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html>
```
- Position the Cursor:
\... |
yticklabels only at major ticks matplotlib | 18,248,696 | 4 | 2013-08-15T08:13:33Z | 18,249,552 | 7 | 2013-08-15T09:07:42Z | [
"python",
"matplotlib"
] | I have a problem regarding yticklabels in matplotlib.
I' m trying to make a vertical barplot (plt.barh) and then trying to use ax.set\_yticklabels command.
The problem that I have is that it only puts the labels at the major ticks! The list that I'm passing is of length 18, however it only labels 10 of the bars!!
Hel... | you need to set `yticks` before you set `yticklabels`:
```
from numpy import *
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x=random.uniform(0,5,size=5)
#plot
ax.barh(arange(len(x)),x,1)
#set ticks
T=arange(len(x))+0.5
ax.set_yticks(T)
#set labels
labels=['a','b','c','d','e']
ax.se... |
Python3 - reload() can not be called on __import__ object? | 18,249,459 | 11 | 2013-08-15T09:02:42Z | 18,249,523 | 26 | 2013-08-15T09:06:27Z | [
"python",
"python-3.x",
"module",
"reload",
"python-3.3"
] | Ok so for a number of reasons, I've been using `s = __import__('parse')` for the longest time in Python2, now I sorta need to being my transitions to Python3 for certain projects (mainly due to SSL).
But there's no `reload()` equivilant in Python3 as far as i've spotted.
There's only one option:
```
import parse
pars... | The `reload` built-in function has been moved to `imp` module in Python 3:
```
In [18]: from imp import reload
In [19]: reload?
Reload the module and return it.
The module must have been successfully imported before.
```
As pointed out by @JPaget in comments [`reload()`](https://docs.python.org/3/library/importlib.... |
How do I make NLTK pos_tag words instead of characters? | 18,249,538 | 2 | 2013-08-15T09:07:15Z | 18,249,711 | 7 | 2013-08-15T09:19:10Z | [
"python",
"nltk"
] | I have this code to find nouns and verbs in a sentence.
```
# -*- coding: utf-8 -*-
from nltk.corpus import wordnet as wn
from nltk import pos_tag
import nltk
syno =[]
sentence = '''His father suggested he study to become a parson instead, but Darwin was far more inclined to study natural history.DarwinDar·win (dÃ... | You need to tokenize first:
```
>>> from nltk import pos_tag, word_tokenize
>>> sentence = "Hello my name is Derek. I live in Salt Lake city."
>>> pos_tag(word_tokenize(sentence))
[('Hello', 'NNP'), ('my', 'PRP$'), ('name', 'NN'), ('is', 'VBZ'), ('Derek.', 'NNP'), ('I', 'PRP'), ('live', 'VBP'), ('in', 'IN'), ('Salt', ... |
How to check if a value is in the list in selection from pandas data frame? | 18,250,298 | 3 | 2013-08-15T09:55:32Z | 18,250,457 | 12 | 2013-08-15T10:05:29Z | [
"python",
"select",
"numpy",
"pandas",
"dataframe"
] | Looks ugly:
```
df_cut = df_new[
(
(df_new['l_ext']==31) |
(df_new['l_ext']==22) |
(df_new['l_ext']==30) |
(df_new['l_ext']==25) |
(df_new['l_ext']==64)
)
]
```
Does not work:
```
df_cut = df_new[(df_new['l_ext'] i... | Use [isin](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.isin.html#pandas.Series.isin)
```
df_new[df_new['l_ext'].isin([31, 22, 30, 25, 64])]
``` |
Creating a numpy array of 3D coordinates from three 1D arrays | 18,253,210 | 7 | 2013-08-15T13:03:23Z | 18,256,546 | 8 | 2013-08-15T15:53:26Z | [
"python",
"arrays",
"performance",
"numpy"
] | Suppose I have three arbitrary 1D arrays, for example:
```
x_p = np.array((1.0, 2.0, 3.0, 4.0, 5.0))
y_p = np.array((2.0, 3.0, 4.0))
z_p = np.array((8.0, 9.0))
```
These three arrays represent sampling intervals in a 3D grid, and I want to construct a 1D array of three-dimensional vectors for all intersections, somet... | To use numpy mesh grid on the above example the following will work:
```
np.vstack(np.meshgrid(x_p,y_p,z_p)).reshape(3,-1).T
```
Numpy meshgrid for grids of more then two dimensions require numpy 1.7. To circumvent this and pulling the relevant data from the [source code](http://github.com/numpy/numpy/blob/v1.7.0/num... |
How do I print the content of a .txt file in Python? | 18,256,363 | 4 | 2013-08-15T15:44:19Z | 18,256,401 | 7 | 2013-08-15T15:46:09Z | [
"python",
"ubuntu"
] | I'm very new to programming (obviously) and really advanced computer stuff in general. I've only have basic computer knowledge, so I decided I wanted to learn more. Thus I'm teaching myself (through videos and ebooks) how to program.
Anyways, I'm working on a piece of code that will open a file, print out the contents... | Just do this:
```
>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
... print f.read()
```
This will print the file in the terminal. |
Adding 1 to a set containing True does not work | 18,257,980 | 6 | 2013-08-15T17:15:57Z | 18,258,082 | 7 | 2013-08-15T17:20:58Z | [
"python",
"python-3.x"
] | I have recently started to learn Python and have encountered something a little strange when playing with sets. The following code sample doesn't produce the expected results.
```
a_set = {True,2,3,4}
a_set.add(1)
```
I expected a\_set to have the values `{True, 1, 2, 3, 4}` but instead this code produced `{True, 2, ... | For historical (hysterical?) reasons Python's `bool` type is a subclass of `int`, and `True` is equal to 1 and `False` is equal to 0.
They hash to the same location as well:
```
>>> True == 1
True
>>> hash(True) == hash(1)
True
>>> False == 0
True
>>> hash(False) == hash(0)
True
```
Since both `True` and `1` are con... |
python evaluate functions with parameters given by a dictionary | 18,259,304 | 3 | 2013-08-15T18:32:56Z | 18,259,320 | 8 | 2013-08-15T18:33:52Z | [
"python",
"dictionary",
"functional-programming"
] | With python how can I evaluate a dictionary of functions with their associate parameters. To be more specific, the keys are the functions and the values are a list of paramters.
for example, consider the dictionary:
```
{f1: [a, b, c], f2: [q], f3: [5, c]}
```
How would I iterate over the functions to compute:
```
... | ```
for func, args in the_dictionary.items():
func(*args)
``` |
Embed an interactive 3D plot in PySide | 18,259,350 | 6 | 2013-08-15T18:35:48Z | 18,278,457 | 7 | 2013-08-16T16:53:59Z | [
"python",
"matplotlib",
"pyside"
] | What is the best way to embed an interactive 3D plot in a PySide GUI? I have looked at some examples on here of 2D plots embedded in a PySide GUI:
[Getting PySide to Work With Matplotlib](http://stackoverflow.com/questions/6723527/getting-pyside-to-work-with-matplotlib)
[Matplotlib Interactive Graph Embedded In PyQt... | You are not using `FigureCanvas` right:
```
class Mpwidget(FigureCanvas):
def __init__(self, parent=None):
self.figure = Figure(facecolor=(0, 0, 0))
super(Mpwidget, self).__init__(self.figure) # this object _is_ your canvas
self.setParent(parent)
# plot random 3D data
self.... |
Numpy loading csv TOO slow compared to Matlab | 18,259,393 | 19 | 2013-08-15T18:38:39Z | 18,260,092 | 26 | 2013-08-15T19:20:47Z | [
"python",
"matlab",
"csv",
"numpy"
] | I posted this question because I was wondering whether I did something terribly wrong to get this result.
I have a medium-size csv file and I tried to use numpy to load it. For illustration, I made the file using python:
```
import timeit
import numpy as np
my_data = np.random.rand(1500000, 3)*10
np.savetxt('./test.... | Yeah, reading `csv` files into `numpy` is pretty slow. There's a lot of pure Python along the code path. These days, even when I'm using pure `numpy` I still use `pandas` for IO:
```
>>> import numpy as np, pandas as pd
>>> %time d = np.genfromtxt("./test.csv", delimiter=",")
CPU times: user 14.5 s, sys: 396 ms, total... |
Deploy flask application on 1&1 shared hosting (with CGI) | 18,259,435 | 4 | 2013-08-15T18:41:23Z | 24,848,407 | 10 | 2014-07-20T07:40:27Z | [
"python",
"cgi",
"flask"
] | I've written a web application for my sports club with the flask web framework. I did everything on my local machine with the build-in test server.
Know they told me to deploy it on an 1&1 shared hosting web space. They have python support but it seems like they only allow CGI to run python scripts.
I tried this tuto... | I'm writing in to provide an answer after nearly a year because the given answer is incomplete and because the suggestion to leave off the /$1 is wrong. Other stackoverflow threads that can be reached by an Internet search using the string "deploy flask on cgi" have also ended without satisfactory solutions.
To begin,... |
Can't override __init__ of class from Cython extension | 18,260,095 | 6 | 2013-08-15T19:20:53Z | 18,260,629 | 16 | 2013-08-15T19:51:45Z | [
"python",
"inheritance",
"cython"
] | I am trying to subclass [pysam's `Tabixfile`](http://www.cgat.org/~andreas/documentation/pysam/api.html#pysam.Tabixfile) class and add additional attributes on instantiation.
```
class MyTabixfile(pysam.Tabixfile):
def __init__(self, filename, mode='r', *args, **kwargs):
super().__init__(filename, mode=mo... | The documentation is a little confusing here, in that it assumes that you're familiar with using `__new__` and `__init__`.
The `__cinit__` method is roughly equivalent to a `__new__` method in Python.\*
Like `__new__`, `__cinit__` is *not* called by your `super().__init__`; it's called before Python even gets to your... |
Transposing a 3D list in Python | 18,260,103 | 5 | 2013-08-15T19:21:42Z | 18,260,188 | 12 | 2013-08-15T19:26:18Z | [
"python"
] | I have to transpose a 3d list the following way:
Input:
```
matrix7 = [[['A ', 'E ', 'C#'], ['B ', 'E ', 'C#'], ['C ', 'E ', 'C#']],
[[' ', 'F#', 'D '], [' ', 'F#', 'D '], [' ', 'F#', 'D ']],
[[' ', 'E ', 'B '], [' ', 'E ', 'B '], [' ', 'E ', 'B ']],
[[' ', 'E ', 'C#'], [' ', 'E ', 'C#'], [' ', 'E ', 'C#'... | I think this is what you want:
```
numpy.transpose(matrix7, axes=(1, 0, 2)).tolist() # The 'axes' attribute tells transpose to swaps axes 0 and 1, leaving the last one alone.
```
**OUTPUT:**
```
[[['A ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '],... |
python equivalent of quote in lisp | 18,260,277 | 4 | 2013-08-15T19:31:28Z | 18,260,305 | 9 | 2013-08-15T19:32:53Z | [
"python",
"functional-programming",
"lisp",
"quote"
] | In python what is the equivalent of the quote operator? I am finding the need to delay evaluation. For example, suppose in the following lisp psuedocode I have:
```
a = '(func, 'g)
g = something
(eval a)
```
What I am doing is deferring evaluation of `g` till a later time. This is necessary because I want to define `... | ```
a = lambda: func(g)
g = something
a()
```
This isn't quite the most literal translation - the most literal translation would use a string and `eval` - but it's probably the best fit. Quoting probably isn't what you wanted in Lisp anyway; you probably wanted to `delay` something or create a `lambda`. Note that `fun... |
if i!=0 in list comprehension gives syntax error | 18,260,700 | 4 | 2013-08-15T19:55:11Z | 18,260,709 | 11 | 2013-08-15T19:55:44Z | [
"python",
"syntax-error",
"list-comprehension"
] | This question is very much like:
[Python: if/else in list comprehension?](http://stackoverflow.com/questions/4260280/python-if-else-in-list-comprehension)
and
[Simple Syntax Error in Python if else dict comprehension](http://stackoverflow.com/questions/17664841/simple-syntax-error-in-python-if-else-dict-comprehension) ... | Move the `if` to the end. Refer to [The Python Docs entry on List Comprehensions](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions).
```
>>> [i for i in range(2) if i!=0] # Or [i for i in range(2) if i]
[1]
```
If you were looking for a [conditional expression](http://docs.python.org/2/refere... |
Cannot load pickled object | 18,261,898 | 5 | 2013-08-15T21:09:11Z | 18,261,955 | 11 | 2013-08-15T21:13:07Z | [
"python",
"python-3.x",
"pickle"
] | The problem I am having is when I try to load the **[pickled](http://docs.python.org/3/library/pickle.html)** object. I have tried using both `pickle.loads` and `pickle.load` Here are the results:
pickle.loads - `TypeError: 'str' does not support the buffer interface`
pickle.load - `TypeError: file must have 'read' a... | You need to either *read* the file first (as binary `bytes`) and use `pickle.loads()`, or pass an open file object to the `pickle.load()` command. The latter is preferable:
```
with open('out/cache/' +hashed_url, 'rb') as pickle_file:
content = pickle.load(pickle_file)
```
Neither method supports loading a pickle... |
Python Open Every File in a Folder | 18,262,293 | 40 | 2013-08-15T21:36:23Z | 18,262,324 | 102 | 2013-08-15T21:38:38Z | [
"python",
"file",
"pipe",
"stdout",
"stdin"
] | I have a python script parse.py, which in the script open a file, say file1, and then do something maybe print out the total number of characters.
```
filename = 'file1'
f = open(filename, 'r')
content = f.read()
print filename, len(content)
```
Right now, I am using stdout to direct the result to my output file - ou... | You can list all files in the current directory using:
```
import os
for filename in os.listdir(os.getcwd()):
# do your stuff
```
Or you can list only some files, depending on the file pattern using the `glob` module:
```
import glob
for filename in glob.glob('*.txt'):
# do your stuff
```
It doesn't have to b... |
Python Open Every File in a Folder | 18,262,293 | 40 | 2013-08-15T21:36:23Z | 18,274,231 | 13 | 2013-08-16T13:15:58Z | [
"python",
"file",
"pipe",
"stdout",
"stdin"
] | I have a python script parse.py, which in the script open a file, say file1, and then do something maybe print out the total number of characters.
```
filename = 'file1'
f = open(filename, 'r')
content = f.read()
print filename, len(content)
```
Right now, I am using stdout to direct the result to my output file - ou... | you should try using os.walk
```
yourpath = 'path'
import os
for root, dirs, files in os.walk(yourpath, topdown=False):
for name in files:
print(os.path.join(root, name))
stuff
for name in dirs:
print(os.path.join(root, name))
stuff
``` |
Quick sort with Python | 18,262,306 | 30 | 2013-08-15T21:37:08Z | 18,262,384 | 76 | 2013-08-15T21:42:31Z | [
"python",
"algorithm",
"sorting",
"quicksort"
] | I am totally new to python and I am trying to implement quick sort in it.
Could someone please help me complete my code?
I do not know how to concatenate the three arrays and printing them.
```
def sort(array=[12,4,5,6,7,3,1,15]):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = a... | ```
def sort(array=[12,4,5,6,7,3,1,15]):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = array[0]
for x in array:
if x < pivot:
less.append(x)
if x == pivot:
equal.append(x)
if x > pivot:
gr... |
Quick sort with Python | 18,262,306 | 30 | 2013-08-15T21:37:08Z | 20,258,416 | 47 | 2013-11-28T05:32:06Z | [
"python",
"algorithm",
"sorting",
"quicksort"
] | I am totally new to python and I am trying to implement quick sort in it.
Could someone please help me complete my code?
I do not know how to concatenate the three arrays and printing them.
```
def sort(array=[12,4,5,6,7,3,1,15]):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = a... | There is another concise and beautiful version
```
def qsort(arr):
if len(arr) <= 1:
return arr
else:
return qsort([x for x in arr[1:] if x<arr[0]]) + [arr[0]] + qsort([x for x in arr[1:] if x>=arr[0]])
``` |
Quick sort with Python | 18,262,306 | 30 | 2013-08-15T21:37:08Z | 25,114,037 | 11 | 2014-08-04T07:57:31Z | [
"python",
"algorithm",
"sorting",
"quicksort"
] | I am totally new to python and I am trying to implement quick sort in it.
Could someone please help me complete my code?
I do not know how to concatenate the three arrays and printing them.
```
def sort(array=[12,4,5,6,7,3,1,15]):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = a... | There are many answers to this already, but I think this approach is the most clean implementation:
```
def quicksort(arr):
""" Quicksort a list
:type arr: list
:param arr: List to sort
:returns: list -- Sorted list
"""
if not arr:
return []
pivots = [x for x in arr if x == arr[0]... |
Quick sort with Python | 18,262,306 | 30 | 2013-08-15T21:37:08Z | 27,461,889 | 32 | 2014-12-13T17:53:52Z | [
"python",
"algorithm",
"sorting",
"quicksort"
] | I am totally new to python and I am trying to implement quick sort in it.
Could someone please help me complete my code?
I do not know how to concatenate the three arrays and printing them.
```
def sort(array=[12,4,5,6,7,3,1,15]):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = a... | Quick sort without additional memory (in place)
Usage:
```
array = [97, 200, 100, 101, 211, 107]
quicksort(array)
# array -> [97, 100, 101, 107, 200, 211]
```
```
def partition(array, begin, end):
pivot = begin
for i in xrange(begin+1, end+1):
if array[i] <= array[begin]:
pivot += 1
... |
Quick sort with Python | 18,262,306 | 30 | 2013-08-15T21:37:08Z | 31,102,672 | 8 | 2015-06-28T17:31:19Z | [
"python",
"algorithm",
"sorting",
"quicksort"
] | I am totally new to python and I am trying to implement quick sort in it.
Could someone please help me complete my code?
I do not know how to concatenate the three arrays and printing them.
```
def sort(array=[12,4,5,6,7,3,1,15]):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = a... | If I search "python quicksort implementation" in Google, this question is the first result to pop up. I understand that the initial question was to "help correct the code" but there already are many answers that disregard that request: the currently [second most voted one](http://stackoverflow.com/a/20258416/1269892), ... |
python - should I use static methods or top-level functions | 18,262,595 | 20 | 2013-08-15T21:59:17Z | 18,262,662 | 26 | 2013-08-15T22:04:00Z | [
"python",
"design-patterns",
"static"
] | I come from a Java background and I'm new to python. I have a couple scripts that share some helper functions unique to the application related to reading and writing files. Some functions associated with reading, some with writing. While searching for the correct approach, I saw this: [Static methods in Python?](http:... | In Java there's the (IMHO wrong) idea to use classes everywhere, even just group together static functions that don't share any state (and thus such classes will never be instantiated).
Python here begs to differ; if you have functions that don't have some shared state1 (and thus in Java would typically be `static` fu... |
python - should I use static methods or top-level functions | 18,262,595 | 20 | 2013-08-15T21:59:17Z | 18,262,744 | 8 | 2013-08-15T22:11:20Z | [
"python",
"design-patterns",
"static"
] | I come from a Java background and I'm new to python. I have a couple scripts that share some helper functions unique to the application related to reading and writing files. Some functions associated with reading, some with writing. While searching for the correct approach, I saw this: [Static methods in Python?](http:... | From the Zen of Python (`import this`) :
```
Namespaces are one honking great idea -- let's do more of those!
```
One of the main reasons to create static methods in a language like Java is to ensure that those methods don't wind up polluting the global namespace. (Although Java enforces its own namespace conventions... |
Flask and Werkzeug: Testing a post request with custom headers | 18,263,844 | 11 | 2013-08-16T00:02:13Z | 18,266,224 | 16 | 2013-08-16T05:11:13Z | [
"python",
"flask",
"werkzeug"
] | I'm currently testing my app with suggestions from <http://flask.pocoo.org/docs/testing/>, but I would like to add a header to a post request.
My request is currently:
```
self.app.post('/v0/scenes/test/foo', data=dict(image=(StringIO('fake image'), 'image.png')))
```
but I would like to add a content-md5 to the req... | `open` also take `*args` and `**kwargs` which used as `EnvironBuilder` arguments. So you can add just `headers` argument to your first post request:
```
with self.app.test_client() as client:
client.post('/v0/scenes/test/foo',
data=dict(image=(StringIO('fake image'), 'image.png')),
... |
self.instance in Django ModelForm | 18,265,023 | 6 | 2013-08-16T02:42:54Z | 18,265,184 | 7 | 2013-08-16T03:03:46Z | [
"python",
"django"
] | What does self.instance in Django ModelForm constructor mean and where can I find a documentation about it?
```
class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
if self.instance:
...
``` | You can find the documentation on django's website.
<https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method>
Just search the page for every reference to "instance", and you should find what you need.
```
# Load up an instance
my_poll = Poll.objects.get(id=1)
# Declare a ModelForm... |
Python - Create list with numbers between 2 values? | 18,265,935 | 80 | 2013-08-16T04:43:05Z | 18,265,979 | 115 | 2013-08-16T04:47:21Z | [
"python",
"list"
] | How would I create a list with values between 2 values I put in?
For example, following list is generated for values between 11 and 16:
```
list = [11, 12, 13, 14, 15, 16]
``` | Use [`range`](http://docs.python.org/2.7/library/functions.html#range). In Python 2.x it returns a list so all you need is,
```
>>> range(11, 17)
[11, 12, 13, 14, 15, 16]
```
In Python 3.x it's a iterator so you need to convert it to a list,
```
>>> list(range(11, 17))
[11, 12, 13, 14, 15, 16]
```
**Note**: Second ... |
Multiple imshow-subplots, each with colorbar | 18,266,642 | 14 | 2013-08-16T05:51:50Z | 18,278,607 | 27 | 2013-08-16T17:02:57Z | [
"python",
"matplotlib"
] | I want to have a figure consisting of, let's say, four subplots. Two of them are usual line-plots, two of them imshow-images.
I can format the imshow-images to proper plots itself, because every single one of them needs its own colorbar, a modified axis and the other axis removed.
This, however, seems to be absolutely... | You can make use of matplotlibs object oriented interface rather than the state-machine interace in order to get better control over each axes. Also, to get control over the height/width of the colorbar you can make use of the [AxesGrid](http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html) toolkit of matpl... |
ImportError: No module named apiclient.discovery | 18,267,749 | 42 | 2013-08-16T07:10:57Z | 23,521,799 | 80 | 2014-05-07T15:18:26Z | [
"python",
"google-app-engine",
"google-api-python-client"
] | I got this error in **Google App Engine's Python** have used Google Translate API,
But I don't know how to fix,
```
<module>
from apiclient.discovery import build
ImportError: No module named apiclient.discovery
```
I'll try to **set environment which indicates to Google App Engine SDK**,
And upload to Google Apps En... | You should be able to get these dependencies with this simple install:
```
sudo pip install --upgrade google-api-python-client
```
This is described on the [quick start page for python](https://developers.google.com/drive/web/quickstart/quickstart-python) |
ImportError: No module named apiclient.discovery | 18,267,749 | 42 | 2013-08-16T07:10:57Z | 30,811,628 | 23 | 2015-06-12T20:24:49Z | [
"python",
"google-app-engine",
"google-api-python-client"
] | I got this error in **Google App Engine's Python** have used Google Translate API,
But I don't know how to fix,
```
<module>
from apiclient.discovery import build
ImportError: No module named apiclient.discovery
```
I'll try to **set environment which indicates to Google App Engine SDK**,
And upload to Google Apps En... | `apiclient` was the original name of the library.
At some point, it was switched over to be `googleapiclient`.
If your code is running on Google App Engine, both should work.
If you are running the application yourself, with the [google-api-python-client](https://github.com/google/google-api-python-client) installe... |
Python, functional programming, mapping to a higher level | 18,268,832 | 5 | 2013-08-16T08:16:28Z | 18,268,865 | 7 | 2013-08-16T08:19:03Z | [
"python",
"map",
"functional-programming"
] | Does anybody know how to map in Python easily a function to a higher level in a nested list, i.e. the equivalent to `Map[f, expr, levelspec]` in Mathematica. | You can trivially roll your own
```
def map_level(f, item, level):
if level == 0:
return f(item)
else:
return [map_level(f, i, level - 1) for i in item]
```
```
>>> double = lambda x: x * 2
>>> data = [[1, 2, 3], [4, 5, 6]]
>>> map_level(double, data, 0)
[[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5... |
Not enough arguments? | 18,269,390 | 4 | 2013-08-16T08:50:28Z | 18,269,426 | 12 | 2013-08-16T08:53:18Z | [
"python"
] | ```
print "%r"
```
vs
```
print "%r %r"%("hello")
```
I want to compare above two lines of code in python.The latter statement gives an error with not enough arguements to print but in first case we have no arguements but still it works.Can anybody explain this to someone who is new to programming.
Any help would be... | The `%` *inside* the string only comes into play once Python has established you're using the `%` printf-like operator *outside* the string.
In the first case, you're not, so it doesn't complain. All you're doing in that case is printing a string.
The second case, you *are* using the `%` operator so it complains that... |
Options for building a python web based application | 18,270,558 | 5 | 2013-08-16T09:51:53Z | 18,271,069 | 11 | 2013-08-16T10:21:18Z | [
"python",
"web"
] | I am building a simple Python web application and I want it to run stand alone like SABNZBD or Couch Patato. These applications are self contained web applications. What do these products use to serve up the web interface?
The application im building will do a lookup of images albums (folders) and when selected, prese... | why don't you use **flask** in python ?
take a look at this
<http://flask.pocoo.org/>
```
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
``` |
Options for building a python web based application | 18,270,558 | 5 | 2013-08-16T09:51:53Z | 18,271,791 | 10 | 2013-08-16T11:01:31Z | [
"python",
"web"
] | I am building a simple Python web application and I want it to run stand alone like SABNZBD or Couch Patato. These applications are self contained web applications. What do these products use to serve up the web interface?
The application im building will do a lookup of images albums (folders) and when selected, prese... | There are many options and they're all very easy to pick up in a couple of days. Which one you choose is completely up to you.
Here are a few worth mentioning:
**[Tornado](http://www.tornadoweb.org/): a Python web framework and asynchronous networking library, originally developed at FriendFeed.**
```
import tornado... |
Do I need to use virtualenv with Vagrant? | 18,270,859 | 16 | 2013-08-16T10:09:32Z | 18,271,644 | 10 | 2013-08-16T10:53:51Z | [
"python",
"django",
"virtual-machine",
"virtualenv",
"vagrant"
] | I was used VirtualBox manual setups with virtualenvs inside them to run Django projects on my local machine. Recently I discovered Vagrant and decided to switch to it, because it seems very easy and useful.
But I can not figure - do I need still use virtualenv Vagrant VM, is it encouraged practice or forbidden? | If you run one vagrant VM per project, then there is no direct reason to use virtualenv.
If other contributors do not use vagrant, but do use virtualenv, then you might want to use it and support it to make their lives easier. |
Do I need to use virtualenv with Vagrant? | 18,270,859 | 16 | 2013-08-16T10:09:32Z | 18,273,476 | 24 | 2013-08-16T12:36:21Z | [
"python",
"django",
"virtual-machine",
"virtualenv",
"vagrant"
] | I was used VirtualBox manual setups with virtualenvs inside them to run Django projects on my local machine. Recently I discovered Vagrant and decided to switch to it, because it seems very easy and useful.
But I can not figure - do I need still use virtualenv Vagrant VM, is it encouraged practice or forbidden? | As [Devin stated](http://stackoverflow.com/a/18271644/41747), it is not necessary to use `virtualenv` when you deploy to a vagrant machine as long as you are the sole user of the machine. However, I would still enable the use of a `virtualenv`, *setup.py*, etc. even if you do not use it for development or deployment.
... |
Easy way to convert a unicode list to a list containing python strings? | 18,272,066 | 15 | 2013-08-16T11:15:17Z | 18,272,106 | 13 | 2013-08-16T11:17:21Z | [
"python",
"python-2.7",
"unicode"
] | Template of the list is:
```
EmployeeList = [u'<EmpId>', u'<Name>', u'<Doj>', u'<Salary>']
```
I would like to convert from this
```
EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
```
to this:
```
EmployeeList = ['1001', 'Karick', '14-12-2020', '1$']
```
After conversion, I am actually checking if "... | `[str(x) for x in EmployeeList]` would do a conversion, but it would fail if the unicode string characters do not lie in the ascii range.
```
>>> EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
['1001', 'Karick', '14-12-2020', '1$']
>>> EmployeeList = [u'1001', u'à¤à¤°à¤... |
Easy way to convert a unicode list to a list containing python strings? | 18,272,066 | 15 | 2013-08-16T11:15:17Z | 18,272,133 | 33 | 2013-08-16T11:18:54Z | [
"python",
"python-2.7",
"unicode"
] | Template of the list is:
```
EmployeeList = [u'<EmpId>', u'<Name>', u'<Doj>', u'<Salary>']
```
I would like to convert from this
```
EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
```
to this:
```
EmployeeList = ['1001', 'Karick', '14-12-2020', '1$']
```
After conversion, I am actually checking if "... | Encode each value in the list to a string:
```
[x.encode('UTF8') for x in EmployeeList]
```
You need to pick a valid encoding; don't use `str()` as that'll use the system default (for Python 2 that's ASCII) which will not encode all possible codepoints in a Unicode value.
UTF-8 is capable of encoding all of the Unic... |
Access multiple elements of list knowing their index | 18,272,160 | 60 | 2013-08-16T11:20:46Z | 18,272,245 | 20 | 2013-08-16T11:24:58Z | [
"python",
"list",
"indexing",
"elements"
] | I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. What I did is:
```
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
```
Is there any better way to do it? someth... | Alternatives:
```
>>> map(a.__getitem__, b)
[1, 5, 5]
```
---
```
>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)
``` |
Access multiple elements of list knowing their index | 18,272,160 | 60 | 2013-08-16T11:20:46Z | 18,272,249 | 51 | 2013-08-16T11:25:16Z | [
"python",
"list",
"indexing",
"elements"
] | I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. What I did is:
```
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
```
Is there any better way to do it? someth... | You can use [`operator.itemgetter`](http://docs.python.org/2/library/operator.html#operator.itemgetter):
```
>>> from operator import itemgetter
>>> a = [-2, 1, 5, 3, 8, 5, 6]
>>> b = [1, 2, 5]
>>> print itemgetter(*b)(a)
(1, 5, 5)
```
Or you can use [numpy](http://www.numpy.org/):
```
>>> import numpy as np
>>> a ... |
Django make_password too slow for creating large list of users programatically | 18,273,110 | 5 | 2013-08-16T12:13:48Z | 18,273,177 | 11 | 2013-08-16T12:17:58Z | [
"python",
"django",
"django-models"
] | I need to create hundreds (possibly thousands) of users programatically in Django. I am using something like:
```
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
for username, email, pwd in big_user_list:
m = User(username=username, email=email, password=make_passw... | You could use the `django.contrib.auth.hashers.MD5PasswordHasher` for an initial password. As per [Django docs on how Django stores passwords](https://docs.djangoproject.com/en/1.6/topics/auth/passwords/),
> **By default, Django uses the PBKDF2 algorithm with a SHA256 hash**, a
> password stretching mechanism recommen... |
Assigning identical array indices at once in Python/Numpy | 18,273,634 | 6 | 2013-08-16T12:44:05Z | 18,274,593 | 7 | 2013-08-16T13:33:20Z | [
"python",
"arrays",
"numpy",
"indices"
] | I want to find a fast way (without for loop) in Python to assign reoccuring indices of an array.
This is the desired result using a for loop:
```
import numpy as np
a=np.arange(9, dtype=np.float64).reshape((3,3))
# The array indices: [2,3,4] are identical.
Px = np.uint64(np.array([0,1,1,1,2]))
Py = np.uint64(np.array(... | Yes, it can be done, but it is a little tricky:
```
# convert yourmulti-dim indices to flat indices
flat_idx = np.ravel_multi_index((Px, Py), dims=a.shape)
# extract the unique indices and their position
unique_idx, idx_idx = np.unique(flat_idx, return_inverse=True)
# Aggregate the repeated indices
deltas = np.bincou... |
How to pass django rest framework response to html? | 18,273,966 | 7 | 2013-08-16T13:01:18Z | 20,668,896 | 21 | 2013-12-18T21:34:57Z | [
"python",
"django",
"django-rest-framework"
] | How to pass django restframework response for any request to html.
Example: A list which contains objects, and html be articles.html.
I tried by using rest framework Response :
```
data= {'articles': Article.objects.all() }
return Response(data, template_name='articles.html')
```
I am getting this error :
```
""" A... | If it's a function based view, you made need to use an @api\_view decorator to display properly. I've seen this particular error happen for this exact reason (missing API View declaration in function based views).
```
from rest_framework.decorators import api_view
# ....
@api_view(['GET', 'POST', ])
def articles(requ... |
Closure in python? | 18,274,051 | 4 | 2013-08-16T13:06:32Z | 18,274,104 | 13 | 2013-08-16T13:09:51Z | [
"python",
"closures",
"python-2.x"
] | When I run this code, I get this result:
```
15
15
```
I expect the output should be
```
15
17
```
but it is not. The question is: why?
```
def make_adder_and_setter(x):
def setter(n):
x = n
return (lambda y: x + y, setter)
myadder, mysetter = make_adder_and_setter(5)
print myadder(10)
mysetter(7... | You are setting a **local** variable `x` in the `setter()` function. Assignment to a name in a function marks it as a local, unless you specifically tell the Python compiler otherwise.
In Python 3, you can explicitly mark `x` as non-local using the `nonlocal` keyword:
```
def make_adder_and_setter(x):
def setter(... |
Closure in python? | 18,274,051 | 4 | 2013-08-16T13:06:32Z | 18,274,153 | 8 | 2013-08-16T13:11:57Z | [
"python",
"closures",
"python-2.x"
] | When I run this code, I get this result:
```
15
15
```
I expect the output should be
```
15
17
```
but it is not. The question is: why?
```
def make_adder_and_setter(x):
def setter(n):
x = n
return (lambda y: x + y, setter)
myadder, mysetter = make_adder_and_setter(5)
print myadder(10)
mysetter(7... | Python 2.x has a syntax limitation that doesn't allow to capture a variable in read/write.
The reason is that if a variable is assigned in a function there are only two possibilities:
1. the variable is a global and has been declared so with `global x`
2. the variable is a local of the function
more specifically it'... |
What does 'is' operator do in Python? | 18,275,616 | 6 | 2013-08-16T14:25:18Z | 18,275,645 | 10 | 2013-08-16T14:26:28Z | [
"python",
"operators"
] | I was (maybe wrongfully) thinking that `is` operator is doing id() comparison.
```
>>> x = 10
>>> y = 10
>>> id(x)
1815480092
>>> id(y)
1815480092
>>> x is y
True
```
However, with `val is not None`, it seems like that it's not that simple.
```
>>> id(not None)
2001680
>>> id(None)
2053536
>>> val = 10
>>> id(val)
1... | You missed that `is not` is an operator *too*.
Without `is`, the regular `not` operator returns a boolean:
```
>>> not None
True
```
`not None` is thus the inverse boolean 'value' of `None`. In a boolean context `None` is false:
```
>>> bool(None)
False
```
so `not None` is boolean `True`.
Both `None` and `True` ... |
Cannot convert array to floats python | 18,275,720 | 3 | 2013-08-16T14:30:30Z | 18,276,639 | 9 | 2013-08-16T15:12:16Z | [
"python",
"arrays",
"csv",
"numpy",
"floating-point"
] | I'm having a problem that seems like the answer would be easily explained.
I'm struggling to convert my array elements to floats (so that I can multiply, add on them etc)
```
import csv
import os
import glob
import numpy as np
def get_data(filename):
with open(filename, 'r') as f:
reader = csv.reader(f) ... | Your script is not the same as the code you've posted... As the traceback of your error shows, in line 20 you are calling `np.ndarray`. That's the [numpy array object](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html), not the `np.array` [factory function](http://docs.scipy.org/doc/numpy/reference... |
Python open file unicode error | 18,276,283 | 4 | 2013-08-16T14:56:39Z | 18,677,162 | 8 | 2013-09-07T19:38:22Z | [
"python"
] | I'm learning how to open a file in Python, but when I type the path to the file I want to open, a window pops up, saying "(unicode error) 'unicodeescape codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape". It highlights the first of my parentheses. Here's the code:
```
with open ("C:\Users\Rajrishi\... | One obvious problem is that you're using a normal string, not a raw string. In
```
open ("C:\Users\Rajrishi\Documents\MyJava\text.txt")
^^
```
the `\t` is interpreted as a tab character, not a literal backslash, followed by `t`.
Use one of the following:
```
open("C:\\Users... |
Python: Find newest file with .MP3 extension in directory | 18,279,063 | 42 | 2013-08-16T17:35:19Z | 18,279,182 | 64 | 2013-08-16T17:42:59Z | [
"python",
"file-io"
] | I am trying to find the most recently modified (From here on out 'newest') file of a specific type in Python. I can currently get the newest, but it doesn't matter what type. I would like to only get the newest MP3 file.
Currently I have:
```
import os
newest = max(os.listdir('.'), key = os.path.getctime)
print newe... | Use [glob.glob](http://docs.python.org/2/library/glob#glob.glob):
```
import os
import glob
newest = max(glob.iglob('*.[Mm][Pp]3'), key=os.path.getctime)
``` |
Two sums from one list | 18,279,069 | 3 | 2013-08-16T17:35:37Z | 18,279,111 | 7 | 2013-08-16T17:38:21Z | [
"python",
"list"
] | I'd like to get the sums for two different values in a list. For example:
```
sample = [(1,3), (4,5), (8,2)]
```
I'd like the output to be
```
13, 10
```
I could do it in a couple of different ways. Here's how I have it currently:
```
t1 = 0
t2 = 0
for item1, item2 in sample:
t1 += item1
t2 += item2
```
W... | You can try this:
```
from itertools import izip
sample = [(1,3), (4,5), (8,2)]
t1, t2 = map(sum, izip(*sample))
```
You can also use a list comprehension instead of `map`.
```
from itertools import izip
sample = [(1,3), (4,5), (8,2)]
t1, t2 = [sum(t) for t in izip(*sample)]
```
And you can deal with more than two ... |
XLWT multiple styles | 18,279,785 | 7 | 2013-08-16T18:21:29Z | 18,279,979 | 12 | 2013-08-16T18:34:11Z | [
"python",
"excel",
"xlwt"
] | This has been bogging my mind with my current project. I'm trying to write styles into an excel sheet using XLWT, see below:
```
sheet.write(rowi,coli,value,stylesheet.bold,stylesheet.bordered)
```
I'm running into this error:
> TypeError: write() takes at most 5 arguments (6 given)
Any idea how to get around this ... | You should pass only row number, col number, value and style (`XFStyle` class instance) to the `write` method, for example:
```
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Test')
style = xlwt.XFStyle()
# font
font = xlwt.Font()
font.bold = True
style.font = font
# borders
borders = xlwt.... |
Performing POST on a URL string in Django | 18,279,865 | 4 | 2013-08-16T18:26:29Z | 18,321,066 | 7 | 2013-08-19T18:56:53Z | [
"python",
"django",
"post",
"linkedin"
] | I'm using the LinkedIn Authentication at: <http://developer.linkedin.com/documents/authentication> and I need to make a post. I'm familiar with making a GET request for example as:
```
client = oauth.Client(consumer, access_token)
resp,content = client.request("http://api.linkedin.com/v1/people/~?format=json", "GET", ... | Take a look at [requests](http://docs.python-requests.org/en/latest/) (install with `pip install requests`), you can make the POST request easily with just some lines of code:
```
import requests
accesscode = request.GET.get('code')
redirect_uri = 'http://www.example.com'
url = 'https://www.linkedin.com/uas/oauth2/ac... |
ImportError: matplotlib requires dateutil | 18,280,436 | 49 | 2013-08-16T19:07:50Z | 18,280,786 | 65 | 2013-08-16T19:31:39Z | [
"python",
"matplotlib",
"python-dateutil"
] | I have successfully installed matplotlib with python 2.6 on x64 Windows7. When I try to import matplotlib, it shows the following error. I have also installed numpy following this link: [Installing Numpy on 64bit Windows 7 with Python 2.7.3](http://stackoverflow.com/questions/11200137/installing-numpy-on-64bit-windows-... | Here's a list of the programs you can install on windows:
<http://www.lfd.uci.edu/~gohlke/pythonlibs/>
And you'll need the following dependencies:
Requires numpy, dateutil, pytz, pyparsing, six |
ImportError: matplotlib requires dateutil | 18,280,436 | 49 | 2013-08-16T19:07:50Z | 25,770,368 | 45 | 2014-09-10T16:16:41Z | [
"python",
"matplotlib",
"python-dateutil"
] | I have successfully installed matplotlib with python 2.6 on x64 Windows7. When I try to import matplotlib, it shows the following error. I have also installed numpy following this link: [Installing Numpy on 64bit Windows 7 with Python 2.7.3](http://stackoverflow.com/questions/11200137/installing-numpy-on-64bit-windows-... | You're probably looking for:
```
pip install python-dateutil
``` |
Flask handling a PDF as its own page | 18,281,433 | 4 | 2013-08-16T20:12:42Z | 20,732,393 | 14 | 2013-12-22T18:04:22Z | [
"python",
"pdf",
"web",
"flask"
] | For my personal website, I want to have a separate page just for my résumé, which is a PDF. I've tried multiple ways, but I can't figure out how to get flask to handle a PDF.
Thanks. Let me know if I need to better explain what I am trying to do. | A note for anyone that came to this question because they're trying to serve PDF files from a database with Flask. Embedding a PDF when the file is stored on a database isn't as simple as when it's in the static folder. You have to use the `make_response` function and give it the appropriate headers so the browser know... |
Write a unicode character to a file in a binary way | 18,281,642 | 2 | 2013-08-16T20:28:12Z | 18,281,702 | 7 | 2013-08-16T20:32:42Z | [
"python",
"unicode"
] | I have the following code to write an ASCII "@" character to a file in a binary fashion:
```
fin=open('a.bin','wb')
fin.write('\x40')
fin.close()
```
It turns out the a "@" character has been written to "a.bin", which has a length of 1-byte.
However, when I tried to write a unicode character instead:
```
fin=open('... | You are confusing Unicode with encodings. An encoding is a standard that represents text as within the confines of individual values in the range of 0-255 (bytes), while Unicode is a standard that describes codepoints representing textual glyphs. The two are related but *not the same thing*.
The Unicode standard inclu... |
TDD with python book, functional test doesnt find assertRegex | 18,281,731 | 6 | 2013-08-16T20:34:47Z | 18,281,793 | 13 | 2013-08-16T20:39:10Z | [
"python",
"django"
] | Following the test driven development with python book I got stuck
I have tried several different imports but still nothing.. anyone?
Error
```
$python manage.py test functional_tests
ERROR: test_can_start_a_list_and_retrieve_it_later (functional_tests.tests.NewVisitorTest)
-------------------------------------------... | I'm assuming you are on Python 2 - then use [`assertRegexpMatches`](http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRegexpMatches) instead of `assertRegex`.
[`assertRegex`](http://docs.python.org/3.2/library/unittest.html#unittest.TestCase.assertRegex) was introduced in Python 3:
> Changed in v... |
Why doesn't .rstrip('\n') work? | 18,281,865 | 6 | 2013-08-16T20:46:16Z | 18,281,941 | 9 | 2013-08-16T20:51:52Z | [
"python",
"line"
] | Let's say `doc.txt` contains
```
a
b
c
d
```
and that my code is
```
f = open('doc.txt')
doc = f.read()
doc = doc.rstrip('\n')
print doc
```
why do I get the same values? | `str.rstrip()` removes the *trailing* newline, not all the newlines in the middle. You have one long string, after all.
Use [`str.splitlines()`](http://docs.python.org/2/library/stdtypes.html#str.splitlines) to split your document into lines *without newlines*; you can rejoin it if you want to:
```
doclines = doc.spl... |
os.walk iterates in what order? | 18,282,370 | 31 | 2013-08-16T21:27:23Z | 18,282,401 | 45 | 2013-08-16T21:29:25Z | [
"python",
"order",
"os.walk"
] | I am concerned about the order of files and directories given by `os.walk()`. If I have these directories, 1, 10, 11, 12, 2, 20, 21, 22, 3, 30, 31, 32, what is the order of the output list?
Is it ordered by numeric values?
```
1 2 3 10 20 30 11 21 31 12 22 32
```
Or ordered by ASCII values, like what is given by `ls... | `os.walk` uses `os.listdir`. Here is the docstring for `os.listdir`:
> listdir(path) -> list\_of\_strings
>
> Return a list containing the names of the entries in the directory.
>
> ```
> path: path of directory to list
> ```
>
> **The list is in arbitrary order**. It does not include the special
> entries '.' and '..... |
os.walk iterates in what order? | 18,282,370 | 31 | 2013-08-16T21:27:23Z | 18,282,602 | 15 | 2013-08-16T21:47:02Z | [
"python",
"order",
"os.walk"
] | I am concerned about the order of files and directories given by `os.walk()`. If I have these directories, 1, 10, 11, 12, 2, 20, 21, 22, 3, 30, 31, 32, what is the order of the output list?
Is it ordered by numeric values?
```
1 2 3 10 20 30 11 21 31 12 22 32
```
Or ordered by ASCII values, like what is given by `ls... | `os.walk()` yields in each step what it will do in the next steps. You can in each step influence the order of the next steps by sorting the lists the way you want them. Quoting [the 2.7 manual](http://docs.python.org/2/library/os.html#os.walk):
> When topdown is True, the caller can modify the dirnames list in-place ... |
argparse with required subcommands | 18,282,403 | 11 | 2013-08-16T21:29:34Z | 18,283,730 | 18 | 2013-08-16T23:58:58Z | [
"python",
"argparse"
] | With python's argparse, how do I make a subcommand a required argument? I want to do this because I want argparse to error out if a subcommand is not specified. I override the error method to print help instead. I have 3-deep nested subcommands, so it's not a matter of simply handling zero arguments at the top level.
... | There was a change in 3.3 in the error message for required arguments, and subcommands got lost in the dust.
<http://bugs.python.org/issue9253#msg186387>
There I suggest this work around, setting the `required` attribute after the `subparsers` is defined.
```
parser = ArgumentParser(prog='test')
subparsers = parser.... |
Python 32-bit memory limits on 64bit windows | 18,282,867 | 13 | 2013-08-16T22:10:39Z | 18,282,931 | 26 | 2013-08-16T22:16:00Z | [
"python",
"windows",
"memory",
"file-io",
"numpy"
] | I'm getting a memory issue I can't seem to understand.
I'm on a windows 7 64 bit machine with 8GB of memory and running a 32bit python program.
The programs reads a 5,118 zipped numpy files (npz).
Windows reports that the files take up 1.98 GB on disk
Each npz file contains two pieces of data:
'arr\_0' is of type np... | I don't know why you think your process should be able to access 4GB. According to [Memory Limits for Windows Releases](http://msdn.microsoft.com/en-us/library/aa366778.aspx) at MSDN, on 64-bit Windows 7, a default 32-bit process gets 2GB.\* Which is exactly where it's running out.
So, is there a way around this?
Wel... |
Efficiently processing DataFrame rows with a Python function? | 18,282,988 | 9 | 2013-08-16T22:20:56Z | 18,283,014 | 16 | 2013-08-16T22:23:57Z | [
"python",
"numpy",
"pandas"
] | In many places in our Pandas-using code, we have some Python function `process(row)`. That function is used over `DataFrame.iterrows()`, taking each `row`, and doing some processing, and returning a value, which we ultimate collect into a new `Series`.
I realize this usage pattern circumvents most of the performance b... | You should apply your function along the axis=1. Function will receive a row as an argument, and anything it returns will be collected into a new series object
```
df.apply(you_function, axis=1)
```
Example:
```
>>> df = pd.DataFrame({'a': np.arange(3),
'b': np.random.rand(3)})
>>> df
a ... |
How to create a Python dictionary with double quotes as default quote format? | 18,283,725 | 16 | 2013-08-16T23:58:37Z | 18,283,758 | 25 | 2013-08-17T00:02:27Z | [
"python",
"python-2.7",
"dictionary",
"python-3.x"
] | I am trying to create a python dictionary which is to be used as a java script var inside a html file for visualization purposes. As a requisite, I am in need of creating the dictionary with all names inside double quotes instead of default single quotes which Python uses. Is there an easy and elegant way to achieve th... | `json.dumps()` is what you want here, if you use `print json.dumps(pairs)` you will get your expected output:
```
>>> pairs = {'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}
>>> print pairs
{'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}
>>> import json
>>> print jso... |
How to create a Python dictionary with double quotes as default quote format? | 18,283,725 | 16 | 2013-08-16T23:58:37Z | 18,283,909 | 13 | 2013-08-17T00:28:20Z | [
"python",
"python-2.7",
"dictionary",
"python-3.x"
] | I am trying to create a python dictionary which is to be used as a java script var inside a html file for visualization purposes. As a requisite, I am in need of creating the dictionary with all names inside double quotes instead of default single quotes which Python uses. Is there an easy and elegant way to achieve th... | It is not clear why you would want to do this but you can construct your own version of a dict with special printing:
```
>>> import json
>>> class mydict(dict):
def __str__(self):
return json.dumps(self)
>>> couples = [['jack', 'ilena'],
['arun', 'maya'],
['hari', ... |
Matplotlib: using a figure object to initialize a plot | 18,284,296 | 3 | 2013-08-17T01:43:36Z | 18,302,072 | 9 | 2013-08-18T17:55:43Z | [
"python",
"matplotlib",
"plot"
] | I am building a class of plot tools for a specific experiment.
I currently have two plot methods, a static plot using imshow(), and a "movie" format also
using imshow() .
Both methods and any future methods, get parameters that are the same for any specific plotting method that I might write. I have all those paramete... | You need to understand a bit of architecture of `matplotlib` first (see [here](http://www.aosabook.org/en/matplotlib.html) for a long article by the founder and current lead developer). At the bottom of the `backend` layer which deals with rendering and talking to the hardware. On top of that layer are `artists` which ... |
sqlalchemy.exc.CircularDependencyError: Circular dependency detected | 18,284,464 | 6 | 2013-08-17T02:16:54Z | 18,284,518 | 9 | 2013-08-17T02:27:57Z | [
"python",
"sqlalchemy",
"circular-dependency"
] | The business logic - One Category may have multiple (1:M) attributes, like Category "Memory" could have attributes Speed, Size, Type etc.
at the same time one Category could be sorted by the attribute value (this is stored inside Category.sortByAttribute - which is foreign key to LookupCategoryAttributes table.
Tryin... | Okay found the answer - use post\_update in relationship
<http://docs.sqlalchemy.org/en/latest/orm/relationship_persistence.html#post-update>
so what I did is inside **Category** class is changed this:
```
SortByAttribute = relationship("Attribute", uselist=False, foreign_keys=[sortByAttribute], primaryjoin="Attrib... |
How to use a test tornado server handler that authenticates a user via a secure cookie | 18,285,947 | 6 | 2013-08-17T06:44:31Z | 18,286,742 | 7 | 2013-08-17T08:27:44Z | [
"python",
"unit-testing",
"cookies",
"tornado"
] | How can I write a unit test for a tornado handler that authenticates a user via a secure cookie? Here is the code (and sudo code) for a dummy test that I'd like to make pass. I'm using Tornado 3.1.
```
from tornado.web import Application, RequestHandler
from tornado.escape import to_unicode, json_decode, json_encode
... | Using [mock](https://pypi.python.org/pypi/mock):
```
import mock
...
class UserAPITest(AsyncHTTPTestCase):
def get_app(self):
self.app = Application([('/', MainHandler)],
cookie_secret='asdfasdf')
return self.app
def test_user_profile_annoymous(self):
with mock.pa... |
Python : Java throws equivalent in python | 18,289,352 | 5 | 2013-08-17T13:28:18Z | 18,289,414 | 7 | 2013-08-17T13:35:43Z | [
"java",
"python",
"exception-handling",
"throws"
] | Not attempting to compare the languages but just for knowledge,
Is there any way to have equivalent of java `throws` keyword/functionality in Python?
or the way we can recognize checked exception thrown by any method at static time?
or Passing(chaining) exception handling responsibility?
Java:
```
public void some... | There is no standard equivalent of this in Python as far as I know, and it's not necessary either. The best you can do is indicate in the docstring what exceptions/errors are raised in what circumstances, and leave it to whoever is using your functions to work out the rest.
In Java, the throws clause is a sort of book... |
Python : Java throws equivalent in python | 18,289,352 | 5 | 2013-08-17T13:28:18Z | 18,289,516 | 8 | 2013-08-17T13:48:44Z | [
"java",
"python",
"exception-handling",
"throws"
] | Not attempting to compare the languages but just for knowledge,
Is there any way to have equivalent of java `throws` keyword/functionality in Python?
or the way we can recognize checked exception thrown by any method at static time?
or Passing(chaining) exception handling responsibility?
Java:
```
public void some... | If you can't have statically typed arguments, you can't have static throws declarations. For instance, there's no way for me to annotate this function:
```
def throw_me(x):
raise x
```
Or even this one:
```
def call_func(f):
f() # f could throw any exception
```
What you can do is make it an error to throw... |
python Hiding raw_input | 18,290,340 | 7 | 2013-08-17T15:24:48Z | 18,290,450 | 28 | 2013-08-17T15:35:22Z | [
"python",
"masking",
"raw-input"
] | so this is my code and i want to hide my password, but i dont know how. i have looked around and none of them seem to fit in my coding, this is the current coding. i mean i have seen show="\*" and also getpass but i dont know how to place them into this coding. im using python 2.7.3 and im coding on a raspberry pi.
``... | `getpass` hides the input, just replace `raw_input` after importing the module `getpass`, like this:
```
import getpass
.
.
.
pa = getpass.getpass()
``` |
Python extension - construct and inspect large integers efficiently | 18,290,507 | 10 | 2013-08-17T15:40:36Z | 18,326,068 | 7 | 2013-08-20T02:27:38Z | [
"python",
"python-2.7",
"python-3.x",
"python-c-api"
] | I have a native library for which a natural interface would involve passing potentially large numbers. I anticipate about half being < 32 bits; another quarter < 64 bits; the next eighth < 128 bits - and so on, without a fixed length limit.
PyLong\_FromUnsignedLongLong() and PyLong\_AsUnsignedLongLong() would be suita... | The underscore prefix largely means the same thing in the C API as in normal Python: "this function is an implementation detail subject to change, so watch yourself if you use it". You're not forbidden to use such functions, and if it's the only way to achieve a particular goal (e.g. significant efficiency gains in you... |
"AttributeError: sqrt" when calculating a simple standard deviation | 18,292,318 | 5 | 2013-08-17T18:58:40Z | 18,316,030 | 7 | 2013-08-19T14:14:01Z | [
"python",
"numpy"
] | I found a very unusual error when trying to calculate the standard deviation of a two dimensional numpy array. Basically, I'm doing this:
```
np.std(myarray, axis=1)
```
which gives the following error:
```
/home/user/env/local/lib/python2.7/site-packages/numpy/core/fromnumeric.pyc in std(a, axis, dtype, out, ddof, ... | It seems that the problem is the dtype set as `object`. Even if numpy allows it, it is generally a bad idea, as you lose most internal optimizations.
The exception is present only with the axis keyword :
```
>>> import numpy as np
>>> a = np.arange(10).reshape(5,2)
>>> b = np.arange(10, dtype=object).reshape(5,2)
>>>... |
Python logging typeerror | 18,292,500 | 2 | 2013-08-17T19:21:30Z | 18,292,518 | 7 | 2013-08-17T19:23:36Z | [
"python",
"debugging",
"logging",
"typeerror",
"info"
] | Could you please help me, whats wrong.
```
import logging
if (__name__ == "__main__"):
logging.basicConfig(format='[%(asctime)s] %(levelname)s::%(module)s::%(funcName)s() %(message)s', level=logging.DEBUG)
logging.INFO("test")
```
And I can't run it, I've got an error:
```
Traceback (most recent call last):... | [`logging.INFO` denotes](http://docs.python.org/2/howto/logging.html#logging-advanced-tutorial) an integer constant with value of 20
> INFO Confirmation that things are working as expected.
What you need is [`logging.info`](http://docs.python.org/2/library/logging.html#logging.info)
```
logging.info("test")
``` |
is there a 'foreach' function in python3? | 18,294,534 | 17 | 2013-08-18T00:14:35Z | 18,294,549 | 8 | 2013-08-18T00:18:40Z | [
"python",
"python-3.x",
"foreach"
] | when I meet the situation I can do it in javascript, I always think if there's an 'foreach' function it would be convenience .a foreach function can be described as this below:
```
def foreach(fn,iterable):
for x in iterable:
fn(x)
```
they just do it on every element and didn't yield or return something,... | Python doesn't have a `foreach` statement *per se*. It has `for` loops built into the language.
```
for element in iterable:
operate(element)
```
If you really wanted to, you could define your own `foreach` function:
```
def foreach(function, iterable):
for element in iterable:
function(element)
```
... |
is there a 'foreach' function in python3? | 18,294,534 | 17 | 2013-08-18T00:14:35Z | 18,294,631 | 35 | 2013-08-18T00:33:51Z | [
"python",
"python-3.x",
"foreach"
] | when I meet the situation I can do it in javascript, I always think if there's an 'foreach' function it would be convenience .a foreach function can be described as this below:
```
def foreach(fn,iterable):
for x in iterable:
fn(x)
```
they just do it on every element and didn't yield or return something,... | Every occurence of "foreach" I've seen (PHP, C#, ...) does basically the same as pythons "for" statement.
These are more or less equivalent:
```
// PHP:
foreach ($array as $val) {
print($val);
}
// C#
foreach (String val in array) {
console.writeline(val);
}
// Python
for val in array:
print(val)
```
S... |
AWS Elastic Beanstalk error - ImportError: No module named flask.ext.sqlalchemy | 18,294,680 | 16 | 2013-08-18T00:42:18Z | 18,301,218 | 15 | 2013-08-18T16:24:04Z | [
"python",
"amazon-web-services",
"flask",
"elastic-beanstalk",
"flask-sqlalchemy"
] | I deployed my flask application into aws beanstalk and ran into an import error:
```
ImportError: No module named flask.ext.sqlalchemy
```
In my application.py file, I have this statement
```
from flask.ext.sqlalchemy import SQLAlchemy
```
and it runs fine on my machine but does not work in aws elastic beanstalk.
... | Make sure you have included a requirements.txt file in root directory of your project.
The file should include any pip package that needs to be installed
```
Flask-SQLAlchemy=1.0
```
<http://www.pip-installer.org/en/latest/cookbook.html#requirements-files> |
AttributeError: module object has no attribute "Series". Code works in iPython | 18,295,314 | 7 | 2013-08-18T03:11:11Z | 18,295,349 | 15 | 2013-08-18T03:18:28Z | [
"python",
"python-2.7",
"pandas",
"ipython",
"python-import"
] | Submodules aren't *implicitly* imported, and must be *explicitly* declared, but I'm making an *explicit* call to the `pd.Series` submodule, aren't I?
Regardless, shouldn't `import pandas as pd` allow for `pd.Series` to be called? The following code works flawlessly in **iPython**, but fails when executed from a script... | The issue is that you've called your module `pandas`. Call it something else. And don't forget to delete the `pandas.pyc` generated on `import pandas` or else it will keep failing. |
Vim [compile and] run shortcut | 18,296,192 | 17 | 2013-08-18T06:00:25Z | 18,296,266 | 19 | 2013-08-18T06:15:10Z | [
"c++",
"python",
"c",
"shell",
"vim"
] | Basically what I want is a keyboard shortcut in vim that lets me [compile and] run the currently being edited C, C++ or Python program. In psuedocode:
```
when a shortcut key is pressed:
if current_extension == 'c' then
shell: gcc this_filename.c -o this_filename_without_extension
if retcode == 0 t... | Something like this would work. Just create filetype autocmd that map `<F4>` or whatever you want to save and compile and run the program. It uses exec to build the string and uses shellescape to escape the file name.
```
autocmd filetype python nnoremap <F4> :w <bar> exec '!python '.shellescape('%')<CR>
autocmd filet... |
Vim [compile and] run shortcut | 18,296,192 | 17 | 2013-08-18T06:00:25Z | 18,296,293 | 7 | 2013-08-18T06:18:05Z | [
"c++",
"python",
"c",
"shell",
"vim"
] | Basically what I want is a keyboard shortcut in vim that lets me [compile and] run the currently being edited C, C++ or Python program. In psuedocode:
```
when a shortcut key is pressed:
if current_extension == 'c' then
shell: gcc this_filename.c -o this_filename_without_extension
if retcode == 0 t... | <http://singlecompile.topbug.net> seems to do more than what you want. For a simpler solution you could also just add the following to your vimrc
```
au BufEnter *.cpp set makeprg=g++\ -g\ %\ -o\ %<
au BufEnter *.c set makeprg=gcc\ -g\ %\ -o\ %<
au BufEnter *.py set makeprg=python\ %
au BufEnter *.[rR] set makeprg=... |
Print the Python Exception/Error Hierarchy | 18,296,653 | 6 | 2013-08-18T07:16:34Z | 18,296,681 | 12 | 2013-08-18T07:20:07Z | [
"python",
"class",
"exception"
] | Is the any command line option in python to print the Exception/Error Class hierarchy?
The output should be similar to <http://docs.python.org/2/library/exceptions.html#exception-hierarchy> | [inspect](http://docs.python.org/2/library/inspect.html) module might help, specifically [getclasstree()](http://docs.python.org/library/inspect.html#inspect.getclasstree) function:
> Arrange the given list of classes into a hierarchy of nested lists.
> Where a nested list appears, it contains classes derived from the... |
python max function using 'key' and lambda expression | 18,296,755 | 53 | 2013-08-18T07:33:12Z | 18,296,814 | 91 | 2013-08-18T07:41:34Z | [
"python",
"function",
"lambda"
] | I come from OOP background and trying to learn python.
I am using the `max` function which uses a lambda expression to return the instance of type `Player` having maximum `totalScore` among the list `players`.
```
def winner():
w = max(players, key=lambda p: p.totalScore)
```
The function correctly returns instan... | `lambda` is an anonymous function, it is equivalent to:
```
def func(p):
return p.totalScore
```
Now `max` becomes:
```
max(players, key=func)
```
But as `def` statements are compound statements they can't be used where an expression is required, that's why sometimes `lambda`'s are used.
Note that lambda is equ... |
I'm not able to import Flask-WTF TextField and BooleanField | 18,297,041 | 8 | 2013-08-18T08:10:20Z | 18,297,150 | 25 | 2013-08-18T08:24:19Z | [
"python",
"import",
"flask",
"wtforms",
"flask-wtforms"
] | I'm using virtualenv to set up a new project. I installed a lot of things using virtualenv pip from the script folder like below:
```
flask\scripts\pip install Flask-WTF
```
I have no other packages installed in the global python folder. My code looks like this:
```
# Importing TextField and BooleanField is not work... | > From version 0.9.0, Flask-WTF will not import anything from wtforms, you need to import fields from wtforms.
>
> [**Source**](https://flask-wtf.readthedocs.org/en/latest/quickstart.html)
You need to import them from `wtforms` (note that according to [`docs`](https://flask-wtf.readthedocs.org/en/latest/quickstart.htm... |
MySQL password in Django | 18,299,322 | 2 | 2013-08-18T12:56:10Z | 18,299,371 | 7 | 2013-08-18T13:01:21Z | [
"python",
"mysql",
"django"
] | I just started on a Django project and in the settings.py file of the project, the daabase section looks like this:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'blogengine', # Or path to da... | There is no point in trying to protect that password.
**Any** token in that file that can be used to access the database can be used by anyone else to access the database. That's how shared secret security works. Replace the password by a randomly generated token, and you still have to communicate that token to `setti... |
Basic example for PCA with matplotlib | 18,299,523 | 6 | 2013-08-18T13:19:55Z | 18,299,834 | 18 | 2013-08-18T13:56:30Z | [
"python",
"matplotlib",
"pca"
] | I trying to do a simple principal component analysis with matplotlib.mlab.PCA but with the attributes of the class I can't get a clean solution to my problem. Here's an example:
Get some dummy data in 2D and start PCA:
```
from matplotlib.mlab import PCA
import numpy as np
N = 1000
xTrue = np.linspace(0,1000,N)
... | I don't think the `mlab.PCA` class is appropriate for what you want to do. In particular, the `PCA` class rescales the data before finding the eigenvectors:
```
a = self.center(a)
U, s, Vh = np.linalg.svd(a, full_matrices=False)
```
The `center` method divides by `sigma`:
```
def center(self, x):
'center the dat... |
os.path.isdir() returns False even when folder exists | 18,299,949 | 3 | 2013-08-18T14:10:31Z | 18,299,955 | 11 | 2013-08-18T14:11:20Z | [
"python",
"filesystems"
] | I'm currently writing a script which has to check if all specified folders actually exist.
I found out I have to use os.path.isdir() with absolute paths.
I have the following directory structure:
```
X:\
pythonscripts\
files\
Films\
Series\
src\
```
When I open op my python command line and try... | Escape backslash (`\`)
```
os.path.isdir('X:\\pythonscripts\\src')
```
or use raw string:
```
os.path.isdir(r'X:\pythonscripts\src')
```
---
without escape, you get wrong path:
```
>>> '\f'
'\x0c'
>>> print '\f'
>>> print '\\f'
\f
>>> print r'\f'
\f
``` |
How to prevent setuptools install package as an .egg | 18,300,017 | 7 | 2013-08-18T14:16:33Z | 18,342,941 | 10 | 2013-08-20T18:55:26Z | [
"python",
"setuptools",
"egg"
] | For example, installing IPython on Linux (where setuptools is not installed) I've got IPython installed in `site-packages\IPython`.
Installing IPython on Windows (where IPython requires setuptools), after executing the same command
```
python setup.py install
```
I get IPython installed in `site-packages\ipython-0.1... | I've discovered that
```
python setup.py install --old-and-unmanageable
```
does the job, but I am not sure it is a good way as `--old-and-unmanageable` is marked "Try not to use this!". |
count the number of images on a webpage, using urllib | 18,303,095 | 2 | 2013-08-18T19:56:29Z | 18,303,129 | 7 | 2013-08-18T19:59:49Z | [
"python",
"html",
"regex",
"html-parsing",
"urllib"
] | For a class, I have an exercise where i need to to count the number of images on any give web page. I know that every image starts with , so I am using a regexp to try and locate them. But I keep getting a count of one which i know is wrong, what is wrong with my code:
```
import urllib
import urllib.request
import re... | Don't ever use regex for parsing HTML, use an html parser, like [lxml](http://lxml.de/) or [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/). Here's a working example, how to get `img` tag count using `BeautifulSoup` and [requests](http://docs.python-requests.org/en/latest/):
```
from bs4 import B... |
Name is not defined in Django model | 18,303,406 | 6 | 2013-08-18T20:36:13Z | 18,303,424 | 11 | 2013-08-18T20:37:43Z | [
"python",
"django"
] | I have a Django app with the following in its **models.py** file:
```
from django.db import models
class Event(models.Model):
date = models.DateField()
name = models.TextField(max_length=60)
venue = models.ForeignKey(Venue)
def __unicode__(self):
return self.name
class Venue(models.Model):
... | Move the definition of `Venue` before the definition of `Event`.
The reason is that Event references the Venue class in its ForeignKey relationship before Venue is defined.
Or you can do this:
```
venue = models.ForeignKey('Venue')
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.