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
Extract a specific file from a zip archive without maintaining directory structure in python
17,729,703
4
2013-07-18T16:59:49Z
17,729,939
7
2013-07-18T17:13:13Z
[ "python", "zip", "apk", "directory-structure" ]
I'm trying to extract a specific file from a zip archive using python. In this case, extract an apk's icon from the apk itself. I am currently using ``` ziphandle = open(tDir + mainapk[0],'rb') #`pwd`/temp/x.apk zip = zipfile.ZipFile(ziphandle) zip.extract(icon[1], tDir) # extract /res/drawable/icon.png from apk to ...
You can use [zipfile.ZipFile.read](http://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.read): ``` import os with zipfile.ZipFile(tDir + mainapk[0]) as z: with open(os.path.join(tDir, os.path.basename(icon[1])), 'wb') as f: f.write(z.read(icon[1])) ``` Or use [zipfile.ZipFile.open](http://docs.p...
Set value for a selected cell in pandas DataFrame
17,729,853
16
2013-07-18T17:08:17Z
17,729,985
29
2013-07-18T17:15:28Z
[ "python", "pandas" ]
this is a rather similar question to [this question](http://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe "Set value for particular cell in pandas DataFrame") but with one key difference: I'm selecting the data I want to change not by its index but by some criteria. If the crit...
Many ways to do that ### 1 ``` In [7]: d.sales[d.sales==24] = 100 In [8]: d Out[8]: day flavour sales year 0 sat strawberry 10 2008 1 sun strawberry 12 2008 2 sat banana 22 2008 3 sun banana 23 2008 4 sat strawberry 11 2009 5 sun strawberry 13 2009 6 sat ...
matplotlib bitmap plot with vector text
17,730,013
8
2013-07-18T17:17:26Z
17,730,816
9
2013-07-18T18:02:43Z
[ "python", "matplotlib", "bitmap", "vector-graphics" ]
So, I'm plotting a waveform (and other things) that result in a bigger vector file (PDF) than the corresponding raster file (PNG). I imagine this is because the dataset plotted is very large and there are millions of instructions in the vector file. Other than being bigger, the PDF is also quite hard for the PDF reader...
It should be as simple as passing in `rasterized=True` to the `plot` command. E.g. ``` import matplotlib.pyplot as plt plt.plot(range(10), rasterized=True) plt.savefig('test.pdf') ``` For me, this results in a pdf with a rasterized line (the resolution is controlled by the dpi you specified with `savefig` -- by def...
Python cant get full path name of file
17,730,173
8
2013-07-18T17:25:36Z
17,730,247
7
2013-07-18T17:29:10Z
[ "python", "path", "directory" ]
Trying to drill through a directory on my drive that has subfoldrs within it. When I find files that have the file extensions I'm looking for I want the full file path. Right now this is what I have: ``` import os import Tkinter import tkFileDialog from Tkinter import Tk from tkFileDialog import askopenfilename root ...
You probably need to join the filename with the directory that contains it: ``` os.path.realpath(os.path.join(root,name)) ``` e.g. I just tested this: ``` import os for root, dirs, files in os.walk('.'): for name in files: if name == 'foo': name = str(name) name = os.path.realpath(o...
Why __instancecheck__ is not always called depending on argument?
17,731,207
9
2013-07-18T18:26:09Z
17,731,521
7
2013-07-18T18:45:24Z
[ "python", "python-3.x" ]
There is this code: ``` class Meta(type): def __instancecheck__(self, instance): print("__instancecheck__") return True class A(metaclass=Meta): pass a = A() isinstance(a, A) # __instancecheck__ not called isinstance([], A) # __instancecheck__ called ``` Why `__instancecheck__` is called for `[]` argum...
`PyObject_IsInstance` does a quick test for exact match. [`Objects/abstract.c`](http://svn.python.org/projects/python/trunk/Objects/abstract.c): ``` int PyObject_IsInstance(PyObject *inst, PyObject *cls) { static PyObject *name = NULL; /* Quick test for an exact match */ if (Py_TYPE(inst) == (PyTypeObjec...
Getting the correct timezone offset in Python using local timezone
17,733,139
8
2013-07-18T20:21:08Z
17,775,976
15
2013-07-21T19:22:35Z
[ "python", "timezone", "pytz", "timezoneoffset" ]
Ok let me first start by saying my timezone is CET/CEST. The exact moment it changes from CEST to CET (back from DST, which is GMT+2, to normal, which GMT+1, thus) is always the last Sunday of October at 3AM. In 2010 this was 31 October 3AM. Now note the following: ``` >>> import datetime >>> import pytz.reference >>...
According to [Wikipedia](https://en.wikipedia.org/wiki/European_Summer_Time), the transition to and from Summer Time occurs at 01:00 UTC. * At 00:12 UTC you are still in Central European Summer Time (i.e. UTC+02:00), so the local time is 02:12. * At 01:12 UTC you are back in the standard Central European Time (i.e. UT...
Dynamic Method Call In Python 2.7 using strings of method names
17,734,618
5
2013-07-18T21:54:57Z
17,734,692
14
2013-07-18T21:59:17Z
[ "python", "python-2.7" ]
I have a tuple which lists down the methods of a class like: ``` t = ('methA','methB','methC','methD','methE','methF') ``` and so on.. Now I need to dynamically call these methods based on a user made selection. The methods are to be called based on the index. So if a user selects '0', `methA` is called, if '5', `me...
If you're calling a method on an object (including imported modules) you can use: ``` getattr(obj, t[i])(*args) ``` If you need to call a function in the current module ``` getattr(sys.modules[__name__], t[i])(*args) ``` where `args` is a list or tuple of arguments to send, or you can just list them out in the call...
Find item in list inside list
17,734,928
3
2013-07-18T22:18:02Z
17,734,997
7
2013-07-18T22:22:43Z
[ "python", "list" ]
I have a list that is made out of lists of say 3 items: ``` a = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]] ``` I need to check if a given value, say 7, exists in any of the *first* items (ie: the items `[0]`) of any of the lists in `a`. In this case the outcome is `True` since it exists in `a[2][0]`. This is what I've ...
There is a number of ways to write it more compactly: ``` 7 in (x[0] for x in a) # using a generator to avoid creating the full list of values ``` or using some standard library modules: ``` import operator import itertools first_elem = operator.itemgetter(0) 7 in itertools.imap(first_elem, a) ```
Share extension types in Cython for static typing
17,735,051
7
2013-07-18T22:26:53Z
17,755,039
7
2013-07-19T20:34:24Z
[ "python", "cython" ]
I converted a Python class to an extension type inside a .pyx file. I can create this object in the other Cython module, but I **can't do static typing** with it. Here is a part of my class: ``` cdef class PatternTree: cdef public PatternTree previous cdef public PatternTree next cdef public PatternTree ...
I found out a fix for it. Here is the solution: In .pyx: ``` cdef class PatternTree: # NO ATTRIBUTE DECLARATIONS! def __init__(self, name, parent=None, nodeType=XML): # Some code cpdef int isExpressions(self): # Some code cpdef MatchResult isMatch(self, PatternTree other): ...
Why does python allow an empty function (with doc-string) body without a "pass" statement?
17,735,170
15
2013-07-18T22:36:36Z
17,735,171
13
2013-07-18T22:36:36Z
[ "python", "syntax" ]
``` class SomeThing(object): """Represents something""" def method_one(self): """This is the first method, will do something useful one day""" def method_two(self, a, b): """Returns the sum of a and b""" return a + b ``` In a recent review of some code similar to the above, a coll...
According to the [Python 2.7.5 grammar specification](http://docs.python.org/2/reference/grammar.html), which is read by the parser generator and used to parse Python source files, a function looks like this: ``` funcdef: 'def' NAME parameters ':' suite ``` The function body is a `suite` which looks like this ``` su...
Determine if given class attribute is a property or not, Python object
17,735,520
20
2013-07-18T23:11:09Z
17,735,709
9
2013-07-18T23:28:10Z
[ "python" ]
It's all in the title. Here is the following example: ``` class A(object): my_var = 5 def my_method(self, drink='beer'): return 'I like %s' % drink @property def my_property(self): return 'I do not drink coffee' ``` I instantiate an A object and I want to know the type of each attrib...
I once asked a similar question. The trouble you'll run into, of course, is that you can't access the property through the instance to determine its type without calling the getter, which gets you the type of whatever the getter returns. So you have to access the property through its class rather than through the insta...
Determine if given class attribute is a property or not, Python object
17,735,520
20
2013-07-18T23:11:09Z
17,735,716
14
2013-07-18T23:28:56Z
[ "python" ]
It's all in the title. Here is the following example: ``` class A(object): my_var = 5 def my_method(self, drink='beer'): return 'I like %s' % drink @property def my_property(self): return 'I do not drink coffee' ``` I instantiate an A object and I want to know the type of each attrib...
You need to look at the class (This is the case for descriptors in general) ``` >>> obj.__class__.my_property <property object at 0xb74bd16c> ``` or ``` >>> type(obj).my_property <property object at 0xb720b93c> ``` so ``` >>> isinstance(type(obj).my_property, property) True ```
How can I "count from the back" in python lists?
17,736,921
3
2013-07-19T01:53:50Z
17,736,930
9
2013-07-19T01:55:08Z
[ "python", "string", "list", "python-2.5" ]
Say I have a list `l = ['h','e','l','l','o']` I want to be able to take the last two items and use them, but I don't know how long the list is(It's user input). So can't do `l[3:]` because what if the list is seven(or any number) items long instead of five? How can I count from the back of the list?
``` print l[-2:] ``` Negative numbers count from the end. ``` >>> l = ['h','e','l','l','o'] >>> print l[-2:] ['l', 'o'] >>> print l[-5:] ['h', 'e', 'l', 'l', 'o'] >>> print l[-6:] ['h', 'e', 'l', 'l', 'o'] >>> ```
Python and Virtualenv on Windows
17,737,203
18
2013-07-19T02:30:05Z
17,737,980
15
2013-07-19T04:10:45Z
[ "python", "virtualenv" ]
How do you install virtualenv correctly on windows? I downloaded virtualenv1.9.1 from [here](https://pypi.python.org/pypi/virtualenv) and tried installing it with: ``` python virtualenv.py install ``` but it does not appear in MyPythonPath/Scripts I tried the same way installing [virutalenvwrapper-win](https://pypi...
The suggested way to install Python packages is to use `pip` Please follow this documentation to install `pip`: <http://www.pip-installer.org/en/latest/installing.html> Note: Python 2.7.9 and above, and Python 3.4 and above include pip already. Then install `virtualenv`: ``` pip install virtualenv ```
count number of rows in flask templates
17,739,264
9
2013-07-19T06:16:07Z
17,739,359
15
2013-07-19T06:23:07Z
[ "python", "templates", "loops", "count", "flask" ]
i have send a variable from my views to templates which consist of the data from database this is what i am using in my template ``` {% for i in data %} <tr> <td>{{i.id}}</td> <td>{{i.first_name}}</td> <td>{{i.last_name}}</td> <td>{{i.email}}</td> </tr> {% endfor %...
Inside the loop you can access a special variable called `loop` and you can see the number of items with `{{ loop.length }}` This is all you can do with loop auxiliary variable: * **loop.index** The current iteration of the loop. (1 indexed) * **loop.index0** The current iteration of the loop. (0 indexed) * **loop.re...
wrapping around slices in Python / numpy
17,739,543
7
2013-07-19T06:36:45Z
17,739,659
14
2013-07-19T06:45:26Z
[ "python", "numpy" ]
I have a numpy array, and I want to get the "neighbourhood" of the i'th point. Usually the arrays I'm using are two-dimensional, but the following 1D example illustrates what I'm looking for. If ``` A = numpy.array([0,10,20,30,40,50,60,70,80,90]) ``` Then the (size 5) neighbourhood of element 4 is `[20,30,40,50,60]`,...
`numpy.take` in `'wrap'` mode will use your indices modulo the length of the array. ``` indices = range(i-2,i+3) neighbourhood = A.take(indices, mode='wrap') ``` See documentation for details [`numpy.take`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html#numpy.take)
Checking fuzzy/approximate substring existing in a longer string, in Python?
17,740,833
22
2013-07-19T07:51:40Z
17,741,165
12
2013-07-19T08:11:13Z
[ "python", "python-2.7", "fuzzy-search" ]
Using algorithms like leveinstein ( leveinstein or difflib) , it is easy to find approximate matches.eg. ``` >>> import difflib >>> difflib.SequenceMatcher(None,"amazing","amaging").ratio() 0.8571428571428571 ``` The fuzzy matches can be detected by deciding a threshold as needed. Current requirement : To find fuzzy...
How about using `difflib.SequenceMatcher.get_matching_blocks`? ``` >>> import difflib >>> large_string = "thelargemanhatanproject" >>> query_string = "manhattan" >>> s = difflib.SequenceMatcher(None, large_string, query_string) >>> sum(n for i,j,n in s.get_matching_blocks()) / float(len(query_string)) 0.88888888888888...
Checking fuzzy/approximate substring existing in a longer string, in Python?
17,740,833
22
2013-07-19T07:51:40Z
19,694,766
8
2013-10-30T22:09:30Z
[ "python", "python-2.7", "fuzzy-search" ]
Using algorithms like leveinstein ( leveinstein or difflib) , it is easy to find approximate matches.eg. ``` >>> import difflib >>> difflib.SequenceMatcher(None,"amazing","amaging").ratio() 0.8571428571428571 ``` The fuzzy matches can be detected by deciding a threshold as needed. Current requirement : To find fuzzy...
Recently I've written an alignment library for Python: <https://github.com/eseraygun/python-alignment> Using it, you can perform both global and local alignments with arbitrary scoring strategies on any pair of sequences. Actually, in your case, you need semi-local alignments as you don't care for the substrings of `q...
Python function optional arguments - possible to add as condition?
17,742,177
2
2013-07-19T09:07:08Z
17,742,407
7
2013-07-19T09:18:03Z
[ "python", "function", "arguments", "conditional-statements", "optional-parameters" ]
Is it possible, somehow, to aassign a condtional statement toan optional argument? My initial attempts, using the following construct, have been unsuccessful: ``` y = {some value} if x == {someValue} else {anotherValue} ``` where x has assigned beforehand. More specifically, I want my function signature to look som...
Sure, that's exactly how you do it. You may want to keep in mind that `b`'s default value will be set immediately after you define the function, which may not be desirable: ``` def test(): print("I'm called only once") return False def foo(b=5 if test() else 10): print(b) foo() foo() ``` And the output:...
running multiple bash commands with subprocess
17,742,789
8
2013-07-19T09:36:13Z
17,743,548
20
2013-07-19T10:11:16Z
[ "python", "bash", "subprocess" ]
If I run `echo a; echo b` in bash the result will be that both commands are run. However if I use subprocess then the first command is run, printing out the whole of the rest of the line. The code below echos `a; echo b` instead of `a b`, how do I get it to run both commands? ``` import subprocess, shlex def subproces...
You have to use shell=True in subprocess and no shlex.split: ``` def subprocess_cmd(command): process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True) proc_stdout = process.communicate()[0].strip() print proc_stdout subprocess_cmd('echo a; echo b') ``` returns: ``` a b ```
Flask logging - Cannot get it to write to a file
17,743,019
13
2013-07-19T09:46:46Z
17,784,974
31
2013-07-22T10:15:32Z
[ "python", "logging", "python-2.7", "flask" ]
Ok, here's the code where I setup everything: ``` if __name__ == '__main__': app.debug = False applogger = app.logger file_handler = FileHandler("error.log") file_handler.setLevel(logging.DEBUG) applogger.setLevel(logging.DEBUG) applogger.addHandler(file_handler) app.run(host='0.0.0.0')...
Why not do it like this: ``` if __name__ == '__main__': init_db() # or whatever you need to do import logging logging.basicConfig(filename='error.log',level=logging.DEBUG) app.run(host="0.0.0.0") ``` If you now start you application, you'll see that error.log contains: ``` INFO:werkzeug: * Running...
Flask logging - Cannot get it to write to a file
17,743,019
13
2013-07-19T09:46:46Z
17,787,567
9
2013-07-22T12:27:45Z
[ "python", "logging", "python-2.7", "flask" ]
Ok, here's the code where I setup everything: ``` if __name__ == '__main__': app.debug = False applogger = app.logger file_handler = FileHandler("error.log") file_handler.setLevel(logging.DEBUG) applogger.setLevel(logging.DEBUG) applogger.addHandler(file_handler) app.run(host='0.0.0.0')...
Ok, my failure stemmed from two misconceptions: 1) Flask will apparently ignore all your custom logging unless it is running in production mode 2) debug=False is not enough to let it run in production mode. You have to wrap the app in any sort of WSGI server to do so After i started the app from gevent's WSGI server...
How do I revert sys.stdout.close()?
17,743,052
2
2013-07-19T09:48:11Z
17,743,950
7
2013-07-19T10:31:12Z
[ "python" ]
In the interactive console: ``` >>> import sys >>> sys.stdout <open file '<stdout>', mode 'w' at 0xb7810078> >>> sys.stdout.close() >>> sys.stdout # confirming that it's closed (...) ValueError: I/O operation on closed file ``` Attempting to revert: ``` >>> sys.stdout.open() (...) AttributeError: 'file' object has n...
Okay, so I hope you are on a unix system... Basically sys.stdout is just a variable containing any writable object. So we can do magic like ``` sys.stdout = open("file", "w") ``` and now we can write to that file as if it was stdout. Knowing unix is just one big box of files. Unix is kind enough to give us `/dev/s...
Python 2: AttributeError: 'file' object has no attribute 'strip'
17,743,083
4
2013-07-19T09:49:55Z
17,743,099
14
2013-07-19T09:50:48Z
[ "python", "list", "split" ]
I have a **.txt** document called **new\_data.txt**. All data in this document separated by dots. I want to open my file inside python, split it and put inside a list. ``` output = open('new_data.txt', 'a') output_list = output.strip().split('.') ``` But I have an error: ``` AttributeError: 'file' object has no attr...
First, you want to open the file in read mode (you have it in append mode) Then you want to `read()` the file: ``` output = open('new_data.txt', 'r') # See the r output_list = output.read().strip().split('.') ``` This will get the whole content of the file. Currently you are working with the file object (hence the ...
Python logging module is printing lines multiple times
17,745,914
5
2013-07-19T12:18:48Z
17,745,953
9
2013-07-19T12:20:51Z
[ "python", "logging" ]
I have the following code: ``` import logging class A(object): def __init__(self): self._l = self._get_logger() def _get_logger(self): loglevel = logging.INFO l = logging.getLogger(__name__) l.setLevel(logging.INFO) h = logging.StreamHandler() f = logging.Format...
logger is created once, but multiple handlers are created. Create `A` once. ``` a = A() for msg in ["hey", "there"]: a.p(msg) ``` Or change `_get_logger` as follow: ``` def _get_logger(self): loglevel = logging.INFO l = logging.getLogger(__name__) if not getattr(l, 'handler_set', None): l.se...
Call the same function when clicking the Button and pressing enter
17,747,058
3
2013-07-19T13:15:27Z
17,747,152
8
2013-07-19T13:19:41Z
[ "python", "events", "python-3.x", "tkinter", "event-handling" ]
I have a GUI that has `Entry` widget and a submit `Button`. I am basically trying to use `get()` and print the values that are inside the `Entry` widget. I wanted to do this by clicking the *submit* `Button` or by pressing *enter* or *return* on keyboard. I tried to bind the `"<Return>"` event with the same function ...
You can create a function that takes any number of arguments like this: ``` def clickOrEnterSubmit(self, *args): #code goes here ``` This is called an [arbitrary argument list](http://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-lists). The caller is free to pass in as many arguments as they wis...
ValueError: negative number cannot be raised to a fractional power
17,747,124
12
2013-07-19T13:18:32Z
17,747,293
11
2013-07-19T13:26:37Z
[ "python" ]
When I tried this in terminal ``` >>> (-3.66/26.32)**0.2 ``` I got the following error ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: negative number cannot be raised to a fractional power ``` However, I am able to do this in two steps like, ``` >>> (-3.66/26.32) -0.139057...
Raising to a power takes precedence over the unary minus sign. So you have `-(0.13905775075987842 ** 0.2)` and not `(-0.13905775075987842) ** 0.2` as you expect: ``` >>> -0.13905775075987842 ** 0.2 -0.6739676327771593 >>> (-0.13905775075987842) ** 0.2 Traceback (most recent call last): File "<stdin>", line 1, in <m...
Correct way to check for empty or missing file in Python
17,747,330
8
2013-07-19T13:28:04Z
17,747,614
11
2013-07-19T13:42:02Z
[ "python", "python-2.7" ]
I want to check both whether a file exists and, if it does, if it is empty. If the file doesn't exist, I want to exit the program with an error message. If the file is empty I want to exit with a different error message. Otherwise I want to continue. I've been reading about using Try: Except: but I'm not sure how t...
I'd use [`os.stat`](http://docs.python.org/2/library/os.html#os.stat) here: ``` try: if os.stat(filename).st_size > 0: print "All good" else: print "empty file" except OSError: print "No file" ```
Daemon vs Upstart for python script
17,747,605
29
2013-07-19T13:41:27Z
17,836,284
52
2013-07-24T14:02:33Z
[ "python", "daemon", "upstart", "monit", "python-daemon" ]
I have written a module in Python and want it to run continuously once started and need to stop it when I need to update other modules. I will likely be using monit to restart it, if module has crashed or is otherwise not running. I was going through different techniques like [Daemon](https://pypi.python.org/pypi/pyth...
From your mention of Upstart I will assume that this question is for a service being run on an Ubuntu server. On an Ubuntu server an upstart job is really the simplest and most convenient option for creating an always on service that starts up at the right time and can be stopped or reloaded with familiar commands. T...
combine multiple text files into one text file using python
17,749,058
8
2013-07-19T14:46:42Z
17,749,339
20
2013-07-19T14:59:59Z
[ "python", "python-2.7", "python-3.x" ]
suppose we have many text files as follows: file1: ``` abc def ghi ``` file2: ``` ABC DEF GHI ``` file3: ``` adfafa ``` file4: ``` ewrtwe rewrt wer wrwe ``` How can we make one text file like below: result: ``` abc def ghi ABC DEF GHI adfafa ewrtwe rewrt wer wrwe ``` Related code may be: ``` import csv imp...
You can read the content of each file directly into the write method of the output file handle like this: ``` import glob read_files = glob.glob("*.txt") with open("result.txt", "wb") as outfile: for f in read_files: with open(f, "rb") as infile: outfile.write(infile.read()) ```
python script to concatenate all the files in the directory into one file
17,749,484
2
2013-07-19T15:08:05Z
17,749,560
16
2013-07-19T15:11:50Z
[ "python" ]
I have written the following script to concatenate all the files in the directory into one single file. Can this be optimized, in terms of 1. idiomatic python 2. time Here is the snippet: ``` import time, glob outfilename = 'all_' + str((int(time.time()))) + ".txt" filenames = glob.glob('*.txt') with open(outfil...
Use [`shutil.copyfileobj`](http://docs.python.org/2/library/shutil.html#shutil.copyfileobj) to copy data: ``` import shutil with open(outfilename, 'wb') as outfile: for filename in glob.glob('*.txt'): if filename == outfilename: # don't want to copy the output into the output conti...
Python library to generate regular expressions
17,749,987
8
2013-07-19T15:33:08Z
17,777,260
8
2013-07-21T21:46:04Z
[ "python", "regex" ]
Is there any lib out there that can take a text (like a html document) and a list of strings (like the name of some products) and then find a pattern in the list of strings and generate a regular expression that would extract all the strings in the text (html document) that match the pattern it found? For example, giv...
Your requirement is at the same time very specific and very general. I don't think you would ever find any library for your purpose unless you write your own. On the other hand, if you spend too much time writing regex, you could use some GUI tools to help you build them, like: <http://www.regular-expressions.info/re...
Django: display time it took to load a page on every page
17,751,163
29
2013-07-19T16:33:51Z
17,777,539
58
2013-07-21T22:19:19Z
[ "python", "django" ]
In Django, how can I return the time **it took to load a page** (not the date) in **every** page of the site, **without** having to **write in every views.py** a code similar to the following one? ``` start = time.time() #model operations loadingpagetime = time.time() - start ``` If using a `TEMPLATE_CONTEXT_PROCESSO...
You can create a custom [middleware](https://docs.djangoproject.com/en/dev/topics/http/middleware/) to log this. Here is how I create a middleware to achieve this purpose base on <http://djangosnippets.org/snippets/358/> (I modified the code a bit). Firstly, assuming your project has a name: `test_project`, create a f...
Django: display time it took to load a page on every page
17,751,163
29
2013-07-19T16:33:51Z
17,841,295
17
2013-07-24T17:51:25Z
[ "python", "django" ]
In Django, how can I return the time **it took to load a page** (not the date) in **every** page of the site, **without** having to **write in every views.py** a code similar to the following one? ``` start = time.time() #model operations loadingpagetime = time.time() - start ``` If using a `TEMPLATE_CONTEXT_PROCESSO...
[Geordi](https://bitbucket.org/brodie/geordi) gives you an awesome breakdown of everything that happens in the request cycle. It's a middleware that generates a full call-tree to show you exactly what's going on and how long is spent in each function. It looks like this: ![enter image description here](http://i.stack...
Python 2: AttributeError: 'list' object has no attribute 'strip'
17,751,322
6
2013-07-19T16:42:52Z
17,751,349
10
2013-07-19T16:44:19Z
[ "python", "list", "split" ]
I have a small problem with list. So i have a list called `l`: ``` l = ['Facebook;Google+;MySpace', 'Apple;Android'] ``` And as you can see I have only 2 strings in my list. I want to separate my list `l` by **';'** and put my new 5 strings into a new list called `l1`. How can I do that? And also I have tried to do...
[`strip()`](http://docs.python.org/2/library/string.html#string.strip) is a method for strings, you are calling it on a `list`, hence the error. ``` >>> 'strip' in dir(str) True >>> 'strip' in dir(list) False ``` To do what you want, just do ``` >>> l = ['Facebook;Google+;MySpace', 'Apple;Android'] >>> l1 = [elem.st...
Is there any way to access the result something never assigned?
17,751,652
4
2013-07-19T17:01:43Z
17,751,719
7
2013-07-19T17:05:07Z
[ "python", "python-3.x" ]
``` while int(input("choose a number")) != 5 : ``` Say I wanted to see what number was input. Is there an indirect way to get at that? EDIT Im probably not being very clear lol. . I know that in the debugger, you can step through and see what number gets input. Is there maybe a memory hack or something like it that l...
Nope - you have to assign it... Your example could be written using the two-argument style `iter` though: ``` for number in iter(lambda: int(input('Choose a number: ')), 5): print number # prints it if it wasn't 5... ```
PyGObject with GStreamer examples?
17,752,043
2
2013-07-19T17:25:10Z
17,756,669
7
2013-07-19T22:48:41Z
[ "python", "python-3.x", "gstreamer", "pygobject" ]
I'd like to see some examples that uses PyGObject and GStreamer, but I could not find anything on web. The only information available in the official website is the link to the source code for the Python binding: <http://gstreamer.freedesktop.org/modules/gst-python.html> As you can see in the page on the link above: ...
A good way to turn up examples using the introspected bindings offered by pygobject 3 (in contrast to the "old" static bindings offered by pygobject 2 and pygtk) is to use "gi.repository" as a search keyword. For example, searching for "gi.repository gst" quickly leads to [a simple media player](http://lzone.de/Media%2...
Difference between os.path.exists and os.path.isfile in python
17,752,078
16
2013-07-19T17:26:45Z
17,752,147
14
2013-07-19T17:30:30Z
[ "python", "file", "directory" ]
I'm curious when these two functions will return different values. Also if you could clarify the difference between a path/directory/file that would be appreciated.
As you have already found out, the difference between `exists` and `isfile` is the fact that the former returns `True` in case the given path is a directory **or** a file, while the latter only returns `True` if the path points to a file. **Directories** and **files** are quite similar from the technical point of view...
Dynamic form fields in flask.request.form
17,752,301
10
2013-07-19T17:40:42Z
17,752,717
15
2013-07-19T18:06:27Z
[ "python", "flask", "werkzeug" ]
I've looked through the documentation, but for the life of me, I can't figure out how the `request.form` object in Flask is populated. [The documentation](http://flask.pocoo.org/docs/api/#flask.Request.form) says that it's filled with parsed form data from POST or PUT requests, but my form is dynamic so I don't necessa...
`request.form` returns a `MultiDict` object. Basically, it means that for 1 key, you could have multiple values. If you want to test what your form POST looks like, just do a quick print statement as follows ``` f = request.form for key in f.keys(): for value in f.getlist(key): print key,":",value ``` If ...
How can I write C's do-while(0) in Python?
17,753,029
7
2013-07-19T18:25:07Z
17,753,143
7
2013-07-19T18:31:08Z
[ "python", "loops", "do-while" ]
In C there's a clever trick that lets you avoid pyramid-style code by turning: ``` if (check1()) if (check2()) if (check3()) do_something(); ``` into: ``` do { if (!check1()) break; if (!check2()) break; if (!check3()) break; do_something(); } while (0); ``` What's the cleanest wa...
The Pythonic way of writing this would be ``` if check1() and check2() and check3(): do_something() ``` In Python we emphasize clarity and simplicity of the code, not using clever programming tricks. --- **[Edit]** If you need to *"create a variable and use it in the first check"*, then you would use the pyrami...
Can I have a Django form without Model
17,754,295
15
2013-07-19T19:46:23Z
17,754,333
20
2013-07-19T19:48:37Z
[ "python", "django", "django-models", "django-forms", "django-views" ]
Can I have a Form in my template which is not backed by a model. I do not need to store the data just need that data to generate a POST request of my own in the view. Template - The form with text fields. View - get data from form, and generate another request. Flow --> Form submit takes to a url which calls the view...
Yes. This is very much possible. You can read up on [Form objects](https://docs.djangoproject.com/en/dev/topics/forms/#form-objects). It would be the same way you would treat a `ModelForm`, except that you are not bound by the model, and you have to explicitly declare all the form attributes. ``` def form_handle(reque...
Elegant way to unpack limited dict values into local variables in Python
17,755,178
8
2013-07-19T20:44:27Z
17,755,259
15
2013-07-19T20:50:01Z
[ "python" ]
I'm looking for an elegant way to extract some values from a Python dict into local values. Something equivalent to this, but cleaner for a longer list of values, and for longer key/variable names: ``` d = { 'foo': 1, 'bar': 2, 'extra': 3 } foo, bar = d['foo'], d['bar'] ``` I was originally hoping for something like...
You can do something like ``` foo, bar = map(d.get, ('foo', 'bar')) ``` or ``` foo, bar = itemgetter('foo', 'bar')(d) ``` This may save some typing, but essentially is the same as what you are doing (which is a good thing).
Python: list() as default value for dictionary
17,755,996
9
2013-07-19T21:43:53Z
17,756,005
20
2013-07-19T21:44:38Z
[ "python", "dictionary", "default-value" ]
I have Python code that looks like: ``` if key in dict: dict[key].append(some_value) else: dict[key] = [some_value] ``` but I figure there should be some method to get around this 'if' statement. I tried ``` dict.setdefault(key, []) dict[key].append(some_value) ``` and ``` dict[key] = dict.get(key, []).append(...
The best method is to use [`collections.defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict) with a `list` default: ``` from collections import defaultdict dct = defaultdict(list) ``` Then just use: ``` dct[key].append(some_value) ``` and the dictionary will create a new list for...
Make all new directories have 777 permissions
17,756,585
3
2013-07-19T22:39:24Z
17,756,652
9
2013-07-19T22:46:58Z
[ "python", "perl", "unix", "file-permissions" ]
I have a script that, when run, creates a directory inside `/home/test/` and then writes some files in it. When I run this script, it works fine. However, when I call it from a perl script with ``` $ret = `/home/..../testscript.py` ``` it doesn't have permissions so it can't create the folder, or can't write inside i...
Put: ``` os.umask(0000) ``` in the Python script before it creates the directory. If you can't change the Python script, put: ``` umask(0000) ``` in the Perl script before it calls the Python script. When a new file or directory is created, the permissions are determined by taking the permissions specified in the ...
How to plot heatmap colors in 3D in Matplotlib
17,756,925
2
2013-07-19T23:18:17Z
17,756,969
7
2013-07-19T23:24:18Z
[ "python", "matplotlib", "plot", "heatmap" ]
I am using Matplotlib 3D to plot 3 dimensions of my dataset like below: ![enter image description here](http://i.stack.imgur.com/vstvD.png) But now I also want to visualize a 4th dimension (which is a scalar value between 0 to 20) as a heatmap. So basically, I want each point to take it's color based on this 4th dimen...
Yes, something like this: **update** here is a version with a colorbar. ``` import numpy as np from pylab import * from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt def randrange(n, vmin, vmax): return (vmax-vmin)*np.random.rand(n) + vmin fig = plt.figure(figsize=(8,6)) ax = fig.add_subpl...
What does the Python version line mean?
17,757,819
13
2013-07-20T01:39:55Z
17,757,935
16
2013-07-20T01:59:31Z
[ "python", "32bit-64bit" ]
What does the line that's displayed when you start an instance of the Python interpreter mean? ``` Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32 ``` So I know I have Python 2.7, but what about the rest? Especially confusing to me are the `64 bit (AMD64) on win32` and `r27:82525` ...
That line you see indicates how the python interpreter was built. Breaking it down: ``` Python 2.7 -- Python version (r27:82525, Jul 4 2010, 07:43:08) -- The build date and revision from src trunk that was used to build this. [MSC v.1500 64 bit (AMD64)] ...
return rows in a dataframe closest to a user-defined number
17,758,023
7
2013-07-20T02:18:41Z
17,758,115
18
2013-07-20T02:38:02Z
[ "python", "python-2.7", "pandas" ]
I have a user defined number which I want to compare to a certain column of a dataframe. I would like to return the rows of a dataframe which contain (in a certain column of df, say, df.num) the 5 closest numbers to the given number x. Any suggestions for the best way to do this without loops would be greatly appreci...
I think you can use the [`argsort`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.argsort.html) method: ``` >>> df = pd.DataFrame({"A": 1e4*np.arange(100), "num": np.random.random(100)}) >>> x = 0.75 >>> df.ix[(df.num-x).abs().argsort()[:5]] A num 66 660000 0.748261 92 920000 0.75...
PyMysql UPDATE query
17,758,074
4
2013-07-20T02:29:36Z
17,758,158
8
2013-07-20T02:47:09Z
[ "python", "mysql", "sql-update", "pymysql" ]
I've been trying using PyMysql and so far everything i did worked (Select/insert) but when i try to update it just doesn't work, no errors no nothing, just doesn't do anything. ``` import pymysql connection = pymysql.connect(...) cursor = connection.cursor() cursor.execute("UPDATE Users SET IsConnected='1' WHERE Usern...
When you execute your update, MySQL is implicitly starting a transaction. You need to commit this transaction by calling `connection.commit()` after you execute your update to keep the transaction from automatically rolling back when you disconnect. MySQL (at least when using the InnoDB engine for tables) supports [tr...
Python: EOFError: EOF when reading a line
17,758,782
8
2013-07-20T04:52:43Z
17,758,807
16
2013-07-20T04:57:10Z
[ "python", "text", "python-2.7", "compiler-construction", "sublimetext2" ]
This may be repeated, but none of the existing answers solved my problem. So, I'm using `Python 2.7`, and I get this error (title) whenever I try this: ``` number = int(raw_input('Number : ')) ``` I tried this in Sublime Text 2, compileronline.com and in codecademy; it fails in the first 2 of this sites. It works on...
[The issue here is that Sublime text 2's console doesn't support input.](http://www.bestpythonide.com/python-input-eoferror-in-sublime-text-2.html) To fix this issue, you can install a package called [SublimeREPL](http://sublimerepl.readthedocs.org/en/latest/). SublimeREPL provides a Python interpreter that takes in i...
Python pandas stuck at version 0.7.0
17,759,128
13
2013-07-20T05:48:46Z
17,779,230
20
2013-07-22T02:54:35Z
[ "python", "pandas" ]
First off, I'm a novice... I'm a newbie to Python, pandas, and Linux. I'm getting some errors when trying to populate a DataFrame (sql.read\_frame() gives an exception when trying to read from my MySQL DB, but I am able to execute and fetch a query / stored proc). I noticed that pandas is at version 0.7.0, and running...
As nitin points out, you can simply upgrade pandas using pip: ``` pip install --upgrade pandas ``` Since this version of pandas will be installed in `site-packages`, you will in fact be at the mercy of any automatic updates to packages within that directory. To get around this, it's wise to install the versions of pa...
Python under Mac OS X: Framework
17,759,740
10
2013-07-20T07:12:13Z
17,760,868
31
2013-07-20T09:43:47Z
[ "python", "osx", "frameworks", "xcode4.5", "homebrew" ]
I like to use Python with numpy, scipy and some other packages. I am an absolute Python beginner and have some issues with the installation under Mac OS X. I am following these two tutorials to install python: [1](http://hackercodex.com/guide/mac-osx-mountain-lion-10.8-configuration/) and [2](http://hackercodex.com/gu...
1. The Apple Python is functional and the normal site-packages folder is */Library/Python/2.7/site-packages* (and not */System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages*). You can use it without problem. 2. I never had any problem to install all modules (numpy, scipy, matplotlib, pand...
Django regex validator message has no effect
17,760,367
5
2013-07-20T08:34:45Z
17,761,914
16
2013-07-20T11:45:27Z
[ "python", "django" ]
I am trying to get it so that the validator tells you "username must be alphanumeric". This is my code so far. I have confirmed that it validates at the correct time. The only problem is that no matter what I try, The RegexValidator still chucks the default error ("enter a valid value"). This is my code. I also tried ...
How about adding the error code: ``` user = CharField( max_length=30, required=True, validators=[ RegexValidator( regex='^[a-zA-Z0-9]*$', message='Username must be Alphanumeric', code='invalid_username' ), ] ) ```
Python Tkinter PhotoImage
17,760,871
3
2013-07-20T09:44:02Z
17,761,218
7
2013-07-20T10:24:05Z
[ "python", "class", "tkinter" ]
This is the format of code I currently have: ``` import Tkinter as tk class mycustomwidow: def __init__(self,parent,......) ...... ...... tk.Label(parent,image=Myimage) tk.pack(side='top') def main(): root=tk.Tk() mycustomwindow(root) root.mainlopp() if __name__ == '_...
It does not matter much where you declare the image, as long as 1. you create it *after* initializing `Tk()` (the problem in your first approach) 2. the image is *in the variable scope* when you are using it (the problem in your second approach) 3. the image object does *not get garbage-collected* (another [common](ht...
Is Python dict an Object?
17,761,202
8
2013-07-20T10:21:56Z
17,761,240
19
2013-07-20T10:25:56Z
[ "python", "dictionary" ]
I have a `dict` like this: ``` >>> my_dict = {u'2008': 6.57, u'2009': 4.89, u'2011': 7.74, ... u'2010': 7.44, u'2012': 7.44} ``` Output with `has_key`: ``` >>> my_dict.has_key(unicode(2012)) True ``` Output with `hasattr`: ``` >>> hasattr(my_dict, unicode(2012)) False ``` I couldn't understand why this...
`dict` instances are objects too. But their keys are just not exposed as as attributes. Exposing the keys as attributes (too or instead of item access) would lead to namespace pollution; you'd never be able to use a `has_key` key, for example. `has_key` is *already* an attribute on dictionaries: ``` >>> hasattr({}, '...
MapperParsingException: No handler for type [date_hour_minute_second] declared on field
17,761,685
2
2013-07-20T11:19:12Z
17,763,505
11
2013-07-20T14:59:07Z
[ "python", "elasticsearch", "pyes" ]
I am developing a driver with Python Pyes client for Elasticsearch. I need mapping indexes with a date column has format No "date\_hour\_minute\_second" based on docs <http://www.elasticsearch.org/guide/reference/mapping/date-format/> also I check pyes docs <https://pyes.readthedocs.org/en/latest/guide/reference/mappin...
I think you have put the mapping in slightly wrong, the `"date"` you have is the field name, you also need `"type": "date"` Try this: ``` "date": { "type": "date", "format": "date_hour_minute_second_fraction", "store": "yes" } ``` `"boost"` is 1.0 by default, so not needed. Also I would question why you ...
python: sys is not defined
17,761,697
8
2013-07-20T11:21:24Z
17,761,735
16
2013-07-20T11:23:55Z
[ "python", "sys" ]
I have a piece of code which is working in Linux, and I am now trying to run it in windows, I import sys but when I use sys.exit(). I get an error, sys is not defined. Here is the begining part of my code ``` try: import numpy as np import pyfits as pf import scipy.ndimage as nd import pylab as pl ...
Move `import sys` *outside* of the `try`-`except` block: ``` import sys try: # ... except ImportError: # ... ``` If any of the imports *before* the `import sys` line fails, the *rest* of the block is not executed, and `sys` is never imported. Instead, execution jumps to the exception handling block, where you...
TypeError: 'int' object is not callable,,, len()
17,762,210
4
2013-07-20T12:20:35Z
17,762,220
15
2013-07-20T12:22:14Z
[ "python", "python-2.7", "int" ]
I wrote a program to play hangman---it's not finished but it gives me an error for some reason... ``` import turtle n=False y=True list=() print ("welcome to the hangman! you word is?") word=raw_input() len=len(word) for x in range(70): print print "_ "*len while n==False: while y==True: print "insert ...
You assigned to a local name `len`: ``` len=len(word) ``` Now `len` is an integer and shadows the built-in function. You want to use a *different* name there instead: ``` length = len(word) # other code print "_ " * length ``` Other tips: * Use `not` instead of testing for equality to `False`: ``` while not n...
Cannot show image from STATIC_FOLDER in Flask template
17,764,156
8
2013-07-20T16:18:52Z
17,765,064
18
2013-07-20T17:58:16Z
[ "python", "flask" ]
I set folder for static files like this ``` app.config['STATIC_FOLDER'] = 'tmp' ``` In template i use img tag to show an image stored in /tmp: ``` <img src='IKE2low.jpg' width="200" height="85"> ``` In firebug i see 404 error instead of image. Please tell me what did i do wrong? Thanks in advance.
I'm not sure what is this `STATIC_FOLDER` configuration item you are using. Where did you find it? There are actually two arguments to the `Flask` class constructor that govern the configuration of static files: * **static\_folder**: defaults to "static". This is the prefix that you have to use in URLs to access the ...
pandas dataframe group year index by decade
17,764,619
5
2013-07-20T17:12:27Z
17,764,741
12
2013-07-20T17:24:52Z
[ "python", "pandas" ]
suppose I have a dataframe with index as monthy timestep, I know I can use `dataframe.groupby(lambda x:x.year)` to group monthly data into yearly and apply other operations. Is there some way I could quick group them, let's say by decade? thanks for any hints.
To get the decade, you can integer-divide the year by 10 and then multiply by 10. For example, if you're starting from ``` >>> dates = pd.date_range('1/1/2001', periods=500, freq="M") >>> df = pd.DataFrame({"A": 5*np.arange(len(dates))+2}, index=dates) >>> df.head() A 2001-01-31 2 2001-02-28 7 2001-03...
Avoid using global without confusing new programming students in Python?
17,765,560
9
2013-07-20T18:51:41Z
17,765,647
7
2013-07-20T19:00:05Z
[ "python", "python-3.x" ]
I've been teaching 8th-9th graders basic computer programming for two weeks, and yesterday I tried to show them how they could make real simple text-adventure games in Python. Scenes are functions, (e.g `dragons_cave()`) which consist of some print statements and then a call to `input()`, asking the player where they ...
I would encourage them to start learning OO ``` class Location: name="a place" description = "A dark place. there are exits to the North and East" exits = "North","East" def __str__(self): return "%s\n%s"%(self.name,self.description) class Player: current_location = "Home" inv...
How do I ensure that re.findall() stops at the right place?
17,765,805
8
2013-07-20T19:15:03Z
17,765,823
13
2013-07-20T19:16:56Z
[ "python", "regex", "python-2.7", "findall" ]
Here is the code I have: ``` a='<title>aaa</title><title>aaa2</title><title>aaa3</title>' import re re.findall(r'<(title)>(.*)<(/title)>', a) ``` The result is: ``` [('title', 'aaa</title><title>aaa2</title><title>aaa3', '/title')] ``` If I ever designed a crawler to get me titles of web sites, I might end up with ...
Use `re.search` instead of `re.findall` if you only want one match: ``` >>> s = '<title>aaa</title><title>aaa2</title><title>aaa3</title>' >>> import re >>> re.search('<title>(.*?)</title>', s).group(1) 'aaa' ``` If you wanted all tags, then you should consider changing it to be non-greedy (ie - `.*?`): ``` print re...
Python gets Killed (probably memory leak)
17,766,142
8
2013-07-20T19:57:30Z
17,766,202
8
2013-07-20T20:04:32Z
[ "python" ]
I have been working on this for a few weeks now and I've read many questions about python memory leak but I just can't figure it out. I have a file that contains about 7 million lines. For each line, I need to create a dictionary. So this is a list of dictionary that looks like: ``` [{'a': 2, 'b':1}{'a':1, 'b':2, 'c'...
Try: ``` from collections import Counter with open('input') as fin: term_counts = [Counter(line.split()) for line in fin] ``` I believe this is what you're trying to achieve with your code. This avoids the `.readlines()` loading the file into memory first, utilises `Counter` to do the counting and builds the lis...
403 Forbidden error with Django and mod_wsgi
17,766,595
25
2013-07-20T20:52:57Z
19,448,643
37
2013-10-18T11:31:02Z
[ "python", "django", "apache2", "mod-wsgi" ]
I created Django project in home directory so it is in home directory. **Setup** ``` Django Verison : 1.5.1 Python Version : 2.7.5 mod_wsgi Version: 3.4 Home Directory : /home/aettool ``` **Contents of `/home/aettool/aet/apache/django.wsgi`** ``` import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'aet.s...
Apparently this is an issue that is related to Apache 2.4 and older versions. You need to replace in your apache configuration: ``` Allow from all ``` with ``` Require all granted ``` in the `<Files wsgi.py>` section
403 Forbidden error with Django and mod_wsgi
17,766,595
25
2013-07-20T20:52:57Z
19,648,902
16
2013-10-29T03:02:41Z
[ "python", "django", "apache2", "mod-wsgi" ]
I created Django project in home directory so it is in home directory. **Setup** ``` Django Verison : 1.5.1 Python Version : 2.7.5 mod_wsgi Version: 3.4 Home Directory : /home/aettool ``` **Contents of `/home/aettool/aet/apache/django.wsgi`** ``` import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'aet.s...
You can use the following: ``` <Directory /home/aettool/aet/apache> <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> </Directory> ```
How to re-install lxml?
17,766,725
10
2013-07-20T21:11:35Z
19,613,627
8
2013-10-27T01:12:18Z
[ "python", "beautifulsoup", "lxml", "easy-install" ]
I am using python 2,7.5 on mac 10.7.5, beautifulsoup 4.2.1. I am going to parse a xml page using the lxml library, as taught in the beautifulsoup tutorial. However, when I run my code, it shows ``` bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml,xml. Do you need to install a par...
I am using BeautifulSoup 4.3.2 and OS X 10.6.8. I also have a problem with improperly installed `lxml`. Here are some things that I found out: First of all, check this related question: [Removed MacPorts, now Python is broken](http://stackoverflow.com/questions/14153221/removed-macports-now-python-is-broken) Now, in ...
How can I take the square root of -1 using python?
17,766,774
2
2013-07-20T21:16:45Z
17,767,080
17
2013-07-20T21:54:59Z
[ "python", "numpy" ]
When I take the square root of -1 it gives me an error: > invalid value encountered in sqrt How do I fix that? ``` ///////// arr=sqrt(-1) print(arr) OUTPUT ```
To avoid the `invalid value` warning/error, the argument to numpy's `sqrt` function must be complex: ``` In [8]: import numpy as np In [9]: np.sqrt(-1+0j) Out[9]: 1j ``` As @AshwiniChaudhary pointed out in a comment, you could also use the `cmath` standard library: ``` In [10]: cmath.sqrt(-1) Out[10]: 1j ```
defaultdict is not defined
17,767,084
7
2013-07-20T21:55:28Z
17,767,101
12
2013-07-20T21:57:45Z
[ "python", "python-3.x" ]
Using python 3.2. ``` import collections d = defaultdict(int) ``` run ``` NameError: name 'defaultdict' is not defined ``` Ive restarted Idle. I know collections is being imported, because typing ``` collections ``` results in ``` <module 'collections' from '/usr/lib/python3.2/collections.py'> ``` also help(col...
``` >>> import collections >>> d = collections.defaultdict(int) >>> d defaultdict(<type 'int'>, {}) ``` It might behoove you to read about [the `import` statement](http://docs.python.org/2/reference/simple_stmts.html#the-import-statement).
defaultdict is not defined
17,767,084
7
2013-07-20T21:55:28Z
17,767,102
11
2013-07-20T21:57:46Z
[ "python", "python-3.x" ]
Using python 3.2. ``` import collections d = defaultdict(int) ``` run ``` NameError: name 'defaultdict' is not defined ``` Ive restarted Idle. I know collections is being imported, because typing ``` collections ``` results in ``` <module 'collections' from '/usr/lib/python3.2/collections.py'> ``` also help(col...
You're not importing `defaultdict`. Do either: ``` from collections import defaultdict ``` or ``` import collections d = collections.defaultdict(list) ```
Relative order of elements in list
17,767,646
9
2013-07-20T23:21:09Z
17,767,662
11
2013-07-20T23:23:46Z
[ "python", "list", "order", "relative" ]
I'm writing a function that takes in a list of integers and returns a list of relative positioned elements. That is to say, if my input into said function is *[1, 5, 4]* the output would be *[0, 2, 1]*, since 1 is the lowest element, 5 is the highest and 4 in the middle, all elements are unique values, or a *set()* B...
This can be written as a list comprehension like this: ``` lst = [1, 5, 4] s = sorted(lst) [s.index(x) for x in lst] => [0, 2, 1] ``` And here's another test, using @frb's example: ``` lst = [10, 2, 3, 9] s = sorted(lst) [s.index(x) for x in lst] => [3, 0, 1, 2] ```
Relative order of elements in list
17,767,646
9
2013-07-20T23:21:09Z
17,767,859
10
2013-07-21T00:04:06Z
[ "python", "list", "order", "relative" ]
I'm writing a function that takes in a list of integers and returns a list of relative positioned elements. That is to say, if my input into said function is *[1, 5, 4]* the output would be *[0, 2, 1]*, since 1 is the lowest element, 5 is the highest and 4 in the middle, all elements are unique values, or a *set()* B...
Here's another go that should be more efficient that keeping `.index`'ing into the list as it's stated that no duplicate values will occur, so we can do the lookup O(1) instead of linear... (and actually meets the requirements): ``` >>> a = [10, 2, 3, 9] >>> indexed = {v: i for i, v in enumerate(sorted(a))} >>> map(in...
How to cast string back into a list
17,768,509
6
2013-07-21T02:31:57Z
17,768,535
12
2013-07-21T02:35:12Z
[ "python", "string", "list", "casting" ]
I have a list: ``` ab = [1, 2, a, b, c] ``` I did: ``` strab = str(ab). ``` So `strab` is now a string. I want to cast that string back into a list. How can I do that?
The easiest and safest way would be to use [`ast.literal_eval()`](http://docs.python.org/2/library/ast.html#ast.literal_eval): ``` import ast ab = [1, 2, 'a', 'b', 'c'] # a list strab = str(ab) # the string representation of a list strab => "[1, 2, 'a', 'b', 'c']" lst = ast.literal_eval(strab) # con...
Target database is not up to date
17,768,940
17
2013-07-21T04:07:17Z
17,776,558
20
2013-07-21T20:25:44Z
[ "python", "postgresql", "sqlalchemy", "migration", "flask" ]
I'd like to make a migration for a Flask app. I am using Alembic. However, I receive the following error. ``` Target database is not up to date. ``` Online, I read that it has something to do with this. <https://alembic.readthedocs.org/en/latest/tutorial.html#building-an-up-to-date-database-from-scratch> Unfortunat...
After creating a migration, either manually or as `--autogenerate`, you must apply it with `alembic upgrade head`. If you used `db.create_all()` from a shell, you can use `alembic stamp head` to indicate that the current state of the database represents the application of all migrations.
Print Python Exception Type (Raised in Fabric)
17,769,405
4
2013-07-21T05:32:52Z
17,769,459
7
2013-07-21T05:42:59Z
[ "python", "exception", "python-2.7", "exception-handling" ]
I'm using Fabric to automate, including the task of creating a directory. Here is my fabfile.py: ``` #!/usr/bin/env python from fabric.api import * def init(): try: local('mkdir ./www') except ##what exception?##: #print exception name to put in above ``` Run fab `fabfile.py` and f I already ...
The issue is that fabric uses subprocess for doing these sorts of things. If you look at the source code for `local` you can see it doesn't actually raise an exception. It calls suprocess.Popen and uses `communicate()` to read stdout and stderr. If there is a non-zero return code then it returns a call to either `warn`...
Something I do not understand about dictionaries
17,772,254
2
2013-07-21T12:18:59Z
17,772,284
7
2013-07-21T12:21:44Z
[ "python" ]
When I was trying to understand Python dictionaries, I compared the output of two programs. I don't understand why the output is different. Both programs start with ``` data = { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } ``` First program: ``` for keys in data.items(): ...
`dict.items` returns a sequence of 2-tuples, of (key, value). What happens in the first example is that you're taking a single element from the that at at time, which in this case is the whole tuple (key, value). When you use `for key, value in` Python performs "unpacking" which means it assigns the first element of t...
How to call a python script from a web page
17,772,623
3
2013-07-21T13:05:33Z
17,772,652
9
2013-07-21T13:09:35Z
[ "php", "python", "python-2.7", "web", "json-rpc" ]
I'm pretty new to Python and Web applications, so I apologize for possible terms/keywords mix up. I have a Python script that runs a json-rpc server, exporting some management APIs of a device. I've written another Python script to implement a CLI control application (using Python's cmd module). Everything is run in a...
You can run a python script via php, and outputs on browser. Basically you have to call the python script this way: ``` $command = "python /path/to/python_script.py 2>&1"; $pid = popen( $command,"r"); while( !feof( $pid ) ) { echo fread($pid, 256); flush(); ob_flush(); usleep(100000); } pclose($pid); ``` Note: i...
Getting a list of values from a list of dict in python: Without using list comprehension
17,773,230
2
2013-07-21T14:11:43Z
17,773,259
10
2013-07-21T14:15:02Z
[ "python" ]
I have a list of dict for example, ``` [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name': u'Sports'}] ``` Now, I have to retrieve the following list from this dict without using list comprehension ``` [u'Library', u'Arts', u'Sports'] ``` Is there any way to achieve this in python? I s...
You could use `itemgetter`: ``` from operator import itemgetter categories = map(itemgetter('name'), things) ``` But a list comprehension is good too. What's wrong with list comprehensions?
Real world example of using os.plock?
17,773,782
3
2013-07-21T15:13:04Z
17,773,820
7
2013-07-21T15:17:47Z
[ "python", "locking" ]
Are there any real world usages for using [`os.plock`](http://docs.python.org/3.3/library/os.html#os.plock) from a Python application? I really can't imagine for what it could be used, not even talking about real world use cases...
The thing that you would normally use process or memory locking for is to avoid the OS swapping to disk. In the case of a memlock this could be data used for cryptographic purposes that shouldn't be written (even temporarily) to a form of more permanent storage. In the case of a large process, this could also include t...
File upload - Bad request (400)
17,774,216
7
2013-07-21T16:06:38Z
25,099,285
14
2014-08-02T20:49:47Z
[ "python", "django" ]
When I try to upload file via FileField of my model using Django administration I get following response from Django development server: ``` <h1>Bad Request (400)</h1> ``` The only output in console is: ``` [21/Jul/2013 17:55:23] "POST /admin/core/post/add/ HTTP/1.1" 400 26 ``` I have tried to find an error log, bu...
In my case it was a leading '/' character in models.py. Changed `/products/` to `products/` in: `product_image = models.ImageField(upload_to='products/')`
Python list comprehension: list sub-items without duplicates
17,774,394
2
2013-07-21T16:24:06Z
17,774,436
10
2013-07-21T16:28:23Z
[ "python" ]
I am trying to print all the letters in all the words in a list, without duplicates. ``` wordlist = ['cat','dog','rabbit'] letterlist = [] [[letterlist.append(x) for x in y] for y in wordlist] ``` The code above generates `['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']`, while I am looking for `['c', 'a...
Do you care about maintaining order? ``` >>> wordlist = ['cat','dog','rabbit'] >>> set(''.join(wordlist)) {'o', 'i', 'g', 'd', 'c', 'b', 'a', 't', 'r'} ```
can %s be an integer? *Python code*
17,775,742
2
2013-07-21T18:55:40Z
17,775,768
11
2013-07-21T18:57:56Z
[ "python" ]
Looking at this django code from the djangobook: ``` from django.http import Http404, HttpResponse import datetime def hours_ahead(request, offset): try: offset = int(offset) except ValueError: raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = "<htm...
`%s` calls the `str()` method on its corresponding argument... (similar to `%r` calls `repr()`) - so either of those can be used for *any* object... Unlike `%d` (`%i` is the same) and `%f` for instance which will require appropriate types.
Python's "re" module not working?
17,776,670
6
2013-07-21T20:38:46Z
17,776,699
9
2013-07-21T20:41:31Z
[ "python", "string", "get" ]
I'm using Python's "re" module as follows: ``` request = get("http://www.allmusic.com/album/warning-mw0000106792") print re.findall('<hgroup>(.*?)</hgroup>', request) ``` All I'm doing is getting the HTML of [this site](http://www.allmusic.com/album/warning-mw0000106792), and looking for this particular snippet of co...
The HTML you are parsing is on multiple lines. You need to pass the `re.DOTALL` flag to `findall` like this: ``` print re.findall('<hgroup>(.*?)</hgroup>', request, re.DOTALL) ``` This allows `.` to match newlines, and returns the correct output. @jsalonen is right, of course, that parsing HTML with regex is a trick...
How to add elements from a dictonary of lists in python
17,777,182
2
2013-07-21T21:36:39Z
17,777,202
9
2013-07-21T21:38:30Z
[ "python" ]
given a dictionary of lists ``` vd = {'A': [1,0,1], 'B':[-1,0,1], 'C':[0,1,1]} ``` I want to add the lists element wise. So I want to add first element from list A to first element of list B vice versa the complexity is that you cannot rely on the labels being A, B, C. It can be anything. second the length of the dic...
So you just want to add up all the values elementwise? `[sum(l) for l in zip(*vd.values())]`
zip variable empty after first use
17,777,219
4
2013-07-21T21:41:12Z
17,777,230
7
2013-07-21T21:42:33Z
[ "python", "python-3.x" ]
Python 3.2.3, using Idle, Python shell ``` t = (1,2,3) t2 = (5,6,7) z = zip(t,t2) for x in z : print(x) ``` result : (1,5) (2,6) (3,7) Putting in EXACTLY the same loop code to display z in a for loop again, immediately after (doing nothing between the above and next part) : ``` for x in z : print(x) ``` r...
That's how it works in python 3.x. In python2.x, `zip` returned a list of tuples, but for python3.x, `zip` behaves like `itertools.izip` behaved in python2.x. To regain the python2.x behavior, just construct a list from `zip`'s output: ``` z = list(zip(t,t2)) ``` Note that in python3.x, a lot of the builtin functions...
How to remove every other element of an array in python? (The inverse of np.repeat()?)
17,777,482
15
2013-07-21T22:13:02Z
17,777,520
31
2013-07-21T22:16:48Z
[ "python", "arrays", "numpy" ]
If I have an array x, and do an `np.repeat(x,2)`, I'm practically duplicating the array. ``` >>> x = np.array([1,2,3,4]) >>> np.repeat(x, 2) array([1, 1, 2, 2, 3, 3, 4, 4]) ``` How can I do the opposite so that I end up with the original array? It should also work with a random array y: ``` >>> y = np.array([1,...
`y[1::2]` should do the job. Here the second element is chosen by indexing with 1, and then taken at an interval of 2.
Replacing a string with counts of streaks
17,777,749
4
2013-07-21T22:51:40Z
17,777,771
15
2013-07-21T22:54:34Z
[ "python", "string", "list" ]
Let's say I have a string of the following form: ``` "000000111100011100001011000000001111" ``` and I want to create a list containing the lengths of the 1-streaks: ``` [4, 3, 1, 2, 4] ``` Is there a nice one-liner for this?
If you don't mind the `from itertools import groupby`... ``` >>> from itertools import groupby >>> [len(list(g)) for k, g in groupby(s) if k == '1'] [4, 3, 1, 2, 4] ```
Python requests arguments/dealing with api pagination
17,777,845
6
2013-07-21T23:04:26Z
17,777,982
8
2013-07-21T23:23:30Z
[ "python", "api", "http", "pagination", "python-requests" ]
I'm playing around with the Angel List (AL) API and want to pull all jobs in San San Francisco. Since I couldn't find an active Python wrapper for the api (if I make any headway, I think I'd like to make my own), I'm using the requests library. The AL API's results are paginated, and I can't figure out how to move bey...
Read `last_page` and make a get request for each page in the range: ``` import requests r_sanfran = requests.get("https://api.angel.co/1/tags/1664/jobs").json() num_pages = r_sanfran['last_page'] for page in range(2, num_pages + 1): r_sanfran = requests.get("https://api.angel.co/1/tags/1664/jobs", params={'page'...
Append a dictionary in Python
17,778,028
3
2013-07-21T23:31:38Z
17,778,033
7
2013-07-21T23:32:50Z
[ "python", "list" ]
How can I append a dictionary like the following in Python? ``` list1 = {'value1':1} list2 = {'value2':2} list1.append(list2) ``` When appending: ``` 'dict' object has no attribute 'append' ``` How can I join both list then?
These are dictionaries, not lists. Try `list1.update(list2)` The semantics of update and append are different, because the underlying data structures are different. Values for existing keys in the dictionary will be overwritten by their values in the argument dictionary. The section of the Python Tutorial on [Data S...
Why does my python function return None?
17,778,372
11
2013-07-22T00:29:02Z
17,778,390
23
2013-07-22T00:31:19Z
[ "python", "function", "return" ]
This may be an easy question to answer, but I can't get this simple program to work and it's driving me crazy. I have this piece of code: ``` def Dat_Function(): my_var = raw_input("Type \"a\" or \"b\": ") if my_var != "a" and my_var != "b": print "You didn't type \"a\" or \"b\". Try again." ...
It is returning `None` because when you recursively call it: ``` if my_var != "a" and my_var != "b": print "You didn't type \"a\" or \"b\". Try again." print " " Dat_Function() ``` ..you don't return the value. So while the recursion does happen, the return value gets discarded, and then you fall off t...
List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?
17,778,394
7
2013-07-22T00:31:30Z
17,778,786
7
2013-07-22T01:43:58Z
[ "python", "pandas" ]
How do you find the top correlations in a correlation matrix with Pandas? There are many answers on how to do this with R ([Show correlations as an ordered list, not as a large matrix](http://stackoverflow.com/questions/7074246/show-correlations-as-an-ordered-list-not-as-a-large-matrix) or [Efficient way to get highly ...
You can use `DataFrame.values` to get an numpy array of the data and then use NumPy functions such as `argsort()` to get the most correlated pairs. But if you want to do this in pandas, you can `unstack` and `order` the DataFrame: ``` import pandas as pd import numpy as np shape = (50, 4460) data = np.random.normal...
Make one PDF file of Python documentation
17,780,713
6
2013-07-22T05:48:16Z
17,781,138
10
2013-07-22T06:23:26Z
[ "python", "documentation", "python-sphinx" ]
The Python official site offers PDF documentation downloads, but they are separated by chapters. I downloaded the source code and built the PDF documentation, which were separate PDFs also. How can I **build one PDF file from the Makefile in the source code**? I think that would be more convenient to read. If concate...
If you already have PDFs, there is no need to re-create them. Instead, use something like [PDF Split & Merge](http://pdfmerge.sourceforge.net/) or [PDFArchitect](http://www.pdfarchitect.org/). --- edit --- Since the above mentioned solutions work only partially, I googled a bit and found [sejda](http://www.sejda.org/...
Why doesn't requests.get() return? What is the default timeout that requests.get() uses?
17,782,142
36
2013-07-22T07:31:57Z
17,782,541
48
2013-07-22T07:59:49Z
[ "python", "get", "python-requests" ]
In my script, `requests.get` never returns: ``` import requests print ("requesting..") # This call never returns! r = requests.get( "http://www.justdial.com", proxies = {'http': '222.255.169.74:8080'}, ) print(r.ok) ``` What could be the possible reason(s)? Any remedy? What is the default timeout that `get...
> What is the default timeout that get uses? I believe the timeout is `None`, which means it'll wait (hang) until the connection is closed. What happens when you pass in a timeout value? ``` r = requests.get( 'http://www.justdial.com', proxies={'http': '222.255.169.74:8080'}, timeout=5 ) ```
Why doesn't requests.get() return? What is the default timeout that requests.get() uses?
17,782,142
36
2013-07-22T07:31:57Z
22,377,499
15
2014-03-13T11:40:17Z
[ "python", "get", "python-requests" ]
In my script, `requests.get` never returns: ``` import requests print ("requesting..") # This call never returns! r = requests.get( "http://www.justdial.com", proxies = {'http': '222.255.169.74:8080'}, ) print(r.ok) ``` What could be the possible reason(s)? Any remedy? What is the default timeout that `get...
From [requests documentation](http://docs.python-requests.org/en/latest/user/quickstart/#timeouts): > You can tell Requests to stop waiting for a response after a given > number of seconds with the timeout parameter: > > ``` > >>> requests.get('http://github.com', timeout=0.001) > Traceback (most recent call last): > ...
Executing code after construction of class object
17,784,398
3
2013-07-22T09:47:38Z
17,784,466
11
2013-07-22T09:50:21Z
[ "python" ]
I was hoping to make a list of all subclasses of a given class by having each subclass register itself in a list that a parent class holds, ie something like this: ``` class Monster(object): monsters = list() class Lochness(Monster): Monster.monsters.append(Lochness) class Yeti(Monster): Monster.monsters.a...
Classes *already* register what subclasses are defined; call the [`class.__subclasses__()` method](http://docs.python.org/2/library/stdtypes.html#class.__subclasses__) to get a list: ``` >>> class Monster(object): ... pass ... >>> class Lochness(Monster): ... pass ... >>> class Yeti(Monster): ... pass .....
gradient descent using python and numpy
17,784,587
25
2013-07-22T09:55:30Z
17,796,231
61
2013-07-22T19:53:47Z
[ "python", "numpy", "machine-learning", "linear-regression", "gradient-descent" ]
``` def gradient(X_norm,y,theta,alpha,m,n,num_it): temp=np.array(np.zeros_like(theta,float)) for i in range(0,num_it): h=np.dot(X_norm,theta) #temp[j]=theta[j]-(alpha/m)*( np.sum( (h-y)*X_norm[:,j][np.newaxis,:] ) ) temp[0]=theta[0]-(alpha/m)*(np.sum(h-y)) temp[1]=theta[1]-(alp...
I think your code is a bit too complicated and it needs more structure, because otherwise you'll be lost in all equations and operations. In the end this regression boils down to four operations: 1. Calculate the hypothesis h = X \* theta 2. Calculate the loss = h - y and maybe the squared cost (loss^2)/2m 3. Calculat...
How do I print an error message without printing a traceback and close the program when a condition is not met?
17,784,849
2
2013-07-22T10:08:47Z
21,556,806
26
2014-02-04T15:42:54Z
[ "python", "exception", "error-handling", "customization", "traceback" ]
I've seen similar questions to this one but none of them really address the trackback. If I have a class like so ``` class Stop_if_no_then(): def __init__(self, value one, operator, value_two, then, line_or_label, line_number): self._firstvalue = value_one self._secondvalue = value_two self...
You can turn off the traceback by limiting its depth. ## Python 2.x ``` import sys sys.tracebacklimit = 0 ``` ## Python 3.x In Python 3.5, setting [`tracebacklimit`](https://docs.python.org/3/library/sys.html#sys.tracebacklimit) to `0` does not seem to have the intended effect. This is a known [bug](https://bugs.py...
Share Large, Read-Only Numpy Array Between Multiprocessing Processes
17,785,275
56
2013-07-22T10:31:16Z
17,786,444
26
2013-07-22T11:29:14Z
[ "python", "numpy", "multiprocessing", "shared-memory", "cython" ]
I have a 60GB SciPy Array (Matrix) I must share between 5+ `multiprocessing` `Process` objects. I've seen numpy-sharedmem and read [this discussion](http://grokbase.com/t/python/python-list/1144s75ps4/multiprocessing-shared-memory-vs-pickled-copies) on the SciPy list. There seem to be two approaches--`numpy-sharedmem` ...
If you are on Linux (or any POSIX-compliant system), you can define this array as a global variable. `multiprocessing` is using `fork()` on Linux when it starts a new child process. A newly spawned child process automatically shares the memory with its parent as long as it does not change it ([copy-on-write](http://en....
Share Large, Read-Only Numpy Array Between Multiprocessing Processes
17,785,275
56
2013-07-22T10:31:16Z
17,880,120
10
2013-07-26T11:26:30Z
[ "python", "numpy", "multiprocessing", "shared-memory", "cython" ]
I have a 60GB SciPy Array (Matrix) I must share between 5+ `multiprocessing` `Process` objects. I've seen numpy-sharedmem and read [this discussion](http://grokbase.com/t/python/python-list/1144s75ps4/multiprocessing-shared-memory-vs-pickled-copies) on the SciPy list. There seem to be two approaches--`numpy-sharedmem` ...
If your array is that big you can use `numpy.memmap`. For example, if you have an array stored in disk, say `'test.array'`, you can use simultaneous processes to access the data in it even in "writing" mode, but your case is simpler since you only need "reading" mode. Creating the array: ``` a = np.memmap('test.array...
Share Large, Read-Only Numpy Array Between Multiprocessing Processes
17,785,275
56
2013-07-22T10:31:16Z
17,913,222
16
2013-07-28T21:45:21Z
[ "python", "numpy", "multiprocessing", "shared-memory", "cython" ]
I have a 60GB SciPy Array (Matrix) I must share between 5+ `multiprocessing` `Process` objects. I've seen numpy-sharedmem and read [this discussion](http://grokbase.com/t/python/python-list/1144s75ps4/multiprocessing-shared-memory-vs-pickled-copies) on the SciPy list. There seem to be two approaches--`numpy-sharedmem` ...
You may be interested in a tiny piece of code I wrote: [github.com/vmlaker/benchmark-sharedmem](https://github.com/vmlaker/benchmark-sharedmem) The only file of interest is `main.py`. It's a benchmark of [numpy-sharedmem](https://bitbucket.org/cleemesser/numpy-sharedmem) -- the code simply passes arrays (either `numpy...
Share Large, Read-Only Numpy Array Between Multiprocessing Processes
17,785,275
56
2013-07-22T10:31:16Z
17,951,754
20
2013-07-30T15:54:18Z
[ "python", "numpy", "multiprocessing", "shared-memory", "cython" ]
I have a 60GB SciPy Array (Matrix) I must share between 5+ `multiprocessing` `Process` objects. I've seen numpy-sharedmem and read [this discussion](http://grokbase.com/t/python/python-list/1144s75ps4/multiprocessing-shared-memory-vs-pickled-copies) on the SciPy list. There seem to be two approaches--`numpy-sharedmem` ...
@Velimir Mlaker gave a great answer. I thought I could add some bits of comments and a tiny example. (I couldn't find much documentation on sharedmem - these are the results of my own experiments.) 1. Do you need to pass the handles when the subprocess is starting, or after it has started? If it's just the former, yo...
Django Crispy Form Split Field Layouts
17,785,451
9
2013-07-22T10:40:29Z
17,786,634
13
2013-07-22T11:39:22Z
[ "python", "django", "layout", "django-forms", "django-crispy-forms" ]
We have a crispy form where we want to be able to render different fields in different parts of our forms `HTML` template, however we can't find a way of doing this in the [Crispy Documentation](http://django-crispy-forms.readthedocs.org/en/latest/index.html). Below is some slightly made-up code to illustrate what we a...
Update: This does not work for `forms.ModelForm` Try creating two helpers instead of two layouts then explicitly calling your separate helpers. Doing it this way you will have to manually write `<form>` tags to enclose both forms in your template but hopefully provides the solution you need. ``` forms.py class Form(...