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
Django dumpdata django.contrib.auth
16,126,586
6
2013-04-21T00:06:48Z
16,127,248
18
2013-04-21T02:03:01Z
[ "python", "django", "manage.py" ]
I want dump data of `django.contrib.auth` app. I've tried: ``` >> python manage.py dumpdata django.contrib.auth > 'django.contrib.admin.json' Error: Unknown application: django.contrib.auth >> python manage.py dumpdata 'django.contrib.auth' > 'django.contrib.admin.json' Error: Unknown application: django.contrib.auth...
Solution was much more easy than a thought. Just run ``` python manage.py dumpdata auth ```
What is the purpose of calling __init__ directly?
16,126,734
2
2013-04-21T00:27:16Z
16,126,757
7
2013-04-21T00:31:39Z
[ "python", "init" ]
I am having a hard time figuring out the purpose behind some code that I've come across. The code has a class 'Foo', which has an init method that takes multiple arguments. From what I've learned of python so far, by calling Foo('bar'), it will pass this string as a parameter to `__init__` (which I think is supposed to...
The \_\_init\_\_() method gets called for you when you instantiate a class. However, the \_\_init\_\_() method in a parent class doesn't get called automatically, so need you to call it directly if you want to extend its functionality: ``` class A: def __init__(self, x): self.x = x class B(A): d...
python scipy.odrpack.odr example (with sample input / output)?
16,126,884
4
2013-04-21T00:52:46Z
16,127,329
9
2013-04-21T02:21:52Z
[ "python", "scipy" ]
I am a satisfied user of `scipy.optimize.leastsq`. I now have -- really have always had -- x,y data with variable error bars, and it looks like scipy.odrpack.odr is what I need to use to respect the greater uncertainty in some of the data. Unfortunately, I cannot find an online tutorial which includes sample code wit...
This is a fleshed-out version of the example in [the docs](http://www.scipy.org/doc/api_docs/SciPy.odr.odrpack.html): ``` import numpy as np import scipy.odr.odrpack as odrpack np.random.seed(1) N = 100 x = np.linspace(0,10,N) y = 3*x - 1 + np.random.random(N) sx = np.random.random(N) sy = np.random.random(N) def f(...
Creating command line switches in python
16,127,036
5
2013-04-20T12:56:27Z
16,127,037
8
2013-04-20T13:04:44Z
[ "python" ]
For example, sqlmap uses `python sqlmap.py -h`. This command above lists all available switches in sqlmap, and `-h` is a switch itself. When you are creating a python tool for use in terminal, what is the basic method to create a switch? A hello world example would be most appreciative!
These are command line options. You can use the stdlib [`argparse` module](http://docs.python.org/2/library/argparse.html) for that. ``` import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an ...
cc1: error: unrecognized command line option "-Wno-null-conversion" within installing python-mysql on mac 10.7.5
16,127,493
9
2013-04-21T02:55:21Z
16,132,663
26
2013-04-21T15:15:04Z
[ "python", "mysql", "osx", "python-2.7", "mysql-python" ]
This error broke my python-mysql installation on Mac 10.7.5. Here are the steps 1. The installed python is 2.7.1, mysql is 64 bit for 5.6.11. 2. The being installed python-mysql is 1.2.4, also tried 1.2.3 3. Configurations for the installation ``` 1) sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql ...
Try to Remove `cflags -Wno-null-conversion -Wno-unused-private-field` in ``` /usr/local/mysql/bin/mysql_config. ``` like: ``` cflags="-I$pkgincludedir -Wall -Os -g -fno-strict-aliasing -DDBUG_OFF -arch x86_64 " #note: end space! ```
in Python, how to convert list of float numbers to string with certain format?
16,127,862
4
2013-04-21T04:06:11Z
16,127,903
9
2013-04-21T04:13:26Z
[ "python", "string", "python-2.7", "floating-point" ]
I have a list of tuple of float numbers, something like ``` [ (1.00000001, 349183.1430, 2148.12222222222222), ( , , ), ..., ( , ,) ] ``` How can I convert all numbers to strings, with same format (scientific notation with 8 decimal point precision), while maintaining the same structure (list of tuples, or list of lis...
Assuming you have some list-of-lists or list-of-tuples: ``` lst = [ [ 1,2,3 ], [ 1e6, 2e6, 3e6], [1e-6, 2e-6, 3e-6] ] ``` You can create a parallel list-of-lists using list comprehension: ``` str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst] ``` Or a list-of-tuples: ``` str_list = [tuple('...
Using inheritance in python
16,128,833
4
2013-04-21T07:15:44Z
16,128,853
7
2013-04-21T07:19:39Z
[ "python", "class", "inheritance" ]
this is my homework assignment, I saw it posted on the website before, but it looks like it was unsolved and I got a different error message than a person asking that question before. the first part of the problem is to define the subclass Worker that inherits from Employee and includes an attribute that refers to ano...
The error is pretty clear. `salary` is not defined in the `__init__` method of `Executive`. You used `wage` as an argument to `__init__`, but `salary` when calling `__init__` of your parent class, so you should stick to one variable name: ``` class Executive(Employee): def __init__(self, name, salary, yearlyBonus...
Train scikit svm one by one (online or stochastic training)
16,128,834
4
2013-04-21T07:15:58Z
16,129,225
12
2013-04-21T08:15:05Z
[ "python", "machine-learning", "svm", "scikit-learn" ]
I am using scikit library for using svm. I have huge amount of data which I can't read together to give [`fit()` function](http://scikit-learn.org/stable/modules/generated/sklearn.svm.libsvm.fit.html#sklearn.svm.libsvm.fit). I want to give iterate over all my data which is in a file and train svm one by one. Is there...
Support Vector Machine (at least as implemented in libsvm which scikit-learn is a wrapper of) is fundamentally a batch algorithm: it needs to have access to all the data in memory at once. Hence they are not scalable. Instead you should use models that support incremental learning with the `partial_fit` method. For in...
Pagination using scrapy
16,129,071
5
2013-04-21T07:54:28Z
16,133,788
8
2013-04-21T17:01:49Z
[ "python", "request", "web-scraping", "scrapy" ]
I'm trying to crawl this website: <http://www.aido.com/eshop/cl_2-c_189-p_185/stationery/pens.html> I can get all the products in this page, but how do I issue the request for "View More" link at the bottom of the page? My code till now is: ``` rules = ( Rule(SgmlLinkExtractor(restrict_xpaths='//li[@class="norma...
First of all, you should take a look at this thread on how to deal with scraping ajax dynamically loaded content: [Can scrapy be used to scrape dynamic content from websites that are using AJAX?](http://stackoverflow.com/questions/8550114/can-scrapy-be-used-to-scrape-dynamic-content-from-websites-that-are-using-ajax) ...
Accessing JSON elements
16,129,652
14
2013-04-21T09:19:05Z
16,129,667
28
2013-04-21T09:20:50Z
[ "python", "json" ]
I am getting the weather information from a URL. ``` weather = urllib2.urlopen('url') wjson = weather.read() ``` and what I am getting is: ``` { "data": { "current_condition": [{ "cloudcover": "0", "humidity": "54", "observation_time": "08:49 AM", "precipMM": "0.0", "pr...
``` import json weather = urllib2.urlopen('url') wjson = weather.read() wjdata = json.loads(wjson) print wjdata['data']['current_condition'][0]['temp_C'] ``` What you get from the url is a json string. And your can't parse it with index directly. You should convert it to a dict by `json.loads` and then you can parse i...
Accessing JSON elements
16,129,652
14
2013-04-21T09:19:05Z
16,130,026
10
2013-04-21T10:05:57Z
[ "python", "json" ]
I am getting the weather information from a URL. ``` weather = urllib2.urlopen('url') wjson = weather.read() ``` and what I am getting is: ``` { "data": { "current_condition": [{ "cloudcover": "0", "humidity": "54", "observation_time": "08:49 AM", "precipMM": "0.0", "pr...
Here's an alternative solution using [requests](http://docs.python-requests.org/en/latest/): ``` import requests wjdata = requests.get('url').json() print wjdata['data']['current_condition'][0]['temp_C'] ```
Python 3 replacement for PyFile_AsFile
16,130,268
6
2013-04-21T10:37:02Z
16,132,269
7
2013-04-21T14:39:07Z
[ "python", "python-3.x", "ctypes", "ffi" ]
The following code works in Python 2: ``` from ctypes import * ## Setup python file -> c 'FILE *' conversion : class FILE(Structure): pass FILE_P = POINTER(FILE) PyFile_AsFile = pythonapi.PyFile_AsFile # problem here PyFile_AsFile.argtypes = [py_object] PyFile_AsFile.restype = FILE_P fp = open(filename,'wb') gd.g...
> I just needed a way to convert a file object to a ctypes FILE\* so that I can pass it to GD. You are out of luck. That was possible in Python 2.x, but is not possible in Python 3.x. The [documentation](http://docs.python.org/3.3/c-api/file.html) explains why not: > These APIs are a minimal emulation of the Python 2...
REGEX-String and escaped quote
16,130,404
2
2013-04-21T10:56:19Z
16,130,746
9
2013-04-21T11:43:24Z
[ "python", "regex" ]
How to get what is between the quotes in the following two texts ? ``` text_1 = r""" "Some text on \"two\" lines with a backslash escaped\\" \ + "Another text on \"three\" lines" """ text_2 = r""" "Some text on \"two\" lines with a backslash escaped\\" + "Another text on \"three\" lines" """ ``` The problem for...
``` "(?:\\.|[^"\\])*" ``` matches a quoted string, including any escaped characters that occur within it. **Explanation:** ``` " # Match a quote. (?: # Either match... \\. # an escaped character | # or [^"\\] # any character except quote or backslash. )* # Repeat any number of times. " ...
Why am I getting the error "connection refused" in Python? (Sockets)
16,130,786
28
2013-04-21T11:49:46Z
16,130,819
41
2013-04-21T11:53:36Z
[ "python", "sockets" ]
I'm new to Sockets, please excuse my complete lack of understanding. I have a server script(server.py): ``` #!/usr/bin/python import socket #import the socket module s = socket.socket() #Create a socket object host = socket.gethostname() #Get the local machine name port = 12397 # Reserve a port for your service s.b...
Instead of ``` host = socket.gethostname() #Get the local machine name port = 12397 # Reserve a port for your service s.bind((host,port)) #Bind to the port ``` you should try ``` port = 12397 # Reserve a port for your service s.bind(('', port)) #Bind to the port ``` so that the listening socket isn't too restricted...
Open() and codecs.open() in Python 2.7 behave strangely different
16,130,904
6
2013-04-21T12:04:43Z
16,155,098
11
2013-04-22T19:24:36Z
[ "python", "python-2.7", "file-io", "codec", "python-unicode" ]
I have a text file with first line of unicode characters and all other lines in ASCII. I try to read the first line as one variable, and all other lines as another. However, when I use the following code: ``` # -*- coding: utf-8 -*- import codecs import os filename = '1.txt' f = codecs.open(filename, 'r3', encoding='u...
Because you used `.readline()` *first*, the `codecs.open()` file has filled a linebuffer; the subsequent call to `.readlines()` returns *only* the buffered lines. If you call `.readlines()` *again*, the rest of the lines are returned: ``` >>> f = codecs.open(filename, 'r3', encoding='utf-8') >>> line = f.readline() >...
Synchronous/Asynchronous behaviour of python Pipes
16,132,299
7
2013-04-21T14:41:28Z
16,192,680
8
2013-04-24T12:59:22Z
[ "python", "linux", "multiprocessing", "pipe" ]
In my application I'm using pipes from the multiprocessing module to communicate between python processes. Lately I've observed a weird behaviour depending on the size of data I'm sending through them. According to the python documentation these pipes are based on the connections and should behave in an asynchronous ma...
First of all, it's worth noting the implementation of the [`multiprocessing.Pipe`](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Pipe) class... ``` def Pipe(duplex=True): ''' Returns pair of connection objects at either end of a pipe ''' if duplex: s1, s2 = socket.socket...
Python Mocking a method from an imported module
16,134,281
30
2013-04-21T17:48:07Z
16,134,754
37
2013-04-21T18:35:36Z
[ "python", "unit-testing", "python-unittest", "python-mock" ]
I want to understand how to `@patch` a function from an imported module. This is where I am so far. **app/mocking.py:** ``` from app.my_module import get_user_name def test_method(): return get_user_name() if __name__ == "__main__": print "Starting Program..." test_method() ``` **app/my\_module/\_\_init\_\_...
When you are using the `patch` decorator from the `unittest.mock` package you are **not** patching the namespace the module is imported from (in this case `app.my_module.get_user_name`) you are patching it in the namespace under test `app.mocking.get_user_name`. To do the above with `Mock` try something like the below...
Python/Regex to parse code
16,136,328
2
2013-04-21T21:18:42Z
16,136,353
7
2013-04-21T21:21:35Z
[ "python", "regex", "parsing" ]
so i have some lines that looks like this in FORTRAN. ``` call const (hsno, npoi*nsnolay, 0.0) ``` I have been using regex and python string functions to parse this code and edit some of the variables. however lines like the one above give me a problem, as the string wont split on the parentheses. I want it to be: ...
Matched parenthesis are not a regular language. That means that they can't be recognized by regular expressions in the mathematical sense. Most programming languages add additional features to make regular expressions more powerful, but it's still a pain to do stuff like this. I'd recommend you get a proper parser. Th...
Using SocksiPy with SSL
16,136,916
6
2013-04-21T22:32:38Z
19,615,059
7
2013-10-27T05:44:30Z
[ "python", "ssl" ]
I'm trying to use SocksIPy with ssl module (from stdlib) to grab a site's remote certificate but SocksIPy won't play with ssl. The below code will connect to check.torproject.org and state we are not using Tor (meaning SocksIPy is not working) (bad). Not sure if SocksIPy is the best solution for this but I haven't be...
I have tested this code while running tcpdump so it should work. ``` import socks import ssl s = socks.socksocket() s.setproxy(socks.PROXY_TYPE_SOCKS5,"127.0.0.1",port=9050) s.connect(('83.94.121.246', 443)) ss = ssl.wrap_socket(s) print ss.send("hello") ss.close() ``` I didn't review the ssl.py but I guess you have...
Python Error importing Curses - not sure why
16,137,108
2
2013-04-21T22:57:57Z
16,137,124
9
2013-04-21T23:01:07Z
[ "python", "curses" ]
So I do have curses installed Ive checked it with dpkg. Now when I try to import it, this happens ``` Python 2.7.3 (default, Jan 13 2013, 11:20:46) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import curses Traceback (most recent call last): File "<stdin>", line 1,...
``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "curses.py", line 3, in <module> ``` It seems you named your own file curses.py, Python looks in the current directory first so you cannot have the same name as a library.
List Iteration in Python
16,137,837
2
2013-04-22T00:45:30Z
16,137,846
13
2013-04-22T00:47:02Z
[ "python", "list", "for-loop" ]
So i get this error: ``` TypeError: list indices must be integers, not str ``` pointing to this line of code: ``` if snarePattern[i] == '*': ``` whenever I use what I thought was simple Python ``` snarePattern = ['-', '*', '-', '*'] for i in snarePattern: if snarePattern[i] == '*': ... ``` Is this not...
`for i in snarePattern:` goes through each **item** not each index: ``` >>> snarePattern = ['-', '*', '-', '*'] >>> for c in snarePattern: print c - * - * ``` You can change it to ``` for i in range(len(snarePattern)): ``` if you really need it, but it looks like you don't, just check if `c == '*'` for ex...
Checking if all the elements in one list are also in another
16,138,015
19
2013-04-22T01:16:26Z
16,138,094
42
2013-04-22T01:26:01Z
[ "python", "list" ]
I'm trying to compare two lists and simply print a message if the same value was found in both lists. ``` def listCompare(): list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] if list1 in list2: print("Number was found") else: print("Number not in list") ``` This doesnt work, and I'm not sure of the simp...
You could solve this many ways. One that is pretty simple to understand is to just use a loop. ``` def comp(list1, list2): for val in list1: if val in list2: return True return False ``` A more compact way you can do it is to use [`map`](https://docs.python.org/2/library/functions.html#map...
Checking if all the elements in one list are also in another
16,138,015
19
2013-04-22T01:16:26Z
16,138,120
11
2013-04-22T01:29:39Z
[ "python", "list" ]
I'm trying to compare two lists and simply print a message if the same value was found in both lists. ``` def listCompare(): list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] if list1 in list2: print("Number was found") else: print("Number not in list") ``` This doesnt work, and I'm not sure of the simp...
There are different ways. If you just want to check if one list contains any element from the other list, you can do this.. ``` not set(list1).isdisjoint(list2) ``` I believe using `isdisjoint` is better than `intersection` for Python 2.6 and above.
Correct way to generate random numbers in Cython?
16,138,090
11
2013-04-22T01:25:44Z
16,138,495
7
2013-04-22T02:21:59Z
[ "python", "random", "numpy", "cython" ]
What is the most efficient and portable way to generate a random random in `[0,1]` in Cython? One approach is to use `INT_MAX` and `rand()` from the C library: ``` from libc.stdlib cimport rand cdef extern from "limits.h": int INT_MAX cdef float randnum = rand() / float(INT_MAX) ``` Is it OK to use `INT_MAX` in t...
The C standard says `rand` returns an `int` in the range 0 to RAND\_MAX inclusive, so dividing it by RAND\_MAX (from `stdlib.h`) is the proper way to normalise it. In practice, RAND\_MAX will almost always be equal to MAX\_INT, but don't rely on that. Because `rand` has been part of ISO C since C89, it's guaranteed to...
Is it a good practice to use try-except-else in Python?
16,138,232
158
2013-04-22T01:44:52Z
16,138,256
17
2013-04-22T01:47:55Z
[ "python", "exception", "exception-handling", "try-catch" ]
From time to time in Python, I see the block: ``` try: try_this(whatever) except SomeException as exception: #Handle exception else: return something ``` **What is the reason for the try-except-else to exist?** I do not like that kind of programming, as it is using exceptions to perform flow control. Howeve...
Python doesn't subscribe to the idea that exceptions should only be used for exceptional cases, in fact the idiom is ['ask for forgiveness, not permission'](http://docs.python.org/2/glossary.html#term-eafp). This means that using exceptions as a routine part of your flow control is perfectly acceptable, and in fact, en...
Is it a good practice to use try-except-else in Python?
16,138,232
158
2013-04-22T01:44:52Z
16,138,864
232
2013-04-22T03:13:38Z
[ "python", "exception", "exception-handling", "try-catch" ]
From time to time in Python, I see the block: ``` try: try_this(whatever) except SomeException as exception: #Handle exception else: return something ``` **What is the reason for the try-except-else to exist?** I do not like that kind of programming, as it is using exceptions to perform flow control. Howeve...
> "I do not know if it is out of ignorance, but i do not like that > kind of programming, as it is using exceptions to perform flow control." In the Python world, using exceptions for flow control is common and normal. Even the Python core developers use exceptions for flow-control and that style is heavily baked int...
Is it a good practice to use try-except-else in Python?
16,138,232
158
2013-04-22T01:44:52Z
28,304,423
10
2015-02-03T16:54:25Z
[ "python", "exception", "exception-handling", "try-catch" ]
From time to time in Python, I see the block: ``` try: try_this(whatever) except SomeException as exception: #Handle exception else: return something ``` **What is the reason for the try-except-else to exist?** I do not like that kind of programming, as it is using exceptions to perform flow control. Howeve...
> **Is it a good practice to use try-except-else in python?** The answer to this is that it is context dependent. If you do this: ``` d = dict() try: item = d['item'] except KeyError: item = 'default' ``` It demonstrates that you don't know Python very well. This functionality is encapsulated in the `dict.ge...
Is it a good practice to use try-except-else in Python?
16,138,232
158
2013-04-22T01:44:52Z
31,626,974
26
2015-07-25T13:30:17Z
[ "python", "exception", "exception-handling", "try-catch" ]
From time to time in Python, I see the block: ``` try: try_this(whatever) except SomeException as exception: #Handle exception else: return something ``` **What is the reason for the try-except-else to exist?** I do not like that kind of programming, as it is using exceptions to perform flow control. Howeve...
> # What is the reason for the try-except-else to exist? A `try` block allows you to handle a expected error. The `except` block should only catch exceptions you are prepared to handle. If you handle an unexpected error, your code may do the wrong thing and hide bugs. An `else` clause will execute if there were no er...
Extract time from datetime and determine if time (not date) falls within range?
16,138,744
5
2013-04-22T02:56:15Z
16,139,085
7
2013-04-22T03:43:32Z
[ "python", "datetime", "python-2.6" ]
The problem is that I want it to ignore the date and only factor in the time. Here is what I have: ``` import time from time import mktime from datetime import datetime def getTimeCat(Datetime): # extract time categories str_time = datetime.strptime(Datetime, "%m/%j/%y %H:%M") ts = datetime.fromtimestamp(...
This line: ``` str_time = datetime.strptime(Datetime, "%m/%j/%y %H:%M") ``` returns a `datetime` object [as per the docs](http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime). You can test this yourself by running the following command interactively in the interpreter: ``` >>> import datetime ...
Getting error in scrapy web crawler
16,139,846
5
2013-04-22T05:12:50Z
16,141,121
9
2013-04-22T06:56:08Z
[ "python", "web-scraping", "scrapy", "web-crawler", "scrapy-spider" ]
Hi I tried to implement this in my code.But I am getting the following error: `exceptions.NameError: global name 'Request' is not defined`. ``` from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from bs4 import BeautifulSoup class spider_aicte(BaseSpider): name = "Indian_Colleges"...
You should import [`Request`](http://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Request) before using: ``` from scrapy.http import Request ``` --- Or, there is also a "shortcut" import: ``` from scrapy import Request ``` Or, if you have `import scrapy` line, use `scrapy.Request`.
Conflicting variable and function names in python
16,140,986
2
2013-04-22T06:46:54Z
16,141,282
11
2013-04-22T07:06:25Z
[ "python" ]
Let's say I've got the following functions: ``` def xplusy(x, y): return x+y def xplus1(x): xplusy = xplusy(x, 1) return xplusy ``` Now if I call `a = xplus1(4)` it throws the following error: ``` UnboundLocalError: local variable 'xplusy' referenced before assignment ``` The error is because of the na...
In Python, functions are data, and typing is dynamic. This means that the following lines are valid Python: ``` def func(x): return x + 3 func = 3 ``` `func` is now an int. The original function `func` is no longer referenced. The fact that `func` was originally a function doesn't have any bearing on what types ...
Raspberry Pi- GPIO Events in Python
16,143,842
14
2013-04-22T09:37:31Z
18,596,063
16
2013-09-03T15:29:17Z
[ "python", "events", "raspberry-pi", "motion", "gpio" ]
I am using the GPIO pins on my Raspberry Pi with a PIR sensor to detect motion. When the sensor detects motion I want to then move the software onto other functions. At the moment, to detect motion I have my program constantly running in a loop while it is waiting for motion to be detected. While this works at the mom...
The **RPi.GPIO** Python library now supports **Events**, which are explained in the [Interrupts and Edge detection](http://code.google.com/p/raspberry-gpio-python/wiki/Inputs#Interrupts_and_Edge_detection) paragraph. So after updating your Raspberry Pi with `sudo rpi-update` to get the latest version of the library, y...
Python requests - POST data from a file
16,145,116
11
2013-04-22T10:41:55Z
16,145,232
27
2013-04-22T10:48:07Z
[ "python", "python-requests" ]
I have used curl to send POST requests with data from files. I am trying to achieve the same using python requests module. Here is my python script ``` import requests payload=open('data','rb').read() r = requests.post('https://IP_ADDRESS/rest/rest/2', auth=('userid', 'password'), data=payload , verify=False) print r...
You do not need to use `.read()` here, simply stream the object directly. You do need to set the Content-Type header explicitly; `curl` does this when using `--data` but `requests` doesn't: ``` with open('data','rb') as payload: headers = {'content-type': 'application/x-www-form-urlencoded'} r = requests.post(...
Use python wand to grayscale image
16,145,959
6
2013-04-22T11:22:39Z
16,361,343
13
2013-05-03T14:30:54Z
[ "python", "imagemagick", "grayscale", "magickwand", "wand" ]
I want to use the Python API binding for ImageMagick <http://wand-py.org> to directly manipulate images. I am however not able to deduce from the documentation how to use a grayscale transformation. Can anybody provide information on this problem? ``` from wand.image import Image try: with Image(file=path) as img: ...
This can be achieved by setting the colorspace of the image. ``` from wand.image import Image with Image(filename='color.jpg') as img: img.type = 'grayscale'; img.save(filename='grayscale.jpg'); ``` further reading: * <http://docs.wand-py.org/en/latest/wand/image.html#wand.image.IMAGE_TYPES> * <http://docs.w...
I exit() a script but it does NOT exit
16,147,779
4
2013-04-22T13:02:08Z
16,147,803
22
2013-04-22T13:03:16Z
[ "python" ]
I try to exit a script but it doesn't exit. Here is my code: ``` import sys try: ... print "I'm gonna die!" sys.exit() except: ... print 'Still alive!' ``` And the results are: ``` I'm gonna die! Still alive! ``` WHY?
You are catching the `SystemExit` exception with your blanket `except` clause. Don't do that. Always specify what exceptions you are expecting to avoid exactly these things.
Histogram with base 2 logarithmic y-scale in matplotlib?
16,147,827
3
2013-04-22T13:04:33Z
16,148,260
7
2013-04-22T13:23:40Z
[ "python", "matplotlib", "histogram" ]
Is there any way of doing this? The `hist` command doesn't seem to recognise it when I try and specify `base` or `basey`.
Note: The solution below works with matplotlib version <1.3.1. --- Use ``` ax.set_yscale('log', basey=2) ``` --- ``` import numpy as np import matplotlib.pyplot as plt mu, sigma = 100, 15 fig, ax = plt.subplots() x = mu + sigma * np.random.randn(10000) ax.set_yscale('log', basey=2) n, bins, histpatches = ax.hist(x...
Python - looping over files - order
16,148,951
5
2013-04-22T13:55:04Z
16,149,019
10
2013-04-22T13:58:04Z
[ "python" ]
Does anyone know how Python arranges files when looping over them? I need to loop over some files in a folder in a fixed order (preferably alphanumerically according to the filenames), but Python seems to loop over them in a rather random order. So far I am using this code: ``` filelist = glob.glob(os.path.join(path, ...
As far as I can see in the docs, [`glob.glob()`](http://docs.python.org/3.3/library/glob.html) has no defined order. Given this, the easiest way to be sure is to sort the list returned to you: ``` filelist = glob.glob(os.path.join(path, 'FV/*.txt')) for infile in sorted(filelist): #do some fancy stuff print str(i...
Installing lxml with pip in virtualenv Ubuntu 12.10 error: command 'gcc' failed with exit status 4
16,149,613
30
2013-04-22T14:26:41Z
16,150,603
23
2013-04-22T15:14:33Z
[ "python", "django", "gcc", "lxml" ]
I'm having the following error when trying to run "pip install lxml" into a virtualenv in Ubuntu 12.10 x64. I have Python 2.7. I have seen other related questions here about the same problem and tried installing python-dev, libxml2-dev and libxslt1-dev. Please take a look of the traceback from the moment I tip the co...
Here is the my saved note. ``` sudo apt-get install libxml2 sudo apt-get install libxslt1.1 sudo apt-get install libxml2-dev sudo apt-get install libxslt1-dev sudo apt-get install python-libxml2 sudo apt-get install python-libxslt1 sudo apt-get install python-dev sudo apt-get install python-setuptools easy_install lx...
Installing lxml with pip in virtualenv Ubuntu 12.10 error: command 'gcc' failed with exit status 4
16,149,613
30
2013-04-22T14:26:41Z
17,110,281
63
2013-06-14T13:59:35Z
[ "python", "django", "gcc", "lxml" ]
I'm having the following error when trying to run "pip install lxml" into a virtualenv in Ubuntu 12.10 x64. I have Python 2.7. I have seen other related questions here about the same problem and tried installing python-dev, libxml2-dev and libxslt1-dev. Please take a look of the traceback from the moment I tip the co...
Make sure you have enough memory. Try `dmesg | tail` to see if it outputs something like: ``` ... [3778136.277570] Out of memory: Kill process 21267 (cc1) score 557 or sacrifice child [3778136.277587] Killed process 21267 (cc1) total-vm:365836kB, anon-rss:336228kB, file-rss:0kB ```
Installing lxml with pip in virtualenv Ubuntu 12.10 error: command 'gcc' failed with exit status 4
16,149,613
30
2013-04-22T14:26:41Z
22,912,266
14
2014-04-07T12:20:17Z
[ "python", "django", "gcc", "lxml" ]
I'm having the following error when trying to run "pip install lxml" into a virtualenv in Ubuntu 12.10 x64. I have Python 2.7. I have seen other related questions here about the same problem and tried installing python-dev, libxml2-dev and libxslt1-dev. Please take a look of the traceback from the moment I tip the co...
According to lxml site you could use such construction: ``` CFLAGS="-O0" pip install lxml ``` [installation guide](http://lxml.de/installation.html)
Installing lxml with pip in virtualenv Ubuntu 12.10 error: command 'gcc' failed with exit status 4
16,149,613
30
2013-04-22T14:26:41Z
24,547,445
8
2014-07-03T07:21:58Z
[ "python", "django", "gcc", "lxml" ]
I'm having the following error when trying to run "pip install lxml" into a virtualenv in Ubuntu 12.10 x64. I have Python 2.7. I have seen other related questions here about the same problem and tried installing python-dev, libxml2-dev and libxslt1-dev. Please take a look of the traceback from the moment I tip the co...
I met the similar question(error: command 'gcc' failed with exit status 4) this morning. It seems you need check your machine's memory. If the memory is lower than 512M,that may be the cause.Try to close some services temporarily,like apache server,and try "pip install lxml" again.It maybe work!
Working with big data in python and numpy, not enough ram, how to save partial results on disc?
16,149,803
13
2013-04-22T14:36:25Z
16,633,274
18
2013-05-19T09:38:52Z
[ "python", "arrays", "numpy", "scipy", "bigdata" ]
I am trying to implement algorithms for 1000-dimensional data with 200k+ datapoints in python. I want to use numpy, scipy, sklearn, networkx and other usefull libraries. I want to perform operations such as pairwise distance between all of the points and do clustering on all of the points. I have implemented working al...
Using `numpy.memmap` you create arrays directly mapped into a file: ``` import numpy a = numpy.memmap('test.mymemmap', dtype='float32', mode='w+', shape=(200000,1000)) # here you will see a 762MB file created in your working directory ``` You can treat it as a conventional array: a += 1000. It is possible even to as...
Baffling AttributeError in python with simple sqlite query
16,150,475
3
2013-04-22T15:08:08Z
16,150,509
12
2013-04-22T15:09:54Z
[ "python", "sqlite3" ]
I'm baffled and frustrated by an error I'm getting when I call a function in python to execute a query. I have checked to make sure I don't have tabs instead of spaced indents (checking the obscure). I've followed the convention used here: <http://zetcode.com/db/sqlitepythontutorial/> and here: [How to check the existe...
I believe `cur1 = con1.cursor` should be `cur1 = con1.cursor()`
Common xlabel/ylabel for matplotlib subplots
16,150,819
39
2013-04-22T15:25:51Z
16,153,475
11
2013-04-22T17:49:00Z
[ "python", "matplotlib" ]
I have the following plot: ``` fig,ax = plt.subplots(5,2,sharex=True,sharey=True,figsize=fig_size) ``` and now I would like to give this plot common x-axis labels and y-axis labels. With "common", I mean that there should be one big x-axis label below the whole grid of subplots, and one big y-axis label to the right....
Since the command: ``` fig,ax = plt.subplots(5,2,sharex=True,sharey=True,figsize=fig_size) ``` you used returns a tuple consisting of the figure and a list of the axes instances, it is already sufficient to do something like (mind that I've changed `fig,ax`to `fig,axes`): ``` fig,axes = plt.subplots(5,2,sharex=True,...
Common xlabel/ylabel for matplotlib subplots
16,150,819
39
2013-04-22T15:25:51Z
23,638,795
14
2014-05-13T18:21:55Z
[ "python", "matplotlib" ]
I have the following plot: ``` fig,ax = plt.subplots(5,2,sharex=True,sharey=True,figsize=fig_size) ``` and now I would like to give this plot common x-axis labels and y-axis labels. With "common", I mean that there should be one big x-axis label below the whole grid of subplots, and one big y-axis label to the right....
Without `sharex=True, sharey=True` you get: ![enter image description here](http://i.stack.imgur.com/TICJb.png) With it you should get it nicer: ``` fig, axes2d = plt.subplots(nrows=3, ncols=3, sharex=True, sharey=True, figsize=(6,6)) for i, row in enumerate(axe...
Common xlabel/ylabel for matplotlib subplots
16,150,819
39
2013-04-22T15:25:51Z
26,892,326
51
2014-11-12T16:56:58Z
[ "python", "matplotlib" ]
I have the following plot: ``` fig,ax = plt.subplots(5,2,sharex=True,sharey=True,figsize=fig_size) ``` and now I would like to give this plot common x-axis labels and y-axis labels. With "common", I mean that there should be one big x-axis label below the whole grid of subplots, and one big y-axis label to the right....
This looks like what you actually want. It applies the same approach of [this answer](http://stackoverflow.com/questions/6963035/) to your specific case: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots(nrows=3, ncols=3, sharex=True, sharey=True, figsize=(6, 6)) fig.text(0.5, 0.04, 'common X', ha='center')...
Python: how can I check whether an object is of type datetime.date?
16,151,402
9
2013-04-22T15:56:22Z
16,151,611
25
2013-04-22T16:06:15Z
[ "python", "datetime" ]
I have tried a few obvious options but none of them works: ``` In [150]: x Out[150]: datetime.date(2012, 9, 1) In [151]: type(x) Out[151]: datetime.date In [152]: isinstance(x, datetime.date) --------------------------------------------------------------------------- TypeError Traceba...
i believe the reason it is not working in your example is that you have imported `datetime` like so : ``` from datetime import datetime ``` this leads to the error you see ``` In [30]: isinstance(x, datetime.date) --------------------------------------------------------------------------- TypeError ...
Replicating struct in python
16,151,660
2
2013-04-22T16:08:32Z
16,151,679
8
2013-04-22T16:09:50Z
[ "python", "struct" ]
Is there anyway to support structures in python and does it not support the normal keyword *struct*? for eg: ``` struct node { unsigned dist[20]; unsigned from[20]; }rt[10]; ``` How can i covert this into a python struct?
I think the Python's equivalent to C-structs is [`classes`](http://docs.python.org/2/tutorial/classes.html): ``` class Node: def __init__(self): self.dist_ = [] self.from_ = [] rt = [] ```
AttributeError: 'int' object has no attribute '_sa_instance_state'
16,151,729
24
2013-04-22T16:12:27Z
16,152,945
33
2013-04-22T17:19:36Z
[ "python", "sqlalchemy", "flask", "one-to-many", "flask-sqlalchemy" ]
I'm working on forum template using Flask. When I attempt creating a new thread in the browser using forms, SQLAlchemy throws an AttributeError. The problem showed up when I tried implementing a one-to-many relationship with Forum-to-Thread and a one-to-many relationship with Thread-to-User. models.py ``` class User(...
the problem is this: ``` post = Post(body=form.body.data, timestamp=datetime.utcnow(), thread=thread.id, author=g.user.id) ``` you want to work with ORM objects, not primary key columns: ``` post = Post(body=form.body.data, timestamp=datetime.utcnow(), thre...
Sort keys in dictionary by value in a list in Python
16,152,634
2
2013-04-22T17:01:35Z
16,152,657
9
2013-04-22T17:02:44Z
[ "python", "list", "sorting", "dictionary" ]
I have seen [this post](http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value) and [this post](http://stackoverflow.com/questions/72899/in-python-how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary) as well as many others, but haven't quite found the answer to my question nor can I fi...
Supply a `key` function, a `lambda` is easiest, and sort reversed: ``` sorted(Dict.keys(), key=lambda k: Dict[k][3], reverse=True) ``` The key function tells `sorted` what to sort *by*; the 4th item in the value for the given key. Demo: ``` >>> sorted(Dict.keys(), key=lambda k: Dict[k][3], reverse=True) ['b', 'a', ...
Conditional replacement in pandas
16,153,530
9
2013-04-22T17:51:55Z
16,153,657
10
2013-04-22T17:59:58Z
[ "python", "replace", "conditional", "pandas" ]
I have a dataframe spanning several years and at some point they changed the codes for ethnicity. So I need to recode the values conditional on the year - which is another column in the same dataframe. For instance 1 to 3, 2 to 3, 3 to 4 and so on: ``` old = [1, 2, 3, 4, 5, 91] new = [3, 3, 4, 2, 1, 6] ``` And this i...
It may just be simpler to do it a different way: ``` oldNewMap = {1: 3, 2: 3, 3: 4, 4: 2, 5: 1, 91: 6} df['ethnicity'][df.year==year] = df['ethnicity'][df.year==year].map(oldNewMap) ```
Tornado socket.error on ARM
16,153,804
4
2013-04-22T18:08:29Z
16,451,489
7
2013-05-08T22:46:42Z
[ "python", "tornado", "raspberry-pi" ]
I'm trying to run a small python webapp on a RasPi using the Tornado server, but whenever I try to start it, I get the error ``` Traceback (most recent call last): File "main.py", line 78, in <module> application.listen(8080) File "/usr/local/lib/python2.7/dist-packages/tornado-3.0.1-py2.7.egg/tornado/web.py",...
This turns out to have nothing to do with ARM. As per [the answer](http://stackoverflow.com/a/8549132/190887) `artless noise` linked in one of his comments, it *looks* like Tornado gets confused if the system you start it up on supports IPv6, and this apparently includes the Raspberry Pi. Starting the server up with ...
Catch KeyError in Python
16,154,032
8
2013-04-22T18:23:09Z
16,154,204
18
2013-04-22T18:32:35Z
[ "python", "try-catch", "except" ]
If I run the code: ``` connection = manager.connect("I2Cx") ``` The program crashes and reports a KeyError because I2Cx doesn't exist (it should be I2C). But if I do: ``` try: connection = manager.connect("I2Cx") except Exception, e: print e ``` It doesn't print anything for e. I would like to be able to p...
If it's raising a KeyError with no message, then it won't print anything. If you do... ``` try: connection = manager.connect("I2Cx") except Exception, e: print repr(e) ``` ...you'll at least get the exception class name. A better alternative is to use multiple `except` blocks, and only 'catch' the exceptions...
remove element if it has a certain string in it
16,154,640
4
2013-04-22T19:00:05Z
16,154,714
8
2013-04-22T19:03:55Z
[ "python", "list" ]
I have a list `['1 2 4 5 0.9', '1 2 4 5 0.6', '1 2 4 5 0.3', '1 2 4 5 0.4']` I also have another list: `[0.9, 0.3, 0.7, 0.8]` I want to use the second list and the first list elements include whats in the second list then the element gets removed, so the first list ends up like: ``` [1 2 4 5 0.6', '1 2 4 5 0.4'] ```
You mean something like this: ``` >>> lst = ['1 2 4 5 0.9','1 2 4 5 0.6','1 2 4 5 0.3','1 2 4 5 0.4'] >>> s = set([0.9,0.3,0.7,0.8]) >>> [x for x in lst if float(x.split()[-1]) not in s] ['1 2 4 5 0.6', '1 2 4 5 0.4'] ```
Using Amazon s3 boto library, how can I get the URL of a saved key?
16,156,062
30
2013-04-22T20:24:17Z
16,158,333
55
2013-04-22T23:20:35Z
[ "python", "amazon-s3", "boto" ]
I am saving a key to a bucket with: ``` key = bucket.new_key(fileName) key.set_contents_from_string(base64.b64decode(data)) key.set_metadata('Content-Type', 'image/jpeg') key.set_acl('public-read') ``` After the save is successful, how can I access the URL of the newly created file?
If the key is publicly readable (as shown above) you can use [`Key.generate_url`](http://boto.readthedocs.org/en/latest/ref/s3.html#boto.s3.key.Key.generate_url): ``` url = key.generate_url(expires_in=0, query_auth=False) ``` If the key is private and you want to generate an expiring URL to share the content with som...
How can I convert windows timezones to timezones pytz understands?
16,156,597
7
2013-04-22T20:59:00Z
16,157,307
9
2013-04-22T21:46:03Z
[ "python", "timezone", "pytz" ]
In a windows python environment I can get the local timezone like this, but it's not usable with pytz: ``` >>> import win32timezone >>> win32timezone.TimeZoneInfo.local() TimeZoneInfo(u'US Mountain Standard Time', True) >>> win32timezone.TimeZoneInfo.local().timeZoneName u'US Mountain Standard Time' >>> tz = pytz.time...
Don't make any assumptions about what a Windows time zone ID means based on its name. For example `US Mountain Standard Time` is actually the Windows time zone for the majority of Arizona, which is permanently in MST because it does not implement daylight savings. But the Windows ID for the rest of the mountain time zo...
SQLAlchemy __init__ not running
16,156,650
8
2013-04-22T21:01:46Z
16,157,178
23
2013-04-22T21:38:02Z
[ "python", "sqlalchemy" ]
I have the following code: ``` session = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=engine)) Base = declarative_base() Base.query = session.query_property() class CommonBase(object): created_at = Column(DateTime, default=datetime.datetime.now) updated_at = Column(DateTime, default=datetim...
Check out the [SQLAlchemy documentation on reconstruction](http://docs.sqlalchemy.org/en/latest/orm/constructors.html): > The SQLAlchemy ORM does not call `__init__` when recreating objects from > database rows. The ORM’s process is somewhat akin to the Python > standard library’s pickle module, invoking the low l...
AttributeError: 'Class' object has no attribute 'a'
16,158,684
6
2013-04-22T23:57:53Z
16,158,729
11
2013-04-23T00:01:53Z
[ "python", "class", "attributes" ]
Here I have an attribute 'a', which is defined in first class method and should be changed in second. When calling them in order, this message appears: > AttributeError: 'Class' object has no attribute 'a' The only way I've found - define 'a' again in second method, but in real code it has long inheritance and app wi...
Short answer, no. The problem with your code is that each time you create a new instance. **Edit**: As abarnert mentions below, there is a big difference between `Class.a` and `c.a`. Instance attributes (the second case) belong to each specific object, whereas class attributes belong to the class. Look at abarnert's c...
Want to find a way of doing an average of multiple lists
16,158,764
5
2013-04-23T00:05:22Z
16,158,798
9
2013-04-23T00:08:56Z
[ "python", "list", "nested" ]
Say we create a list like so in python: ``` [[1, 2, 3], [1, 3, 4], [2, 4, 5]] ``` And then I want to take `1+1+2` and divide by 3, giving me the average for that element and store in a new list. I want to do that again for the second elements and lastly for the third. How would one do it succinctly? (I cannot think o...
Averages: ``` >>> data = [[1, 2, 3], [1, 3, 4], [2, 4, 5]] >>> from __future__ import division >>> [sum(e)/len(e) for e in zip(*data)] [1.3333333333333333, 3.0, 4.0] ``` Sums: ``` >>> data = [[1, 2, 3], [1, 3, 4], [2, 4, 5]] >>> [sum(e) for e in zip(*data)] [4, 9, 12] ``` --- * [zip](http://docs.python.org/2/lib...
Can't convert dates to datetime64
16,158,795
5
2013-04-23T00:08:38Z
16,158,887
8
2013-04-23T00:18:50Z
[ "python", "numpy", "pandas" ]
The following piece of code: ``` import pandas as pd import numpy as np data = pd.DataFrame({'date': ('13/02/2012', '14/02/2012')}) data['date'] = data['date'].astype('datetime64') ``` works fine on one machine (windows) and doesn't work on another (linux). Both numpy and pandas are installed on both. The error I g...
Do this instead. Pandas keeps datestimes internally as `datetime64[ns]`. Conversions like this are very buggy (because of issues in various numpy version, 1.6.2 especially). Use the pandas routines, then operate like thesee are actual datetime objects. What are you trying to do? ``` In [30]: pandas.to_datetime(data['d...
SQLAlchemy filter in_ operator
16,158,809
7
2013-04-23T00:10:20Z
16,158,968
12
2013-04-23T00:30:29Z
[ "python", "sqlite", "sqlalchemy" ]
I am trying to do a simple filter operation on a query in sqlalchemy, like this: ``` q = session.query(Genotypes).filter(Genotypes.rsid.in_(inall)) ``` where inall is a list of strings Genotypes is mapped to a table: class Genotypes(object): pass ``` Genotypes.mapper = mapper(Genotypes, kg_table, properties={'rsid'...
If the table where you are getting your `rsid`s from is available in the same database I'd use a [subquery](http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.subquery) to pass them into your `Genotypes` query rather than passing the one million entries around in your Python code. ``` sq = ...
flask-admin not showing foreignkey columns
16,160,507
6
2013-04-23T03:39:43Z
16,193,335
8
2013-04-24T13:29:47Z
[ "python", "flask", "flask-sqlalchemy", "flask-extensions" ]
``` class Parent(db.Model): id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(120)) def __repr_(self): return '<Parent %r>' % (self.name) admin.add_view(ModelView(Parent, db.session)) class Child(db.Model): id = db.Column(db.Integer, primary_key = True) name = db....
How about if you change the `Child` class to this: ``` class Child(db.Model): id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(120)) parent_id = db.Column(db.Integer, db.ForeignKey('parent.id')) parent = db.relationship('Parent', backref=db.backref('children', lazy='dynamic')) ...
flask-admin not showing foreignkey columns
16,160,507
6
2013-04-23T03:39:43Z
16,210,942
7
2013-04-25T09:19:16Z
[ "python", "flask", "flask-sqlalchemy", "flask-extensions" ]
``` class Parent(db.Model): id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(120)) def __repr_(self): return '<Parent %r>' % (self.name) admin.add_view(ModelView(Parent, db.session)) class Child(db.Model): id = db.Column(db.Integer, primary_key = True) name = db....
You likely need to specify some additional options to flask-admin via a subclass: ``` class ChildView(ModelView): column_display_pk = True # optional, but I like to see the IDs in the list column_hide_backrefs = False column_list = ('id', 'name', 'parent') admin.add_view(ChildView(Parent, db.session)) ``...
Efficient pagination and database querying in django
16,161,727
8
2013-04-23T05:36:23Z
16,163,124
12
2013-04-23T07:11:25Z
[ "python", "django", "pagination", "querying" ]
There were some code examples for django pagination which I used a while back. I may be wrong but when looking over the code it looks like it wastes tons of memory. I was looking for a better solution, here is the code: ``` # in views.py from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger ... .....
`mymodel.objects.all()` yields a queryset, not a list. Querysets are lazy - no request is issued and nothing done until you actually try to use them. Also slicing a query set does not load the whole damn thing in memory only to get a subset but adds limit and offset to the SQL query before hitting the database.
Mocking python function based on input arguments
16,162,015
32
2013-04-23T05:59:10Z
16,162,114
50
2013-04-23T06:05:45Z
[ "python", "unit-testing", "mocking", "mockito" ]
We have been using [Mock](http://www.voidspace.org.uk/python/mock/) for python for a while. Now, we have a situation in which we want to mock a function ``` def foo(self, my_param): #do something here, assign something to my_result return my_result ``` Normally, the way to mock this would be (assuming foo be...
> If `side_effect` is a function then whatever that function returns is > what calls to the mock return. The `side_effect` function is called with > the same arguments as the mock. This allows you to vary the return > value of the call dynamically, based on the input: > > ``` > >>> def side_effect(value): > ... ret...
python - OpenCV mat::convertTo in python
16,162,227
8
2013-04-23T06:13:13Z
16,162,359
10
2013-04-23T06:22:52Z
[ "python", "opencv" ]
Is there any function in the OpenCV python wrapper that does the same thing as Mat's convertTo method in OpenCV 2? I basically want to call this function in python ``` out.convertTo( out, CV_32F, 1.0/255, 0 ); ``` where out is a grayscale image. I have already made use of cv.ConvertScale by keeping my dst argument ...
You can simply use Numpy functions for this. eg : ``` res = np.float32(out) ``` scaling, you will have to do separately: ``` res = res*scaling_factor ```
How to easily write a multi-line file with variables (python 2.6)?
16,162,383
5
2013-04-23T06:24:07Z
16,162,599
23
2013-04-23T06:38:52Z
[ "python", "file", "output", "multiline" ]
At the moment I'm writing a multi-line file from a python program by doing ``` myfile = open('out.txt','w') myfile.write('1st header line\nSecond header line\n') myfile.write('There are {0:5.2f} people in {1} rooms\n'.format(npeople,nrooms)) myfile.write('and the {2} is {3}\n'.format('ratio','large')) myfile.close() `...
Triple-quoted strings are your friend: ``` template = """1st header line second header line There are {npeople:5.2f} people in {nrooms} rooms and the {ratio} is {large} """ context = { "npeople":npeople, "nrooms":nrooms, "ratio": ratio, "large" : large } with open('out.txt','w') as myfile: myfile.write(te...
In pandas, how can I reset index without adding a new column?
16,167,829
12
2013-04-23T11:10:32Z
16,168,245
18
2013-04-23T11:30:00Z
[ "python", "pandas" ]
``` In [37]: df = pd.DataFrame([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]) In [38]: df2 = pd.concat([df, df]) In [39]: df2.reset_index() Out[39]: index 0 1 2 3 0 0 1 2 3 4 1 1 2 3 4 5 2 2 3 4 5 6 3 0 1 2 3 4 4 1 2 3 4 5 5 2 3 4 5 6 ``` My problem is that ...
You can use the `drop=True` option in `reset_index()`. See [here](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html).
deleting file if it exists; python
16,168,018
3
2013-04-23T11:19:38Z
16,168,152
7
2013-04-23T11:25:44Z
[ "python", "file-io", "try-catch" ]
I want to create a file; if it already exists I want to delete it and create it anew. I tried doing it like this but it throws a Win32 error. What am I doing wrong? ``` try: with open(os.path.expanduser('~') + '\Desktop\input.txt'): os.remove(os.path.expanduser('~') + '\Desktop\input.txt') f1 = ope...
You're trying to delete an open file, and the docs for [`os.remove()`](http://docs.python.org/2/library/os.html#os.remove) state... > On Windows, attempting to remove a file that is in use causes an exception to be raised You could change the code to... ``` filename = os.path.expanduser('~') + '\Desktop\input.txt' t...
coercing to Unicode: need string or buffer, NoneType found when rendering in django admin
16,169,035
34
2013-04-23T12:10:54Z
17,182,948
60
2013-06-19T04:36:49Z
[ "python", "django", "django-admin" ]
I have this error since a long time but can't figure it out : **Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found** It happens in admin when I try to add or modify on one of my models (display works fine) This is the model: ``` class PS(models.Model): id_ps = models.In...
This error happens when you have a `__unicode__` method that is a returning a field that is not entered. Any blank field is `None` and Python cannot convert `None`, so you get the error. In your case, the problem most likely is with the `PCE` model's `__unicode__` method, specifically the field its returning. You can...
coercing to Unicode: need string or buffer, NoneType found when rendering in django admin
16,169,035
34
2013-04-23T12:10:54Z
20,336,155
8
2013-12-02T19:23:11Z
[ "python", "django", "django-admin" ]
I have this error since a long time but can't figure it out : **Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found** It happens in admin when I try to add or modify on one of my models (display works fine) This is the model: ``` class PS(models.Model): id_ps = models.In...
This error might occur when you return an object instead of a string in your `__unicode__` method. For example: ``` class Author(models.Model): . . . name = models.CharField(...) class Book(models.Model): . . . author = models.ForeignKey(Author, ...) . . . def __unicode__(self): retu...
Pyramid: multiple resource factories -- how to
16,169,590
3
2013-04-23T12:39:55Z
16,174,192
9
2013-04-23T16:08:20Z
[ "python", "pyramid" ]
I have a simple root resource factory: ``` class Root: __acl__ = [ (Allow, Authenticated, 'edit') ] ``` Now for some "special" routes, I need to create another resource factory ``` config.add_route('special', '/special/test', factory=SpecialFactory) class SpecialFactory: __acl__ = [ (All...
`__name__` only comes into account when generating urls via traversal, so don't worry about it. First off, the factory argument is a factory. Meaning, it's "some object" that accepts a `request` object, and expects to receive back an object that is actually the root of the tree. ``` class Root: def __init__(self,...
Integer difference in python between two dates
16,170,737
3
2013-04-23T13:33:51Z
16,170,792
11
2013-04-23T13:36:40Z
[ "python", "date", "datetime" ]
I've RTFM and read many questions and answers here on SO regarding this, and was happily using strftime and strptime yesterday, so I would swear this should work, but it isn't.... I just want an integer. Not a "timedelta object." Not an "aware yet hashable object" (see, I RTFM). Not a tuple. Not a dictionary. Just a s...
You want to get the *classmethod* `datetime.datetime.strptime()`, then take the `.days` **attribute** from the resulting timedelta: ``` import datetime mdate = "2010-10-05" rdate = "2010-10-05" mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d").date() rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d").date() ...
How to create a non-instantiable class?
16,170,968
3
2013-04-23T13:44:57Z
16,171,212
9
2013-04-23T13:54:58Z
[ "python", "instantiation", "objectinstantiation" ]
For one of the project I am currently working I was thinking of creating a class that could not be instantiate by a client and only be supplied an instance of through a particular interface i.e. the client would not be able create further instance out of it by some hackery such as: ``` >>> try: ... raise WindowsEr...
What you're doing is a bad idea, you shouldn't do it. I'm sure there's an other, better solution. If you do decide to go with your way anyways (you shouldn't), here's how you can create an object without using `__init__()`: --- Objects in python are created with the `__new__()` method. The method `__init__()` only ed...
Why does the shelve module in python sometimes create files with different extensions?
16,171,833
6
2013-04-23T14:22:03Z
16,231,228
16
2013-04-26T07:45:02Z
[ "python", "unix", "pickle", "shelve" ]
I'm running a Python program which uses the `shelve` module on top of `pickle`. After running this program sometimes I get one output file as `a.data` but at other times I get three output files as `a.data.bak`, `a.data.dir` and `a.data.dat`. Why is that?
There is quite some indirection here. Follow me carefully. The `shelve` module is implemented on top of the [`anydbm` module](http://docs.python.org/2/library/anydbm.html). This module acts as a facade for 4 different specific DBM implementations, and it will pick the first module available when creating a new databas...
Json in Python: Receive/Check duplicate key error
16,172,011
5
2013-04-23T14:29:56Z
16,172,132
9
2013-04-23T14:35:29Z
[ "python", "json" ]
The `json` module of python acts a little of the specification when having duplicate keys in a map: ``` import json >>> json.loads('{"a": "First", "a": "Second"}') {u'a': u'Second'} ``` I know that this behaviour is specified in the [documentation](http://docs.python.org/2/library/json.html#repeated-names-within-an-o...
Well, you could try using the [`JSONDecoder`](http://docs.python.org/2/library/json.html#json.JSONDecoder) class and specifying a custom `object_pairs_hook`, which will receive the duplicates before they would get deduped. ``` import json def dupe_checking_hook(pairs): result = dict() for key,val in pairs: ...
Accessing nested dictionary items in Python
16,173,809
6
2013-04-23T15:49:41Z
16,173,851
19
2013-04-23T15:51:57Z
[ "python", "dictionary", "python-3.3" ]
I am trying to format a string using an item from a nested dictionary (below) ``` people = { 'Alice': { 'phone': '2341', 'addr': '87 Eastlake Court' }, 'Beth': { 'phone': '9102', 'addr': '563 Hartford Drive' }, 'Randy...
Use the [new string formatting](http://docs.python.org/3.3/library/string.html#format-string-syntax): ``` print("Randy's phone # is {0[Randy][phone]}".format(people)) ``` or ``` print("Randy's phone # is {Randy[phone]}".format(**people)) ``` There's no point in passing the entire dictionary if you only use one valu...
Download a remote image and save it to a Django model
16,174,022
12
2013-04-23T15:59:03Z
16,174,886
20
2013-04-23T16:49:05Z
[ "python", "django", "django-models" ]
I am writing a Django app which will fetch all images of particular URL and save them in the database. But I am not getting on how to use ImageField in Django. Settings.py ``` MEDIA_ROOT = os.path.join(PWD, "../downloads/") # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # ...
[Documentation](https://docs.djangoproject.com/en/1.5/ref/models/fields/#imagefield) is always good place to start ``` class ModelWithImage(models.Model): image = models.ImageField( upload_to='images', ) ``` **UPDATED** So this script works. * Loop over images to download * Download image * Save to ...
OverflowError: long int too large to convert to float in python
16,174,399
10
2013-04-23T16:20:50Z
16,174,565
15
2013-04-23T16:29:25Z
[ "python" ]
I tried to calculate poisson distribution in python as below: ``` p = math.pow(3,idx) depart = math.exp(-3) * p depart = depart / math.factorial(idx) ``` idx ranges from 0 But I got `OverflowError: long int too large to convert to float` I tried to convert depart to `float` but no results.
Factorials get large *real fast*: ``` >>> math.factorial(170) 72574156153079989673967282111292631147169916812964513765435777989005618434017061578523507492426174595114909912378385207766660225654427530253289007732075109024004302800582956039666125996582571043985582942575689663134396122625710949468067112055688804571933402...
Can't get argparse to read quoted string with dashes in it?
16,174,992
22
2013-04-23T16:55:18Z
16,175,115
17
2013-04-23T17:02:15Z
[ "python", "argparse", "command-line-interface" ]
Is there a way to make argparse recognize anything between two quotes as a single argument? It seems to keep seeing the dashes and assuming that it's the start of a new option I have something like: ``` mainparser = argparse.ArgumentParser() subparsers = mainparser.add_subparsers(dest='subcommand') parser = subparser...
**Updated answer:** You can put an equals sign when you call it: ``` python Application.py -env="-env" ``` --- **Original answer:** I too have had troubles doing what you are trying to do, but there is a workaround build into argparse, which is the [parse\_known\_args](http://docs.python.org/3.4/library/argparse.h...
Can't get argparse to read quoted string with dashes in it?
16,174,992
22
2013-04-23T16:55:18Z
21,894,384
8
2014-02-19T22:54:18Z
[ "python", "argparse", "command-line-interface" ]
Is there a way to make argparse recognize anything between two quotes as a single argument? It seems to keep seeing the dashes and assuming that it's the start of a new option I have something like: ``` mainparser = argparse.ArgumentParser() subparsers = mainparser.add_subparsers(dest='subcommand') parser = subparser...
This issue is discussed in depth in <http://bugs.python.org/issue9334>. Most of the activity was in 2011. I added a patch last year, but there's quite a backlog of `argparse` patches. At issue is the potential ambiguity in a string like `'--env'`, or `"-s WHATEVER -e COOL STUFF"` when it follows an option that takes a...
python pandas dataframe slicing by date conditions
16,175,874
23
2013-04-23T17:48:05Z
16,176,457
28
2013-04-23T18:22:19Z
[ "python", "dataframe", "pandas" ]
I am able to read and slice pandas dataframe using python datetime objects, however I am forced to use only *existing dates* in index. For example, this works: ``` >>> data <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 252 entries, 2010-12-31 00:00:00 to 2010-04-01 00:00:00 Data columns: Adj Close 252 non-n...
Use `searchsorted` to find the nearest times first, and then use it to slice. ``` In [15]: df = pd.DataFrame([1, 2, 3], index=[dt.datetime(2013, 1, 1), dt.datetime(2013, 1, 3), dt.datetime(2013, 1, 5)]) In [16]: df Out[16]: 0 2013-01-01 1 2013-01-03 2 2013-01-05 3 In [22]: start = df.index.searchsort...
python pandas dataframe slicing by date conditions
16,175,874
23
2013-04-23T17:48:05Z
16,179,190
14
2013-04-23T21:07:12Z
[ "python", "dataframe", "pandas" ]
I am able to read and slice pandas dataframe using python datetime objects, however I am forced to use only *existing dates* in index. For example, this works: ``` >>> data <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 252 entries, 2010-12-31 00:00:00 to 2010-04-01 00:00:00 Data columns: Adj Close 252 non-n...
Short answer: Sort your data (`data.sort()`) and then I think everything will work the way you are expecting. Yes, you can slice using datetimes not present in the DataFrame. For example: ``` In [12]: df Out[12]: 0 2013-04-20 1.120024 2013-04-21 -0.721101 2013-04-22 0.379392 2013-04-23 0.924535...
How do I group this list of dicts by the same month?
16,176,469
3
2013-04-23T18:23:06Z
16,176,538
14
2013-04-23T18:26:27Z
[ "python" ]
Python newb... I have a list of dicts that I am trying to organize into the same month & year: ``` [{'date':'2008-04-23','value':'1'}, {'date':'2008-04-01','value':'8'}, {'date':'2008-04-05','value':'3'}, {'date':'2009-04-19','value':'5'}, {'date':'2009-04-21','value':'8'}, {'date':'2010-09-09','value':'3'}, {'date':'...
First, I would sort the data1: ``` >>> lst = [{'date':'2008-04-23','value':'1'}, ... {'date':'2008-04-01','value':'8'}, ... {'date':'2008-04-05','value':'3'}, ... {'date':'2009-04-19','value':'5'}, ... {'date':'2009-04-21','value':'8'}, ... {'date':'2010-09-09','value':'3'}, ... {'date':'2010-09-10','value':'4'}, ... ...
Conditional Formatting xlwt
16,176,738
6
2013-04-23T18:37:25Z
16,266,642
7
2013-04-28T19:07:38Z
[ "python", "formatting", "conditional", "xlrd", "xlwt" ]
I have seen some posts that say you can NOT perform conditional formatting using `xlwt`, but they were rather old. I was curious if this has evolved? I have been searching for about half a day now. Furthermore, if I con't write it directly from `xlwt`, can I create an `.xls` file containing a single cell with the cond...
`xlrd` and `xlwt` still *don't support conditional formatting*. `xlrd` doesn't read it, `xlwt` doesn't write it. There is a new and awesome module, called [xlsxwriter](https://xlsxwriter.readthedocs.org/en/latest/). *It does support [conditional formatting](https://xlsxwriter.readthedocs.org/en/latest/working_with_con...
Python 3 replacement for deprecated compiler.ast flatten function
16,176,742
7
2013-04-23T18:37:38Z
16,176,779
9
2013-04-23T18:39:16Z
[ "python", "python-3.x", "flatten" ]
What's the recommended way to flatten nested lists since the [deprecation of the compiler package](http://docs.python.org/2/library/compiler.html#module-compiler)? ``` >>> from compiler.ast import flatten >>> flatten(["junk",["nested stuff"],[],[[]]]) ['junk', 'nested stuff'] ``` I know that there are a few stack ove...
[`itertools.chain`](http://docs.python.org/3/library/itertools.html#itertools.chain) is the best solution for flattening any nested iterable one level - it's highly efficient compared to any pure-python solution. That said, it will work on *all* iterables, so some checking is required if you want to avoid it flattenin...
Python - How can I install xlutils?
16,176,864
3
2013-04-23T18:44:04Z
16,178,944
7
2013-04-23T20:51:27Z
[ "python", "excel" ]
I am using Python 2.5 (and need to stay with that) and have already downloaded xlrd 0.8.0 and xlwt 0.7.2, and they both seem to be working OK. I will be needing to read from and write to Excel spreadsheets, and so believe I will need to add xlutils as well. The problem is, I can't install it so far. I have pip and tr...
First of all, you do not *need* `xlutils` just to read and write Excel files. You can read them with `xlrd` and write them with `xlwt` and provide your own "glue" in the Python code that you write yourself. That said, `xlutils` does provide features that make some things more convenient than writing them for yourself ...
Keep only date part when using pandas.to_datetime
16,176,996
18
2013-04-23T18:50:36Z
34,277,514
20
2015-12-14T22:07:34Z
[ "python", "datetime", "pandas" ]
I am using pandas.to\_datetime to parse the dates in my data. Pandas by default represent the dates with datetime64[ns] even though the dates are all daily only. I wonder whether there is an elegant/clever way to convert the dates to datetime.date or datetime64[D] so that when I write the data to csv, the dates are not...
Since version `0.15.0` this can now be easily done using [`.dt`](http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#dt-accessor) to access just the date component: ``` df['just_date'] = df['dates'].dt.date ```
Numpy running at half the speed of MATLAB
16,178,471
12
2013-04-23T20:21:29Z
16,178,896
10
2013-04-23T20:48:01Z
[ "python", "performance", "matlab", "numpy", "atlas" ]
I've been porting MATLAB code over to Python and, after quite a lot of work, I have stuff that works. The downside, however, is that Python is running my code more slowly than MATLAB did. I understand that using optimised ATLAS libraries will speed things up, but actually implementing this is confusing me. Here's what'...
## Simple example Numpy is calculating both the eigenvectors and eigenvalues, so it will take roughly twice longer, which is consistent with your slowdown (use `np.linalg.eigvals` to compute only the eigenvalues). In the end, `np.linalg.eig` is a tiny wrapper around dgeev, and likely the same thing happens in Matlab,...
Command line input in Python
16,179,875
13
2013-04-23T21:56:40Z
16,179,897
51
2013-04-23T21:58:10Z
[ "python", "command-line", "input", "python-2.7", "user-input" ]
Is it possible to run first the program then wait for the input of the user in command line. e.g. ``` Run... Process... Input from the user(in command line form)... Process... ```
It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question: ## For interactive user input (or piped commands or redirected input) Use `raw_input` in Python 2.x, and `input` in Python 3. (These are built in, so you don...
Command line input in Python
16,179,875
13
2013-04-23T21:56:40Z
16,179,928
7
2013-04-23T22:01:10Z
[ "python", "command-line", "input", "python-2.7", "user-input" ]
Is it possible to run first the program then wait for the input of the user in command line. e.g. ``` Run... Process... Input from the user(in command line form)... Process... ```
## Just Taking Input ``` the_input = raw_input("Enter input: ") ``` And that's it. Moreover, if you want to make a list of inputs, you can do something like: ``` a = [] for x in xrange(1,10): a.append(raw_input("Enter Data: ")) ``` In that case, you'll be asked for data 10 times to store 9 items in a list. O...
Command line input in Python
16,179,875
13
2013-04-23T21:56:40Z
16,180,611
8
2013-04-23T23:04:18Z
[ "python", "command-line", "input", "python-2.7", "user-input" ]
Is it possible to run first the program then wait for the input of the user in command line. e.g. ``` Run... Process... Input from the user(in command line form)... Process... ```
If you're using Python 3, `raw_input` has changed to `input` Python 3 example: ``` line = input('Enter a sentence:') ```
Drawing average line in histogram (matplotlib)
16,180,946
11
2013-04-23T23:35:56Z
16,181,102
36
2013-04-23T23:56:00Z
[ "python", "matplotlib", "axis" ]
I am drawing a histogram using matplotlib in python, and would like to draw a line representing the average of the dataset, overlaid on the histogram as a dotted line (or maybe some other color would do too). Any ideas on how to draw a line overlaid on the histogram? I am using the plot() command, but not sure how to ...
You can use the `plot` or `vlines` to draw a vertical line, but to draw a vertical line from the bottom to the top of the y axis, `axvline` is the probably the simplest function to use. Here's an example: ``` In [39]: import numpy as np In [40]: import matplotlib.pyplot as plt In [41]: x = np.random.gamma(4, 0.5, 10...
Python - very simple multithreading parallel URL fetching (without queue)
16,181,121
11
2013-04-23T23:58:42Z
16,182,076
10
2013-04-24T01:50:02Z
[ "python", "multithreading", "callback", "python-multithreading", "urlfetch" ]
I spent a whole day looking for the simplest possible multithreaded URL fetcher in Python, but most scripts I found are using queues or multiprocessing or complex libraries. Finally I wrote one myself, which I am reporting as an answer. Please feel free to suggest any improvement. I guess other people might have been...
Simplifying your original version as far as possible: ``` import threading import urllib2 import time start = time.time() urls = ["http://www.google.com", "http://www.apple.com", "http://www.microsoft.com", "http://www.amazon.com", "http://www.facebook.com"] def fetch_url(url): urlHandler = urllib2.urlopen(url) ...
Django DoesNotExist
16,181,188
24
2013-04-24T00:06:29Z
16,181,252
58
2013-04-24T00:12:40Z
[ "python", "django", "django-models", "django-views" ]
I am having issues on trying to figure "DoesNotExist Errors", I have tried to find the right way for manage the no answer results, however I continue having issues on "DoesNotExist" or "Object hast not Attribute DoestNotExists" ``` from django.http import HttpResponse from django.contrib.sites.models import Site from ...
This line ``` except Vehicle.vehicledevice.device.DoesNotExist ``` means look for device *instance* for DoesNotExist exception, but there's none, because it's on class level, you want something like ``` except Device.DoesNotExist ```
Django DoesNotExist
16,181,188
24
2013-04-24T00:06:29Z
16,288,605
24
2013-04-29T21:32:37Z
[ "python", "django", "django-models", "django-views" ]
I am having issues on trying to figure "DoesNotExist Errors", I have tried to find the right way for manage the no answer results, however I continue having issues on "DoesNotExist" or "Object hast not Attribute DoestNotExists" ``` from django.http import HttpResponse from django.contrib.sites.models import Site from ...
I have found the solution to this issue using ObjectDoesNotExist on this way ``` from django.core.exceptions import ObjectDoesNotExist ...... try: # try something except ObjectDoesNotExist: # do something ``` After this, my code works as I need Thanks any way, your post help me to solve my issue
Installing MySQL Python on Mac OS X
16,182,294
12
2013-04-24T02:18:04Z
16,193,384
17
2013-04-24T13:32:36Z
[ "python", "mysql", "osx" ]
Long story short, when I write the following: ``` sudo easy_install MySQL-python ``` I get the error > EnvironmentError: mysql\_config not found All right, so there are plenty of threads and the like on how to fix that, so I run this code: ``` export PATH=$PATH:/usr/local/mysql/bin ``` Then I rerun my sudo code: ...
Another option is to use [pymysql](https://github.com/PyMySQL/PyMySQL) it is a pure Python client connection to MySQL so you don't have to mess around with compiling, a good exercise, but it can be frustrating if you are just trying to get something done. pymysql follows the same API as MySQLdb, it can essentially be u...
Installing MySQL Python on Mac OS X
16,182,294
12
2013-04-24T02:18:04Z
25,356,073
10
2014-08-18T03:46:50Z
[ "python", "mysql", "osx" ]
Long story short, when I write the following: ``` sudo easy_install MySQL-python ``` I get the error > EnvironmentError: mysql\_config not found All right, so there are plenty of threads and the like on how to fix that, so I run this code: ``` export PATH=$PATH:/usr/local/mysql/bin ``` Then I rerun my sudo code: ...
Install mysql via [homebrew](http://brew.sh/), then you can install mysql python via pip. ``` pip install MySQL-python ``` It works for me.
Installing MySQL Python on Mac OS X
16,182,294
12
2013-04-24T02:18:04Z
25,920,020
32
2014-09-18T18:36:54Z
[ "python", "mysql", "osx" ]
Long story short, when I write the following: ``` sudo easy_install MySQL-python ``` I get the error > EnvironmentError: mysql\_config not found All right, so there are plenty of threads and the like on how to fix that, so I run this code: ``` export PATH=$PATH:/usr/local/mysql/bin ``` Then I rerun my sudo code: ...
Here's what I would install, especially if you want to use [homebrew](http://brew.sh): * XCode and the command line tools (as suggested by @7stud, @kjti) * Install [homebrew](http://brew.sh/) * `brew install mysql-connector-c` * `pip install mysql-python`
saving images in python at a very high quality
16,183,462
21
2013-04-24T04:38:27Z
16,183,647
33
2013-04-24T04:55:09Z
[ "python", "graphics", "matplotlib", "save" ]
How can I save python plots at very high quality? That is, when I keep zooming in on the object saved in a pdf file, there is no blurring? Also, what would be the best mode to save it in? `png`, `eps`? Or some other? I can't do `pdf` because there is a hidden number that happens that mess with `Latexmk` compilation.
If you are using `matplotlib` and trying to get good figures in a latex document, save as an eps. Specifically, try something like this after running the commands to plot the image: ``` plt.savefig('destination_path.eps', format='eps', dpi=1000) ``` I have found that eps files work best and the `dpi` parameter is wha...