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 |
|---|---|---|---|---|---|---|---|---|---|
Add user specific fields to Django REST Framework serializer | 19,468,478 | 12 | 2013-10-19T16:47:00Z | 23,648,966 | 26 | 2014-05-14T08:07:13Z | [
"python",
"django",
"django-rest-framework"
] | I want to add a field to a serializer that contains information specific to the user making the current request (I don't want to create a separate endpoint for this). Here is the way I did it:
**The viewset:**
```
class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class =... | you can do it with `SerializerMethodField`
**Example :**
```
class PostSerializer(serializers.ModelSerializer):
fav = serializers.SerializerMethodField('likedByUser')
def likedByUser(self, obj):
request = self.context.get('request', None)
if request is not None:
try:
... |
Cutting of unused frequencies in specgram matplotlib | 19,468,923 | 7 | 2013-10-19T17:29:59Z | 19,470,773 | 15 | 2013-10-19T20:25:34Z | [
"python",
"matplotlib",
"frequency",
"spectrogram"
] | I have a signal with sampling rate 16e3, its frequency range is from 125 to 1000 Hz.
So if i plot a specgram i get a pretty small colorrange because of all the unused frequencys.
ive tried to fix it with setting ax limits but that does not work.
is there any way to cut off unused frequencys or replace them with NaNs?... | specgram() is doing all the work for you. If you look in axes.py at the specgram function you can see how it works. The original function is in `Python27\Lib\site-packages\matplotlib\axes.py` on my computer.
```
<snip>
Pxx, freqs, bins = mlab.specgram(x, NFFT, Fs, detrend,
window, noverlap, pad_to, ... |
Why is this elif statement throwing an error? | 19,469,006 | 3 | 2013-10-19T17:38:52Z | 19,469,097 | 11 | 2013-10-19T17:46:52Z | [
"python"
] | ```
class TheBridge(Scene):
def enter(self):
print "You burst into the bridge with the bomb"
print "There are a number of gothons standing about"
print "and looking scared of the bomb you currently have underneath your arm"
print "They look nervous about what you are going to do"
action = raw_inpu... | You are mixing tabs and spaces (your copied post here certainly does).
Run your code with `python -tt` and fix any problems that finds.
Preferably, replace all tabs with spaces and configure your editor to do so automatically. |
Return multiple lists in Python function | 19,469,697 | 2 | 2013-10-19T18:46:20Z | 19,469,725 | 7 | 2013-10-19T18:48:44Z | [
"python",
"list",
"function",
"return"
] | I am new to Python, and am trying to create a function which creates lists with different material parameters from user inputs as shown in the code below.
```
def material():
layers = int(raw_input("State the number of material layers in the wall (0 for default material): "))
rho = [] # Density [kg/m3]
c ... | > How should I return rho, c, k, d and layers [...] ?
Simply do it:
```
return rho, c, k, d, layers
```
And then you'd call it like
```
rho, c, k, d, layers = material()
print d[1]
```
Note that the more stuff you're returning, the more likely it is you're going to want to wrap it all together into some structure ... |
Project Name vs Application Name in Django | 19,469,932 | 4 | 2013-10-19T19:08:21Z | 19,470,001 | 14 | 2013-10-19T19:14:31Z | [
"python",
"django",
"pycharm"
] | I'm trying to create a new Django/Python project in the JetBrains PyCharm IDE.
However, while typing my software name it informs me that "You cannot call your app the same as your project".
Trying to fully understand the distinction between projects and applications in Django, I'd love someone to demonstrate the diffe... | My try with Facebook:
```
facebook
users
messages
notifications
posts
...
```
Basically the gist is that an app represents a specific part of your whole project. Moreover, the app can be "pluggable" into a similar project. In order to be maintainable an app should have it's own objectives that differ from t... |
View pdf image in an iPython Notebook | 19,470,099 | 19 | 2013-10-19T19:23:14Z | 19,470,377 | 31 | 2013-10-19T19:49:39Z | [
"python",
"pdf",
"ipython-notebook"
] | The following code allows me to view a `png` image in an iPython notebook. Is there a way to view `pdf` image? I don't need to use IPython.display necessarily. I am looking for a way to print a pdf image in a file to the iPython notebook output cell.
```
## This is for an `png` image
from IPython.display import Image
... | The problem you (and others) face is that PDFs cannot be displayed directly in the browser.
The only possible way to get something similar is to use an image-converter to create a PNG or JPG out of the PDF and display this one.
This could be done via imagemagick and a custom display function.
## Update 1
A simple s... |
View pdf image in an iPython Notebook | 19,470,099 | 19 | 2013-10-19T19:23:14Z | 35,655,134 | 7 | 2016-02-26T15:05:56Z | [
"python",
"pdf",
"ipython-notebook"
] | The following code allows me to view a `png` image in an iPython notebook. Is there a way to view `pdf` image? I don't need to use IPython.display necessarily. I am looking for a way to print a pdf image in a file to the iPython notebook output cell.
```
## This is for an `png` image
from IPython.display import Image
... | To show pdf-s inside ipython/jupyter notebooks you can use `IFrame`
```
from IPython.display import IFrame
IFrame("./samples/simple3.pdf", width=600, height=300)
```
Here is the screenshot
[](http://i.stack.imgur.com/59flK.png) |
Tulip/asyncIO: why not all calls be async and specify when things should be synchronous? | 19,471,967 | 10 | 2013-10-19T22:45:42Z | 19,472,481 | 11 | 2013-10-20T00:05:20Z | [
"python",
"asynchronous",
"python-3.x",
"python-asyncio"
] | I went to the SF Python meetup when Guido [talked](http://www.youtube.com/watch?v=1coLC-MUCJc&feature=youtu.be) about Tulip, the future asyncIO library for asynchronous operations in Python.
The take away is that if you want something to be run asynchronously you can use the `"yield from" + expression` and a couple of... | Note that the possible uses of `yield from` are a small part of the [asynch PEP](http://www.python.org/dev/peps/pep-3156/), and never *need* to be used. Maybe Guido oversold them in his talk ;-)
As to why functions aren't being changed to always be async by default, that's just realism. Asynch gimmicks bring new overh... |
Tulip/asyncIO: why not all calls be async and specify when things should be synchronous? | 19,471,967 | 10 | 2013-10-19T22:45:42Z | 20,218,758 | 13 | 2013-11-26T13:45:31Z | [
"python",
"asynchronous",
"python-3.x",
"python-asyncio"
] | I went to the SF Python meetup when Guido [talked](http://www.youtube.com/watch?v=1coLC-MUCJc&feature=youtu.be) about Tulip, the future asyncIO library for asynchronous operations in Python.
The take away is that if you want something to be run asynchronously you can use the `"yield from" + expression` and a couple of... | The real answer is that Guido *likes* the fact that asynchronous yield points are explicit in coroutines, because if you don't realize that a call can yield, then that's an invitation to concurrency problems -- like with threads. But if you have to write an explicit `yield from`, it's fairly easy to make sure it doesn'... |
How to avoid "Permission denied" when using pip with virtualenv | 19,471,972 | 33 | 2013-10-19T22:46:17Z | 19,472,082 | 37 | 2013-10-19T23:02:02Z | [
"python",
"virtualenv",
"pip"
] | I attempt to deploy a Python package with `pip` in a virtual environment on an Ubuntu machine, but encounter a permission-related issue. For example:
```
(TestVirtualEnv)test@testServer:~$ pip install markdown2
```
terminates by:
> error: could not create '/home/test/virtualenvs/TestVirtualEnv/lib/python3.3/site-pac... | `virtualenv` permission problems might occur when you create the `virtualenv` as `sudo` and then operate without `sudo` in the `virtualenv`.
As found out in your question's comment, the solution here is to **create** the `virtualenv` without `sudo` to be able to **work** (esp. write) in it without `sudo`. |
How to avoid "Permission denied" when using pip with virtualenv | 19,471,972 | 33 | 2013-10-19T22:46:17Z | 28,984,415 | 27 | 2015-03-11T10:42:45Z | [
"python",
"virtualenv",
"pip"
] | I attempt to deploy a Python package with `pip` in a virtual environment on an Ubuntu machine, but encounter a permission-related issue. For example:
```
(TestVirtualEnv)test@testServer:~$ pip install markdown2
```
terminates by:
> error: could not create '/home/test/virtualenvs/TestVirtualEnv/lib/python3.3/site-pac... | **Solution:**
If you created the virtualenv as root, run the following command:
```
sudo chown -R your_username:your_username path/to/virtuaelenv/
```
This will probably fix your problem.
Cheers |
In python, can one iterate through large text files using buffers and get the correct file position at the same time? | 19,472,441 | 5 | 2013-10-20T00:00:45Z | 19,472,783 | 8 | 2013-10-20T00:55:21Z | [
"python",
"file-io"
] | I'm trying to search some keywords through a large text file (~232GB). I want to take advantage of buffering for speed concerns and also want to record beginning positions of lines containing those keywords.
I've seen many posts here discussing similar questions. However, those solutions with buffering (use file as it... | What's wrong with using `.readline()`?
The sample you found is incorrect for files opened in text mode. It should work OK on Linux systems, but not on Windows. On Windows, the only way to return to a former position in a text-mode file is to seek to one of:
1. 0 (start of file).
2. End of file.
3. A position formerly... |
Blender 2.6: Select object by name through Python | 19,472,499 | 14 | 2013-10-20T00:08:12Z | 19,472,632 | 16 | 2013-10-20T00:32:59Z | [
"python",
"blender",
"bpy"
] | I know, this is an extremely simple question, but I've looked everywhere. Maybe I'm missing the point, I don't know; but this should be reasonably easy.
My question is simply, *how do you select objects by name through Python in Blender 2.6?*
---
In 2.4-5, one could simply use:
```
bpy.ops.object.select_name("OBJEC... | ```
bpy.data.objects['OBJECT'].select = True
```
---
Selection data is contained within the individual objects. You can read *and* write them as shown. In a slightly more readable form:
```
object = bpy.data.objects['OBJECT']
object.select = True
``` |
Blender 2.6: Select object by name through Python | 19,472,499 | 14 | 2013-10-20T00:08:12Z | 20,168,990 | 15 | 2013-11-23T23:00:38Z | [
"python",
"blender",
"bpy"
] | I know, this is an extremely simple question, but I've looked everywhere. Maybe I'm missing the point, I don't know; but this should be reasonably easy.
My question is simply, *how do you select objects by name through Python in Blender 2.6?*
---
In 2.4-5, one could simply use:
```
bpy.ops.object.select_name("OBJEC... | `bpy.ops.object.select_name()` has been replaced by `bpy.ops.object.select_pattern()` (around 2.62, I think?), which is a more powerful version (it can select an exact name, but also use patterns with wildcards, be case-insensitive, etc.):
```
bpy.ops.object.select_pattern(pattern="Cube")
``` |
Representing graphs (data structure) in Python | 19,472,530 | 15 | 2013-10-20T00:13:02Z | 30,747,003 | 24 | 2015-06-10T04:16:19Z | [
"python",
"python-2.7",
"data-structures",
"python-3.x",
"graph"
] | How can one neatly represent a [graph](https://en.wikipedia.org/wiki/Graph_%28data_structure%29) in [Python](https://en.wikipedia.org/wiki/Python_(programming_language))? (Starting from scratch i.e. no libraries!)
What data structure (e.g. dicts/tuples/dict(tuples)) will be fast but also memory efficient?
One must ... | Even though this is a somewhat old question, I thought I'd give a practical answer for anyone stumbling across this.
Let's say you get your input data for your connections as a list of tuples like so:
```
[('A', 'B'), ('B', 'C'), ('B', 'D'), ('C', 'D'), ('E', 'F'), ('F', 'C')]
```
The data structure I've found to be... |
reading external sql script in python | 19,472,922 | 8 | 2013-10-20T01:21:27Z | 19,473,206 | 23 | 2013-10-20T02:12:57Z | [
"python",
"sql"
] | I am working on a learning how to execute SQL in python (I know SQL, not Python).
I have an external sql file. It creates and inserts data into three tables 'Zookeeper', 'Handles', 'Animal'.
Then I have a series of queries to run off the tables. The below queries are in the zookeeper.sql file that I load in at the to... | Your code already contains a beautiful way to execute all statements from a specified sql file
```
# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()
# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')
# Execute every command from the input fil... |
What is a None value? | 19,473,185 | 42 | 2013-10-20T02:10:22Z | 19,473,207 | 24 | 2013-10-20T02:13:19Z | [
"python",
"variables",
"if-statement"
] | I have been studying Python, and I read a chapter which describes the `None` value, but unfortunately this book isn't very clear at some points. I thought that I would find the answer to my question, if I share it there.
I want to know what the `None` value *is* and what do you use it for?
And also, I don't get this ... | `None` is just a value that commonly is used to signify 'empty', or 'no value here'. It is a *signal object*; it only has meaning because the Python documentation says it has that meaning.
There is only one copy of that object in a given Python interpreter session.
If you write a function, and that function doesn't u... |
What is a None value? | 19,473,185 | 42 | 2013-10-20T02:10:22Z | 19,473,658 | 10 | 2013-10-20T03:34:34Z | [
"python",
"variables",
"if-statement"
] | I have been studying Python, and I read a chapter which describes the `None` value, but unfortunately this book isn't very clear at some points. I thought that I would find the answer to my question, if I share it there.
I want to know what the `None` value *is* and what do you use it for?
And also, I don't get this ... | This is what the [Python documentation](http://docs.python.org/2/library/constants.html?highlight=none#None) has got to say about `None`:
> The sole value of types.NoneType. None is frequently used to represent
> the absence of a value, as when default arguments are not passed to a
> function.
>
> Changed in version 2... |
What is a None value? | 19,473,185 | 42 | 2013-10-20T02:10:22Z | 19,474,250 | 26 | 2013-10-20T05:29:23Z | [
"python",
"variables",
"if-statement"
] | I have been studying Python, and I read a chapter which describes the `None` value, but unfortunately this book isn't very clear at some points. I thought that I would find the answer to my question, if I share it there.
I want to know what the `None` value *is* and what do you use it for?
And also, I don't get this ... | Martijn's answer explains what `None` is in Python, and correctly states that the book is misleading. Since Python programmers as a rule would never say
> Assigning a value of `None` to a variable is one way to reset it to
> its original, empty state.
it's hard to explain what Briggs means in a way which makes sense ... |
How to get user email after OAUTH with Google API Python Client | 19,473,250 | 3 | 2013-10-20T02:24:03Z | 19,486,003 | 7 | 2013-10-21T03:53:18Z | [
"python",
"api",
"oauth"
] | I'm currently building a web app interacting with Google API in Python. Using the oauth to get access to the users resources. After successful authentication and upgrade of the token like this:
```
gd_client = gdata.photos.service.PhotosService()
gd_client.SetAuthSubToken(token)
gd_client.UpgradeToSessionToken()
```
... | So I found a great way to do it!
Request the extra scope of <https://www.googleapis.com/auth/userinfo.email> then I can access that with a Gdata.Client to get the e-mail address.
Complete example code: <https://code.google.com/p/google-api-oauth-demo/>
Complete write up of how I got there: <http://www.hackviking.com... |
Using Django models in external python script | 19,475,955 | 9 | 2013-10-20T09:41:46Z | 19,476,096 | 8 | 2013-10-20T10:00:27Z | [
"python",
"django"
] | I was very confused today.
I was trying to use my django app models in my python script.
here is my approach
```
import os, sys
sys.path.append("/var/www/cloudloon/horizon")
os.environ["DJANGO_SETTINGS_MODULE"] = "openstack_dashboard.settings"
from django.contrib.auth.models import User
```
I was confused why its ... | The below script should work provided that the layout of your project (and the path to your settings file) looks like this:
> /var/www/cloudloon/horizon/openstack\_dashboard/settings.py
```
#!/usr/bin/env python
import os, sys
sys.path.append("/var/www/cloudloon/horizon")
os.environ["DJANGO_SETTINGS_MODULE"] = "open... |
Using Django models in external python script | 19,475,955 | 9 | 2013-10-20T09:41:46Z | 19,477,157 | 19 | 2013-10-20T12:09:25Z | [
"python",
"django"
] | I was very confused today.
I was trying to use my django app models in my python script.
here is my approach
```
import os, sys
sys.path.append("/var/www/cloudloon/horizon")
os.environ["DJANGO_SETTINGS_MODULE"] = "openstack_dashboard.settings"
from django.contrib.auth.models import User
```
I was confused why its ... | You need to write a [custom management command](https://docs.djangoproject.com/en/1.5/howto/custom-management-commands/), instead of doing these weird acrobatics.
Create a *module* called management (in other words, create a directory `management` and inside it create an empty `__init__.py` file) inside the directory ... |
Save File Dialog in Tkinter | 19,476,232 | 4 | 2013-10-20T10:17:25Z | 19,476,284 | 10 | 2013-10-20T10:23:12Z | [
"python",
"tkinter"
] | I am implementing a GUI based text editor in python.
I have displayed the text area but when I try to use the asksaveasfile method in Tkinter, it shows that the file has been saved but when I try and open the same file in my desktop editor, it gives me a blank file.
Only, the file is created and saved. Its contents ... | The function name is `asksaveasfilename`. And it should be qualified as `tkFileDialog.asksaveasfilename`. And it does not accept `mode` argument.
Maybe you want to use `tkFileDialog.asksaveasfile`.
```
def file_save():
f = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt")
if f is None: # asksaveas... |
Creating an empty object in Python | 19,476,816 | 14 | 2013-10-20T11:27:54Z | 19,476,832 | 7 | 2013-10-20T11:29:50Z | [
"python",
"oop"
] | Are there any shortcuts for defining an empty object in Python or do you always have to create an instance of a custom empty class?
Edit: I mean an empty object usable for duck typing. | What do you mean by "empty object"? Instance of class `object`? You can simply run
```
a = object()
```
or maybe you mean initialization to the null reference? Then you can use
```
a = None
``` |
Creating an empty object in Python | 19,476,816 | 14 | 2013-10-20T11:27:54Z | 19,476,841 | 25 | 2013-10-20T11:30:41Z | [
"python",
"oop"
] | Are there any shortcuts for defining an empty object in Python or do you always have to create an instance of a custom empty class?
Edit: I mean an empty object usable for duck typing. | You can use type to create a new class on the fly and then instantiate it. Like so:
```
>>> t = type('test', (object,), {})()
>>> t
<__main__.test at 0xb615930c>
```
The arguments to type are: Class name, a tuple of base classes, and the object's dictionary. Which can contain functions (the object's methods) or attri... |
urllib3 on python 2.7 SNI error on Google App Engine | 19,477,214 | 3 | 2013-10-20T12:16:52Z | 19,477,363 | 7 | 2013-10-20T12:34:27Z | [
"python",
"google-app-engine",
"sni",
"urllib3"
] | I'm trying to download an HTTPS page from my site hosted on Google App Engine with SNI.
No matter what library I use, I get the following error:
```
[Errno 8] _ssl.c:504: EOF occurred in violation of protocol
```
I've tried solving the error in many ways, including using the urllib3 openssl monkeypatch:
```
from url... | Unfortunately for urllib3, the Python standard library did not add SNI support until Python 3.2.
(See [Issue #118 @ urllib3](https://github.com/shazow/urllib3/pull/118))
To use SNI in Python 2.7 with urllib3, you'll need to use the PyOpenSSL injection monkeypatch.
(See [Issue #156 @ urllib3](https://github.com/shazow/... |
Does Tkinter have a refresh method? | 19,477,636 | 6 | 2013-10-20T13:02:05Z | 19,477,781 | 9 | 2013-10-20T13:14:22Z | [
"python",
"user-interface",
"tkinter"
] | I am using Tkinter.
```
import Tkinter as tk
class App(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
....
root = tk.Tk()
root.title("title")
app = App(root)
root.mainloop()
```
Does it has a refresh? Because I want to refresh my frame.
Is `root.refresh()` is pos... | There is a [Tk.update()](http://epydoc.sourceforge.net/stdlib/Tkinter.Misc-class.html#update) and a [Tk.update\_idletasks()](http://epydoc.sourceforge.net/stdlib/Tkinter.Misc-class.html#update_idletasks). Both will force the UI to be refreshed, but depending on what you're actually trying to do it might not be what you... |
TypeError: 'str' does not support the buffer interface, Python 3 | 19,478,446 | 2 | 2013-10-20T14:20:52Z | 19,478,573 | 7 | 2013-10-20T14:31:30Z | [
"python",
"csv"
] | I have many `CSV` files, and I want to them join then into one `txt` file, `binary` format..
The following code give the above error:
```
import os
from csv import reader
from csv import writer
CONST_DATA_DIR = "F:/Data/"
CONST_DATABIN_DIR = "F:/DataBinary/"
def createFilesArr():
filesArr = []
os.chdir(CO... | Python distinguishes between binary and text I/O.
```
newFile = open(CONST_DATABIN_DIR + newFileName, 'wb')
```
Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding.
```
currentFile = open(CONST_DATA_DIR + file, 'r', newline='', encoding='UTF8')
newFi... |
Printing List as a String doesn't print all the values | 19,478,568 | 2 | 2013-10-20T14:31:16Z | 19,478,611 | 8 | 2013-10-20T14:34:39Z | [
"python"
] | I am trying to Print the List of Integers as Characters in Python,
But when I am trying to Print it the first few values are being missing,
Here is what is happening,
```
S = [55, 58, 5, 13, 14, 12, 22, 20, 70, 83, 90, 69, 84, 91, 80, 91]
# Now create an empty String,
D = ""
for i in S:
D += chr(i)
D = ', '.join... | Ascii 13 is carriage return(`\r`, enter key). Think as in type writer, it returns the cursor to start of the line, but it doesn't create a new line(`\n`), so when you print something, it overwrites what was in that line before. Look at this:
```
for i in range(10):
print("\r%d" % i, end="")
sleep(1)
```
Extra... |
Is numpy.transpose reordering data in memory? | 19,479,384 | 6 | 2013-10-20T15:46:02Z | 19,479,436 | 9 | 2013-10-20T15:49:59Z | [
"python",
"arrays",
"optimization",
"numpy"
] | In order to speed up the functions like np.std, np.sum etc along an axis of an n dimensional huge numpy array, it is recommended to apply along the last axis.
When I do, np.transpose to rotate the axis I want to operate, to the last axis. Is it really reshuffling the data in memory, or just changing the way the axis a... | Transpose just changes the [strides](https://en.wikipedia.org/wiki/Stride_of_an_array), it doesn't touch the actual array. I think the reason why `sum` etc. along the final axis is recommended (I'd like to see the source for that, btw.) is that when an array is C-ordered, walking along the final axis preserves locality... |
What does -> do in python | 19,479,644 | 24 | 2013-10-20T16:11:05Z | 19,479,663 | 7 | 2013-10-20T16:12:41Z | [
"python",
"python-3.x"
] | I saw a python example today and it used -> for example this was what I saw:
```
spam = None
bacon = 42
def monty_python(a:spam,b:bacon) -> "different:":
pass
```
What is that code doing? I'm not quite sure I've never seen code like that I don't really get what
```
a:spam,b:bacon
```
is doing either, can someo... | They're [function annotations](http://ceronman.com/2013/03/12/a-powerful-unused-feature-of-python-function-annotations/). They don't really do anything by themselves, but they can be used for documentation or in combination with metaprogramming. |
What does -> do in python | 19,479,644 | 24 | 2013-10-20T16:11:05Z | 19,479,681 | 29 | 2013-10-20T16:13:51Z | [
"python",
"python-3.x"
] | I saw a python example today and it used -> for example this was what I saw:
```
spam = None
bacon = 42
def monty_python(a:spam,b:bacon) -> "different:":
pass
```
What is that code doing? I'm not quite sure I've never seen code like that I don't really get what
```
a:spam,b:bacon
```
is doing either, can someo... | It is function annotation for a return type. [`annotations`](http://stackoverflow.com/questions/3038033/what-are-good-uses-for-python3s-function-annotations) do nothing inside the code, they are there to help a user with code completion (in my experience).
Here is the [PEP](http://www.python.org/dev/peps/pep-3107/) fo... |
AttributeError: 'module' object has no attribute 'strptime' // class? | 19,480,028 | 42 | 2013-10-20T16:45:24Z | 19,480,037 | 11 | 2013-10-20T16:46:02Z | [
"python",
"class",
"python-2.7"
] | Here is my `Transaction` class:
```
class Transaction(object):
def __init__(self, company, num, price, date, is_buy):
self.company = company
self.num = num
self.price = price
self.date = datetime.strptime(date, "%Y-%m-%d")
self.is_buy = is_buy
```
And when I'm trying to run... | Use the correct call: `strptime` is a classmethod of the `datetime.datetime` class, it's not a function in the `datetime` module.
```
self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")
```
---
As mentioned by Jon Clements in the comments, some people do `from datetime import datetime`, which would bind the `... |
AttributeError: 'module' object has no attribute 'strptime' // class? | 19,480,028 | 42 | 2013-10-20T16:45:24Z | 19,480,045 | 88 | 2013-10-20T16:46:37Z | [
"python",
"class",
"python-2.7"
] | Here is my `Transaction` class:
```
class Transaction(object):
def __init__(self, company, num, price, date, is_buy):
self.company = company
self.num = num
self.price = price
self.date = datetime.strptime(date, "%Y-%m-%d")
self.is_buy = is_buy
```
And when I'm trying to run... | If I had to guess, you did this:
```
import datetime
```
at the top of your code. This means that you have to do this:
```
datetime.datetime.strptime(date, "%Y-%m-%d")
```
to access the `strptime` method. Or, you could change the import statement to this:
```
from datetime import datetime
```
and access it as you... |
Measuring Celery task execution time | 19,481,470 | 3 | 2013-10-20T18:56:36Z | 31,731,622 | 12 | 2015-07-30T18:40:46Z | [
"python",
"rabbitmq",
"celery"
] | I have converted a standalone batch job to use celery for dispatching the work to be done. I'm using RabbitMQ. Everything is running on a single machine and no other processes are using the RabbitMQ instance. My script just creates a bunch of tasks which are processed by workers.
Is there a simple way to measure the t... | You could use [celery signals](http://celery.readthedocs.org/en/latest/userguide/signals.html), functions registered will be called before and after a task is executed, it is trivial to measure elapsed time:
```
from time import time
from celery.signals import task_prerun, task_postrun
d = {}
@task_prerun.connect
d... |
Using reshape in Python to reshape an array | 19,482,527 | 3 | 2013-10-20T20:32:26Z | 19,482,987 | 7 | 2013-10-20T21:20:06Z | [
"python",
"numpy",
"shape",
"reshape"
] | I have an array that looks like below:
```
array([[0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2, 2, 2],
[3, 3, 3, 3, 3, 3, 3, 3],
[4, 4, 4, 4, 4, 4, 4, 4],
[5, 5, 5, 5, 5, 5, 5, 5],
[6, 6, 6, 6, 6, 6, 6, 6],
[7, 7, 7, 7, 7, 7, 7, 7]])
```
How ca... | Edit: Sorry, I didn't realize it was a 3-d result, not a 4-d result. To get the 3-d one, you would have to reshape once more. And that extra reshape *will* copy the data.
You can't, you need to tranpose as well:
```
In [1]: a = np.arange(8)[:,None].repeat(8,axis=1)
In [2]: a
Out[2]:
array([[0, 0, 0, 0, 0, 0, 0, 0],... |
Allowed characters in Python function names | 19,482,730 | 4 | 2013-10-20T20:51:22Z | 19,482,755 | 10 | 2013-10-20T20:54:36Z | [
"python",
"function"
] | Are there any other allowed characters in Python function names except alphabetical characters, numbers, and underscores? If yes, what are they? | Not in Python 2.x. From [the docs](http://docs.python.org/2/reference/lexical_analysis.html#grammar-token-identifier):
```
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
```
[In Python 3 it's expa... |
Get list from pandas DataFrame column headers | 19,482,970 | 170 | 2013-10-20T21:18:37Z | 19,482,988 | 8 | 2013-10-20T21:20:06Z | [
"python",
"pandas",
"dataframe"
] | I want to get a list of the column headers from a pandas DataFrame. The DataFrame will come from user input so I won't know how many columns there will be or what they will be called.
For example, if I'm given a DataFrame like this:
```
>>> my_dataframe
y gdp cap
0 1 2 5
1 2 3 9
2 8 7 2
... | That's available as `my_dataframe.columns`. |
Get list from pandas DataFrame column headers | 19,482,970 | 170 | 2013-10-20T21:18:37Z | 19,483,025 | 318 | 2013-10-20T21:23:07Z | [
"python",
"pandas",
"dataframe"
] | I want to get a list of the column headers from a pandas DataFrame. The DataFrame will come from user input so I won't know how many columns there will be or what they will be called.
For example, if I'm given a DataFrame like this:
```
>>> my_dataframe
y gdp cap
0 1 2 5
1 2 3 9
2 8 7 2
... | You can get the values as a list by doing:
```
list(my_dataframe.columns.values)
``` |
Get list from pandas DataFrame column headers | 19,482,970 | 170 | 2013-10-20T21:18:37Z | 19,483,602 | 135 | 2013-10-20T22:25:15Z | [
"python",
"pandas",
"dataframe"
] | I want to get a list of the column headers from a pandas DataFrame. The DataFrame will come from user input so I won't know how many columns there will be or what they will be called.
For example, if I'm given a DataFrame like this:
```
>>> my_dataframe
y gdp cap
0 1 2 5
1 2 3 9
2 8 7 2
... | There is a built in method which is the most performant:
```
my_dataframe.columns.values.tolist()
```
`.columns` returns an `Index`, `.columns.values` returns an `array` and this has a helper function to return a `list`.
**EDIT**
For those who hate typing this is probably the shortest method:
```
list(df)
``` |
Get list from pandas DataFrame column headers | 19,482,970 | 170 | 2013-10-20T21:18:37Z | 27,236,748 | 28 | 2014-12-01T20:31:56Z | [
"python",
"pandas",
"dataframe"
] | I want to get a list of the column headers from a pandas DataFrame. The DataFrame will come from user input so I won't know how many columns there will be or what they will be called.
For example, if I'm given a DataFrame like this:
```
>>> my_dataframe
y gdp cap
0 1 2 5
1 2 3 9
2 8 7 2
... | Did some quick tests, and perhaps unsurprisingly the built-in version using `dataframe.columns.values.tolist()` is the fastest:
```
In [1]: %timeit [column for column in df]
1000 loops, best of 3: 81.6 µs per loop
In [2]: %timeit df.columns.values.tolist()
10000 loops, best of 3: 16.1 µs per loop
In [3]: %timeit l... |
Get list from pandas DataFrame column headers | 19,482,970 | 170 | 2013-10-20T21:18:37Z | 29,494,537 | 7 | 2015-04-07T14:50:33Z | [
"python",
"pandas",
"dataframe"
] | I want to get a list of the column headers from a pandas DataFrame. The DataFrame will come from user input so I won't know how many columns there will be or what they will be called.
For example, if I'm given a DataFrame like this:
```
>>> my_dataframe
y gdp cap
0 1 2 5
1 2 3 9
2 8 7 2
... | Its gets even simpler (by pandas 0.16.0) :
```
df.columns.tolist()
```
will give you the column names in a nice list. |
Get list from pandas DataFrame column headers | 19,482,970 | 170 | 2013-10-20T21:18:37Z | 30,511,605 | 12 | 2015-05-28T15:58:05Z | [
"python",
"pandas",
"dataframe"
] | I want to get a list of the column headers from a pandas DataFrame. The DataFrame will come from user input so I won't know how many columns there will be or what they will be called.
For example, if I'm given a DataFrame like this:
```
>>> my_dataframe
y gdp cap
0 1 2 5
1 2 3 9
2 8 7 2
... | ```
>>> list(my_dataframe)
['y', 'gdp', 'cap']
```
To list the columns of a dataframe while in debugger mode, use a list comprehension:
```
>>> [c for c in my_dataframe]
['y', 'gdp', 'cap']
``` |
Converting JSON String to Dictionary, Not List (Python) | 19,483,351 | 39 | 2013-10-20T21:56:20Z | 19,483,437 | 58 | 2013-10-20T22:05:58Z | [
"python",
"json",
"list",
"python-3.x",
"dictionary"
] | I'm a beginner with Python, and I am trying to pass in a json file and convert the data into a dictionary.
So far this is what I have done:
```
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)
```
Here i'm expecting **json1\_data** to be a dict type but it ac... | Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:
```
json1_data = json.loads(json1_str)[0]
```
Now you can access the data stored in *datapoints* just as you were expecting... |
Python zipfile.extract() doesn't extract all files | 19,483,775 | 6 | 2013-10-20T22:46:58Z | 19,484,046 | 10 | 2013-10-20T23:21:40Z | [
"python",
"zip",
"extract"
] | I'm trying to extract zipped folder using code found here.
```
def unzip(source_filename, dest_dir):
with zipfile.ZipFile(source_filename) as zf:
for member in zf.infolist():
words = member.filename.split('/')
path = dest_dir
for word in words[:-1]:
drive, word = os.path.splitd... | The first place to look is [the documentation](http://docs.python.org/2/library/zipfile#zipfile-objects):
```
ZipFile.extractall([path[, members[, pwd]]])
```
Applying that to your situation, I'd try:
```
def unzip(source_filename, dest_dir):
with zipfile.ZipFile(source_filename) as zf:
zf.extractall(des... |
Other builtin or practical examples of python `with` statement usage? | 19,484,175 | 4 | 2013-10-20T23:39:50Z | 19,484,315 | 7 | 2013-10-20T23:59:04Z | [
"python",
"python-2.7",
"with-statement",
"conceptual",
"contextmanager"
] | Does anyone have a real world example outside of python's file object implementation of an `__enter__` and `__exit__` use case? Preferably your own, since what I'm trying to achieve is a better way to conceptualize the cases where it would be used.
I've already read [this](http://effbot.org/zone/python-with-statement.... | There are *many* uses. Just in the standard library we have:
* `sqlite3`; using the [connection as a context manager](http://docs.python.org/2/library/sqlite3.html#using-the-connection-as-a-context-manager) translates to committing or aborting the transaction.
* `unittest`; using [`assertRaises`](http://docs.python.or... |
Extract csv file specific columns to list in Python | 19,486,369 | 7 | 2013-10-21T04:39:40Z | 19,487,003 | 13 | 2013-10-21T05:42:51Z | [
"python",
"csv",
"numpy",
"matplotlib"
] | I'm a newb to Python so please bare with me. What I'm trying to do is plot the latitude and longitude values of specific storms on a map using matplotlib,basemap,python, etc. My problem is that I'm trying to extract the latitude, longitude, and name of the storms on map but I keep getting errors between lines 41-44 whe... | This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use [Pandas](http://pandas.pydata.org) for the CSV reading part, which is both more robust and more useful than just the `csv` module:
```
import pandas
colnames = ['year', 'name',... |
Extract csv file specific columns to list in Python | 19,486,369 | 7 | 2013-10-21T04:39:40Z | 29,082,892 | 13 | 2015-03-16T17:11:09Z | [
"python",
"csv",
"numpy",
"matplotlib"
] | I'm a newb to Python so please bare with me. What I'm trying to do is plot the latitude and longitude values of specific storms on a map using matplotlib,basemap,python, etc. My problem is that I'm trying to extract the latitude, longitude, and name of the storms on map but I keep getting errors between lines 41-44 whe... | ### A standard-lib version (no pandas)
This assumes that the first row of the csv is the headers
```
import csv
# open the file in universal line ending mode
with open('test.csv', 'rU') as infile:
# read the file as a dictionary for each row ({header : value})
reader = csv.DictReader(infile)
data = {}
for r... |
Plone: pypi specific download issue behind a proxy server - can't install eggs | 19,488,508 | 3 | 2013-10-21T07:28:58Z | 19,488,784 | 7 | 2013-10-21T07:45:43Z | [
"python",
"proxy",
"plone",
"pypi"
] | Have a weird problem here.
I am in a network that uses an authenticated proxy to connect to the outside world. I do not control this proxy server.
This fact has in the past tripped me up with use of wget, curl, etc. (this is on Mac OSX 10.8). So, I set the environment variables:
```
HTTP_PROXY=proxyserveraddress:312... | It is possible that the secured socket authentication used by pypi is causing your problems as it probably uses a different port that you are not including in your proxy forwarding list. You may be able to resolve this in the same manner as your other poxy settings.
Another way round would be to manually download and ... |
Merge DataFrames in Pandas using the mean | 19,490,064 | 7 | 2013-10-21T08:57:22Z | 19,490,199 | 8 | 2013-10-21T09:04:12Z | [
"python",
"merge",
"pandas"
] | I have a set of DataFrames with numeric values and partly overlapping indices. I would like to merge them an take the mean if an index occurs in more than one DataFrame.
```
import pandas as pd
import numpy as np
df1 = pd.DataFrame([1,2,3], columns=['col'], index=['a','b','c'])
df2 = pd.DataFrame([4,5,6], columns=['c... | something like this:
```
df3 = pd.concat((df1, df2))
df3.groupby(df3.index).mean()
# col
# a 1
# b 3
# c 4
# d 6
```
or other way around, as in @unutbu answer:
```
pd.concat((df1, df2), axis=1).mean(axis=1)
``` |
Does range have to calculate all previous values when using a index | 19,494,933 | 5 | 2013-10-21T12:46:45Z | 19,495,101 | 8 | 2013-10-21T12:53:44Z | [
"python",
"python-3.x"
] | In python 3, range supports indexing but I am wondering exactly how that works.
For example: `range(100000000000000000000000000)[-1]`
I have a basic understanding that the range function actually returns a range object that takes up a limited amount of memory. Does that mean that to get to the last value, it has to c... | It is not required to get previous value to get the last value.
It is computed by [`compute_item` function](http://hg.python.org/cpython/file/d8e352e2f110/Objects/rangeobject.c#l236) (which is called by [`compute_range_item`](http://hg.python.org/cpython/file/d8e352e2f110/Objects/rangeobject.c#l251) <- [`range_item`](... |
Python - Extracting inner most lists | 19,495,848 | 21 | 2013-10-21T13:26:53Z | 19,496,080 | 31 | 2013-10-21T13:36:43Z | [
"python",
"python-2.7"
] | Just started toying around with Python so please bear with me :)
Assume the following list which contains nested lists:
```
[[[[[1, 3, 4, 5]], [1, 3, 8]], [[1, 7, 8]]], [[[6, 7, 8]]], [9]]
```
In a different representation:
```
[
[
[
[
[1, 3, 4, 5]
],
... | This seems to work, assuming no 'mixed' lists like `[1,2,[3]]`:
```
def get_inner(nested):
if all(type(x) == list for x in nested):
for x in nested:
for y in get_inner(x):
yield y
else:
yield nested
```
Output of `list(get_inner(nested_list))`:
```
[[1, 3, 4, 5], [... |
Python - Extracting inner most lists | 19,495,848 | 21 | 2013-10-21T13:26:53Z | 19,496,438 | 12 | 2013-10-21T13:51:56Z | [
"python",
"python-2.7"
] | Just started toying around with Python so please bear with me :)
Assume the following list which contains nested lists:
```
[[[[[1, 3, 4, 5]], [1, 3, 8]], [[1, 7, 8]]], [[[6, 7, 8]]], [9]]
```
In a different representation:
```
[
[
[
[
[1, 3, 4, 5]
],
... | Using [`itertools.chain.from_iterable`](http://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable):
```
from itertools import chain
def get_inner_lists(xs):
if isinstance(xs[0], list): # OR all(isinstance(x, list) for x in xs)
return chain.from_iterable(map(get_inner_lists, xs))
re... |
how to set values to rows of boolean filtered dataframe column | 19,497,054 | 5 | 2013-10-21T14:20:25Z | 19,498,086 | 10 | 2013-10-21T15:04:23Z | [
"python",
"pandas"
] | I'm trying to set the values of "FreeSec" column to `True` for the filtered rows of my pandas dataframe. Here is the code:
```
data[data["Brand"].isin(group_clients)].FreeSec = True
```
However, when I check the values they are still set to `False`.
```
>>> data[data["Brand"].isin(group_clients)].FreeSec
12 Fal... | You should use loc to do this **without chaining**, which will garauntee that assignment works:
```
data.loc[data["Brand"].isin(group_clients), "FreeSec"] = True
```
*Assignment in loc is overridden so that the implementation detail of whether it's actually [a view or a copy](http://pandas.pydata.org/pandas-docs/dev/... |
Python: How can I use ggplot with a simple 2 column array? | 19,497,282 | 4 | 2013-10-21T14:29:56Z | 19,499,418 | 8 | 2013-10-21T16:04:13Z | [
"python",
"python-2.7",
"python-ggplot"
] | I try to use ggplot for python I have the following data:
```
power_data = [[ 4.13877565e+04, 2.34652000e-01],
[ 4.13877565e+04, 2.36125000e-01],
[ 4.13877565e+04, 2.34772000e-01],
...
[ 4.13882896e+04, 2.29006000e-01],
[ 4.13882896e+04, 2.29019000e-01],
[ 4.13882896e+04, 2.28404000e-01]]
```
And I ... | There were 3 important steps that I missed:
**1)** First the data needs to be in a format like this:
```
[{'TIME': 41387.756495162001, 'Watts': 0.234652},
{'TIME': 41387.756500821, 'Watts': 0.236125},
{'TIME': 41387.756506480997, 'Watts': 0.23477200000000001},
{'TIME': 41387.756512141001, 'Watts': 0.23453099999999... |
Compress Python Object in Memory | 19,500,530 | 4 | 2013-10-21T17:02:25Z | 19,500,651 | 9 | 2013-10-21T17:08:47Z | [
"python",
"compression"
] | Most tutorials on compressing a file in Python involve immediately writing that file to disk with no intervening compressed python object. I want to know how to pickle and then compress a python object in memory without ever writing to or reading from disk. | I use this to save memory in one place:
```
import cPickle
import zlib
# Compress:
compressed = zlib.compress(cPickle.dumps(obj))
# Get it back:
obj = cPickle.loads(zlib.decompress(compressed))
```
If `obj` has references to a number of small objects, this can reduce the amount of memory used by a lot. A lot of sma... |
How can i convert os.path.getctime() | 19,501,711 | 6 | 2013-10-21T18:12:45Z | 19,502,375 | 12 | 2013-10-21T18:52:47Z | [
"python",
"os.path"
] | How can i convert `os.path.getctime()` to the right time?
My source code is :
```
import os
print("My Path: "+os.getcwd())
print(os.listdir("."))
print("Root/: ",os.listdir("/"))
for items in os.listdir("."):
if os.path.isdir(items):
print(items+" "+"Is a Directory")
print("---Information:")
... | I assume that by *right time* you mean converting timestamp to something with more meaning to humans. If that is the case then this should work:
```
>>> from datetime import datetime
>>> datetime.fromtimestamp(1382189138.4196026).strftime('%Y-%m-%d %H:%M:%S')
'2013-10-19 16:25:38'
``` |
Python find first instance of non zero number in list | 19,502,378 | 5 | 2013-10-21T18:52:54Z | 19,502,403 | 17 | 2013-10-21T18:54:03Z | [
"python",
"list"
] | I have a list like this
```
myList = [0.0 , 0.0, 0.0, 2.0, 2.0]
```
I would like find the location of the first number in list that is not equal to zero.
```
myList.index(2.0)
```
Works in this example but sometimes the first non zero number will be 1 or 3.
Is there a fast way of doing this? | Use `next` with `enumerate`:
```
>>> myList = [0.0 , 0.0, 0.0, 2.0, 2.0]
>>> next((i for i, x in enumerate(myList) if x), None) # x!= 0 for strict match
3
``` |
Python find first instance of non zero number in list | 19,502,378 | 5 | 2013-10-21T18:52:54Z | 19,502,692 | 7 | 2013-10-21T19:08:08Z | [
"python",
"list"
] | I have a list like this
```
myList = [0.0 , 0.0, 0.0, 2.0, 2.0]
```
I would like find the location of the first number in list that is not equal to zero.
```
myList.index(2.0)
```
Works in this example but sometimes the first non zero number will be 1 or 3.
Is there a fast way of doing this? | Use [filter](http://docs.python.org/2/library/functions.html#filter)
```
>>> myList.index(filter(lambda x: x!=0, myList)[0])
3
``` |
convert numpy.datetime64 to string object in python | 19,502,506 | 8 | 2013-10-21T18:58:42Z | 19,503,128 | 16 | 2013-10-21T19:32:45Z | [
"python",
"date",
"datetime",
"numpy"
] | i am having trouble converting python datetime64 object into a string. for example:
```
t = numpy.datetime64('2012-06-30T20:00:00.000000000-0400')
```
into
```
'2012.07.01' as a string. (note time difference)
```
i have already tried to convert the datetime64 object to a datetime long then to a string, but i seem ... | solution was:
```
import pandas as pd
ts = pd.to_datetime(str(date))
d = ts.strftime('%Y.%m.%d')
``` |
Very Basic Python Text Adventure | 19,502,638 | 2 | 2013-10-21T19:05:07Z | 19,502,985 | 8 | 2013-10-21T19:24:37Z | [
"python",
"python-3.x"
] | I'm very new to python, and I'm trying to create a basic text adventure in python. Basically, the way it works is that there is a statement, and then 2 or three choices, each of which leads to something different. My question is this: How can I link 2 statements together so that they lead to the same outcome, when they... | What you're looking for is what is known as a "state machine" (a finite-state machine, more specifically). You have a player who is in state `A`. They then are given a number of choices that can move them to state `B` or `C`. From `B` they are given more choices that can lead them to other states - over to state `C` fo... |
Python 3 How to check if a value is already in a list in a list | 19,503,821 | 4 | 2013-10-21T20:13:07Z | 19,503,844 | 7 | 2013-10-21T20:14:20Z | [
"python",
"list"
] | I have a list of lists in my Python 3:
```
mylist = [[a,x,x][b,x,x][c,x,x]]
```
(x is just some data)
I have my code wich does that:
```
for sublist in mylist:
if sublist[0] == a:
sublist[1] = sublist[1]+1
break
```
now i want to add an entry, if there is any sublistentry ==a
How can I do that... | Use [`any()`](http://docs.python.org/3/library/functions.html#any) to test the sublists:
```
if any(a in subl for subl in mylist):
```
This tests each `subl` but exits the generator expression loop early if a match is found.
This does *not*, however, return the specific sublist that matched. You could use [`next()`]... |
flask sqlalchemy query with keyword as variable | 19,506,105 | 6 | 2013-10-21T22:40:13Z | 19,506,429 | 19 | 2013-10-21T23:12:13Z | [
"python",
"sql",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | Let's say I have a model like this:
```
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
hometown = db.Column(db.String(140))
university = db.Column(db.String(140))
```
To get a list of users from New York, this is my query:
```
User.query.filter_by(hometown='New York').all()
```
To ge... | SQLAlchemy's [`filter_by`](http://docs.sqlalchemy.org/en/rel_0_8/orm/query.html#sqlalchemy.orm.query.Query.filter_by) takes keyword arguments:
> filter\_by(\*\*kwargs)
In other words, the function will allow you to give it any keyword parameter. This is why you can use any keyword that you want in your code: SQLAlche... |
Flask Mega Tutorial - jinja2.exceptions.UndefinedError: 'form' is undefined | 19,506,109 | 5 | 2013-10-21T22:40:25Z | 19,506,161 | 12 | 2013-10-21T22:45:11Z | [
"python",
"flask"
] | I am working through Miguel Grinberg's Flask Mega Tutorial and I cannot figure out why the index page now fails to load. Here is the traceback:
```
File "/home/asdoylejr/microblog/flask/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/home/asdoylej... | The error message that you've received is explained in the stack trace. Specifically, here:
```
File "/home/asdoylejr/microblog/app/templates/index.html", line 7, in block "content"
{{form.hidden_tag()}}
File "/home/asdoylejr/microblog/flask/lib/python2.7/site-packages/jinja2/environment.py", line 397, in getattr
ret... |
How to put appropriate line breaks in a string representing a mathematical expression that is 9000+ characters? | 19,506,790 | 5 | 2013-10-21T23:55:04Z | 19,506,936 | 8 | 2013-10-22T00:13:39Z | [
"python",
"string",
"sympy"
] | I have a many long strings (9000+ characters each) that represent mathematical expressions. I originally generate the expressions using sympy, a python symbolic algebra package. A truncated example is:
```
a = 'm[i]**2*(zb[layer]*m[i]**4 - 2*zb[layer]*m[j]**2*m[i]**2 + zb[layer]*m[j]**4 - zt[layer]*m[i]**4 + 2*zt[laye... | First, just passing [`break_long_words=False`](http://docs.python.org/3.3/library/textwrap.html#textwrap.TextWrapper.break_long_words) will prevent it from splitting `label` in the middle.
But that isn't enough to fix your problem. The output will be valid, but it may exceed 70 columns. In your example, it will:
```
... |
Python error "import: unable to open X server" | 19,507,096 | 15 | 2013-10-22T00:32:51Z | 19,507,173 | 29 | 2013-10-22T00:41:37Z | [
"python"
] | I am getting the following errors when trying to run a piece of python code:
```
import: unable to open X server `' @ error/import.c/ImportImageCommand/366.
from: can't read /var/mail/datetime
./mixcloud.py: line 3: syntax error near unexpected token `('
./mixcloud.py: line 3: `now = datetime.now()'
```
The code:
``... | those are errors from your command shell. you are running code through the shell, not python.
try from a python interpreter ;)
```
$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> from datetime... |
Python: Can a function return an array and a variable? | 19,507,501 | 4 | 2013-10-22T01:22:27Z | 19,507,540 | 10 | 2013-10-22T01:27:27Z | [
"python",
"arrays",
"function"
] | Is there a simple way to get a function to return a np.array and a variable?
eg:
```
my_array = np.zeros(3)
my_variable = 0.
def my_function():
my_array = np.array([1.,2.,3.])
my_variable = 99.
return my_array,my_variable
my_function()
```
so that the values calculated in the function can be used later... | Your function is correct. When you write `return my_array,my_variable`, your function is actually returning a tuple `(my_array, my_variable)`.
You can first assign the return value of `my_function()` to a variable, which would be this tuple I describe:
```
result = my_function()
```
Next, since you know how many ite... |
Python List Comprehension and 'not in' | 19,507,714 | 4 | 2013-10-22T01:48:19Z | 19,507,719 | 10 | 2013-10-22T01:49:52Z | [
"python",
"python-2.x"
] | I'm getting started with Python and is currently learning about list comprehensions so this may sound really strange.
**Question:** Is it possible to use list comprehension to create a list of elements in `t` that is not found in `s`?
I tried the following and it gave me an error:
```
>>> t = [1, 2, 3, 4, 5]
>>> s =... | Try this:
```
[x for x in t if x not in s]
```
You can nest any for if statements in list comprehensions. Try this identation, to get really long chains of conditionals, with a clearer intuition about what the code is doing.
```
my_list = [(x,a)
for x in t
if x not in s
if x > 0
... |
Python Email Parsing Issue | 19,508,393 | 5 | 2013-10-22T03:18:59Z | 19,508,543 | 18 | 2013-10-22T03:37:51Z | [
"python",
"parsing",
"python-3.x",
"gmail",
"smtplib"
] | so I'm trying to write a script in python that logs into my gmail account and then tells me, soon in a GUI, what the message is. I will do a bit more stuff to the code later on to make it a bit program a bit more useful but right now I'm stuck on just being able to parse the raw information that I am getting. Here is m... | Because you are using Python3, instead of using
```
email.message_from_string(raw_email)
```
Use
```
email.message_from_bytes(raw_email)
``` |
Beautiful Soup and Unicode Problems | 19,508,442 | 5 | 2013-10-22T03:23:40Z | 19,508,573 | 17 | 2013-10-22T03:41:14Z | [
"python",
"unicode",
"beautifulsoup"
] | I'm using BeautifulSoup to parse some web pages.
Occasionally I run into a "unicode hell" error like the following :
Looking at the source of this article on TheAtlantic.com [ <http://www.theatlantic.com/education/archive/2013/10/why-are-hundreds-of-harvard-students-studying-ancient-chinese-philosophy/280356/> ]
We ... | You aren't encountering a problem. Everything is behaving as intended.
` ` indicates a [non-breaking space character](https://en.wikipedia.org/wiki/Non-breaking_space). This isn't replaced with a space because it doesn't represent a space; it represents a non-breaking space. Replacing it with a space would lose i... |
class with __iter__ assigned in constructor not recognized as iterator | 19,508,548 | 2 | 2013-10-22T03:38:39Z | 19,508,570 | 10 | 2013-10-22T03:40:45Z | [
"python",
"list",
"iterable"
] | Kind of a weird question about iterators. While investigating a different question, I found the following. Here is an iterable that works:
```
class CacheGen(object):
def __init__(self, iterable):
if isinstance(iterable, (list, tuple, dict)):
self._myiter = iterable
else:
se... | Magic methods like `__iter__` are looked up on the class, not the instance, so it doesn't work to assign them on `self`. They have to actually exist on the class. |
Python, how to write nested list with unequal lengths to a csv file? | 19,510,382 | 5 | 2013-10-22T06:20:00Z | 19,510,491 | 13 | 2013-10-22T06:25:41Z | [
"python",
"list",
"csv",
"numpy"
] | suppose I have an numpy array with structure like this:
```
[['a','b','c'],[1,2,3],['i','j','k','l'],[5,10,15,20]]
```
and I want to save it to a csv file that looks like this
```
a, 1, i, 5
b, 2, j, 10
c, 3, k, 15
, , l, 20
```
the columns with shorter length just fill with blank. How can I do that? | Use `itertools.izip_longest`:
```
>>> from itertools import izip_longest
>>> lis = [['a','b','c'],[1,2,3],['i','j','k','l'],[5,10,15,20]]
>>> list(izip_longest(*lis, fillvalue=''))
[('a', 1, 'i', 5),
('b', 2, 'j', 10),
('c', 3, 'k', 15),
('', '', 'l', 20)]
```
Use `csv.writerows(izip_longest(*lis, fillvalue=''))`... |
Add "b" prefix to python variable? | 19,511,440 | 7 | 2013-10-22T07:16:51Z | 19,511,539 | 9 | 2013-10-22T07:21:59Z | [
"python",
"python-3.x",
"byte"
] | Adding the prefix "b" to a string converts it to bytes:
```
b'example'
```
But I can't figure out how to do this with a variable. Assuming `string = 'example'`, none of these seem to work:
```
b(string)
b string
b'' + string
```
Is there a simple way to do this? | ```
# only an example, you can choose a different encoding
bytes('example', encoding='utf-8')
```
In Python3:
> Bytes literals are always prefixed with 'b' or 'B'; they produce an
> instance of the bytes type instead of the str type. They may only
> contain ASCII characters; bytes with a numeric value of 128 or great... |
sublime - save all open/loaded files that have names? | 19,514,550 | 6 | 2013-10-22T09:54:56Z | 19,516,653 | 7 | 2013-10-22T11:31:00Z | [
"python",
"sublimetext2"
] | In Sublime Text 2, I want to be able to save all open/loaded files that have names.
I like how Sublime can have files with filenames, and have files that were never saved, and can be closed and it remembers about the untitled files and reloads them without me having to save them.
But when a file has a filename and has... | AFAIK, an opened file is represented by one or more views. So try to get all views and save those with file names. I wrote a simple example. Hope it can help you.
By the way, you can check all API's via the following link.
[Sublime Text 2 API Reference](http://www.sublimetext.com/docs/2/api_reference.html)
```
impor... |
How to tokenize a Malayalam word? | 19,515,595 | 14 | 2013-10-22T10:42:22Z | 19,682,422 | 15 | 2013-10-30T12:36:06Z | [
"python",
"unicode",
"nltk"
] | ```
à´à´¤àµà´à´°àµà´¸àµà´à´²à´à´®à´¾à´£àµ
```
*itu oru stalam anu*
This is a Unicode string meaning *this is a place*
```
import nltk
nltk.wordpunct_tokenize('à´à´¤àµà´à´°àµà´¸àµà´¥à´¾à´²à´®à´¾à´£àµ '.decode('utf8'))
```
is not working for me .
```
nltk.word_tokenize('à´à´¤àµà´à´°àµà´¸àµà´¥à´¾à´... | After a crash course of the language from wikipedia (<http://en.wikipedia.org/wiki/Malayalam>), there are some issues in your question and the tools you've requested for your desired output.
**Conflated Task**
Firstly, the OP conflated the task of morphological analysis, segmentation and tokenization. Often there is ... |
List manipulation in python | 19,515,609 | 4 | 2013-10-22T10:43:02Z | 19,515,906 | 12 | 2013-10-22T10:55:45Z | [
"python"
] | You have given a list. Length of list can vary.
```
As an example:
1. ll = [1,2,3]
2. ll = [1,2,3,4]
3. ll = [1,2]
4. ll = []
```
I want to store value in three variables,
```
var1,var2,var3 = None,None,None
If ll[0] exists then var1 = ll[0]
If ll[1] exists then var2 = ll[1]
If ll[3] exists then var3 = ll[2]
```
... | Probably the simplest one
```
var1, var2, var3 = (ll + [None] * 3)[:3]
``` |
Obtaining tags from AWS instances with boto | 19,516,678 | 12 | 2013-10-22T11:32:03Z | 19,587,685 | 20 | 2013-10-25T10:44:26Z | [
"python",
"amazon-web-services",
"boto",
"instances"
] | I'm trying to obtain tags from instances in my AWS account using Python's boto library.
While this snippet works correctly bringing all tags:
```
tags = e.get_all_tags()
for tag in tags:
print tag.name, tag.value
```
(e is an EC2 connection)
When I request tags from individual instances,
```
pr... | You have to be sure that the 'Name' tag exists before accessing it. Try this:
```
import boto.ec2
conn=boto.ec2.connect_to_region("eu-west-1")
reservations = conn.get_all_instances()
for res in reservations:
for inst in res.instances:
if 'Name' in inst.tags:
print "%s (%s) [%s]" % (inst.tags['N... |
Integer division by negative number | 19,517,868 | 14 | 2013-10-22T12:26:34Z | 19,518,866 | 25 | 2013-10-22T13:10:38Z | [
"python",
"ruby",
"math"
] | What should integer division -1 / 5 return? I am totally confused by this behaviour. I think mathematically it should be 0, but python and ruby are returning -1.
Why are different languages behaving differently here? Please someone explain. Thanks.
```
| Language | Code | Result |
|-----------+------------... | **Short answer:** Language designers get to choose if their language will round towards zero, negative infinity, or positive infinity when doing integer division. Different languages have made different choices.
**Long answer:** The language authors of Python and Ruby both decided that rounding towards negative infini... |
How to get error location from json.loads in Python | 19,519,409 | 7 | 2013-10-22T13:33:57Z | 19,520,608 | 8 | 2013-10-22T14:25:49Z | [
"python",
"json"
] | When I use json.loads in Python 3 and catch any resulting errors, like:
```
try:
data = json.loads(string)
except ValueError as err:
print(err)
```
I get a helpful message like:
```
Expecting ',' delimiter: line 12 column 12 (char 271)
```
I would like to be able to display this to the user, along with exactly ... | Scanning the [json/decoder.py source code](http://hg.python.org/cpython/file/4c4f31a1b706/Lib/json/decoder.py), we can see that the decoder's error messages are constructed using the `errmsg` function:
```
def errmsg(msg, doc, pos, end=None):
# Note that this function is called from _json
lineno, colno = linec... |
python catch exception and continue try block | 19,522,990 | 13 | 2013-10-22T16:08:54Z | 19,523,054 | 16 | 2013-10-22T16:12:10Z | [
"python",
"exception"
] | Can I return to executing try-block after exception occurs? (The goal is to write less)
For Example:
```
try:
do_smth1()
except:
pass
try:
do_smth2()
except:
pass
```
vs
```
try:
do_smth1()
do_smth2()
except:
??? # magic word to proceed to do_smth2() if there was exception in do_smth1
``... | No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.
What about a for-loop though?
```
funcs = do_smth1, do_smth2
for func in funcs:
try:
func()
except Exception:
pass # or you could use 'continue'
```
... |
python catch exception and continue try block | 19,522,990 | 13 | 2013-10-22T16:08:54Z | 25,272,170 | 8 | 2014-08-12T19:08:00Z | [
"python",
"exception"
] | Can I return to executing try-block after exception occurs? (The goal is to write less)
For Example:
```
try:
do_smth1()
except:
pass
try:
do_smth2()
except:
pass
```
vs
```
try:
do_smth1()
do_smth2()
except:
??? # magic word to proceed to do_smth2() if there was exception in do_smth1
``... | While the other answers and the accepted one are correct and should be followed in real code, just for completeness and humor, you can try the `fuckitpy` ( <https://github.com/ajalt/fuckitpy> ) module.
Your code can be changed to the following:
```
@fuckitpy
def myfunc():
do_smth1()
do_smth2()
```
Then calli... |
Renaming Column Names in Pandas Groupby function | 19,523,277 | 10 | 2013-10-22T16:23:05Z | 19,523,512 | 12 | 2013-10-22T16:35:08Z | [
"python",
"group-by",
"pandas",
"rename"
] | 1). I have a following example dataset:
```
>>> df
ID Region count
0 100 Asia 2
1 101 Europe 3
2 102 US 1
3 103 Africa 5
4 100 Russia 5
5 101 Australia 7
6 102 US 8
7 104 Asia 10
8 105 Europe 11
9 110 Africa ... | For the first question I think answer would be:
```
<your DataFrame>.rename(columns={'count':'Total_Numbers'})
```
or
```
<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']
```
As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of [python datamodel](http://docs.... |
Python - TypeError: 'int' object is not iterable | 19,523,563 | 12 | 2013-10-22T16:37:54Z | 19,523,620 | 30 | 2013-10-22T16:40:40Z | [
"python",
"list",
"loops",
"iterable"
] | Here's my code:
```
import math
print "Hey, lets solve Task 4 :)"
number1 = input ("How many digits do you want to look at? ")
number2 = input ("What would you like the digits to add up to? ")
if number1 == 1:
cow = range(0,10)
elif number1 == 2:
cow = range(10,100)
elif number1 == 3:
cow = range(100,10... | Your problem is with this line:
```
number4 = list(cow[n])
```
It tries to take `cow[n]`, which returns an integer, and make it a list. This doesn't work, as demonstrated below:
```
>>> a = 1
>>> list(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
... |
Is boto library thread-safe? | 19,523,680 | 6 | 2013-10-22T16:43:59Z | 19,542,645 | 7 | 2013-10-23T13:11:05Z | [
"python",
"thread-safety",
"boto",
"amazon-dynamodb"
] | Specifically I'm interested in using a DynamoDB table object from multiple threads (puts, gets, updates, etc). If that's not safe, then is there a safe way (i.e., maybe one table object per thread)? Any other gotchas or tips about working with threads in boto appreciated. | The boto library uses httplib which has never been, and to my knowledge still is not, thread-safe. The workaround is to make sure each thread creates its own connection to DynamoDB and you should be good. |
django select_related in template | 19,523,698 | 4 | 2013-10-22T16:44:51Z | 19,523,899 | 13 | 2013-10-22T16:55:23Z | [
"python",
"html",
"sql",
"django",
"templates"
] | Sometimes it makes sense to use select\_related in a django template. For example, say I have a class extending DetailView
```
class DemoCarView(DetailView):
model = Car
```
Based on the following contrived model
```
# Cars
class Car(models.Model):
name = models.CharField(max_length=32)
# Manufacturers
clas... | How about a simple method on the `Car` model?
```
class Car(models.Model):
...
def parts_with_manufacturers(self):
return self.part_set.select_related('manufacturer')
```
and then
```
{% for part in car.parts_with_manufacturers %}
<li>{{ part.name }} - {{ part.manufacturer.name }} </li>
{% endfor... |
How to send username:password to unittest's app.get() request? | 19,524,069 | 7 | 2013-10-22T17:03:20Z | 19,529,153 | 11 | 2013-10-22T21:57:18Z | [
"python",
"unit-testing",
"flask",
"http-basic-authentication",
"flask-restful"
] | This is part of my unit test in Flask-RESTful.
```
self.app = application.app.test_client()
rv = self.app.get('api/v1.0/{0}'.format(ios_sync_timestamp))
eq_(rv.status_code,200)
```
Within the command line I could use curl to send the username:password to the service:
```
curl -d username:password http://localhost:50... | From [RFC 1945, Hypertext Transfer Protocol -- HTTP/1.0](https://tools.ietf.org/html/rfc1945)
> [11.1 Basic Authentication Scheme](https://tools.ietf.org/html/rfc1945#section-11.1)
>
> ...
>
> To receive authorization, the client sends the user-ID and password,
> separated by a single colon (":") character, within a b... |
Suppress code in NBConvert? IPython | 19,524,554 | 15 | 2013-10-22T17:28:52Z | 19,528,147 | 23 | 2013-10-22T20:53:32Z | [
"python",
"ipython",
"ipython-notebook"
] | I have figured out how to suppress large code blocks from showing up in final NB convert (PDF) output.
By putting the LaTex command in a "raw cell before the code I don't want to have in the final output
```
\iffalse
```
Followed By this at the end In a raw cell
```
\fi
```
But That still leaves me with some ugly ... | To suppress the code cells (only input) a custom template can be used. Similar as discussed in [this question](http://stackoverflow.com/q/19385350/2870069), a template e.g. *latex\_nocode.tplx* has to be created (in the working directory) with the following content (for IPython 1.x)
```
((*- extends 'latex_article.tpl... |
Python flask flash message exception remains after restarting | 19,525,376 | 2 | 2013-10-22T18:17:28Z | 19,525,521 | 7 | 2013-10-22T18:25:23Z | [
"python",
"flask"
] | I'm making a small flask app where I had something like this:
```
@app.route('/bye')
def logout():
session.pop('logged_in', None)
flash('Adiós')
return redirect('/index')
```
Needless to say when I ran the application and I navigated to '/bye' it gave me a UnicodeDecodeError. Well, now it gives me the sa... | I think that flash() actually creates a session called session['\_flashes']. See this code [here](https://github.com/mitsuhiko/flask/blob/master/flask/helpers.py#L362). So you will probably have to either:
```
clear/delete the cookie
```
OR
```
session.pop('_flashes', None)
``` |
Weakref and __slots__ | 19,526,340 | 13 | 2013-10-22T19:13:38Z | 19,526,505 | 17 | 2013-10-22T19:22:34Z | [
"python",
"weak-references"
] | Consider the following code:
```
from weakref import ref
class Klass(object):
# __slots__ = ['foo']
def __init__(self):
self.foo = 'bar'
k = Klass()
r = ref(k)
```
it works but when I uncomment the `__slots__` it breaks with `TypeError: "cannot create weak reference to 'Klass' object"` under Python ... | > Without a `__weakref__` variable for each instance, classes defining `__slots__` do not support weak references to its instances. If weak reference support is needed, then add `__weakref__` to the sequence of strings in the `__slots__` declaration.
From the [Python documentation](http://docs.python.org/2/reference/d... |
Python - Unicode to ASCII conversion | 19,527,279 | 9 | 2013-10-22T20:05:57Z | 19,527,434 | 31 | 2013-10-22T20:13:58Z | [
"python",
"unicode",
"encoding",
"ascii"
] | I am unable to convert the following Unicode to ASCII without losing data
```
u'ABRA\xc3O JOS\xc9'
```
Tried encode, decode and it won´t do.
Anyone have a suggestion? | The Unicode characters `u'\xce0'` and `u'\xc9'` do not have any corresponding ASCII values. So, if you don't want to lose data, you have to encode that data in some way that's valid as ASCII. Options include:
```
>>> print s.encode('ascii', errors='backslashreplace')
ABRA\xc3O JOS\xc9
>>> print s.encode('ascii', error... |
limit the maximum running time for unit test | 19,527,320 | 7 | 2013-10-22T20:08:25Z | 19,527,487 | 14 | 2013-10-22T20:17:13Z | [
"python",
"py.test"
] | I am currently running some unit tests that might either take a long time before failing or run indefinitely. In a successful test run they will always complete within a certain amount of time. Is it possible to create a pytest unit test that will fail if it does not complete within a certain amount of time? | you can install the pytest-timeout plugin and then mark your test functions with a timeout in milliseconds.
```
@pytest.mark.timeout(300)
def test_foo():
pass
```
Look at the plugin download and usage instructions at <https://pypi.python.org/pypi/pytest-timeout> |
Python: How to convert a timezone aware timestamp to UTC without knowing if DST is in effect | 19,527,351 | 14 | 2013-10-22T20:09:29Z | 19,527,596 | 15 | 2013-10-22T20:24:14Z | [
"python",
"datetime",
"dst",
"pytz"
] | I am trying to convert a naive timestamp that is always in Pacific time to UTC time. In the code below, I'm able to specify that this timestamp I have is in Pacific time, but it doesn't seem to know that it should be an offset of -7 hours from UTC because it's only 10/21 and DST has not yet ended.
The script:
```
imp... | Use the `localize` method:
```
import pytz
import datetime
naive_date = datetime.datetime.strptime("2013-10-21 08:44:08", "%Y-%m-%d %H:%M:%S")
localtz = pytz.timezone('America/Los_Angeles')
date_aware_la = localtz.localize(naive_date)
print(date_aware_la) # 2013-10-21 08:44:08-07:00
```
This is covered in the "Exam... |
How to run python script on terminal (ubuntu)? | 19,530,015 | 9 | 2013-10-22T23:17:32Z | 19,530,080 | 14 | 2013-10-22T23:24:50Z | [
"python",
"linux",
"ubuntu"
] | I'm new with python, I've been learning for a few weeks. However now I've just changed my OS and I'm now using ubuntu and I can't run any script on my terminal.
I made sure to have the `#!/usr/bin/env python`
but when I go to the terminal and type, for example `python test.py`
the terminal shows an error message like ... | This error:
> python: can't open file 'test.py': [Errno 2] No such file or directory
Means that the file "test.py" doesn't exist. (Or, it does, but it isn't in the current working directory.)
> I must save the file in any specific folder to make it run on terminal?
No, it can be where ever you want. However, if you... |
Can pandas groupby aggregate into a list, rather than sum, mean, etc? | 19,530,568 | 12 | 2013-10-23T00:14:15Z | 24,112,443 | 12 | 2014-06-09T01:05:46Z | [
"python",
"pandas"
] | I've had success using the groupby function to sum or average a given variable by groups, but is there a way to aggregate into a list of values, rather than to get a single result? (And would this still be called aggregation?)
I am not entirely sure this is the approach I should be taking anyhow, so below is an exampl... | I am answering the question as stated in its title and first sentence: the following aggregates values to lists.
```
import pandas as pd
df = pd.DataFrame( {'A' : [1, 1, 1, 1, 2, 2, 3], 'B' : [10, 12, 11, 10, 11, 12, 14], 'C' : [22, 20, 8, 10, 13, 10, 0]})
print df
df2=df.groupby(['A']).apply(lambda tdf: pd.Seri... |
Can pandas groupby aggregate into a list, rather than sum, mean, etc? | 19,530,568 | 12 | 2013-10-23T00:14:15Z | 29,500,330 | 17 | 2015-04-07T20:06:14Z | [
"python",
"pandas"
] | I've had success using the groupby function to sum or average a given variable by groups, but is there a way to aggregate into a list of values, rather than to get a single result? (And would this still be called aggregation?)
I am not entirely sure this is the approach I should be taking anyhow, so below is an exampl... | I used the following
```
grouped = df.groupby('A')
df = grouped.aggregate(lambda x: tuple(x))
df['grouped'] = df['B'] + df['C']
``` |
Pandas Dataframe add header without replacing current header | 19,530,708 | 6 | 2013-10-23T00:29:12Z | 19,530,951 | 10 | 2013-10-23T00:59:41Z | [
"python",
"pandas"
] | How can I add a header to a DF without replacing the current one? In other words I just want to shift the current header down and just add it to the dataframe as another record.
\*secondary question: How do I add tables (example dataframe) to stackoverflow question?
I have this (Note header and how it is just added a... | Another option is to add it as an additional level of the column index, to make it a MultiIndex:
```
In [11]: df = pd.DataFrame(randn(2, 2), columns=['A', 'B'])
In [12]: df
Out[12]:
A B
0 -0.952928 -0.624646
1 -1.020950 -0.883333
In [13]: df.columns = pd.MultiIndex.from_tuples(zip(['AA', 'BB'], df... |
How can I install sqlite3 to Python? | 19,530,974 | 20 | 2013-10-23T01:01:51Z | 19,530,987 | 37 | 2013-10-23T01:03:19Z | [
"python",
"sqlite3",
"pip"
] | Can someone tell me how to install sqlite3 package to the very recent version of Python?
I use Macbook, and on the command line I tried:
```
pip install sqlite
```
but an error pops up. | You don't need to install [`sqlite3`](http://docs.python.org/2/library/sqlite3.html) module. It is included in the standard library (since Python 2.5). |
How can I install sqlite3 to Python? | 19,530,974 | 20 | 2013-10-23T01:01:51Z | 28,959,692 | 16 | 2015-03-10T09:06:58Z | [
"python",
"sqlite3",
"pip"
] | Can someone tell me how to install sqlite3 package to the very recent version of Python?
I use Macbook, and on the command line I tried:
```
pip install sqlite
```
but an error pops up. | I have python 2.7.3 and this solved my problem:
```
pip install pysqlite
``` |
Segmentation fault: 11 in OS X | 19,531,969 | 55 | 2013-10-23T02:55:33Z | 19,629,468 | 46 | 2013-10-28T07:46:30Z | [
"python",
"osx"
] | I am getting an issue in Python 3.3.2 on OSX 10.9 where if I open Python in a terminal window, it exits with "Segmentation error: 11" after the second line I enter, regardless of what the two commands are. For example, if I enter:
```
>>> for x in range(1000): print(x)
```
that works fine, but if I enter:
```
>>> fo... | This is a bug in the readline compatibility in python, related to changes introduced in OSX10.9. This weekend, release candidates for Python2.7.6 and Python3.3.3 were released which fix this bug. The download links are below.
<http://python.org/download/releases/2.7.6/>
<http://python.org/download/releases/3.3.3/>
H... |
Segmentation fault: 11 in OS X | 19,531,969 | 55 | 2013-10-23T02:55:33Z | 20,196,286 | 34 | 2013-11-25T15:02:52Z | [
"python",
"osx"
] | I am getting an issue in Python 3.3.2 on OSX 10.9 where if I open Python in a terminal window, it exits with "Segmentation error: 11" after the second line I enter, regardless of what the two commands are. For example, if I enter:
```
>>> for x in range(1000): print(x)
```
that works fine, but if I enter:
```
>>> fo... | A patch is provided on the Python website: <http://bugs.python.org/issue18458#msg201087>
To use it, open a terminal session in Terminal.app (or other shell), then enter:
```
curl -O http://bugs.python.org/file32324/patch_readline_issue_18458.sh
openssl sha1 patch_readline_issue_18458.sh
# the digest should be 7cb0ff5... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.