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
How to exit the cmd loop of cmd module cleanly
15,537,427
3
2013-03-21T00:37:47Z
15,537,821
8
2013-03-21T01:20:44Z
[ "python", "cmd" ]
I'm using the `cmd` module in Python to build a little interactive command-line program. However, from this documentation: <http://docs.python.org/2/library/cmd.html>, it is not clear that what is a clean way to exit the program (i.e. the cmdloop) programmatically. Ideally, I want to issue some command `exit` on the p...
You need to override the `postcmd` method: > Cmd.postcmd(stop, line) > > Hook method executed just after a command dispatch is finished. This > method is a stub in Cmd; it exists to be overridden by subclasses. > line is the command line which was executed, and stop is a flag which > indicates whether execution will b...
Multiplicative combination algorithm
15,537,479
11
2013-03-21T00:43:29Z
15,537,757
8
2013-03-21T01:12:19Z
[ "python", "algorithm", "iteration" ]
### Problem: Given a number n, is there an efficient algorithm to obtain a list of 2-combinations from the set {1...n}, sorted by the value of the product of the combination? I need this in order to determine the largest product of two \*-digit numbers that satisfies a certain condition. If the list is unsorted, I mu...
You can use a heap/priority Q. Start with (n,n), insert in the heap. Your comparison function = compare the products. Whenever you extract (x,y), you insert (x-1,y) and (x,y-1) if needed (you can maintain a hashtable to check for dupes if you want). Here is some quick (and ugly looking) code to demonstrate the above...
get all possible single bytes in python
15,538,354
3
2013-03-21T02:21:50Z
15,538,411
10
2013-03-21T02:29:15Z
[ "python", "byte", "combinations" ]
I'm trying to generate all possible bytes to test for a machine learning algorithm (8-3-8 mural network encoder). is there a way to do this in python without having 8 loops? Could permutations help? I'd prefer an elegant way to do this, but I'll take what I can get at the moment. desired output: ``` [0,0,0,0,0,0,0,...
Yes, there is, [itertools.product](http://docs.python.org/2/library/itertools.html#itertools.product): ``` import itertools itertools.product([0, 1], repeat=8) >>> list(itertools.product([0, 1], repeat=8)) [(0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 1), ``` [...] ``` (1, 1, 1, 1, 1, 1, 1, 0), (1, 1, 1, 1, ...
What's the difference between logging.warn and logging.warning in Python? Or are they the same?
15,539,937
8
2013-03-21T05:06:07Z
15,540,092
17
2013-03-21T05:20:21Z
[ "python", "logging", "warnings" ]
The samples here <http://docs.python.org/2/howto/logging.html> use both warn and warning
Prior to Python 3.3, they are the same, however `warn` is deprecated: ``` >>> import logging >>> logging.warn is logging.warning True ```
What's the difference between logging.warn and logging.warning in Python? Or are they the same?
15,539,937
8
2013-03-21T05:06:07Z
15,655,674
10
2013-03-27T09:40:53Z
[ "python", "logging", "warnings" ]
The samples here <http://docs.python.org/2/howto/logging.html> use both warn and warning
`logging.warn` has been deprecated since Python 3.3 and you should use `logging.warning`. Prior to Python 3.3, `logging.warn` and `logging.warning` were the same function, but `logging.warn` was not documented, as noted in a closed issue in the Python bug tracker <http://bugs.python.org/issue13235>: > That's delibera...
Python string interning
15,541,404
47
2013-03-21T07:07:07Z
15,541,556
51
2013-03-21T07:15:55Z
[ "python", "string", "internals" ]
While this question doesn't have any real use in practise, I am curious as to how Python does string interning. I have noticed the following. ``` >> "string" is "string" >> True ``` This is as I expected. You can also do this. ``` >> "strin"+"g" is "string" >> True ``` And that's pretty clever! But you can't do t...
This is implementation-specific, but your interpreter is probably interning compile-time constants but not the results of run-time expressions. In what follows I use CPython 2.7.3. In the second example, the expression `"strin"+"g"` is evaluated at compile time, and is replaced with `"string"`. This makes the first t...
How to get line number in excel sheet using python?
15,541,641
3
2013-03-21T07:22:36Z
15,541,926
12
2013-03-21T07:42:15Z
[ "python", "xlrd" ]
I have an Excel sheet like this: ``` A B C D E F G 1 0 0 0 2 0 0 3 0 4 5 0 0 0 0 0 0 0 6 0 0 0 ``` And every '0' represents some data values, I am reading the values and comparing them with my original data, when the data match fails it returns a message. What I want is to return the line number of excel sheet ...
Try this: ``` import xlrd workbook = xlrd.open_workbook('book.xls') for sheet in workbook.sheets(): for row in range(sheet.nrows): for column in range(sheet.ncols): print "row::::: ", row print "column:: ", column print "value::: ", sheet.cell(row,column).value ``` It w...
How to use return value of a function as condition of while that returns tuple in python
15,542,329
12
2013-03-21T08:11:39Z
15,542,387
7
2013-03-21T08:16:23Z
[ "python", "opencv", "python-2.7" ]
I was looking for something like this but I couldn't find so here it goes. **Some background** I use opencv to retrieve frames from a video file. Usually people do it in an endless loop like: ``` while (True): s, img = cv.read() ``` or ``` for i in xrange(10000): #just a big number s, img = cv.read() ``` ...
the best way to think pythonic is to forget other languages ``` s = True while s: s, i = capture.read() if s: do_some_stuff(i) ```
How to use return value of a function as condition of while that returns tuple in python
15,542,329
12
2013-03-21T08:11:39Z
15,542,514
19
2013-03-21T08:25:08Z
[ "python", "opencv", "python-2.7" ]
I was looking for something like this but I couldn't find so here it goes. **Some background** I use opencv to retrieve frames from a video file. Usually people do it in an endless loop like: ``` while (True): s, img = cv.read() ``` or ``` for i in xrange(10000): #just a big number s, img = cv.read() ``` ...
You could write a generator function. ``` def readframes(cv): while True: success, frame = cv.read() if success: yield frame else: return ``` This way you can loop through the frames with a for loop. ``` for frame in readframes(cv): do_something_with_frame(fram...
django UnreadablePostError: request data read error
15,544,124
10
2013-03-21T09:51:19Z
28,598,364
9
2015-02-19T03:57:23Z
[ "python", "django", "mod-wsgi" ]
I'm working on django project and I got this error email. **Stack trace** ``` File "/usr/local/lib/python2.7/dist-packages/Django-1.4.3-py2.7.egg/django/core/handlers/wsgi.py", line 180, in _get_post self._load_post_and_files() File "/usr/local/lib/python2.7/dist-packages/Django-1.4.3-py2.7.egg/django/http/__ini...
> Why this error is happening ? because the server is recieving a malformed request, which can happen for many reasons. someone might've canceled loading the page, someone might have a crappy internet connection that cut out, *cosmic rays could have flipped a bit*. it's not something you really need to worry about un...
python regular expression: re.findall(r"(do|re|mi)+","mimi rere midore")
15,547,033
2
2013-03-21T12:04:38Z
15,547,065
8
2013-03-21T12:06:25Z
[ "python", "regex" ]
I couldn't understand why this regular expression, ``` re.findall(r"(do|re|mi)+","mimi rere midore"), ``` generates this result, ``` ['mi', 're', 're']. ``` My expected result is ['mimi', 'rere', 'midore']... However, when I use this regular expression, ``` re.findall(r"(?:do|re|mi)+","mimi rere midore"), ``` it...
The difference is in the capturing group. With a capturing froup, `findall()` returns *only* what was captured. Without a capturing group, the whole match is returned. In your first example, the group *only* captures the two characters, repeated or not. In the second example, the whole match includes any repetitions. ...
Handling months in python datetimes
15,547,217
2
2013-03-21T12:13:14Z
15,547,295
7
2013-03-21T12:17:05Z
[ "python", "datetime", "python-2.4" ]
I have a function which gets the start of the month before the datetime provided: ``` def get_start_of_previous_month(dt): ''' Return the datetime corresponding to the start of the month before the provided datetime. ''' target_month = (dt.month - 1) if target_month == 0: target_month =...
Use a `timedelta(days=1)` offset of the beginning of *this* month: ``` import datetime def get_start_of_previous_month(dt): ''' Return the datetime corresponding to the start of the month before the provided datetime. ''' previous = dt.date().replace(day=1) - datetime.timedelta(days=1) return ...
How to get rid of punctuation using NLTK tokenizer?
15,547,409
41
2013-03-21T12:22:07Z
15,554,045
8
2013-03-21T17:19:21Z
[ "python", "nlp", "tokenize", "nltk" ]
I'm just starting to use NLTK and I don't quite understand how to get a list of words from text. If I use `nltk.word_tokenize()`, I get a list of words and punctuation. I need only the words instead. How can I get rid of punctuation? Also `word_tokenize` doesn't work with multiple sentences: dots are added to the last ...
As noticed in comments start with sent\_tokenize(), because word\_tokenize() works only on a single sentence. You can filter out punctuation with filter(). And if you have an unicode strings make sure that is a unicode object (not a 'str' encoded with some encoding like 'utf-8'). ``` from nltk.tokenize import word_tok...
How to get rid of punctuation using NLTK tokenizer?
15,547,409
41
2013-03-21T12:22:07Z
15,555,162
55
2013-03-21T18:19:48Z
[ "python", "nlp", "tokenize", "nltk" ]
I'm just starting to use NLTK and I don't quite understand how to get a list of words from text. If I use `nltk.word_tokenize()`, I get a list of words and punctuation. I need only the words instead. How can I get rid of punctuation? Also `word_tokenize` doesn't work with multiple sentences: dots are added to the last ...
Take a look at the other tokenizing options that nltk provides [here](http://www.nltk.org/api/nltk.tokenize.html). For example, you can define a tokenizer that picks out sequences of alphanumeric characters as tokens and drops everything else: ``` from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer(...
How to get rid of punctuation using NLTK tokenizer?
15,547,409
41
2013-03-21T12:22:07Z
32,684,992
12
2015-09-20T22:31:23Z
[ "python", "nlp", "tokenize", "nltk" ]
I'm just starting to use NLTK and I don't quite understand how to get a list of words from text. If I use `nltk.word_tokenize()`, I get a list of words and punctuation. I need only the words instead. How can I get rid of punctuation? Also `word_tokenize` doesn't work with multiple sentences: dots are added to the last ...
You do not really need NLTK to remove punctuation. You can remove it with simple python. For strings: ``` import string s = '... some string with punctuation ...' s = s.translate(None, string.punctuation) ``` Or for unicode: ``` import string translate_table = dict((ord(char), None) for char in string.punctuation) ...
Node labels using networkx
15,548,506
9
2013-03-21T13:09:08Z
15,549,916
17
2013-03-21T14:11:40Z
[ "python", "matplotlib", "networkx" ]
I'm creating a graph out of given sequence of Y values held by `curveSeq`. (the X values are enumerated automatically: 0,1,2...) i.e for `curveSeq = [10,20,30]`, my graph will contain the points: ``` <0,10>, <1,20>, <2,30>. ``` I'm drawing a series of graphs on the same `nx.Graph` in order to present everything in o...
You can add the `with_labels=False` keyword to suppress drawing of the labels with `networkx.draw()`, e.g. ``` networkx.draw(G, pos=pos, node_color=colors[curve], node_size=80, with_labels=False) ``` Then draw specific labels with ``` networkx.draw_networkx_labels(G,pos, labels) ``` where labels is a dictionary...
How do I test dictionary-equality with Python's doctest-package?
15,549,429
19
2013-03-21T13:51:16Z
15,549,674
10
2013-03-21T14:01:32Z
[ "python", "dictionary", "doctest" ]
I'm writing a doctest for a function that outputs a dictionary. The doctest looks like ``` >>> my_function() {'this': 'is', 'a': 'dictionary'} ``` When I run it, it fails with ``` Expected: {'this': 'is', 'a': 'dictionary'} Got: {'a': 'dictionary', 'this': 'is'} ``` My best guess as to the cause of this fai...
I ended up using this. Hacky, but it works. ``` >>> p = my_function() >>> {'this': 'is', 'a': 'dictionary'} == p True ```
How do I test dictionary-equality with Python's doctest-package?
15,549,429
19
2013-03-21T13:51:16Z
15,549,731
7
2013-03-21T14:04:09Z
[ "python", "dictionary", "doctest" ]
I'm writing a doctest for a function that outputs a dictionary. The doctest looks like ``` >>> my_function() {'this': 'is', 'a': 'dictionary'} ``` When I run it, it fails with ``` Expected: {'this': 'is', 'a': 'dictionary'} Got: {'a': 'dictionary', 'this': 'is'} ``` My best guess as to the cause of this fai...
Doctest doesn't check `__repr__` equality, per se, it just checks that the output is exactly the same. You have to ensure that whatever is printed will be the same for the same dictionary. You can do that with this one-liner: ``` >>> sorted(my_function().items()) [('a', 'dictionary'), ('this', 'is')] ``` Although thi...
How do I test dictionary-equality with Python's doctest-package?
15,549,429
19
2013-03-21T13:51:16Z
21,227,671
26
2014-01-20T06:37:57Z
[ "python", "dictionary", "doctest" ]
I'm writing a doctest for a function that outputs a dictionary. The doctest looks like ``` >>> my_function() {'this': 'is', 'a': 'dictionary'} ``` When I run it, it fails with ``` Expected: {'this': 'is', 'a': 'dictionary'} Got: {'a': 'dictionary', 'this': 'is'} ``` My best guess as to the cause of this fai...
Another good way is to use `pprint` (in the standard library). ``` >>> import pprint >>> pprint.pprint({"second": 1, "first": 0}) {'first': 0, 'second': 1} ``` According to its source code, it's sorting dicts for you: <http://hg.python.org/cpython/file/2.7/Lib/pprint.py#l158> ``` items = _sorted(object.items()) ```
web scraping google news with python
15,550,655
5
2013-03-21T14:44:13Z
15,552,114
8
2013-03-21T15:48:10Z
[ "python", "web-scraping", "google-news" ]
I am creating a web scraper for different news outlets, for Nytimes and the Guardian it was easy since they have their own API. Now, I want to scrape results from this newspaper GulfTimes.com. They do not provide an advanced search in their website, so I resorted to Google news. However, Google news Api has been depre...
You can use awesome [requests](http://docs.python-requests.org/en/latest/) library: ``` import requests URL = 'https://www.google.com/search?pz=1&cf=all&ned=us&hl=en&tbm=nws&gl=us&as_q={query}&as_occt=any&as_drrb=b&as_mindate={month}%2F%{from_day}%2F{year}&as_maxdate={month}%2F{to_day}%2F{year}&tbs=cdr%3A1%2Ccd_min%3...
Querying models in django (two levels deep)
15,553,167
6
2013-03-21T16:37:26Z
15,553,204
11
2013-03-21T16:39:07Z
[ "python", "django" ]
If I have the following tables ``` class Town(models.Model): created = models.DateTimeField() class Street(models.Model): town = models.ForeignKey(Town) created = models.DateTimeField() class House(models.Model): street = models.ForeignKey(Street) created = models.DateTimeField() ``` How do I ge...
This should do the trick: ``` town_id = 5 houses_in_town = House.objects.filter(street__town__id = town_id) ```
How to check if the n-th element exists in a Python list?
15,554,255
6
2013-03-21T17:30:02Z
15,554,276
15
2013-03-21T17:31:02Z
[ "python", "list" ]
I have a list in python ``` x = ['a','b','c'] ``` with 3 elements. I want to check if a 4th element exists without receiving an error message. How would I do that?
You check for the length: ``` len(x) >= 4 ``` or you catch the `IndexError` exception: ``` try: value = x[3] except IndexError: value = None # no 4th index ``` What you use depends on how often you can *expect* there to be a 4th value. If it is usually there, use the exception handler (*better to ask forgi...
Get inferred dataframe types iteratively using chunksize
15,555,005
5
2013-03-21T18:10:45Z
15,556,579
7
2013-03-21T19:41:15Z
[ "python", "type-conversion", "pandas", "hdfstore" ]
> How can I use pd.read\_csv() to iteratively chunk through a file and > retain the dtype and other meta-information as if I read in the entire > dataset at once? I need to read in a dataset that is too large to fit into memory. I would like to import the file using pd.read\_csv and then immediately append the chunk i...
I didn't think it would be this intuitive, otherwise I wouldn't have posted the question. But once again, pandas makes things a breeze. However, keeping the question as this information might be useful to others working with large data: ``` In [1]: chunker = pd.read_csv('DATASET.csv', chunksize=500, header=0) # Store...
python sqlalchemy label usage
15,555,920
12
2013-03-21T18:58:35Z
15,557,759
9
2013-03-21T20:47:27Z
[ "python", "sqlalchemy", "alias" ]
I know I can use the label method for alias, but I can't figure out how to use the labeled element later in the query - something like the following: ``` session.query(Foo.bar.label("foobar")).filter(foobar > 10).all() ``` Of course, this doesn't work since there is no variable called foobar. How could this be accomp...
Just put foobar in quotes. It'll work for `order_by` like this: ``` session.query(Foo.bar.label("foobar")).order_by('foobar').all() ``` For filter you can use raw sql conditions: ``` session.query(Foo.bar.label("foobar")).filter("foobar > 10").all() ```
python sqlalchemy label usage
15,555,920
12
2013-03-21T18:58:35Z
15,563,673
17
2013-03-22T05:57:22Z
[ "python", "sqlalchemy", "alias" ]
I know I can use the label method for alias, but I can't figure out how to use the labeled element later in the query - something like the following: ``` session.query(Foo.bar.label("foobar")).filter(foobar > 10).all() ``` Of course, this doesn't work since there is no variable called foobar. How could this be accomp...
Offhand, I believe you can use the labeled column itself as an expression: ``` foobar = Foo.bar.label("foobar") session.query(foobar).filter(foobar > 10).all() ```
PyPI is slow. How do I run my own server?
15,556,147
28
2013-03-21T19:11:40Z
15,559,595
24
2013-03-21T22:44:12Z
[ "python", "caching", "pip", "mirroring", "pypi" ]
When a new developer joins the team, or Jenkins runs a complete build, I need to create a fresh virtualenv. I often find that setting up a virtualenv with Pip and a large number (more than 10) of requirements takes a very long time to install everything from PyPI. Often it fails altogether with: ``` Downloading/unpack...
Do you have a shared filesystem? Because I would use pip's cache setting. It's pretty simple. Make a folder called pip-cache in /mnt for example. ``` mkdir /mnt/pip-cache ``` Then each developer would put the following line into their pip config (unix = $HOME/.pip/pip.conf, win = %HOME%\pip\pip.ini) ``` [global] do...
PyPI is slow. How do I run my own server?
15,556,147
28
2013-03-21T19:11:40Z
15,816,816
8
2013-04-04T16:35:02Z
[ "python", "caching", "pip", "mirroring", "pypi" ]
When a new developer joins the team, or Jenkins runs a complete build, I need to create a fresh virtualenv. I often find that setting up a virtualenv with Pip and a large number (more than 10) of requirements takes a very long time to install everything from PyPI. Often it fails altogether with: ``` Downloading/unpack...
While it doesn't solve your PyPI problem, handing built virtualenvs to developers (or deployments) can be done with **[Terrarium](https://github.com/policystat/terrarium)**. Use [terrarium](https://github.com/policystat/terrarium) to package up, compress, and save virtualenvs. You can store them locally or even [store...
PyPI is slow. How do I run my own server?
15,556,147
28
2013-03-21T19:11:40Z
21,416,567
7
2014-01-28T20:51:53Z
[ "python", "caching", "pip", "mirroring", "pypi" ]
When a new developer joins the team, or Jenkins runs a complete build, I need to create a fresh virtualenv. I often find that setting up a virtualenv with Pip and a large number (more than 10) of requirements takes a very long time to install everything from PyPI. Often it fails altogether with: ``` Downloading/unpack...
I recently installed [**devpi**](http://doc.devpi.net/) into my development team's Vagrant configuration such that its package cache lives on the host's file system. This allows each VM to have its own devpi-server daemon that it uses as the index-url for virtualenv/pip. When the VMs are destroyed and reprovisioned, th...
Django DB Settings 'Improperly Configured' Error
15,556,499
87
2013-03-21T19:36:12Z
15,556,596
163
2013-03-21T19:42:18Z
[ "python", "django" ]
Django (1.5) is workin' fine for me, but when I fire up the Python interpreter (Python 3) to check some things, I get the weirdest error when I try importing - `from django.contrib.auth.models import User` - ``` Traceback (most recent call last): File "/usr/local/lib/python3.2/dist-packages/django/conf/__init__.py",...
You can't just fire up python and check things, django doesn't know what project you want to work on. You have to do one of these things: * Use `python manage.py shell` * Use `django-admin.py shell --settings=mysite.settings` (or whatever settings module you use) * Set `DJANGO_SETTINGS_MODULE` environment variable in ...
Django DB Settings 'Improperly Configured' Error
15,556,499
87
2013-03-21T19:36:12Z
31,352,698
17
2015-07-11T02:01:56Z
[ "python", "django" ]
Django (1.5) is workin' fine for me, but when I fire up the Python interpreter (Python 3) to check some things, I get the weirdest error when I try importing - `from django.contrib.auth.models import User` - ``` Traceback (most recent call last): File "/usr/local/lib/python3.2/dist-packages/django/conf/__init__.py",...
In your python shell/ipython do: ``` from django.conf import settings settings.configure() ```
Greenlet Vs. Threads
15,556,718
71
2013-03-21T19:49:46Z
15,596,277
112
2013-03-24T07:47:32Z
[ "python", "concurrency", "gevent", "coroutine", "greenlets" ]
I am new to gevents and greenlets. I found some good documentation on how to work with them, but none gave me justification on how and when I should use greenlets! * What are they really good at? * Is it a good idea to use them in a proxy server or not? * Why not threads? What I am not sure about is how they can prov...
Greenlets provide concurrency but *not* parallelism. Concurrency is when code can run independently of other code. Parallelism is the execution of concurrent code simultaneously. Parallelism is particularly useful when there's a lot of work to be done in userspace, and that's typically CPU-heavy stuff. Concurrency is u...
Greenlet Vs. Threads
15,556,718
71
2013-03-21T19:49:46Z
27,453,709
7
2014-12-12T23:27:33Z
[ "python", "concurrency", "gevent", "coroutine", "greenlets" ]
I am new to gevents and greenlets. I found some good documentation on how to work with them, but none gave me justification on how and when I should use greenlets! * What are they really good at? * Is it a good idea to use them in a proxy server or not? * Why not threads? What I am not sure about is how they can prov...
This is interesting enough to analyze. Here is a code to compare performance of greenlets versus multiprocessing pool versus multi-threading: ``` import gevent from gevent import socket as gsock import socket as sock from multiprocessing import Pool from threading import Thread from datetime import datetime class IpG...
Greenlet Vs. Threads
15,556,718
71
2013-03-21T19:49:46Z
28,907,804
14
2015-03-06T21:16:18Z
[ "python", "concurrency", "gevent", "coroutine", "greenlets" ]
I am new to gevents and greenlets. I found some good documentation on how to work with them, but none gave me justification on how and when I should use greenlets! * What are they really good at? * Is it a good idea to use them in a proxy server or not? * Why not threads? What I am not sure about is how they can prov...
Taking @Max's answer and adding some relevance to it for scaling, you can see the difference. I achieved this by changing the URLs to be filled as follows: ``` URLS_base = ['www.google.com', 'www.example.com', 'www.python.org', 'www.yahoo.com', 'www.ubc.ca', 'www.wikipedia.org'] URLS = [] for _ in range(10000): fo...
Python - Why cmp( ) is useful?
15,556,813
7
2013-03-21T19:54:34Z
15,556,845
9
2013-03-21T19:56:15Z
[ "python" ]
According to the [doc](http://docs.python.org/2/library/functions.html#cmp) and this [tutorial](http://www.tutorialspoint.com/python/number_cmp.htm), `cmp() returns -1 if x < y` and `cmp() returns 0 if x == y` and `cmp() returns 1 if x > y` The tutorial also said that > cmp() returns the sign of the difference o...
> I don't really get what does it mean *sign of the difference of two numbers.* This means: take the difference, and then the sign of that difference. For example, if `x` and `y` are two numbers: * `x < y` => `x - y < 0` and the function returns -1. * `x == y` => `x - y == 0` and the function returns 0. * `x > y` => ...
Python - Why cmp( ) is useful?
15,556,813
7
2013-03-21T19:54:34Z
26,515,234
7
2014-10-22T19:09:43Z
[ "python" ]
According to the [doc](http://docs.python.org/2/library/functions.html#cmp) and this [tutorial](http://www.tutorialspoint.com/python/number_cmp.htm), `cmp() returns -1 if x < y` and `cmp() returns 0 if x == y` and `cmp() returns 1 if x > y` The tutorial also said that > cmp() returns the sign of the difference o...
> # Why cmp( ) is useful? It isn't very useful, which is why it was deprecated (the builtin `cmp` is gone and builtin sorts no longer accept one in Python 3), but here's an interesting usage which uses its result as an index (it returns -1 if the first is less than the second, 0 if equal, and 1 if greater than): ``` ...
turn scatter data into binned data with errors bars equal to standard deviation
15,556,930
3
2013-03-21T20:01:26Z
15,559,654
10
2013-03-21T22:48:32Z
[ "python", "numpy", "histogram", "scatter" ]
I have a bunch of data scattered x, y. If I want to bin these according to x and put error bars equal to the standard deviation on them, how would I go about doing that? The only I know of in python is to loop over the data in x and group them according to bins (max(X)-min(X)/nbins) then loop over those blocks to find...
You can bin your data with `np.histogram`. I'm reusing code from [this other answer](http://stackoverflow.com/questions/15477857/mean-values-depending-on-binning-with-respect-to-second-variable/15478137#15478137) to calculate the mean and standard deviation of the binned `y`: ``` import numpy as np import matplotlib.p...
How to check if SSH connection was established with AWS instance
15,556,958
9
2013-03-21T20:03:20Z
17,656,609
7
2013-07-15T14:25:53Z
[ "python", "ssh", "amazon-web-services", "amazon-ec2", "boto" ]
I'm trying to connect to the Amazon EC2 instance via SSH using `boto`. I know that ssh connection can be established after some time after instance was created. So my questions are: * Can I somehow check if SSH is up on the instance? (if so, how?) * Or how can I check for the output of `boto.manage.cmdshell.sshclient_...
The message "SSH Connection refused, will retry in 5 seconds" is coming from boto: <http://code.google.com/p/boto/source/browse/trunk/boto/manage/cmdshell.py> Initially, 'running' just implicates that the instance has started booting. As long as `sshd` is not up, connections to port 22 are refused. Hence, what you obs...
Django: Remove a field from a Form subclass
15,557,257
25
2013-03-21T20:19:52Z
15,557,335
46
2013-03-21T20:23:38Z
[ "python", "django", "forms", "inheritance", "field" ]
``` class LoginForm(forms.Form): nickname = forms.CharField(max_length=100) username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput) class LoginFormWithoutNickname(LoginForm): # i don't want the field nickname here nickname = None #?? ``` **Is there a way ...
You can alter the fields in a subclass by overriding the **init** method: ``` class LoginFormWithoutNickname(LoginForm): def __init__(self, *args, **kwargs): super(LoginFormWithoutNickname, self).__init__(*args, **kwargs) self.fields.pop('nickname') ```
Django: Remove a field from a Form subclass
15,557,257
25
2013-03-21T20:19:52Z
20,515,384
9
2013-12-11T09:32:13Z
[ "python", "django", "forms", "inheritance", "field" ]
``` class LoginForm(forms.Form): nickname = forms.CharField(max_length=100) username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput) class LoginFormWithoutNickname(LoginForm): # i don't want the field nickname here nickname = None #?? ``` **Is there a way ...
Django 1.7 addressed this in commit [b16dd1fe019](https://github.com/django/django/commit/b16dd1fe019b38d0dcdf4a400e9377fb06b33178) for ticket [#8620](https://code.djangoproject.com/ticket/8620). In Django 1.7, it becomes possible to do `nickname = None` in the subclass as the OP suggests. From the documentation change...
obtain the max y-value of a histogram
15,558,136
4
2013-03-21T21:08:07Z
15,558,796
9
2013-03-21T21:45:26Z
[ "python", "matplotlib" ]
I am looking for suggestions on how to calculate the maximum y-value of a histogram. ``` #simple histogram. how can I obtain the maximum value of, say, x and y? import matplotlib.pyplot as plt hdata = randn(500) x = plt.hist(hdata) y = plt.hist(hdata, bins=40) ```
`hist` returns a tuple that contains the histogram bin locations and y values. Try this: ``` y, x, _ = plt.hist(hdata) print x.max() print y.max() ``` Note that `len(y) = len(x) - 1`.
How to check if character in string is a letter? Python
15,558,392
12
2013-03-21T21:21:48Z
15,558,443
23
2013-03-21T21:24:43Z
[ "python", "string", "find" ]
So I know about islower and isupper, but i can't seem to find out if you can check whether or not that character is a letter? ``` Example: s = 'abcdefg' s2 = '123abcd' s3 = 'abcDEFG' s[0].islower() = True s2[0].islower()= False s3[0].islower()=True ``` is there any way to just ask if it is a character besides doing...
You can use `isalpha()`, see the docs at <http://docs.python.org/2/library/stdtypes.html> An example: ``` >>> s = "a123b" >>> for char in s: ... print char, char.isalpha() ... a True 1 False 2 False 3 False b True ```
Why is peewee including the 'id' column into the mysql select query?
15,559,468
8
2013-03-21T22:33:45Z
15,560,415
9
2013-03-22T00:04:14Z
[ "python", "mysql", "select", "create-table", "peewee" ]
I am trying to learn how to use peewee with mysql. I have an existing database on a mysql server with an existing table. The table is currently empty (I am just testing right now). ``` >>> db = MySQLDatabase('nhl', user='root', passwd='blahblah') >>> db.connect() >>> class schedule(Model): ... date = DateField(...
Most simple active-record pattern ORMs need an `id` column to track object identity. PeeWee appears to be one of them (or at least I am not aware of any way to *not* use an id). You probably can't use PeeWee without altering your tables. Your existing table doesn't seem to be very well designed anyway, since it appear...
Why is peewee including the 'id' column into the mysql select query?
15,559,468
8
2013-03-21T22:33:45Z
16,064,760
7
2013-04-17T15:56:08Z
[ "python", "mysql", "select", "create-table", "peewee" ]
I am trying to learn how to use peewee with mysql. I have an existing database on a mysql server with an existing table. The table is currently empty (I am just testing right now). ``` >>> db = MySQLDatabase('nhl', user='root', passwd='blahblah') >>> db.connect() >>> class schedule(Model): ... date = DateField(...
If your primary key column name is other than 'id' you should add additional field to that table model class: ``` class Table(BaseModel): id_field = PrimaryKeyField() ``` That will tell your script that your table has primary keys stored in the column named 'id\_field' and that column is INT type with Auto Increm...
TypeError: type object argument after * must be a sequence, not generator
15,559,829
10
2013-03-21T23:03:59Z
15,559,890
22
2013-03-21T23:10:19Z
[ "python", "generator", "typeerror" ]
Why does the following Python code raise an error `TypeError: type object argument after * must be a sequence, not generator` while if I comment the first (useless) line in generator f, everything works fine? ``` from itertools import izip def z(): for _ in range(10): yield _ def f(z): for _ in ...
This is amusing: you forgot to call `z` when you passed it to `f`: ``` iterators = izip(*f(z())) ``` So `f` tried to iterate over a function object: ``` for _ in z: pass # z is a function ``` This raised a TypeError: ``` TypeError: 'function' object is not iterable ``` Python innards caught it and reraised with...
Python's equivalent to Javascript's jQuery or Node's cheerio?
15,559,854
4
2013-03-21T23:06:41Z
15,559,873
7
2013-03-21T23:08:44Z
[ "jquery", "python", "api", "node.js", "cheerio" ]
I'm looking for a library that has a similar API and usage as jQuery or Cheerio. **My use case is:** parsing an HTML file for any script or link tags containing javascript/css file references.
Python equivalent for jQuery is [pyQuery](https://pypi.python.org/pypi/pyquery). Under that link you can find usage examples. You can also visit [PyQuery on GitHub](https://github.com/gawel/pyquery).
How to stop flask application without using ctrl-c
15,562,446
21
2013-03-22T03:55:25Z
17,053,522
22
2013-06-11T20:47:13Z
[ "python", "flask", "flask-extensions" ]
I want to implement a command which can stop flask application by using flask-script. I have searched the solution for a while. Because the framework doesn't provide "app.stop()" API, I am curious about how to code this. I am working on Ubuntu 12.10 and Python 2.7.3.
If you are just running the server on your desktop, you can expose an endpoint to kill the server (read more at [Shutdown The Simple Server](http://flask.pocoo.org/snippets/67/)): ``` def shutdown_server(): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not ...
Do python "in" statements automatically return as true
15,563,576
6
2013-03-22T05:48:15Z
15,563,944
15
2013-03-22T06:19:14Z
[ "python", "python-2.7" ]
I wrote this bit of unnecessarily complicated code on my way to learning about how to use the `in` statement to make `if` statements work better. I have two questions following the code snippet. ``` answer = ['Yes', 'yes', 'YES'] answer2 = ['No', 'no', 'NO'] ans = raw_input() for i in range(0, 3): if ans in answer...
To answer your questions in reverse order, the reason why explicitly comparing with `True` did not work for you is that Python did not interpret the expression they way you expected. The Python parser has special handling of compare expressions so that you can chain them together and get a sensible result, like this: ...
scikit learn SVM, how to save/load support vectors?
15,564,410
8
2013-03-22T06:49:24Z
18,445,827
15
2013-08-26T13:52:35Z
[ "python", "machine-learning" ]
using python scikit svm, after running clf.fit(X, Y), you get your support vectors. could I load these support vectors directly (passing them as paramter) when instantiate a svm.SVC object? which means I do not need to running fit() method each time to do predication
From the scikit manual: <http://scikit-learn.org/stable/modules/model_persistence.html> 1.2.4 Model persistence It is possible to save a model in the scikit by using Python’s built-in persistence model, namely pickle. ``` >>> from sklearn import svm >>> from sklearn import datasets >>> clf = svm.SVC() >>> iris = da...
Locally run all of the spiders in Scrapy
15,564,844
6
2013-03-22T07:17:42Z
15,580,406
12
2013-03-22T21:48:46Z
[ "python", "web-crawler", "scrapy" ]
Is there a way to run all of the spiders in a Scrapy project without using the Scrapy daemon? There used to be a way to run multiple spiders with `scrapy crawl`, but that syntax was removed and Scrapy's code changed quite a bit. I tried creating my own command: ``` from scrapy.command import ScrapyCommand from scrapy...
Here is an example that does not run inside a custom command, but runs the Reactor manually and creates a new Crawler [for each spider](http://doc.scrapy.org/en/latest/topics/practices.html#running-multiple-spiders-in-the-same-process): ``` from twisted.internet import reactor from scrapy.crawler import Crawler # scra...
Locally run all of the spiders in Scrapy
15,564,844
6
2013-03-22T07:17:42Z
27,471,668
11
2014-12-14T16:58:13Z
[ "python", "web-crawler", "scrapy" ]
Is there a way to run all of the spiders in a Scrapy project without using the Scrapy daemon? There used to be a way to run multiple spiders with `scrapy crawl`, but that syntax was removed and Scrapy's code changed quite a bit. I tried creating my own command: ``` from scrapy.command import ScrapyCommand from scrapy...
Why didn't you just use something like: ``` scrapy list|xargs -n 1 scrapy crawl ``` ?
Remove time in date time function?
15,567,052
5
2013-03-22T09:40:57Z
15,567,100
9
2013-03-22T09:43:46Z
[ "python", "django", "templates", "datetime" ]
I have a variable `{{value.time}}` in this value executes ``` March 22, 2013, 2:30 a.m ``` But I want to remove the `2:30 a.m` (time) for this value in my templates file. How could I do this?
Put date as extension ``` {{ value.time.date }} ```
How can I check the existence of attributes and tags in XML before parsing?
15,568,126
7
2013-03-22T10:30:40Z
15,568,173
21
2013-03-22T10:33:17Z
[ "python", "parsing", "condition", "elementtree" ]
I'm parsing an XML file via Element Tree in python and and writing the content to a cpp file. The content of children tags will be variant for different tags. For example first event tag has party tag as child but second event tag doesn't have. -->How can I check whether a tag exists or not before parsing? -->Childr...
If a tag doesn't exist, `.find()` indeed returns `None`. Simply test for that value: ``` for event in root.findall('event'): party = event.find('party') if party is None: continue parties = party.text children = event.get('value') ``` You already use `.get()` on event to test for the `value` t...
Is __enter__ and __exit__ behaviour for connection objects specified in the Python database API?
15,568,137
3
2013-03-22T10:31:16Z
15,568,275
12
2013-03-22T10:38:43Z
[ "python", "database", "api", "mysql-python", "specifications" ]
# Background I recently discovered the Python `with` keyword and started seeing its potential usefulness for more prettily handling some scenarios where I'd previously have used `try: ... finally: ...` constructs. I immediately decided to try it out on the MySQLdb connection object in some code I was writing. I didn'...
The Python DBAPI was written well before context managers were added to the Python language. As such, different database libraries made their *own* decisions on how to implement context manager support (if they implemented it at all). *Usually* using the database as a context manager ties you to a transaction. The tr...
Numpy gcd function
15,569,429
7
2013-03-22T11:38:56Z
15,569,615
7
2013-03-22T11:50:24Z
[ "python", "numpy", "greatest-common-divisor" ]
Does `numpy` have a `gcd` function somewhere in its structure of modules? I'm aware of `fractions.gcd` but thought a `numpy` equivalent maybe potentially quicker and work better with `numpy` datatypes. I have been unable to uncover anything on google other than this [link](http://mail.scipy.org/pipermail/numpy-discus...
It seems there is no `gcd` function yet in `numpy`. However, there is a [gcd function in fractions module](http://docs.python.org/2/library/fractions.html#fractions.gcd). If you need to perform `gcd` on `numpy` arrays, you could build a `ufunc` using it: ``` gcd = numpy.frompyfunc(fractions.gcd, 2, 1) ```
Numpy gcd function
15,569,429
7
2013-03-22T11:38:56Z
15,570,694
7
2013-03-22T12:46:34Z
[ "python", "numpy", "greatest-common-divisor" ]
Does `numpy` have a `gcd` function somewhere in its structure of modules? I'm aware of `fractions.gcd` but thought a `numpy` equivalent maybe potentially quicker and work better with `numpy` datatypes. I have been unable to uncover anything on google other than this [link](http://mail.scipy.org/pipermail/numpy-discus...
You can write it yourself: ``` def numpy_gcd(a, b): a, b = np.broadcast_arrays(a, b) a = a.copy() b = b.copy() pos = np.nonzero(b)[0] while len(pos) > 0: b2 = b[pos] a[pos], b[pos] = b2, a[pos] % b2 pos = pos[b[pos]!=0] return a ``` Here is the code to test the result a...
Pandas Pivot tables row subtotals
15,570,099
23
2013-03-22T12:16:10Z
15,570,546
12
2013-03-22T12:38:30Z
[ "python", "pandas", "pivot-table" ]
I'm using Pandas 0.10.1 Considering this Dataframe: ``` Date State City SalesToday SalesMTD SalesYTD 20130320 stA ctA 20 400 1000 20130320 stA ctB 30 500 1100 20130320 stB ctC 10 500 900 20130320 stB ctD ...
You can get the summarized values by using groupby() on the State column. Lets make some sample data first: ``` import pandas as pd import StringIO incsv = StringIO.StringIO("""Date,State,City,SalesToday,SalesMTD,SalesYTD 20130320,stA,ctA,20,400,1000 20130320,stA,ctB,30,500,1100 20130320,stB,ctC,10,500,900 20130320,...
Pandas Pivot tables row subtotals
15,570,099
23
2013-03-22T12:16:10Z
15,574,875
29
2013-03-22T16:07:31Z
[ "python", "pandas", "pivot-table" ]
I'm using Pandas 0.10.1 Considering this Dataframe: ``` Date State City SalesToday SalesMTD SalesYTD 20130320 stA ctA 20 400 1000 20130320 stA ctB 30 500 1100 20130320 stB ctC 10 500 900 20130320 stB ctD ...
If you put State and City not both in the rows, you'll get separate margins. Reshape and you get the table you're after: ``` In [10]: table = pivot_table(df, values=['SalesToday', 'SalesMTD','SalesYTD'],\ rows=['State'], cols=['City'], aggfunc=np.sum, margins=True) In [11]: table.stack('City') O...
Python: A4 size for a plot
15,571,267
4
2013-03-22T13:13:55Z
15,622,986
7
2013-03-25T19:20:46Z
[ "python", "matplotlib" ]
I have a code that saves a figure with: ``` savefig("foo.eps", orientation = 'portrait', format = 'eps') ``` If I don't specify anythingelse, the figure is correctly saved but when I print it, the figure fills only the half of a A4 sheet.If I modify the string as: ``` savefig("foo.eps", papertype = 'a4', orientation...
Try to set the size of the figure (in inches) before you save it. You can do this when you initialize the figure by doing: ``` figure(figsize=(11.69,8.27)) # for landscape ``` or if the figure exists: ``` f = gcf() # f = figure(n) if you know the figure number f.set_size_inches(11.69,8.27) ``` or in advance for al...
Including Local Variables in Django Error Emails
15,571,499
5
2013-03-22T13:25:43Z
15,593,712
7
2013-03-24T00:29:21Z
[ "python", "django", "error-handling", "stack-trace" ]
I have a site built in Django. When an error occurs on the production site, Django automatically sends a stack trace to the email addresses listed in the ADMINS list in settings.py. I would like this stack trace to include local variables for each stack frame (like the standard stack trace does when the site is in de...
It's really simple to set this up. Just put `'include_html': True` in the logging config of whichever handler is sending error emails for you. For example (this is the default logging handler aside from the "include\_html" line): ``` 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['re...
General decorator to wrap try except in python?
15,572,288
20
2013-03-22T14:04:36Z
15,572,816
8
2013-03-22T14:27:03Z
[ "python", "try-catch", "wrapper", "decorator" ]
I'd interacting with a lot of deeply nested json I didn't write, and would like to make my python script more 'forgiving' to invalid input. I find myself writing involved try-except blocks, and would rather just wrap the dubious function up. I understand it's a bad policy to swallow exceptions, but I'd rather they be ...
in your case you first evaluate the value of the meow call (which doesn't exist) and then wrap it in the decorator. this doesn't work that way. first the exception is raised before it was wrapped, then the wrapper is wrongly indented (`silenceit` should not return itself). You might want to do something like: ``` def...
General decorator to wrap try except in python?
15,572,288
20
2013-03-22T14:04:36Z
15,573,313
18
2013-03-22T14:50:33Z
[ "python", "try-catch", "wrapper", "decorator" ]
I'd interacting with a lot of deeply nested json I didn't write, and would like to make my python script more 'forgiving' to invalid input. I find myself writing involved try-except blocks, and would rather just wrap the dubious function up. I understand it's a bad policy to swallow exceptions, but I'd rather they be ...
You could use a defaultdict and [the context manager approach as outlined in Raymond Hettinger's PyCon 2013 presentation](https://speakerdeck.com/pyconslides/transforming-code-into-beautiful-idiomatic-python-by-raymond-hettinger-1) ``` from collections import defaultdict from contextlib import contextmanager @context...
General decorator to wrap try except in python?
15,572,288
20
2013-03-22T14:04:36Z
27,446,895
8
2014-12-12T15:30:58Z
[ "python", "try-catch", "wrapper", "decorator" ]
I'd interacting with a lot of deeply nested json I didn't write, and would like to make my python script more 'forgiving' to invalid input. I find myself writing involved try-except blocks, and would rather just wrap the dubious function up. I understand it's a bad policy to swallow exceptions, but I'd rather they be ...
It's very easy to achieve using configurable decorator. ``` def get_decorator(errors=(Exception, ), default_value=''): def decorator(func): def new_func(*args, **kwargs): try: return func(*args, **kwargs) except errors, e: print "Got error! ", repr(...
General decorator to wrap try except in python?
15,572,288
20
2013-03-22T14:04:36Z
27,500,036
7
2014-12-16T08:01:09Z
[ "python", "try-catch", "wrapper", "decorator" ]
I'd interacting with a lot of deeply nested json I didn't write, and would like to make my python script more 'forgiving' to invalid input. I find myself writing involved try-except blocks, and would rather just wrap the dubious function up. I understand it's a bad policy to swallow exceptions, but I'd rather they be ...
There are lots of good answers here, but I didn't see any that address the question of whether you can accomplish this via decorators. The short answer is "no," at least not without structural changes to your code. Decorators operate at the function level, not on individual statements. Therefore, in order to use decor...
Using DATEADD in sqlalchemy
15,572,292
5
2013-03-22T14:04:50Z
15,573,750
15
2013-03-22T15:12:10Z
[ "python", "sql", "sqlalchemy", "flask", "flask-sqlalchemy" ]
How can I rewrite the following sql statement with sqlalchemy in python. I have been searching for 30 mins but still couldn't find any solutions. ``` DATEADD(NOW(), INTERVAL 1 DAY) ``` or ``` INSERT INTO dates (expire) VALUES(DATEADD(NOW(), INTERVAL 1 DAY)) ``` Thanks in advance
For completeness sake, here is how you'd generate that exact SQL with using [`sqlalchemy.sql.func`](http://docs.sqlalchemy.org/en/rel_0_8/core/tutorial.html#functions): ``` from sqlalchemy.sql import func from sqlalchemy.sql.expression import bindparam from sqlalchemy import Interval tomorrow = func.dateadd(func.now(...
Good Call Hierarchy in Eclipse/PyDev
15,572,295
9
2013-03-22T14:04:59Z
15,580,217
11
2013-03-22T21:33:47Z
[ "python", "eclipse", "pydev" ]
Is there a way to get a good call hierarchy in PyDev? I want to be able to select a function and see in which files it is called and eventually by which other functions. I tried the Hierarchy View in Eclipse by pressing F4, but it does not output what I want.
PyDev has a find references with Ctrl+Shift+G (not sure that'd be what you're calling a call hierarchy).
Splitting letters from numbers within a string
15,572,387
5
2013-03-22T14:09:13Z
15,572,451
20
2013-03-22T14:12:22Z
[ "python", "string", "split" ]
I'm processing strings like this: "125A12C15" I need to split them at boundaries between letters and numbers, e.g. this one should become ["125","A","12","C","15"]. Is there a more elegant way to do this in Python than going through it position by position and checking whether it's a letter or a number, and then conca...
Use [`itertools.groupby`](http://docs.python.org/2/library/itertools.html#itertools.groupby) together with [`str.isalpha`](http://docs.python.org/2/library/stdtypes.html#string-methods) method: > Docstring: > > groupby(iterable[, keyfunc]) -> create an iterator which returns > (key, sub-iterator) grouped by each value...
How to inspect and cancel Celery tasks by task name
15,575,826
17
2013-03-22T16:52:36Z
15,642,110
18
2013-03-26T16:18:03Z
[ "python", "redis", "celery" ]
I'm using Celery (3.0.15) with Redis as a broker. Is there a straightforward way to query the number of tasks with a given name that exist in a Celery queue? And, as a followup, is there a way to cancel all tasks with a given name that exist in a Celery queue? I've been through the [Monitoring and Management Guide](...
``` # Retrieve tasks # Reference: http://docs.celeryproject.org/en/latest/reference/celery.events.state.html query = celery.events.state.tasks_by_type(your_task_name) # Kill tasks # Reference: http://docs.celeryproject.org/en/latest/userguide/workers.html#revoking-tasks for uuid, task in query: celery.control.revo...
How do you remove a column from a structured numpy array?
15,575,878
10
2013-03-22T16:55:16Z
15,577,562
10
2013-03-22T18:37:45Z
[ "python", "numpy" ]
I have another basic question, that I haven't been able to find the answer for, but it seems like something that should be easy to do. Ok, imagine you have a structured numpy array, generated from a csv with the first row as field names. The array has the form: ``` dtype([('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ......
It's not quite a single function call, but the following shows one way to drop the i-th field: ``` In [67]: a Out[67]: array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8')]) In [68]: i = 1 # Drop the 'B' field In [69]: names = list(a.dtype.names) In [70]: names Out[70]...
Logging requests to django-rest-framework
15,578,946
20
2013-03-22T20:02:30Z
27,928,365
17
2015-01-13T17:51:31Z
[ "python", "django", "django-rest-framework" ]
For debugging purposes, I would like to use Django's logging mechanism to log each and every incoming request when it "arrives" at django-rest-framework's doorstep. Djagno offers logging of its requests (only "warning" log level and above) in the following manner (from LOGGING section in settings.py): ``` 'django.req...
I made a generic `RequestLogMiddleware` that can be hooked into any Django `View` using `decorator_from_middleware`. ## request\_log/middleware.py ``` import socket import time class RequestLogMiddleware(object): def process_request(self, request): request.start_time = time.time() def process_respo...
How to combine multiple numpy masks
15,579,260
3
2013-03-22T20:24:18Z
15,579,311
9
2013-03-22T20:27:53Z
[ "python", "numpy" ]
``` m1 = [0,1,1,3] m2 = [0,0,1,1] data = [10,20,30,40] ``` I want to do something like this: ``` mask = (m1 == 1) & (m2 == 1) data[mask] #should return 30 ``` Note, this example results in an error
You are using python lists instead of numpy arrays. Try this instead: ``` import numpy as np m1 = np.array([0,1,1,3]) m2 = np.array([0,0,1,1]) mask = (m1 == 1) & (m2 == 1) data[mask] # returns array([30]) ``` In your example, when `m1` was a list, `m1 == 1` is evaluated as `False` (the same for `m2`), so mask was `...
Preserve whitespaces when using split() and join() in python
15,579,271
5
2013-03-22T20:25:18Z
15,579,296
9
2013-03-22T20:26:52Z
[ "python", "join", "split" ]
I have a data file with columns like ``` BBP1 0.000000 -0.150000 2.033000 0.00 -0.150 1.77 ``` and the individual columns are separated by a varying number of whitespaces. My goal is to read in those lines, do some math on several rows, for example multiplying column 4 by .95, and write them out to a new fi...
You want to use `re.split()` in that case: ``` re.split(r'(\s+)', line) ``` would return both the columns *and* the whitespace so you can rejoin the line later with the same amount of whitespace included. Example: ``` >>> re.split(r'(\s+)', line)['BBP1', ' ', '0.000000', ' ', '-0.150000', ' ', '2.033000', ' ...
python dict to numpy structured array
15,579,649
17
2013-03-22T20:51:49Z
15,579,807
32
2013-03-22T21:04:15Z
[ "python", "numpy", "arcpy" ]
I have a dictionary that I need to convert to a NumPy structured array. I'm using the arcpy function [`NumPyArraytoTable`](http://resources.arcgis.com/en/help/main/10.1/index.html#//018w00000016000000), so a NumPy structured array is the only data format that will work. Based on this thread: [Writing to numpy array fr...
You could use `np.array(result.items(), dtype=dtype)`: ``` import numpy as np result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442} names = ['id','data'] formats = ['f8','f8'] dtype = dict(names = names, formats=fo...
Python output complex line with floats colored by value
15,580,303
2
2013-03-22T21:40:33Z
15,580,392
7
2013-03-22T21:47:53Z
[ "python", "printing", "colors", "floating-point", "format" ]
This is my first python program and my first asking a question on stack overflow so I apologize if my code is a mess and or if my question is ill-formatted. I would like to print the same line I'm already printing, but each float should be a different color based on its value. (specifically `>.7` is green, `.7<` is re...
You can use ASCII color codes at the beginning of your print to change the color, as an example `'\033[91m'` for RED and `'\033[94m'` for BLUE. **e.g** ``` if array[0][i] > 7: print '\033[94m' + oreName[i]+"= %.3f \t 5"%(array[0][i]) elif array[0][i] < 7: print '\033[91m' + oreName[i]+"= %.3f \t 5"%(array[0...
`os.symlink` vs `ln -s`
15,580,425
17
2013-03-22T21:50:03Z
15,580,457
8
2013-03-22T21:52:51Z
[ "python", "linux", "bash", "symlink" ]
I need to create a symlink for every item of dir1 (file or directory) inside dir2. dir2 already exists and is not a symlink. In Bash I can easily achieve this by: `ln -s /home/guest/dir1/* /home/guest/dir2/` But in python using os.symlink I get an error: ``` >>> os.symlink('/home/guest/dir1/*', '/home/guest/dir2/') ...
`*` is a shell extension pattern, which in your case designates "all files starting with `/home/guest/dir1/`". But it's your *shell's role to expand this pattern* to the files it matches. Not the `ln` command's. But `os.symlink` is not a shell, it's an OS call - hence, it doesn't support shell extension patterns. You...
`os.symlink` vs `ln -s`
15,580,425
17
2013-03-22T21:50:03Z
15,580,458
35
2013-03-22T21:52:58Z
[ "python", "linux", "bash", "symlink" ]
I need to create a symlink for every item of dir1 (file or directory) inside dir2. dir2 already exists and is not a symlink. In Bash I can easily achieve this by: `ln -s /home/guest/dir1/* /home/guest/dir2/` But in python using os.symlink I get an error: ``` >>> os.symlink('/home/guest/dir1/*', '/home/guest/dir2/') ...
`os.symlink` creates a single symlink. `ln -s` creates multiple symlinks (if its last argument is a directory, and there's more than one source). The Python equivalent is something like: ``` dst = args[-1] for src in args[:-1]: os.symlink(src, os.path.join(dst, os.path.dirname(src))) ``` So, how does it work whe...
How to remove duplicates in set for objects?
15,580,490
3
2013-03-22T21:55:41Z
15,580,516
7
2013-03-22T21:57:58Z
[ "python" ]
I have set of objects: ``` class Test(object): def __init__(self): self.i = random.randint(1,10) res = set() for i in range(0,1000): res.add(Test()) print len(res) = 1000 ``` How to remove duplicates from set of objects ? Thanks for answers, it's work: ``` class Test(object): def __init__(se...
Your objects must be *[hashable](http://docs.python.org/2/glossary.html#term-hashable)* (i.e. must have [`__eq__()`](http://docs.python.org/2/reference/datamodel.html#object.__eq__) and [`__hash__()`](http://docs.python.org/2/reference/datamodel.html#object.__hash__) defined) for sets to work properly with them: ``` c...
Does NLTK parts of speech tagger use global information or just the word that is being tagged?
15,580,509
2
2013-03-22T21:57:17Z
15,581,205
8
2013-03-22T23:02:38Z
[ "python", "nlp", "nltk" ]
I am currently doing some parts of speech tagging using NLTK's "nltk.pos\_tag". I was wondering does NLTK's tagger use information beyond the word that is currently being tagged to determine the POS of the word? If not does NLTK have a tagger that would do this? Thanks in advance for any info!
The `pos_tag` function makes a call to load the `pickle` at `_POS_TAGGER`. This is a maximum entropy tagger probably trained on [Penn Treebank](http://www.cis.upenn.edu/~treebank/) POS annotated text. The information that a MaxEnt tagger uses to determine the part of speech will be based on the feature set used in trai...
how to solve error in command "python systrace.py --set-tags gfx,view,wm"?
15,581,455
2
2013-03-22T23:29:43Z
15,581,487
9
2013-03-22T23:33:18Z
[ "android", "python", "exception-handling", "command-line-arguments", "android-sdk-tools" ]
i want to do this:- ``` $> cd android-sdk/tools/systrace $> python systrace.py --set-tags gfx,view,wm $> adb shell stop $> adb shell start $> python systrace.py --disk --time=10 -o mynewtrace.html ``` i run this command:- ``` python systrace.py --set-tags gfx,view,wm ``` and error comes :- ``` set-tags gfx,view,wm...
That script was written for python 2. You should install python 2.x, not python 3.x. Android docs should have mentioned it by now, really.
How to pause a pylab figure until a key is pressed or mouse is clicked?
15,582,956
2
2013-03-23T03:18:37Z
27,071,722
14
2014-11-21T22:53:39Z
[ "python", "matplotlib" ]
I am trying to program an animated simulation using pylab and networkx. The simulation is not interesting all the time so most of the time I want it to go fast, however, I want to be able to pause it and look at it when it looks interesting. Pausing the screen until keypress will solve my problem, because I can press t...
Is there some reason not to use waitforbuttonpress()? ``` import matplotlib.pyplot as plt A=[[0,1],[1,0]] B=[[0,1],[0,0]] x=1 while True: if x==1: drawGraph(A) x=0 else: drawGraph(B) x=1 plt.waitforbuttonpress() ``` This will, as it says, wait for a key or button press for...
How to extract text from a PDF file in Python?
15,583,535
16
2013-03-23T04:57:35Z
15,588,435
19
2013-03-23T15:19:17Z
[ "python", "pypdf" ]
How can I extract text from a PDF file in Python? I tried the following: ``` import sys import pyPdf def convertPdf2String(path): content = "" pdf = pyPdf.PdfFileReader(file(path, "rb")) for i in range(0, pdf.getNumPages()): content += pdf.getPage(i).extractText() + " \n" conten...
if you are running linux or mac you can use **ps2ascii** command in your code: ``` import os input="someFile.pdf" output="out.txt" os.system(("ps2ascii %s %s") %( input , output)) ```
flask : how to architect the project with multiple apps?
15,583,671
5
2013-03-23T05:18:26Z
15,590,585
9
2013-03-23T18:37:00Z
[ "python", "flask" ]
Lets say I want to build a project Facebook I need a project structure like ``` facebook/ __init__.py feed/ __init__.py models.py business.py views.py chat/ __init__.py models.py business.py ...
Use [blueprints](http://flask.pocoo.org/docs/blueprints/). Each one of your sub-applications should be a blueprint, and you load every one of them inside your main init file. Answering your second question ``` from flask import Flask app = Flask(__name__) ``` You should put this into `facebook/__init__.py` BTW, my ...
Python OpenCV2 cv2.cv_fourcc not working with VideoWriter
15,584,608
8
2013-03-23T07:56:01Z
15,814,980
13
2013-04-04T15:06:43Z
[ "python", "opencv" ]
As the title states, when I run the cv2.videowriter function I get 'module' object has no attribute CV\_FOURCC. Code: ``` # Creates a video file from webcam stream import cv2 Create test window cv2.namedWindow("cam_out", cv2.CV_WINDOW_AUTOSIZE) # Create vid cap object vid = cv2.VideoCapture(1) # Create video writ...
Change `cv2.CV_FOURCC('M','J','P','G')` to `cv2.cv.CV_FOURCC('M','J','P','G')`.
Python OpenCV2 cv2.cv_fourcc not working with VideoWriter
15,584,608
8
2013-03-23T07:56:01Z
21,869,070
17
2014-02-19T01:22:14Z
[ "python", "opencv" ]
As the title states, when I run the cv2.videowriter function I get 'module' object has no attribute CV\_FOURCC. Code: ``` # Creates a video file from webcam stream import cv2 Create test window cv2.namedWindow("cam_out", cv2.CV_WINDOW_AUTOSIZE) # Create vid cap object vid = cv2.VideoCapture(1) # Create video writ...
Kind of late to the party, but if anyone needs it for newer versions of opencv2, then the command is: ``` cv2.VideoWriter_fourcc(c1, c2, c3, c4) ```
wordnet lemmatization and pos tagging in python
15,586,721
20
2013-03-23T12:23:54Z
15,590,384
34
2013-03-23T18:15:42Z
[ "python", "nltk", "wordnet", "lemmatization" ]
I wanted to use wordnet lemmatizer in python and I have learnt that the default pos tag is NOUN and that it does not output the correct lemma for a verb, unless the pos tag is explicitly specified as VERB. My question is what is the best shot inorder to perform the above lemmatization accurately? I did the pos taggin...
First of all, you can use `nltk.pos_tag()` directly without training it. The function will load a pretrained tagger from a file. You can see the file name with `nltk.tag._POS_TAGGER`: ``` nltk.tag._POS_TAGGER >>> 'taggers/maxent_treebank_pos_tagger/english.pickle' ``` As it was trained with the Treebank corpus, it al...
sheets of Excel Workbook from a URL into a `pandas.DataFrame`
15,588,713
9
2013-03-23T15:46:29Z
15,588,865
20
2013-03-23T16:00:15Z
[ "python", "url", "pandas", "xlrd" ]
After looking at different ways to read an url link, pointing to a .xls file, I decided to go with using xlrd. I am having a difficult time converting a 'xlrd.book.Book' type to a 'pandas.DataFrame' I have the following: ``` import pandas import xlrd import urllib2 link ='http://www.econ.yale.edu/~shiller/data/cha...
You can pass your `socket` to `ExcelFile`: ``` >>> import pandas as pd >>> import urllib2 >>> link = 'http://www.econ.yale.edu/~shiller/data/chapt26.xls' >>> socket = urllib2.urlopen(link) >>> xd = pd.ExcelFile(socket) NOTE *** Ignoring non-worksheet data named u'PDVPlot' (type 0x02 = Chart) NOTE *** Ignoring non-work...
Frequency tables in pandas (like plyr in R)
15,589,354
11
2013-03-23T16:47:03Z
15,590,006
7
2013-03-23T17:41:51Z
[ "python", "group-by", "pandas" ]
My problem is how to calculate frequencies on multiple variables in pandas . I have from this dataframe : ``` d1 = pd.DataFrame( {'StudentID': ["x1", "x10", "x2","x3", "x4", "x5", "x6", "x7", "x8", "x9"], 'StudentGender' : ['F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'M'], ...
This: ``` d1.groupby('ExamenYear').agg({'Participated': len, 'Passed': lambda x: sum(x == 'yes')}) ``` doesn't look way more awkward than the R solution, IMHO.
Frequency tables in pandas (like plyr in R)
15,589,354
11
2013-03-23T16:47:03Z
15,611,666
11
2013-03-25T09:38:12Z
[ "python", "group-by", "pandas" ]
My problem is how to calculate frequencies on multiple variables in pandas . I have from this dataframe : ``` d1 = pd.DataFrame( {'StudentID': ["x1", "x10", "x2","x3", "x4", "x5", "x6", "x7", "x8", "x9"], 'StudentGender' : ['F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'M'], ...
I finally decided to use **apply**. I am posting what I came up with hoping that it can be useful for others. From what I understand from Wes' book "Python for Data analysis" * **apply** is more flexible than agg and transform because you can define your own function. * the only requirement is that the functions ret...
How to crop an image in OpenCV using Python
15,589,517
29
2013-03-23T17:00:43Z
15,589,825
83
2013-03-23T17:26:58Z
[ "python", "opencv" ]
How can I crop images, like I've done before in PIL, using OpenCV. Working example on PIL ``` im = Image.open('0.png').convert('L') im = im.crop((1, 1, 98, 33)) im.save('_0.png') ``` But how I can do it on OpenCV? This is what I tried: ``` im = cv.imread('0.png', cv.CV_LOAD_IMAGE_GRAYSCALE) (thresh, im_bw) = cv.th...
It's very simple. Use numpy slicing. ``` import cv2 img = cv2.imread("lenna.png") crop_img = img[200:400, 100:300] # Crop from x, y, w, h -> 100, 200, 300, 400 # NOTE: its img[y: y + h, x: x + w] and *not* img[x: x + w, y: y + h] cv2.imshow("cropped", crop_img) cv2.waitKey(0) ```
How to crop an image in OpenCV using Python
15,589,517
29
2013-03-23T17:00:43Z
16,823,104
28
2013-05-29T20:21:12Z
[ "python", "opencv" ]
How can I crop images, like I've done before in PIL, using OpenCV. Working example on PIL ``` im = Image.open('0.png').convert('L') im = im.crop((1, 1, 98, 33)) im.save('_0.png') ``` But how I can do it on OpenCV? This is what I tried: ``` im = cv.imread('0.png', cv.CV_LOAD_IMAGE_GRAYSCALE) (thresh, im_bw) = cv.th...
i had this question and found another answer here: [copy region of interest](http://stackoverflow.com/questions/9084609/how-to-copy-a-image-region-using-opencv-in-python) If we consider (0,0) as top left corner of image called `im` with left-to-right as x direction and top-to-bottom as y direction. and we have (x1,y1)...
Fill between x and baseline x position in Matplotlib
15,589,643
9
2013-03-23T17:10:11Z
15,589,909
15
2013-03-23T17:33:49Z
[ "python", "matplotlib", "plot", "fill" ]
I'm looking for a way to use fill\_between in matplotlib to shade between x1 and x2 as opposed to y1 and y2. I have a series of log plots, with depth on the Y axis, and the measured variable on the x axis and would like to shade to the left or right, as opposed to above or below, of the plotted line. I'm sure this sh...
you can use [`fill_betweenx`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.fill_betweenx) ``` ax2.fill_betweenx(y,x, x2=0.5, where=x>0.5,interpolate=True) ```
Networkx : Convert multigraph into simple graph with weighted edges
15,590,812
8
2013-03-23T18:58:21Z
15,598,279
10
2013-03-24T12:09:52Z
[ "python", "graph", "networkx" ]
I have a multigraph object and would like to convert it to a simple graph object with weighted edges. I have looked through the networkx documentation and can't seem to find a built in function to achieve this. I was just wondering if anyone knew of a built-in function in networkx that could achieve this goal. I looked...
Here is one way to create a weighted graph from a weighted multigraph by summing the weights: ``` import networkx as nx # weighted MultiGraph M = nx.MultiGraph() M.add_edge(1,2,weight=7) M.add_edge(1,2,weight=19) M.add_edge(2,3,weight=42) # create weighted graph from M G = nx.Graph() for u,v,data in M.edges_iter(data...
Returning JSON array from a Django view to a template
15,592,811
14
2013-03-23T22:26:32Z
15,592,905
21
2013-03-23T22:36:34Z
[ "javascript", "python", "django", "json" ]
I'm using Django to create a web-based app for a project, and I'm running into issues returning an array from a Django view to a template. The array will be used by a JavaScript (JQuery) script for drawing boxes on an image shown in the page. Therefore, this array will have, among other things, coordinates for the box...
JSON *is* Javascript source code. I.e. the JSON representation of an array is the Javascript source code you need to define the array. So after: ``` var tagbs = {{ tags|safe }}; ``` `tagbs` is a JavaScript array containing the data you want. There's no need to call JSON.parse(), because the web browser already parse...
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module:
15,593,087
4
2013-03-23T22:59:28Z
18,814,501
18
2013-09-15T16:09:22Z
[ "python", "django", "mysql-python" ]
I am following the django tutorial, Many have asked the question but I think my situation is bit unique because after installing python-mysql I still get this error when I try to do python manage.py syncdb, I am in a virtualenv since I use macports to manage my python installation I created my virtualenv ``` virtuale...
My libmysqlclient.18.dylib was located in /usr/local/mysql/lib/ but my system was looking for it in /usr/lib/. I ended up creating a symbolic link of libmysqlclient.18.dylib in /usr/lib which fixed the problem. ### 1.) Make sure that libmysqlclient.18.dylib exists in /usr/local/mysql/lib/. Open your shell. ``` sudo ...
Function to calculate the difference between sum of squares and square of sums
15,593,428
4
2013-03-23T23:50:12Z
15,593,495
8
2013-03-23T23:59:10Z
[ "python", "sum" ]
I am trying to Write a function called `sum_square_difference` which takes a number n and returns the difference between the sum of the squares of the first n natural numbers and the square of their sum. I think i know how to write a function that defines the sum of squares ``` def sum_of_squares(numbers): total...
The function can be written with pure math like this: ![The formula](http://i.stack.imgur.com/pGuwq.gif) Translated into Python: ``` def square_sum_difference(n): return int((3*n**2 + 2*n) * (1 - n**2) / 12) ``` --- The formula is a simplification of two other formulas: ``` def square_sum_difference(n): r...
Downloading a image using Python Mechanize
15,593,925
4
2013-03-24T00:54:55Z
15,594,661
8
2013-03-24T02:54:39Z
[ "python", "mechanize" ]
I'm trying to write a Python script to download a image and set it as my wallpaper. Unfortunately, the Mechanize documentation is quite poor. My script is following the link correctly, but I'm having a hard time to actually save the image on my computer. From what I researched, the .retrieve() method should do the work...
``` import mechanize, os from BeautifulSoup import BeautifulSoup browser = mechanize.Browser() html = browser.open(url) soup = BeautifulSoup(html) image_tags = soup.findAll('img') for image in image_tags: filename = image['src'].lstrip('http://') filename = os.path.join(dir, filename.replace('/', '_')) dat...
Problems with hooks using Requests Python package
15,594,015
4
2013-03-24T01:07:28Z
15,594,097
16
2013-03-24T01:18:45Z
[ "python", "python-2.7", "python-3.x", "request", "typeerror" ]
I'm using the module `requests` and I recieved this message when I started using hooks. ``` File "/Library/Python/2.7/site-packages/requests-1.1.0-py2.7.egg/requests/sessions.py", line 321, in request resp = self.send(prep, **send_kwargs) File "/Library/Python/2.7/site-packages/requests-1.1.0-py2.7.egg/requests/sessi...
According to [the requests documentation](http://docs.python-requests.org/en/latest/), your hook function doesnt need to take any keyword arguments, but according [to the source code on github](https://github.com/kennethreitz/requests/blob/master/requests/hooks.py), the event dispatcher may pass on kwargs to your hook ...
Python - read in a previously 'list' variable from file
15,595,620
5
2013-03-24T05:49:10Z
15,595,639
13
2013-03-24T05:52:31Z
[ "python", "string", "file", "list" ]
I previously created a `list` and saved it to a file 'mylist.txt'. However, when I read it in it's a string, meaning I can't access each element as I like. I have been trying and searching for ways to fix this, but to no avail. In the text document, the list is one line and looks something like: ``` [(['000', '001', ...
Pass the string to [`ast.literal_eval`](http://docs.python.org/3.3/library/ast.html#ast.literal_eval). It will safely parse the string into the appropriate structures: ``` >>> import ast >>> with open("file.txt", 'r') as f: data = ast.literal_eval(f.read()) >>> # You're done! ```
Converting a String into Dictionary python
15,596,121
5
2013-03-24T07:23:36Z
15,596,129
7
2013-03-24T07:25:28Z
[ "python", "string", "dictionary", "python-2.7" ]
I want to have a dictionary from ``` >>> page_detail_string = urllib2.urlopen("http://graph.facebook.com/Ideas4India").read() ``` It returns a string like ``` >>> page_detail_string '{"about":"Ideas for development of India","category":"Community","description":"Platform where you can discuss and share your ideas w...
Use the `json` module ``` import json json.loads(page_detail_string) ``` To read more about the `json` module, check out <http://docs.python.org/2/library/json.html>
Converting a String into Dictionary python
15,596,121
5
2013-03-24T07:23:36Z
15,596,150
16
2013-03-24T07:28:39Z
[ "python", "string", "dictionary", "python-2.7" ]
I want to have a dictionary from ``` >>> page_detail_string = urllib2.urlopen("http://graph.facebook.com/Ideas4India").read() ``` It returns a string like ``` >>> page_detail_string '{"about":"Ideas for development of India","category":"Community","description":"Platform where you can discuss and share your ideas w...
What you get is a json string, you shoule use json.loads to convert to dict ``` import json json.loads(page_detail_string) ```
Prettify JSON from curl in OSX
15,597,785
4
2013-03-24T11:19:45Z
15,597,965
10
2013-03-24T11:39:02Z
[ "python", "json", "osx", "curl", "terminal" ]
I'm trying to prettify JSON response from curl, but it doesn't work. ``` Narnia:~ vitaly$ curl -s https://api.vk.com/method/photos.getAlbums?uid=6015870&access_token=0275127e915981fe795840165e532169482cbdfc4ca1dbd48619a687a65fead88c468cdafe9743e231c37 | python -m json.tool [4] 8822 No JSON object could be decoded Narn...
You need to put quotes around your URL: ``` curl -s "https://api.vk.com/method/photos.getAlbums?uid=6015870&access_token=0275127e915981fe795840165e532169482cbdfc4ca1dbd48619a687a65fead88c468cdafe9743e231c37" | python -m json.tool ``` The `&` character is a shell meta character, it puts the command in the background. ...