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 |
|---|---|---|---|---|---|---|---|---|---|
syslog.syslog vs SysLogHandler | 14,050,081 | 19 | 2012-12-27T05:59:17Z | 14,050,279 | 9 | 2012-12-27T06:17:10Z | [
"python",
"logging",
"syslog"
] | I'm looking at how to log to syslog from within my Python app, and I found there are two ways of doing it:
1. Using [syslog.syslog()](http://docs.python.org/2/library/syslog.html) routines
2. Using the logger module [SysLogHandler](http://docs.python.org/2/library/logging.handlers.html#logging.handlers.SysLogHandler)
... | `syslog.syslog()` can only be used to send messages to the local syslogd. `SysLogHandler` can be used as part of a comprehensive, configurable logging subsystem, and can log to remote machines. |
How to check if a python module exists without importing it | 14,050,281 | 63 | 2012-12-27T06:17:22Z | 14,050,282 | 85 | 2012-12-27T06:17:22Z | [
"python",
"python-import"
] | I need to know if a python module exists, without importing it.
Importing something that might not exist (not what I want):
```
try:
import eggs
except ImportError:
pass
``` | ## Python2
To check if import can find something in python2, using `imp`
```
import imp
try:
imp.find_module('eggs')
found = True
except ImportError:
found = False
```
To find dotted imports, you need to do more:
```
import imp
try:
spam_info = imp.find_module('spam')
spam = imp.load_module('spa... |
How to check if a python module exists without importing it | 14,050,281 | 63 | 2012-12-27T06:17:22Z | 25,045,228 | 9 | 2014-07-30T19:23:36Z | [
"python",
"python-import"
] | I need to know if a python module exists, without importing it.
Importing something that might not exist (not what I want):
```
try:
import eggs
except ImportError:
pass
``` | After use yarbelk's response, I've made this for don't have to import `ìmp`.
```
try:
__import__('imp').find_module('eggs')
# Make things with supposed existing module
except ImportError:
pass
```
Useful in Django's `settings.py`for example. |
Add SUM of values of two LISTS into new LIST | 14,050,824 | 39 | 2012-12-27T07:09:52Z | 14,050,853 | 58 | 2012-12-27T07:12:34Z | [
"python",
"list",
"sum"
] | I have the following two lists:
```
first = [1,2,3,4,5]
second = [6,7,8,9,10]
```
Now I want to add items of both lists into a new list.
output should be
```
three = [7,9,11,13,15]
``` | The `zip` function is useful here, used with a list comprehension.
```
[x + y for x, y in zip(first, second)]
```
If you have a list of lists (instead of just two lists):
```
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]
``` |
Add SUM of values of two LISTS into new LIST | 14,050,824 | 39 | 2012-12-27T07:09:52Z | 14,050,959 | 8 | 2012-12-27T07:20:49Z | [
"python",
"list",
"sum"
] | I have the following two lists:
```
first = [1,2,3,4,5]
second = [6,7,8,9,10]
```
Now I want to add items of both lists into a new list.
output should be
```
three = [7,9,11,13,15]
``` | This extends itself to any number of lists:
```
[sum(sublist) for sublist in itertools.izip(*myListOfLists)]
```
In your case, `myListOfLists` would be `[first, second]` |
Add SUM of values of two LISTS into new LIST | 14,050,824 | 39 | 2012-12-27T07:09:52Z | 14,051,047 | 25 | 2012-12-27T07:29:34Z | [
"python",
"list",
"sum"
] | I have the following two lists:
```
first = [1,2,3,4,5]
second = [6,7,8,9,10]
```
Now I want to add items of both lists into a new list.
output should be
```
three = [7,9,11,13,15]
``` | From [docs](http://docs.python.org/2/library/operator.html)
```
import operator
map(operator.add, first,second)
``` |
How to sort tire sizes in python | 14,050,840 | 4 | 2012-12-27T07:11:17Z | 14,050,941 | 11 | 2012-12-27T07:19:18Z | [
"python",
"list",
"sorting"
] | I'm trying to sort list of (strings) tire sizes from smallest to biggest.
```
['285/30/18',
'285/30/19',
'235/40/17',
'315/25/19',
'275/30/19']
```
should be sort as:
```
['235/40/17',
'285/30/18',
'315/25/19'
'275/30/19',
'285/30/19']
```
I basically have to sort the strings starting from the right, middle... | Python has several features that makes this easy to do. In fact, you can do it all in one statement:
```
sorted(nums, key=lambda x: tuple(reversed(list(map(int, x.split("/"))))))
```
The `x.split("/")` takes each value and makes a list of strings:
```
["235", "40", "17"]
```
Using `map(int, ...)` gives a list of in... |
Is python Queue.queue get and put thread safe? | 14,053,102 | 8 | 2012-12-27T10:25:59Z | 14,053,137 | 15 | 2012-12-27T10:28:30Z | [
"python"
] | <http://docs.python.org/2/library/queue.html#Queue.Queue.put>
It seems a naive question, but I didn't find the answer on the docs nor with Googling, so are these methods thread safe ? I assume so otherwise there is no point in this queue.
Thanks. | See [8.10 Queue â A *synchronized* queue class](http://docs.python.org/2/library/queue.html#module-Queue) (at the top)
> The Queue module implements multi-producer, multi-consumer queues. *It is especially useful in threaded programming when information must be exchanged safely between multiple threads.* |
No response with POST request and Content-Type "application/json" in flask | 14,053,670 | 3 | 2012-12-27T11:08:07Z | 14,061,355 | 9 | 2012-12-27T21:11:23Z | [
"python",
"json",
"post",
"http-headers",
"flask"
] | I'm having problems with a Flask view that should return a response with content-type "application/json" in response to a POST request.
Specifically, if I do:
```
curl -v -d 'foo=bar' http://example.org/jsonpost
```
to this view:
```
@app.route('/jsonpost', methods=['GET', 'POST'])
def json_post():
resp = make_r... | Thanks to Audrius's comments I tracked a possible source of the problem to the interaction between uWSGI and nginx: apparently, if you receive POST data in a request you *must* read it before returning a response.
This, for example, fixes my issue.
```
@app.route('/jsonpost', methods=['GET', 'POST'])
def json_post():... |
PyDev for Eclipse - Resolve Python dependencies (unresolved imports) | 14,054,111 | 11 | 2012-12-27T11:42:40Z | 14,102,275 | 11 | 2012-12-31T13:37:55Z | [
"java",
"python",
"eclipse-plugin",
"pydev",
"m2eclipse"
] | I am using PyDev for Eclipse as my IDE and pip as my package management tool, running virtualenv.
Every time I want to use/include some new libraries or new dependencies in my project, I add them into the **pip-requires** file. The dependencies are installed in my virtual environment with no problem after running `pip... | From your questions I understood that you're manually adding the Python Egg packages to the path. Instead of doing this, you can just go to the Project Settings window, then open "PyDev - PYTHONPATH", navigate to the panel called "External Libraries" and add the *whole* `site-packages` folder of your virtual environmen... |
PyDev for Eclipse - Resolve Python dependencies (unresolved imports) | 14,054,111 | 11 | 2012-12-27T11:42:40Z | 14,142,652 | 11 | 2013-01-03T16:10:04Z | [
"java",
"python",
"eclipse-plugin",
"pydev",
"m2eclipse"
] | I am using PyDev for Eclipse as my IDE and pip as my package management tool, running virtualenv.
Every time I want to use/include some new libraries or new dependencies in my project, I add them into the **pip-requires** file. The dependencies are installed in my virtual environment with no problem after running `pip... | Make sure your system PYTHONPATH include the site-packages folder when you choose python interpreter from your virtualenv. Just like the snapshot.

Then you don't need to add them one by one into PYTHONPATH. You will need to restart eclipse (Refresh do... |
converting string to int python | 14,056,524 | 2 | 2012-12-27T14:48:23Z | 14,056,551 | 8 | 2012-12-27T14:50:05Z | [
"python"
] | how can I convert a string to an int in python
say I have this array
```
['(111,11,12)','(12,34,56)'] to [(111,11,12),(12,34,56)]
```
Any help will be appreciated thanks | ```
import ast
a = "['(111,11,12)','(12,34,56)']"
[ast.literal_eval(b) for b in ast.literal_eval(a)]
# [(111, 11, 12), (12, 34, 56)]
```
**EDIT**: if you have a list of strings (and not a string), just like @DSM suggests, then you have to modify it:
```
a = ['(111,11,12)','(12,34,56)']
[ast.literal_eval(b) for b in a... |
Remove rows not .isin('X') | 14,057,007 | 14 | 2012-12-27T15:24:13Z | 14,058,892 | 27 | 2012-12-27T17:46:47Z | [
"python",
"filtering",
"pandas"
] | Sorry just getting into Pandas, this seems like it should be a very straight forward question. How can I use the `isin('X')` to remove rows that **are in** the list `X`? In R I would write `!which(a %in% b)`. | You can use [`numpy.logical_not`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_not.html#numpy.logical_not) to invert the boolean array returned by `isin`:
```
In [63]: s = pd.Series(np.arange(10.0))
In [64]: x = range(4, 8)
In [65]: mask = np.logical_not(s.isin(x))
In [66]: s[mask]
Out[66]:
0 ... |
Relative importing modules from parent folder subfolder | 14,057,464 | 6 | 2012-12-27T15:58:32Z | 14,057,574 | 9 | 2012-12-27T16:06:31Z | [
"python",
"import",
"module",
"python-2.7"
] | Given a directory structure like this
```
/main/
/main/common/foo.py
/main/A/
/main/A/src/
/main/A/src/bar.py
```
How can I use Python's *relative imports* to import `foo` from `bar`? I've got a working solution by adding it to the path, but this is ugly. Is there a way to simply do with a single `import` in Python 2... | The correct relative import would be this:
```
from ...common import foo
```
However, relative imports are only meant to work within one package. If `main` is a package, then you can use relative imports here. If `main` is not a package, you cannot.
Thus, if you're running a script in `/main/` and doing something li... |
adding noise to a signal in python | 14,058,340 | 19 | 2012-12-27T17:03:19Z | 14,058,425 | 23 | 2012-12-27T17:09:36Z | [
"python"
] | I want to add some random noise to some 100 bin signal that I am simulating in Python - to make it more realistic.
On a basic level, my first thought was to go bin by bin and just generate a random number between a certain range and add or subtract this from the signal.
I was hoping (as this is python) that there mig... | You can generate a noise array, and add it to your signal
```
import numpy as np
noise = np.random.normal(0,1,100)
# 0 is the mean of the normal distribution you are choosing from
# 1 is the standard deviation of the normal distribution
# 100 is the number of elements you get in array noise
``` |
adding noise to a signal in python | 14,058,340 | 19 | 2012-12-27T17:03:19Z | 26,181,710 | 11 | 2014-10-03T15:11:58Z | [
"python"
] | I want to add some random noise to some 100 bin signal that I am simulating in Python - to make it more realistic.
On a basic level, my first thought was to go bin by bin and just generate a random number between a certain range and add or subtract this from the signal.
I was hoping (as this is python) that there mig... | ... And for those who - like me - are very early in their numpy learning curve,
```
import numpy as np
pure = np.linspace(-1, 1, 100)
noise = np.random.normal(0, 1, 100)
signal = pure + noise
``` |
Making Python loggers output all messages to stdout in addition to log | 14,058,453 | 142 | 2012-12-27T17:11:21Z | 14,058,475 | 212 | 2012-12-27T17:12:56Z | [
"python",
"logging",
"error-logging"
] | Is there a way to make Python logging using the `logging` module automatically output things to stdout *in addition* to the log file where they are supposed to go? For example, I'd like all calls to `logger.warning`, `logger.critical`, `logger.error` to go to their intended places but in addition always be copied to `s... | All logging output is handled by the handlers; just add a [`logging.StreamHandler()`](http://docs.python.org/2/library/logging.handlers.html#streamhandler) to the root logger.
Here's an example configuring a stream handler (using `stdout` instead of the default `stderr`) and adding it to the root logger:
```
import l... |
Making Python loggers output all messages to stdout in addition to log | 14,058,453 | 142 | 2012-12-27T17:11:21Z | 24,978,464 | 27 | 2014-07-27T06:24:08Z | [
"python",
"logging",
"error-logging"
] | Is there a way to make Python logging using the `logging` module automatically output things to stdout *in addition* to the log file where they are supposed to go? For example, I'd like all calls to `logger.warning`, `logger.critical`, `logger.error` to go to their intended places but in addition always be copied to `s... | its possible using multiple handlers.
```
import logging
import auxiliary_module
# create logger with 'spam_application'
logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# ... |
Making Python loggers output all messages to stdout in addition to log | 14,058,453 | 142 | 2012-12-27T17:11:21Z | 28,194,953 | 107 | 2015-01-28T14:39:03Z | [
"python",
"logging",
"error-logging"
] | Is there a way to make Python logging using the `logging` module automatically output things to stdout *in addition* to the log file where they are supposed to go? For example, I'd like all calls to `logger.warning`, `logger.critical`, `logger.error` to go to their intended places but in addition always be copied to `s... | the simplest way:
```
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
``` |
Making Python loggers output all messages to stdout in addition to log | 14,058,453 | 142 | 2012-12-27T17:11:21Z | 30,096,875 | 13 | 2015-05-07T09:22:21Z | [
"python",
"logging",
"error-logging"
] | Is there a way to make Python logging using the `logging` module automatically output things to stdout *in addition* to the log file where they are supposed to go? For example, I'd like all calls to `logger.warning`, `logger.critical`, `logger.error` to go to their intended places but in addition always be copied to `s... | The simplest way to log to file and to stderr:
```
import logging
logging.basicConfig(filename="logfile.txt")
stderrLogger=logging.StreamHandler()
stderrLogger.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
logging.getLogger().addHandler(stderrLogger)
``` |
Opinions about Enthought Traits/TraitsUI for Python desktop development | 14,058,555 | 8 | 2012-12-27T17:19:25Z | 14,070,671 | 15 | 2012-12-28T14:03:07Z | [
"python",
"user-interface",
"traits",
"enthought"
] | I'm looking for opinions and experiences about using [Traits](http://code.enthought.com/projects/traits/) / [TraitsUI](http://code.enthought.com/projects/traits_ui/) / [enaml](http://docs.enthought.com/enaml/) for Python desktop development.
The documentation and the Enthought support looks promising, so I wanted to k... | I first started using Traits and TraitsUI to build GUI's as a postdoc researcher in Mechanical Engineering. My previous experience with building GUI's was with MATLAB's GUIDE, and I found TraitsUI to be very straightforward and easy to get started with by comparison. TraitsUI has a very linear progression of progress v... |
Fix native Cygwin Vim Python support | 14,058,943 | 4 | 2012-12-27T17:50:52Z | 14,059,666 | 14 | 2012-12-27T18:48:49Z | [
"python",
"vim",
"plugins",
"cygwin"
] | After installing the python-mode plugin for Vim on my Linux machine, I am getting the following error message on my Windows machine with Cygwin using the same .vim folder:
```
pymode.vim required vim compiled with +python.
```
So basically I need to compile Vim by my own with Python support, like explained in the que... | I am afraid, that is the only way to fix it. Unpleasant, but at least doable with only a few lines:
```
$ hg clone https://vim.googlecode.com/hg/ vim
$ cd vim/src
$ ./configure \
--enable-multibyte \
--without-x \
--enable-gui=no \
--enable-pythoninterp
$ make
$ make install
$ ln -sf /usr/local/bin/vim.exe /usr/bin/v... |
Using Google Calendar API v 3 with Python | 14,058,964 | 11 | 2012-12-27T17:52:54Z | 14,065,505 | 13 | 2012-12-28T06:23:32Z | [
"python",
"google-api",
"google-calendar"
] | Can someone please give me a clear explanation of how to get the Google Calendar API v3 working with the Python Client? Specifically, the initial OAuth stage is greatly confusing me. All I need to do is access my own calendar, read it, and make changes to it. Google provides this code for configuring my app:
```
impor... | A simple (read: way I've done it) way to do this is to create a web application instead of a service account. This may sound weird since you don't need any sort of web application, but I use this in the same way you do - make some queries to my own calendar/add events/etc. - all from the command line and without any so... |
Parsing a lisp file with Python | 14,058,985 | 5 | 2012-12-27T17:54:38Z | 14,059,322 | 17 | 2012-12-27T18:21:08Z | [
"python",
"parsing"
] | I have the following lisp file, which is from the [UCI machine learning database](http://archive.ics.uci.edu/ml/datasets/Bach+Chorales). I would like to convert it into a flat text file using python. A typical line looks like this:
```
(1 ((st 8) (pitch 67) (dur 4) (keysig 1) (timesig 12) (fermata 0))((st 12) (pitch 6... | As shown in [this answer](http://stackoverflow.com/a/14040960/989121), [pyparsing](http://pyparsing.wikispaces.com/) appears to be the right tool for that:
```
inputdata = '(1 ((st 8) (pitch 67) (dur 4) (keysig 1) (timesig 12) (fermata 0))((st 12) (pitch 67) (dur 8) (keysig 1) (timesig 12) (fermata 0)))'
from pyparsi... |
I want to multiply two columns in a pandas DataFrame and add the result into a new column | 14,059,094 | 20 | 2012-12-27T18:02:41Z | 14,059,783 | 14 | 2012-12-27T18:59:12Z | [
"python",
"python-2.7",
"pandas"
] | I'm trying to multiply two existing columns in a pandas Dataframe (orders\_df) - Prices (stock close price) and Amount (stock quantities) and add the calculation to a new column called 'Value'. For some reason when I run this code, all the rows under the 'Value' column are positive numbers, while some of the rows shoul... | You can use the DataFrame [`apply`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html#pandas.DataFrame.apply) method:
```
order_df['Value'] = order_df.apply(lambda row: (row['Prices']*row['Amount']
if row['Action']=='Sell'
... |
I want to multiply two columns in a pandas DataFrame and add the result into a new column | 14,059,094 | 20 | 2012-12-27T18:02:41Z | 14,071,265 | 44 | 2012-12-28T14:47:45Z | [
"python",
"python-2.7",
"pandas"
] | I'm trying to multiply two existing columns in a pandas Dataframe (orders\_df) - Prices (stock close price) and Amount (stock quantities) and add the calculation to a new column called 'Value'. For some reason when I run this code, all the rows under the 'Value' column are positive numbers, while some of the rows shoul... | I think an elegant solution is to use the [`where`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-where-method-and-masking) method (also see the [`API docs`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html)):
```
In [37]: values = df.Prices * df.Amount
In [38]: df['Va... |
Create python soap server based on wsdl | 14,059,142 | 16 | 2012-12-27T18:07:33Z | 14,081,698 | 8 | 2012-12-29T12:31:05Z | [
"python",
"soap",
"wsdl"
] | I have an wsdl file describing the communication server-client on a Java product.
I'm implementing a new server based on Python that will implement the same services.
Do you know of any method to create the Python server code based on the wsdl, that does not requires me to write all of the complextypes involved?
Also... | When it comes to SOAP support, Python unfortunately no longer is with "batteries included". The support on client side is acceptable but on server side you are basically on your own.
You might want to look at the following for starters:
<http://wiki.python.org/moin/WebServices>
<http://pywebsvcs.sourceforge.net/>
<... |
Create python soap server based on wsdl | 14,059,142 | 16 | 2012-12-27T18:07:33Z | 15,955,757 | 9 | 2013-04-11T18:04:54Z | [
"python",
"soap",
"wsdl"
] | I have an wsdl file describing the communication server-client on a Java product.
I'm implementing a new server based on Python that will implement the same services.
Do you know of any method to create the Python server code based on the wsdl, that does not requires me to write all of the complextypes involved?
Also... | > This question has not received enough attention.
>
> The currently accepted answer is good, but its answer is 'no'. Is there really no reasonably maintained and general solution?
Unfortunately, I don't think the negative answer is due to lack of attention to the question. There really is no support for WSDL in pytho... |
Why don't 'pip show' or 'pip list' work for me? | 14,060,043 | 5 | 2012-12-27T19:20:04Z | 14,060,138 | 14 | 2012-12-27T19:26:38Z | [
"python",
"osx",
"pip"
] | Python's `pip` is working for me to install and update packages, but some of the documented commands seem not to be supported (at least with 1.2.1 running on OS 10.8.2 and Python 2.7.2). When I try
```
pip list
```
or
```
pip show <pkgname>
```
I get
```
Usage: pip COMMAND [OPTIONS]
No command by the name pip <cmd... | The new functions you're looking for are very recent -- they're in 1.2.1.post1, but not in 1.2.1, and the docs you're probably looking at (http://www.pip-installer.org/en/latest/) are currently for 1.2.1.post1.
```
localhost-2:~ $ pip --version
pip 1.2.1.post1 from /Library/Frameworks/Python.framework/Versions/2.7/lib... |
How can I render 3D histograms in python? | 14,061,061 | 8 | 2012-12-27T20:43:32Z | 15,035,592 | 11 | 2013-02-23T00:39:17Z | [
"python",
"matplotlib",
"plot",
"data-visualization",
"mayavi"
] | I want to make plots like these from [Hacker's Delight](http://rads.stackoverflow.com/amzn/click/0321842685):

What ways are there to accomplish this in Python? A solution that makes it easy to interactively adjust the graph (changing the slice of X/Y... | Since the example pointed out by TJD seemed "impenetrable" here is a modified version with a few comments that might help clarify things:
```
#! /usr/bin/env python
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
#
# Assuming you have "2D" dataset like the following that you ... |
Python Joining two dictionnary with similar content | 14,061,249 | 3 | 2012-12-27T21:00:08Z | 14,061,288 | 10 | 2012-12-27T21:04:02Z | [
"python",
"dictionary",
"set"
] | I am looking for a Pythonic way (the less code possible) to unite the content of two dictionnaries :
```
basket1 = {"ham":2,"eggs":3}
basket2 = {"eggs":4,"spam":1}
```
I want to get a third basket that is going to be the "sum" of the two other, basket 3 should be:
```
basket3 --> {"ham":2,"eggs":7,"spam":1}
```
If ... | I'd use a `Counter`, which is a kind of `defaultdict` with some nice properties:
```
>>> from collections import Counter
>>> basket1 = {"ham":2,"eggs":3}
>>> basket2 = {"eggs":4,"spam":1}
>>> basket_sum = Counter(basket1) + Counter(basket2)
>>> basket_sum
Counter({'eggs': 7, 'ham': 2, 'spam': 1})
```
which you could ... |
How can I find all placeholders for str.format in a python string using a regex? | 14,061,724 | 3 | 2012-12-27T21:45:52Z | 14,061,832 | 21 | 2012-12-27T21:58:30Z | [
"python",
"regex"
] | I'm creating a class that renames a file using a user-specified format. This format will be a simple string whose `str.format` method will be called to fill in the blanks.
It turns out that my procedure will require extracting variable names contained in braces. For example, a string may contain `{user}`, which should... | Another possibility is to use Python's actual [Formatter](http://docs.python.org/2/library/string.html#string.Formatter.parse) itself to extract the field names for you:
```
>>> import string
>>> s = "{foo} spam eggs {bar}"
>>> string.Formatter().parse(s)
<formatteriterator object at 0x101d17b98>
>>> list(string.Forma... |
Python while loops | 14,062,266 | 5 | 2012-12-27T22:45:59Z | 14,062,319 | 8 | 2012-12-27T22:51:25Z | [
"python"
] | I have this code in python 3,to check for errors on input but i need to determine that the input is an integer and if not to print the error message.
can anyone help me to figure out the code in my while loop.
Thanks
```
price = 110;
ttt = 1;
while price < 0 or price > 100:
price = input('Please enter your mar... | Use the `int()` function to convert to an integer. This will raise a ValueError when it cannot do the conversion:
```
try:
price = int(price)
except ValueError as e:
print 'invalid entry:', e
``` |
How to reference signals outside of models.py | 14,062,951 | 5 | 2012-12-28T00:06:19Z | 14,095,311 | 7 | 2012-12-30T22:27:14Z | [
"python",
"django"
] | In the documentation for `Django`, it specifies that `models.py` is a good place to locate callback functions for signals (`post_save`, `pre_save`, etc).
> Where should this code live?
>
> You can put signal handling and registration code anywhere you like.
> However, you'll need to make sure that the module it's in g... | How about "connecting" signals in models.py while keeping the functions in signals.py?
---
an example:
```
# models
from myapp import signals
class MyModel(models.Model)
pass
post_save.connect(signals.do_some_stuff_with_mymodel, sender = MyModel)
# signals
def do_some_stuff_with_mymodel(**kwargs):
pass
```
... |
subprocess checkoutput error | 14,063,027 | 4 | 2012-12-28T00:17:37Z | 14,063,040 | 8 | 2012-12-28T00:19:55Z | [
"python",
"subprocess"
] | I am trying to check the usage of check\_output using he below script and running into compilation error,where am I going wrong?
```
import os
import subprocess
from subprocess import check_output
#result = subprocess.check_output(['your_program.exe', 'arg1', 'arg2'])
SCRIPT_ROOT=subprocess.check_output(["pwd","shell... | `check_output` has been introduced in Python 2.7. If you're using an earlier version of python, it's just not there.
Alternative is to use `Popen`.
```
output = subprocess.Popen(['pwd'], stdout=subprocess.PIPE).communicate()[0]
```
Proof of this can be found [here](http://docs.python.org/2.7/whatsnew/2.7.html).
> N... |
overlay a smaller image on a larger image python OpenCv | 14,063,070 | 16 | 2012-12-28T00:26:20Z | 14,102,014 | 26 | 2012-12-31T13:07:58Z | [
"python",
"opencv",
"object-detection"
] | Hi I am creating a program that replaces a face in a image with someone else's face. However, I am stuck on trying to insert the new face into the original, larger image. I have researched ROI and addWeight(needs the images to be the same size) but I haven't found a way to do this in python. Any advise is great. I am n... | A simple way to achieve what you want:
```
import cv2
s_img = cv2.imread("smaller_image.png")
l_img = cv2.imread("larger_image.jpg")
x_offset=y_offset=50
l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img
```

## Update
I suppose ... |
ImportError: cannot import name SignedJwtAssertionCredentials | 14,063,124 | 19 | 2012-12-28T00:33:57Z | 14,159,564 | 20 | 2013-01-04T15:01:15Z | [
"python",
"google-api",
"oauth-2.0"
] | I'm trying to access a google app through the Python Client using this code to gain authorization (private info obviously redacted):
```
import gflags
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import SignedJwtAssertionCredentials
from oauth2cl... | It seems like you havn't installed pyopenssl. Install via `easy_install pyopenssl`.
```
Libraries oauth2client.client
if HAS_OPENSSL:
# PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then
# don't create the SignedJwtAssertionCredentials or the verify_id_token()
# method.
class SignedJwt... |
ImportError: cannot import name SignedJwtAssertionCredentials | 14,063,124 | 19 | 2012-12-28T00:33:57Z | 35,447,759 | 50 | 2016-02-17T04:07:36Z | [
"python",
"google-api",
"oauth-2.0"
] | I'm trying to access a google app through the Python Client using this code to gain authorization (private info obviously redacted):
```
import gflags
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import SignedJwtAssertionCredentials
from oauth2cl... | I had this problem today and had to roll back from oauth2client version 2.0 to version 1.5.2 with:
```
pip install oauth2client==1.5.2
``` |
Python 3: get 2nd to last index of occurence in string | 14,063,195 | 6 | 2012-12-28T00:44:59Z | 14,063,214 | 7 | 2012-12-28T00:47:53Z | [
"python",
"python-3.x"
] | I have a string `abcdabababcebc` How do I get the index of the second-to-last occurrence of `b`? I searched and found rfind() but that doesn't work since it's the last index and not the second-to-last.
I am using Python 3. | ```
>>> s = "abcdabababcebc"
>>> s[:s.rfind("b")].rfind("b")
9
``` |
Python 3: get 2nd to last index of occurence in string | 14,063,195 | 6 | 2012-12-28T00:44:59Z | 14,063,233 | 9 | 2012-12-28T00:49:56Z | [
"python",
"python-3.x"
] | I have a string `abcdabababcebc` How do I get the index of the second-to-last occurrence of `b`? I searched and found rfind() but that doesn't work since it's the last index and not the second-to-last.
I am using Python 3. | Here's one way to do it:
```
>>> def find_second_last(text, pattern):
... return text.rfind(pattern, 0, text.rfind(pattern))
...
>>> find_second_last("abracadabra", "a")
7
```
This uses the optional start and end parameters to look for the second occurrence after the first occurrence has been found.
Note: This do... |
unexpected behaviour of `global` variables in Python | 14,063,877 | 2 | 2012-12-28T02:36:12Z | 14,063,958 | 7 | 2012-12-28T02:47:15Z | [
"python"
] | ```
prev, prev_re = '', (None) # these are globals
def find(h, p='', re=None):
print h, p, re
#global prev, prev_re
if p == '' and prev == h: return prev_re
prev, prev_re = h, re
return re
print find ("abc")
```
results in this error:
```
if p == '' and prev == h: return prev_re
UnboundLocalE... | ## Problem and solution
As MAK has mentioned, `prev` is treated as local because you assign value to it (after you check the value). The solution is to explicitly state these two variables as global:
```
prev, prev_re = '', (None) # these are globals
def find(h, p='', re=None):
global prev, prev_re
print h, ... |
Smart way to end a subroutine if file doesnt exist in cwd | 14,064,313 | 4 | 2012-12-28T03:45:49Z | 14,064,332 | 7 | 2012-12-28T03:48:36Z | [
"python"
] | I am trying to open file "data.txt" in the cwd and readthe lines,is there a oneliner(or close ) to exit the subroutine if the file doesnt exist..i know there are ways like using os.path.exists and try/except IO error but am interested in one-liner or the smartest way
```
def readfile ():
f = open('data.txt')
l... | you can use `with` open
```
with open('data.txt') as f:
lines = f.readlines()
```
The with statement will automatically close the file after the nested block of code. The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs bef... |
Python regular expression: how to excluding superstrings? | 14,064,465 | 7 | 2012-12-28T04:10:39Z | 14,064,490 | 8 | 2012-12-28T04:16:02Z | [
"python",
"regex"
] | I want to find all appearances of "not", but does not include the terms "not good" or "not bad".
For example, "not not good, not bad, not mine" will match the first and last "not".
How do I achieve that using the re package in python? | Use negative look-ahead assertion:
```
\bnot\b(?!\s+(?:good|bad))
```
This will match `not`, except the case where `good` and `bad` are right after `not` in the string. I have added word boundary `\b` to make sure we are matching the word `not`, rather than `not` in `nothing` or `knot`.
---
`\b` is word boundary. I... |
How to create filters for QTableView in PyQt | 14,068,823 | 3 | 2012-12-28T11:28:55Z | 14,075,797 | 11 | 2012-12-28T21:06:22Z | [
"python",
"qt",
"pyqt",
"pyqt4",
"qtableview"
] | I am using QTableView to display data retrieved from `QtSql.QSqlQuery`
I want to know how can i create filters for it like in excel.

In the above image i need to get the filters for All heders (Sh\_Code,SH\_Seq,Stage)
The filters will have unique va... | Here is an example of filtering in PyQt using `QSortFilterProxyModel`, `QStandardItemModel` and `QTableView`, it can be easily adapted to other views and models:
```
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtCore, QtGui
class myWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
... |
Getting attributes in PyQuery? | 14,070,197 | 12 | 2012-12-28T13:21:29Z | 14,070,317 | 17 | 2012-12-28T13:32:35Z | [
"python",
"screen-scraping",
"pyquery"
] | I'm using PyQuery and want to print a list of links, but can't figure out how to get the `href` attribute from each link in the PyQuery syntax.
This is my code:
```
e = pq(url=results_url)
links = e('li.moredetails a')
print len(links)
for link in links:
print link.attr('href')
```
This prints `10`, then... | PyQuery wraps [`lxml`](http://lxml.de/), so you use the [ElementTree API](http://docs.python.org/2/library/xml.etree.elementtree.html) to access attributes:
```
e = pq(url=results_url)
for link in e('li.moredetails a'):
print link.attrib['href']
```
Alternatively, to use the PyQuery API on any found element, wrap... |
Add an element in each dictionary of a list (list comprehension) | 14,071,038 | 6 | 2012-12-28T14:33:31Z | 14,071,119 | 7 | 2012-12-28T14:37:53Z | [
"python",
"python-3.x",
"list-comprehension"
] | I have a list of dictionaries, and want to add a key for each element of this list.
I tried:
```
result = [ item.update({"elem":"value"}) for item in mylist ]
```
but the update method returns None, so my result list is full of None.
```
result = [ item["elem"]="value" for item in mylist ]
```
returns a syntax erro... | You don't need to worry about constructing a new list of dictionaries, since the references to your updated dictionaries are the same as the references to your old dictionaries:
```
for item in mylist:
item.update( {"elem":"value"})
``` |
Collectstatic command is not available in Django 1.4 | 14,071,294 | 4 | 2012-12-28T14:50:40Z | 14,071,410 | 11 | 2012-12-28T14:59:08Z | [
"python",
"django",
"python-2.7"
] | So I'm trying to run collectstatic to push some files to AWS, but I keep getting a "unknown command" error. When running manage.py help I get a list of subcommands, and sure enough collectstatic is not there. I have looked also in the installed apps part of settings.py and the staticfiles app is installed. Python is ve... | Check settings.py for `django.contrib.staticfiles` in `INSTALLED_APPS` and `django.core.context_processors.static` in `TEMPLATE_CONTEXT_PROCESSORS` |
Integrating a multidimensional integral in scipy | 14,071,704 | 9 | 2012-12-28T15:21:28Z | 14,075,572 | 15 | 2012-12-28T20:46:07Z | [
"python",
"math",
"numpy",
"scipy",
"scientific-computing"
] | **Motivation:** I have a multidimensional integral, which for completeness I have reproduced below. It comes from the computation of the second virial coefficient when there is significant anisotropy:

Here W is a function of all the variables. It is ... | With a higher-dimensional integral like this, monte carlo methods are often a useful technique - they converge on the answer as the inverse square root of the number of function evaluations, which is better for higher dimension then you'll generally get out of even fairly sophisticated adaptive methods (unless you know... |
App Engine: Structured Property vs Reference Property for one-to-many relationship | 14,072,491 | 7 | 2012-12-28T16:22:20Z | 14,073,332 | 8 | 2012-12-28T17:29:58Z | [
"python",
"database",
"google-app-engine",
"database-design"
] | My background with designing data stores comes from Core Data on iOS, which supports properties having a one-to-many relationship with another entity.
I'm working on an App Engine project which currently has three entity types:
* `User`, which represents a person using the app.
* `Project`, which represents a project... | By reference property you probably mean Key Property. This is a reference to another datastore entity. It is present in both db and ndb APIs. Using these, you can model a many to one relationship by pointing many entities to the key of another entity.
Structured property is a completely different beast. It allows you ... |
Slicing strings in str.format | 14,072,810 | 8 | 2012-12-28T16:47:03Z | 14,072,884 | 7 | 2012-12-28T16:52:02Z | [
"python",
"string",
"format"
] | I want to achieve the following with `str.format`:
```
x,y = 1234,5678
print str(x)[2:] + str(y)[:2]
```
The only way I was able to do it was:
```
print '{0}{1}'.format(str(x)[2:],str(y)[:2])
```
Now, this an example and what I really have is a long and messy string, and so I want to put slicing inside the `{}`. I'... | No, you cannot apply slicing to strings inside a the replacement field.
You'll need to refer to the [Format Specification Mini-Language](http://docs.python.org/2/library/string.html#format-specification-mini-language); it defines what *is* possible. This mini language defines how you format the referenced value (the p... |
Scrapy : storing the data | 14,073,442 | 6 | 2012-12-28T17:38:19Z | 14,074,466 | 21 | 2012-12-28T19:08:32Z | [
"python",
"scrapy"
] | I'm new with python and scrapy. I'm tring to follow the Scrapy tutorial but I don't understand the logic of the [storage step](http://doc.scrapy.org/en/latest/topics/feed-exports.html#topics-feed-storage-backends).
```
scrapy crawl spidername -o items.json -t json
scrapy crawl spidername --set FEED_URI=output.csv --s... | You can view a list of available commands by typing `scrapy crawl -h` from within your project directory.
```
scrapy crawl spidername -o items.json -t json
```
* `-o` specifies the output filename for dumped items (items.json)
* `-t` specifies the format for dumping items (json)
`scrapy crawl spidername --set FEED_U... |
Tastypie with application/x-www-form-urlencoded | 14,074,149 | 6 | 2012-12-28T18:38:49Z | 14,075,440 | 14 | 2012-12-28T20:34:20Z | [
"python",
"django",
"tastypie"
] | I'm having a bit of difficulty figuring out what my next steps should be. I am using tastypie to create an API for my web application.
From another application, specifically ifbyphone.com, I am receiving a POST with no headers that looks something like this:
```
post data:http://myapp.com/api/
callerid=1&someid=2&num... | This worked as expected when I edited my resource model to actually use the serializer class I created. This was not clear in the documentation.
```
class urlencodeSerializer(Serializer):
formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'plist', 'urlencode']
content_types = {
'json': 'application/jso... |
Python yield with no argument in try block | 14,074,796 | 4 | 2012-12-28T19:39:27Z | 14,074,980 | 7 | 2012-12-28T19:54:06Z | [
"python"
] | I was reading [this](http://dietbuddha.blogspot.com/2012/12/52python-encapsulating-exceptions-with.html) article and it was showing this interesting bit of code:
```
class Car(object):
def _factory_error_handler(self):
try:
yield
except FactoryColorError, err:
stacktrace = sys.exc_info... | The code in the post appears to be wrong. It would make sense if the various error handlers were decorated with `contextmanager`. Note that, in the post, the code imports `contextmanager` but doesn't use it. This makes me think the person just made a mistake in creating the post and left `contextmanager` out of that ex... |
Copy a file with a too long path to another directory in Python | 14,075,465 | 6 | 2012-12-28T20:35:59Z | 14,076,169 | 10 | 2012-12-28T21:41:46Z | [
"python",
"copy"
] | I am trying to copy files on Windows with Python 2.7, but sometimes this fails.
```
shutil.copyfile(copy_file, dest_file)
```
I get the following IOError:
```
[Errno 2] No such file or directory
```
But the file does exist! The problem is that the path of the file is too long. (> 255 characters)
How do I copy thes... | I wasn't sure about the 255 char limit so I stumbled on [this post](http://stackoverflow.com/questions/1857335/is-there-any-length-limits-of-file-path-in-ntfs#1857477). There I found a working answer: adding \\?\ before the path.
```
shutil.copyfile("\\\\?\\" + copy_file, dest_file)
```
edit:
I've found that working ... |
Iterating through sites with Python Scrapy | 14,075,785 | 9 | 2012-12-28T21:05:22Z | 14,076,287 | 11 | 2012-12-28T21:53:04Z | [
"python",
"scrapy"
] | How do I iterate through sites with Scrapy? I'd like to extract the body of all sites that match `http://www.saylor.org/site/syllabus.php?cid=NUMBER`, where NUMBER is 1 through 400 or so.
I've written this spider:
```
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import ... | Try this:
```
from scrapy.spider import BaseSpider
from scrapy.http import Request
from syllabi.items import SyllabiItem
class SyllabiSpider(BaseSpider):
name = 'saylor'
allowed_domains = ['saylor.org']
max_cid = 400
def start_requests(self):
for i in range(self.max_cid):
yield Re... |
How to access scrapy settings from item Pipeline | 14,075,941 | 11 | 2012-12-28T21:19:39Z | 14,075,942 | 14 | 2012-12-28T21:19:39Z | [
"python",
"settings",
"processing",
"scrapy",
"pipeline"
] | How do I access the scrapy settings in settings.py from the item pipeline. The documentation mentions it can be accessed through the crawler in extensions, but I don't see how to access the crawler in the pipelines. | Ok, so the documentation at <http://doc.scrapy.org/en/latest/topics/extensions.html> says that
> The main entry point for a Scrapy extension (this also includes
> middlewares and pipelines) is the from\_crawler class method which
> receives a Crawler instance which is the main object controlling the
> Scrapy crawler. ... |
How to access scrapy settings from item Pipeline | 14,075,941 | 11 | 2012-12-28T21:19:39Z | 20,957,690 | 10 | 2014-01-06T19:28:21Z | [
"python",
"settings",
"processing",
"scrapy",
"pipeline"
] | How do I access the scrapy settings in settings.py from the item pipeline. The documentation mentions it can be accessed through the crawler in extensions, but I don't see how to access the crawler in the pipelines. | The way to access your Scrapy settings (as defined in `settings.py`) from within `your_spider.py` is simple. All other answers are way too complicated. The reason for this is the very poor maintenance of the Scrapy documentation, combined with many recent updates & changes. Neither in the "Settings" documentation "[How... |
How to access scrapy settings from item Pipeline | 14,075,941 | 11 | 2012-12-28T21:19:39Z | 21,735,341 | 9 | 2014-02-12T17:35:52Z | [
"python",
"settings",
"processing",
"scrapy",
"pipeline"
] | How do I access the scrapy settings in settings.py from the item pipeline. The documentation mentions it can be accessed through the crawler in extensions, but I don't see how to access the crawler in the pipelines. | The correct answer is: it depends where in the pipeline you wish to access the settings.
avaleske has answered as if you wanted access to the settings outside of your pipelines `process_item` method but it's very likely this is where you'll want the setting and therefore there is a much easier way as the Spider instan... |
Simulating a key press event in Python 2.7 | 14,076,207 | 8 | 2012-12-28T21:45:20Z | 22,894,683 | 11 | 2014-04-06T13:29:17Z | [
"python",
"api",
"events",
"keyboard",
"simulation"
] | What I want to do is to press any keyboard key from the Python script level on Windows. I have tried SendKeys but it works only on python 2.6. Other methods that I have tried including
```
import win32com.client
win32com.client.Dispatch("WScript.Shell").SendKeys('String to be typed')
```
allow only to type strings f... | I wrote this code more than 1 year ago so it is not perfect but it works:
```
from win32api import keybd_event
import time
import random
Combs = {
'A': [
'SHIFT',
'a'],
'B': [
'SHIFT',
'b'],
'C': [
'SHIFT',
'c'],
'D': [
'SHIFT',
'd'],
... |
Django, filter by specified month and year in date range | 14,077,799 | 13 | 2012-12-29T01:11:34Z | 14,077,983 | 21 | 2012-12-29T01:45:16Z | [
"python",
"django"
] | I have the following models
```
class Destination_Deal(models.Model):
name = models.CharField(_("Nombre"),max_length=200)
class Departure_Date(models.Model):
date_from= models.DateField(_('Desde'))
date_to= models.DateField(_('Hasta'))
destination_deal = models.ForeignKey(Destination_Deal,verbose_... | Check the [documentation](https://docs.djangoproject.com/en/dev/ref/models/querysets/#year)
```
year = 2012
month = 09
Departure_Date.objects.filter(date_from__year__gte=year,
date_from__month__gte=month,
date_to__year__lte=year,
... |
Custom metaclass to create hybrid properties in SQLAlchemy | 14,078,052 | 2 | 2012-12-29T01:58:54Z | 14,096,082 | 7 | 2012-12-31T00:14:25Z | [
"python",
"sqlalchemy",
"metaclass"
] | I want to create a custom interface on top of SQLAlchemy so that some pre-defined hybrid properties are supported transparently.
Specifically, I want to create a class `SpecialColumn` and a metaclass so that when a user adds `SpecialColumn` as an attribute of a class, my custom metaclass replaces that attribute with t... | There's no need to use metaclasses for a SQLAlchemy mapped class as we supply plenty of [events](http://docs.sqlalchemy.org/en/rel_0_8/orm/events.html) to add features to classes as they are created and/or mapped. [mapper\_configured](http://docs.sqlalchemy.org/en/rel_0_8/orm/events.html#sqlalchemy.orm.events.MapperEve... |
How do you use subprocess.check_output() in Python? | 14,078,117 | 19 | 2012-12-29T02:11:40Z | 14,078,258 | 32 | 2012-12-29T02:45:57Z | [
"python",
"python-3.x",
"python-2.x"
] | I have found documentation about subprocess.check\_output() but I cannot find one with arguments and the documentation is not very in depth. I am using Python 3 (but am trying to run a Python 2 file through Python 3)
I am trying to run this command:
`python py2.py -i test.txt`
-i is a positional argument for argparse... | The right answer is:
```
py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])
```
To demonstrate, here are my two programs:
py2.py:
```
import sys
print sys.argv
```
py3.py:
```
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py... |
gevent block redis' socket request | 14,078,493 | 5 | 2012-12-29T03:37:59Z | 14,080,840 | 9 | 2012-12-29T10:37:26Z | [
"python",
"redis",
"gevent"
] | GOAL:spawn a few greenlet worker deal with the data pop from redis (pop from redis and then put into queue)
RUNNING ENV: ubuntu 12.04
PYTHON VER: 2.7
GEVENT VER: 1.0 RC2
REDIS VER:2.6.5
REDIS-PY VER:2.7.1
```
from gevent import monkey; monkey.patch_all()
import gevent
from gevent.pool import Group
from gevent.queue i... | gevent provides **cooperative** lightweight processes (not threads). The consequence is when you have an infinite loop somewhere and the scheduler is never reentered, the program will block taking 100% of a CPU core.
In your example, the problem is the way you have defined the crawler loop. Obviously, you have an infi... |
Django custom model fields: to_python() not called | 14,078,755 | 8 | 2012-12-29T04:40:23Z | 14,081,214 | 9 | 2012-12-29T11:29:18Z | [
"python",
"django"
] | I am quite new to Python and Django, and totally new on Stack Overflow, so I hope I won't break any rules here and I respect the question format.
I am facing a problem trying to implement a custom model field with Django (Python 3.3.0, Django 1.5a1), and I didn't find any similar topics, I am actually quite stuck on t... | In python 3 the module-global `__metaclass__` variable is no longer supported. You must use:
```
class CardContainerField(models.CommaSeparatedIntegerField, metaclass=models.SubfieldBase):
...
``` |
Python, Windows, Ansi - encoding, again | 14,079,343 | 3 | 2012-12-29T06:36:27Z | 14,081,428 | 12 | 2012-12-29T11:58:47Z | [
"python",
"windows",
"character-encoding",
"ansi"
] | **Hello there,**
even if i really tried... im stuck and somewhat desperate when it comes to **Python**, **Windows**, **Ansi** and **character encoding**. I need help, seriously... searching the web for the last few hours wasn't any help, it just drives me crazy.
I'm new to Python, so i have almost no clue what's goin... | As mentioned in the comments, your question isn't very specific, so I'll try to give you some hints about character encodings, see if you can apply those to your specific case!
# Unicode and Encoding
Here's a small primer about encoding. Basically, there are two ways to represent text in Python:
* `unicode`. You can... |
Cannot Get TOCTREE in Sphinx to Show Link | 14,079,655 | 6 | 2012-12-29T07:24:31Z | 14,079,691 | 9 | 2012-12-29T07:29:19Z | [
"python",
"python-sphinx"
] | I am new to Sphinx. I tried out the tutorial but I failed to generate the link in the contents. The error that I got
```
C:\Users\mhaikalm\sphinxtest\source\index.rst:11: WARNING: toctree contains refe
rence to document 'intro' that doesn't have a title: no link will be generated
C:\Users\mhaikalm\sphinxtest\source\in... | You are getting this error because you don't have a title in `intro.rst`.
In order to fix this, add a title to `intro.rst`. Suppose you want your title to be `My Title`, then the title can be added by making the following two lines the first lines of `intro.rst`:
```
My Title
*********
```
Note that you must have e... |
Running Python interactively from within Sublime Text 2 | 14,080,041 | 15 | 2012-12-29T08:34:04Z | 14,080,562 | 7 | 2012-12-29T09:59:49Z | [
"python",
"sublimetext2",
"sublimerepl"
] | I have looked at all the answers on this forum but I'm missing something.
I want to be able to hit `Cmd`+`B` while editing a Python file "myfile.py" in Sublime Text 2.
This should open up a Python shell that loads my file and returns me to the interactive prompt so the namespace in my Python script is available.
Sett... | Try to update your user keybindings:
```
[
{ "keys": ["super+shift+r"], "command": "repl_open",
"caption": "Python",
"mnemonic": "p",
"args": {
"type": "subprocess",
"encoding": "utf8",
"cmd": ["python",... |
Running Python interactively from within Sublime Text 2 | 14,080,041 | 15 | 2012-12-29T08:34:04Z | 14,091,739 | 11 | 2012-12-30T14:58:23Z | [
"python",
"sublimetext2",
"sublimerepl"
] | I have looked at all the answers on this forum but I'm missing something.
I want to be able to hit `Cmd`+`B` while editing a Python file "myfile.py" in Sublime Text 2.
This should open up a Python shell that loads my file and returns me to the interactive prompt so the namespace in my Python script is available.
Sett... | ok, thanks to sneawo for the hints! Here's my first cut at doing this.
Step 1. Create a plugin pydev, (from Tools->New Plugin) which creates a command 'pydev'
```
import sublime, sublime_plugin
class PydevCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command('set_layout', {"cols":... |
Why is the global keyword not required in this case? | 14,081,308 | 10 | 2012-12-29T11:44:29Z | 14,081,324 | 8 | 2012-12-29T11:46:17Z | [
"python",
"global-variables"
] | ```
cache = {}
def func():
cache['foo'] = 'bar'
print cache['foo']
```
output
```
bar
```
Why does this work and why doesn't it require use of the `global` keyword? | Because you are not *assigning* to `cache`, you are changing the dictionary itself instead. `cache` is still pointing to the dictionary, thus is itself unchanged. The line `cache['foo'] = 'bar'` translates to `cache.__setitem__('foo', 'bar')`. In other words, the value of `cache` is a python `dict`, and that value is i... |
Troubles while parsing with python very large xml file | 14,081,701 | 2 | 2012-12-29T12:31:16Z | 14,081,988 | 7 | 2012-12-29T13:09:02Z | [
"python",
"xml-parsing"
] | I have a large xml file (about 84MB) which is in this form:
```
<books>
<book>...</book>
....
<book>...</book>
</books>
```
My goal is to extract every single book and get its properties. I tried to parse it (as I did with other xml files) as follows:
```
from xml.dom.minidom import parse, parseString
f... | Try with [lxml](http://lxml.de/) which is more easy to use.
```
#!/usr/bin/env python
from lxml import etree
with open("myfile.xml") as fp:
tree = etree.parse(fp)
root = tree.getroot()
print root.tag
for book in root:
print book.text
``` |
Fixing faulty unicode strings | 14,082,397 | 4 | 2012-12-29T14:07:24Z | 14,082,441 | 10 | 2012-12-29T14:12:41Z | [
"python",
"unicode"
] | A faulty unicode string is one that has accidentally encoded bytes in it.
For example:
Text: `ש×××`, Windows-1255-encoded: `\x99\x8c\x85\x8d`, Unicode: `u'\u05e9\u05dc\u05d5\u05dd'`, Faulty Unicode: `u'\x99\x8c\x85\x8d'`
I sometimes bump into such strings when parsing ID3 tags in MP3 files. How can I fix these st... | You could convert `u'\x99\x8c\x85\x8d'` to `'\x99\x8c\x85\x8d'` using the `latin-1` encoding:
```
In [9]: x = u'\x99\x8c\x85\x8d'
In [10]: x.encode('latin-1')
Out[10]: '\x99\x8c\x85\x8d'
```
However, it seems like this is not a valid Windows-1255-encoded string. Did you perhaps mean `'\xf9\xec\xe5\xed'`? If so, then... |
Should I use encoding declaration in Python3? | 14,083,111 | 24 | 2012-12-29T15:27:17Z | 14,083,123 | 28 | 2012-12-29T15:28:41Z | [
"python",
"python-3.x",
"encoding",
"utf-8"
] | I'm trying to switch python3. I believe there is utf8 encoding by default. Should I still use encoding declaration at the beginning every file?
```
# -*- coding: utf-8 -*-
``` | Because the default *is* UTF-8, you only need to use that declaration when you deviate from the default.
In other words, only when you want to use an encoding that differs do you have to use that declaration.
Note that it only applies to how Python reads the source code. It doesn't apply to printing, opening files, o... |
Configure htaccess to serve static django files | 14,083,882 | 7 | 2012-12-29T16:56:59Z | 14,089,182 | 8 | 2012-12-30T07:56:31Z | [
"python",
"django",
"apache",
".htaccess",
"mod-rewrite"
] | I'm having trouble setting up Apache to serve static Django files. I am on a shared host and don't have access to the Apache config files. All the examples use `Alias` in the Apache config files, so I'm trying to figure out how to do it with mod\_rewrite in .htaccess.
**My setup.py looks like this:**
```
STATIC_ROOT ... | Well, after a whole day of messing with .htaccess regexes (yukk!), I finally figured out the problem.
It actually has nothing to do with the .htaccess file. The problem was in my **settings.py** `STATIC_URL`. Turns out I had to set `STATIC_URL = '/mydjangoproject/static/'` in order to mesh with the `STATIC_ROOT = '/ho... |
getattr() versus dict lookup, which is faster? | 14,084,897 | 6 | 2012-12-29T18:56:21Z | 14,084,917 | 31 | 2012-12-29T18:58:22Z | [
"python",
"performance",
"getattr",
"dynamic-attributes"
] | A somewhat noobish, best practice question. I dynamically look up object attribute values using `object.__dict__[some_key]` as a matter of habit. Now I am wondering which is better/faster: my current habit or `getattr(object,some_key)`. If one is better, why?
```
>>> class SomeObject:
... pass
...
>>> so = SomeOb... | You are much better off using `getattr()` instead of going directly to the `__dict__` structure.
Not because it's faster or slower, but because the official API works in *all* circumstances, including for classes that do *not* have a `__dict__` (when using [`__slots__`](http://docs.python.org/2/reference/datamodel.htm... |
pandas sorting pivot_table or grouping dataframe? | 14,085,517 | 3 | 2012-12-29T20:13:46Z | 14,086,002 | 9 | 2012-12-29T21:17:32Z | [
"python",
"table",
"sorting",
"pivot",
"pandas"
] | I have a problem. I did this:
```
In [405]: pippo=ass_t1.pivot_table(['Rotazioni a volume','Distribuzione Ponderata'],rows=['SEGM1','DESC']).sort()
In [406]: pippo
Out[406]:
Distribuzione Ponderata Rotazioni a volume
SEGM1 DESC
AD ACCA... | ```
import io
import pandas as pd
import numpy as np
text = '''\
SEGM1\tDESC\tDistribuzione Ponderata\tRotazioni a volume
AD\tACCADINAROLO\t74.040\t140249.693409
AD\tZYMIL AMALAT Z\t90.085\t321529.053570
FUN\tSPECIALMALAT S\t88.650\t120711.182177
NORM\tSTD INNAROLO\t49.790\t162259.216710
NORM\tSTD P.NAROLO\t52.125\t12... |
Exposing model method with Tastypie | 14,085,865 | 11 | 2012-12-29T20:57:44Z | 15,658,539 | 19 | 2013-03-27T12:14:58Z | [
"python",
"django",
"tastypie"
] | I am currently working on implementing an API into my Django project and Tastypie seemed like it would be most suitable.
What I can't seem to work out is how to expose a function within my model using Tastypie.
For example, I have this model:
```
class game(models.Model):
id = models.AutoField("ID", primary_key=... | Within your Game-Resource, you can always prepend new urls that can expose methods. For example (Edited according to the comment by @BigglesZX):
```
from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash
class GameResource(ModelResource):
class Meta:
queryset = Game.object... |
Python: How to sort a list by the max of each element? | 14,086,051 | 2 | 2012-12-29T21:23:55Z | 14,086,070 | 12 | 2012-12-29T21:25:27Z | [
"python",
"list"
] | ```
L=[[a,b],[c,d],[e,f],...]
```
I want to sort it by max(a,b), max(c,d), max(e,f), etc. | You can supply a custom `key` functor to `sort`:
```
L.sort(key=lambda e: max(e))
```
or simply
```
L.sort(key=max)
```
(thanks, A. R. S.). |
Python calling method in class | 14,086,830 | 4 | 2012-12-29T23:25:28Z | 14,086,857 | 21 | 2012-12-29T23:29:09Z | [
"python",
"class",
"methods"
] | Im punching way above my weight here, but please bare with this python amateur...im a PHP developer by trade and Ive hardly touched this language before.
What Im trying to do is call a method in a class...sounds simple enough? Im utterly baffled about what 'self' refers too, and what is the correct procedure to call s... | The first argument of all methods is usually called `self`. It refers to the instance for which the method is being called.
Let's say you have:
```
class A(object):
def foo(self):
print 'Foo'
def bar(self, an_argument):
print 'Bar', an_argument
```
Then, doing:
```
a = A()
a.foo() #prints '... |
Python 3 ImportError: No module named 'ConfigParser' | 14,087,598 | 77 | 2012-12-30T01:46:32Z | 14,087,705 | 71 | 2012-12-30T02:12:13Z | [
"python",
"python-3.x"
] | I am trying to `pip install` the `MySQL-python` package, but I get an `ImportError`.
```
Jans-MacBook-Pro:~ jan$ /Library/Frameworks/Python.framework/Versions/3.3/bin/pip-3.3 install MySQL-python
Downloading/unpacking MySQL-python
Running setup.py egg_info for package MySQL-python
Traceback (most recent call las... | In Python 3, [`ConfigParser`](https://docs.python.org/2/library/configparser.html) has been renamed to [`configparser`](https://docs.python.org/3/library/configparser.html) for PEP 8 compliance. It looks like the package you are installing does not support Python 3. |
Python 3 ImportError: No module named 'ConfigParser' | 14,087,598 | 77 | 2012-12-30T01:46:32Z | 23,978,968 | 115 | 2014-06-01T10:35:25Z | [
"python",
"python-3.x"
] | I am trying to `pip install` the `MySQL-python` package, but I get an `ImportError`.
```
Jans-MacBook-Pro:~ jan$ /Library/Frameworks/Python.framework/Versions/3.3/bin/pip-3.3 install MySQL-python
Downloading/unpacking MySQL-python
Running setup.py egg_info for package MySQL-python
Traceback (most recent call las... | You can instead use the [`mysqlclient`](https://pypi.python.org/pypi/mysqlclient) package as a drop-in replacement for MySQL-python. It is a fork of `MySQL-python` with added support for Python 3.
I had luck with simply
```
pip install mysqlclient
```
in my python3.4 virtualenv after
```
sudo apt-get install python... |
Is Lua embedded in C++ capable of having persistent local variables? If not, is there a scripting language that does? | 14,087,686 | 2 | 2012-12-30T02:08:11Z | 14,088,458 | 8 | 2012-12-30T05:05:26Z | [
"python",
"scripting",
"lua",
"v8",
"luabind"
] | I have embedded Lua in my C++ application using LuaBind. I need to have variables that persist across multiple runs, that can't be accessed by other objects that run the same file name.
For example: let's say I have a class called `NPC`. An `NPC` holds a string, that is the name of the script they run. When an `NPC` i... | You could look into Lua's [closures](http://www.lua.org/pil/6.1.html). It would look something like this:
```
function healthPoints()
local health = 10
return function()
health = health - 5
return health
end
end
```
What happens is that each NPC gets their own function with their own count... |
Multithreaded web server in python | 14,088,294 | 22 | 2012-12-30T04:20:10Z | 14,089,457 | 29 | 2012-12-30T08:44:34Z | [
"python",
"multithreading",
"http",
"webserver"
] | I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please?
```
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import Sim... | Check [this](http://pymotw.com/2/BaseHTTPServer/index.html#module-BaseHTTPServer) post from Doug Hellmann's blog.
```
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_r... |
How to change plot background color? | 14,088,687 | 57 | 2012-12-30T06:02:09Z | 14,089,043 | 32 | 2012-12-30T07:26:32Z | [
"python",
"matplotlib"
] | I am making a scatter plot in matplotlib and need to change the background of the actual plot to black. I know how to change the face color of the plot using:
```
fig = plt.figure()
fig.patch.set_facecolor('black')
```
My issue is that this changes the color of the space around the plot. How to I change the actual ba... | Something like this? Use the `axisbg` keyword to `subplot`:
```
>>> from matplotlib.figure import Figure
>>> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
>>> figure = Figure()
>>> canvas = FigureCanvas(figure)
>>> axes = figure.add_subplot(1, 1, 1, axisbg='red')
>>> axes.plot([1,2,3])
[<... |
How to change plot background color? | 14,088,687 | 57 | 2012-12-30T06:02:09Z | 23,645,437 | 58 | 2014-05-14T04:05:02Z | [
"python",
"matplotlib"
] | I am making a scatter plot in matplotlib and need to change the background of the actual plot to black. I know how to change the face color of the plot using:
```
fig = plt.figure()
fig.patch.set_facecolor('black')
```
My issue is that this changes the color of the space around the plot. How to I change the actual ba... | If you already have the `axes` object, for example if you used `f, ax = plt.subplot()` or `plt.subplots()`, or can just get the current axes via `ax = plt.gca()`, you can directly use a method of it, [`set_axis_bgcolor`](http://matplotlib.org/1.3.1/api/axes_api.html#matplotlib.axes.Axes.set_axis_bgcolor):
```
ax.set_a... |
Getting Secure Websockets working on Tornado | 14,088,695 | 8 | 2012-12-30T06:03:42Z | 14,089,427 | 12 | 2012-12-30T08:39:59Z | [
"python",
"websocket",
"tornado"
] | How to set WSS (Secure WebSockets) on Tornado?
In their docstring, they say the following:
`WebSocketHandler.get_websocket_scheme` can be used to select the
appropriate url scheme (`ws://` or `wss://`) in cases where `HTTPRequest.protocol` is not set correctly.
So, how can I use `get_websocket_scheme` and/or `HTTPRe... | I got it :))
Just add this to your application:
```
http_server = tornado.httpserver.HTTPServer(application,ssl_options={
"certfile": "cert.cer",
"keyfile": "key.key",
})
```
This will solve the problem. Just very similar to regular HTTPS.
I also appreciate any other way to make it work. |
Python - reading, parsing and writing back to a file | 14,089,083 | 2 | 2012-12-30T07:34:30Z | 14,089,123 | 15 | 2012-12-30T07:44:26Z | [
"python",
"parsing"
] | I am trying to read around 5000 lines of code from a text file then parse and store the parsed values into another text file.
However, I am able to only do this for the first 967 lines (as indicated by the output file, which contains the parsed values of the first 967 lines only).
Here is the simple code i wrote to d... | Because your `for` iteration is not over the lines in `infile`, but rather over the characters in its first line. Probably, the first line is 967 characters long.
`for line in infile.readline()` means that you're reading the first line from `infile` as a string. Strings are iterable, in the way that iterating over the... |
Iterating and printing JSON objects in Python | 14,089,238 | 2 | 2012-12-30T08:06:45Z | 14,089,373 | 7 | 2012-12-30T08:31:12Z | [
"python",
"json",
"google-spreadsheet",
"google-spreadsheet-api",
"python-requests"
] | I have a Google Spreadsheet that I'd like to get in Python, then process it through JSON. It's halfway working, and after looking through Stackoverflow for several hours, I think it's time to ask a question.
For example, the format of the JSON file looks like this (from <https://developers.google.com/gdata/docs/json>)... | j['feed'] is a dictionary. Your code should look like:
```
for entry in j['feed']['entry']:
print entry['title']['$t']
``` |
Creating a dictionary from a CSV file | 14,091,387 | 10 | 2012-12-30T14:10:25Z | 14,091,464 | 34 | 2012-12-30T14:21:05Z | [
"python",
"csv",
"dictionary"
] | I am in the process of trying to write a python script that will take input from a CSV file and then push it into a dictionary format (I am using Python 3.x).
I use the code below to read in the CSV file and that works:
```
import csv
reader = csv.reader(open('C:\\Users\\Chris\\Desktop\\test.csv'), delimiter=',', qu... | Create a dictionary, then iterate over the result and stuff the rows in the dictionary. Note that if you encounter a row with a duplicate date, you will have to decide what to do (raise an exception, replace the previous row, discard the later row, etc...)
Here's test.csv:
```
Date,Foo,Bar
123,456,789
abc,def,ghi
```... |
get_absolute_url - Django`s sitemap | 14,092,601 | 5 | 2012-12-30T16:58:20Z | 14,092,692 | 7 | 2012-12-30T17:08:18Z | [
"python",
"django"
] | I want to enable sitemap-generation in Django, so I do the following, how it explained [here](https://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/#example)
model:
```
class Car(models.Model):
def __unicode__(self):
return self.name
name = models.CharField('Name', max_length=10)
active =... | You have to define [get\_absolute\_url](https://docs.djangoproject.com/en/1.9/ref/models/instances/#get-absolute-url) for the model:
```
from django.core.urlresolvers import reverse
class Car(models.Model):
name = models.CharField('Name', max_length=10)
active = models.BooleanField()
def __unicode__(self... |
Python - how can I reference a class variable or method from within the __init__ method? | 14,092,983 | 3 | 2012-12-30T17:42:09Z | 14,092,999 | 7 | 2012-12-30T17:44:28Z | [
"python",
"class-method"
] | I have a hierarchy of objects in a python module as follows:
```
class BaseObject(object):
initialized = False
def __init__(self):
self._initialize()
@classmethod
def _initialize(cls):
print "cls.initialized = "+str(cls.initialized)
if not cls.initialized:
cls.x = ... | You need to use the full classname to *set* class variables. `cls` in `double_x` and `tripple_x` will refer to subclasses (`ObjectOne` and `ObjectTwo`, respectively), and setting attributes on those subclasses will store *new* variables, not alter the class variable `BaseObject.x`. You can *only* alter base class varia... |
Can scrapy yield both request and items? | 14,093,242 | 6 | 2012-12-30T18:13:24Z | 15,940,421 | 9 | 2013-04-11T03:48:52Z | [
"python",
"scrapy"
] | When I write `parse()` function, can I yield both a request and items for one single page?
I want to extract some data in page A and then store the data in database, and extract links to be followed (this can be done by rule in CrawlSpider).
I call the links pages of A pages is B pages, so I can write another parse\_... | Yes, you can yield both requests and items. From [what I've seen](https://groups.google.com/forum/?fromgroups=#!topic/scrapy-users/QWd4DEVQ1Y0):
```
def parse(self, response):
hxs = HtmlXPathSelector(response)
base_url = response.url
links = hxs.select(self.toc_xpath)
for index, link in enumerate(link... |
Python - how can I get the class name from within a class method - using @classmethod | 14,094,961 | 6 | 2012-12-30T21:44:09Z | 14,094,983 | 15 | 2012-12-30T21:46:18Z | [
"python",
"class-method"
] | I have the following code:
```
class ObjectOne(object):
@classmethod
def print_class_name(cls):
print cls.__class__.__name__
def print_class_name_again(self):
print self.__class__.__name__
if __name__ == '__main__':
obj_one = ObjectOne()
obj_one.print_class_name()
obj_one.prin... | A classmethod receives the class as its argument. That's why you're calling it `cls`. Just do `cls.__name__`. |
BeautifulSoup in Python - getting the n-th tag of a type | 14,095,511 | 7 | 2012-12-30T22:50:23Z | 14,095,570 | 11 | 2012-12-30T22:58:31Z | [
"python",
"beautifulsoup"
] | I have some html code that contains many `<table>`s in it.
I'm trying to get the information in the second table. Is there a way to do this without using `soup.findAll('table')` ?
When I do use `soup.findAll('table')`, I get an error:
```
ValueError: too many values to unpack
```
Is there a way to get the n-th tag ... | To get the second table from the call `soup.findAll('table')`, use it as a list, just index it:
```
secondtable = soup.findAll('table')[1]
``` |
Python - can I programmatically decorate class methods from a class instance? | 14,095,616 | 4 | 2012-12-30T23:05:20Z | 14,095,728 | 9 | 2012-12-30T23:21:08Z | [
"python",
"decorator",
"class-method"
] | I have an object hierarchy in which almost all of the methods are class methods. It looks like the following:
```
class ParentObject(object):
def __init__(self):
pass
@classmethod
def smile_warmly(cls, the_method):
def wrapper(kls, *args, **kwargs):
print "-smile_warmly - "+kls... | All a decorator does is return a new function. This:
```
@deco
def foo():
# blah
```
is the same as this:
```
def foo():
# blah
foo = deco(foo)
```
You can do the same thing whenever you like, without the `@` syntax, just by replacing functions with whatever you like. So in `__init__` or wherever else, you ... |
Calculating the analogous color with python | 14,095,849 | 5 | 2012-12-30T23:42:17Z | 14,116,553 | 7 | 2013-01-02T03:27:53Z | [
"python",
"colors"
] | If I had RGB values: `255, 165, 0`, what could be done to calculate the analogous color(s) of `218, 255, 0` and `255, 37, 0`, but still applying for any RGB color?
For example:
```
>>> to_analogous(0, 218, 255)
[(0, 255, 165),(0, 90, 255)]
```
EDIT: For simplicity, an analogous color can be viewed as this, green bei... | Converting from RGB to HSL and rotating +/- 30 degrees might be indeed what you want, but you will not get the color wheel showed. Obtaining, respectively, 12 and 128 colors, starting with pure red (at top), this is what you will get:
 ![enter image de... |
How to tweak the NLTK sentence tokenizer | 14,095,971 | 16 | 2012-12-30T23:59:00Z | 14,101,885 | 7 | 2012-12-31T12:55:50Z | [
"python",
"nlp",
"nltk"
] | I'm using NLTK to analyze a few classic texts and I'm running in to trouble tokenizing the text by sentence. For example, here's what I get for a snippet from *[Moby Dick](http://www.gutenberg.org/cache/epub/2701/pg2701.txt)*:
```
import nltk
sent_tokenize = nltk.data.load('tokenizers/punkt/english.pickle')
'''
(Chap... | You can tell the `PunktSentenceTokenizer.tokenize` method to include "terminal" double quotes with the rest of the sentence by setting the `realign_boundaries` parameter to `True`. See the code below for an example.
I do not know a clean way to prevent text like `Mrs. Hussey` from being split into two sentences. Howev... |
How to tweak the NLTK sentence tokenizer | 14,095,971 | 16 | 2012-12-30T23:59:00Z | 14,103,163 | 26 | 2012-12-31T15:08:35Z | [
"python",
"nlp",
"nltk"
] | I'm using NLTK to analyze a few classic texts and I'm running in to trouble tokenizing the text by sentence. For example, here's what I get for a snippet from *[Moby Dick](http://www.gutenberg.org/cache/epub/2701/pg2701.txt)*:
```
import nltk
sent_tokenize = nltk.data.load('tokenizers/punkt/english.pickle')
'''
(Chap... | You need to supply a list of abbreviations to the tokenizer, like so:
```
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters
punkt_param = PunktParameters()
punkt_param.abbrev_types = set(['dr', 'vs', 'mr', 'mrs', 'prof', 'inc'])
sentence_splitter = PunktSentenceTokenizer(punkt_param)
text = "is T... |
How to tweak the NLTK sentence tokenizer | 14,095,971 | 16 | 2012-12-30T23:59:00Z | 25,375,857 | 11 | 2014-08-19T04:52:51Z | [
"python",
"nlp",
"nltk"
] | I'm using NLTK to analyze a few classic texts and I'm running in to trouble tokenizing the text by sentence. For example, here's what I get for a snippet from *[Moby Dick](http://www.gutenberg.org/cache/epub/2701/pg2701.txt)*:
```
import nltk
sent_tokenize = nltk.data.load('tokenizers/punkt/english.pickle')
'''
(Chap... | You can modify the NLTK's pre-trained English sentence tokenizer to recognize more abbreviations by adding them to the set `_params.abbrev_types`. For example:
```
extra_abbreviations = ['dr', 'vs', 'mr', 'mrs', 'prof', 'inc', 'i.e']
sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
sentence_token... |
Easier way to enable verbose logging | 14,097,061 | 21 | 2012-12-31T03:19:20Z | 14,098,306 | 34 | 2012-12-31T06:31:14Z | [
"python",
"python-2.7"
] | * [How to implement the --verbose or -v option into a python script?](http://stackoverflow.com/questions/5980042/how-to-implement-the-verbose-or-v-option-into-a-python-script)
* [Python logging - Is there something below DEBUG?](http://stackoverflow.com/questions/9042919/python-logging-is-there-something-below-debug)
... | You need to combine the wisdom of the [Argparse Tutorial](http://docs.python.org/2/howto/argparse.html) with [Python's Logging HOWTO](http://docs.python.org/2/howto/logging.html). Here's an example...
```
> cat verbose.py
#!/usr/bin/env python
import argparse
import logging
parser = argparse.ArgumentParser(
des... |
Easier way to enable verbose logging | 14,097,061 | 21 | 2012-12-31T03:19:20Z | 20,663,028 | 49 | 2013-12-18T16:11:21Z | [
"python",
"python-2.7"
] | * [How to implement the --verbose or -v option into a python script?](http://stackoverflow.com/questions/5980042/how-to-implement-the-verbose-or-v-option-into-a-python-script)
* [Python logging - Is there something below DEBUG?](http://stackoverflow.com/questions/9042919/python-logging-is-there-something-below-debug)
... | I find both `--verbose` (for users) and `--debug` (for developers) useful. Here's how I do it with `logging` and `argparse`:
```
import argparse
import logging
parser = argparse.ArgumentParser()
parser.add_argument(
'-d', '--debug',
help="Print lots of debugging statements",
action="store_const", dest="lo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.