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 can I print variable and string on same line in Python?
17,153,779
25
2013-06-17T17:58:08Z
17,153,931
14
2013-06-17T18:06:51Z
[ "python", "string", "variables", "printing" ]
I am using python to work out how many children would be born in 5 years if a child was born every 7 seconds. The problem is on my last line. How do I get a variable to work when I'm printing text either side of it? Here is my code: ``` currentPop = 312032486 oneYear = 365 hours = 24 minutes = 60 seconds = 60 # seco...
two more **The First one** ``` >>>births = str(5) >>>print "there are " + births + " births." there are 5 births. ``` When adding strings, they concatenate. **The Second One** Also the `format` (Python 2.6 and newer) method of strings is probably the standard way: ``` >>> births = str(5) >>> >>> print "there a...
Flask error handling: "Response object is not iterable"
17,153,978
6
2013-06-17T18:09:28Z
17,154,441
8
2013-06-17T18:37:48Z
[ "python", "rest", "curl", "flask" ]
I'm trying to set of a REST web service using Flask. I'm having a problem with the error handling `@app.errorhandler(404)` ``` #!flask/bin/python from flask import Flask, jsonify, abort app = Flask(__name__) @app.errorhandler(404) def not_found(error): return jsonify({'error':'not found'}), 404 if __name__ == '...
``` from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(404) def not_found(error): return jsonify({'error':'not found'}), 404 app.run() ``` With code above, `curl http://localhost:5000/` give me: ``` { "error": "not found" } ``` Are you using `flask.jsonify`?
Unit testing an AsyncResult in celery
17,154,146
8
2013-06-17T18:20:01Z
17,155,922
10
2013-06-17T20:09:10Z
[ "python", "django", "unit-testing", "celery" ]
I am trying to test some celery functionality in Django's unit testing framework, but whenever I try to check an AsyncResult the tests act like it was never started. I know this code works in a real environment with RabbitMQ, so I was just wondering why it didn't work when using the testing framework. Here is an exam...
When `CELERY_ALWAYS_EAGER` is `True`, the call to `apply_async()` is actually replaced with `apply()`. The result returned is an `EagerResult`, which already contains the result of your task. So, yes, setting `ALWAYS_EAGER = True` disables the entire `AsyncResult` functionnality. The entire async process is bypassed, ...
Multiple levels of keys and values in Python
17,154,393
5
2013-06-17T18:34:55Z
17,154,492
14
2013-06-17T18:40:59Z
[ "python", "python-2.7", "dictionary" ]
I wanted to know if the functionality i am trying to implement in python is possible. I have a global hash called Creatures. Creatures contain sub-hashes called mammals, amphibians, birds, insects. Mammals have sub-hashes called whales, elephants. Amphibians have sub-hashes called frogs, larvae. Birds have sub-hashes...
The value assigned to a key in a dictionary can itself be another dictionary ``` creatures = dict() creatures['birds'] = dict() creatures['birds']['eagle'] = dict() creatures['birds']['eagle']['female'] = 0 creatures['birds']['eagle']['female'] += 1 ``` You need to explicitly create each dictionary, though. Unlike Pe...
Python - I'm getting an indentation error, but I don't see one. Tabs and spaces aren't mixed
17,154,859
4
2013-06-17T19:02:57Z
17,154,874
14
2013-06-17T19:03:38Z
[ "python", "indentation" ]
My code is: ``` 90 if needinexam > 100: 91 print "We are sorry, but you are unable to get an A* in this class." 92 else: 93 print "You need " + final + "% in your Unit 3 controlled assessment to get an A*" 94 95 elif unit2Done == "n": 96 ...
Try this: ``` elif unit2Done == "n": pass # this is used as a placeholder, so the condition's body isn't empty else: print "Sorry. That's not a valid answer." ``` The problem here is that the body of the `unit2Done == "n"` condition can not be empty. In this case, a `pass` must be used as a kind of placeholde...
Converting identifier naming between camelCase and underscores during JSON serialization/deserialization
17,156,078
4
2013-06-17T20:17:29Z
17,156,414
9
2013-06-17T20:38:53Z
[ "python", "json" ]
I am working on a python/django application that serves as a web API server to its frontend counterpart. The data exchange between the server and the client is in JSON format with the use of XMLHttpRequest (Javascript). For those that are familiar with both Python and Javascript, you know that they have different ident...
One way to do it using regular expressions, ``` import re camel_pat = re.compile(r'([A-Z])') under_pat = re.compile(r'_([a-z])') def camel_to_underscore(name): return camel_pat.sub(lambda x: '_' + x.group(1).lower(), name) def underscore_to_camel(name): return under_pat.sub(lambda x: x.group(1).upper(), nam...
Pandas DataFrame.unstack() Changes Order of Row and Column Headers
17,156,662
6
2013-06-17T20:54:11Z
17,157,110
7
2013-06-17T21:23:08Z
[ "python", "pandas" ]
I have run into the following problem of sorting the row and column headers. Here is how to reproduce this: ``` X =pd.DataFrame(dict(x=np.random.normal(size=100), y=np.random.normal(size=100))) A=pd.qcut(X['x'], [0,0.25,0.5,0.75,1.0]) #create a factor B=pd.qcut(X['y'], [0,0.25,0.5,0.75,1.0]) # create another factor ...
This seems like a little bit of a hack, but here goes: ``` In [11]: g_unstacked = g.unstack() In [12]: g_unstacked Out[12]: y (-0.565, 0.12] (0.12, 0.791] (0.791, 2.57] [-2.177, -0.565] x (-0.068, 0.625] 0.389408 0.267252 0.283344 0.258337 (-0.892, -0.068] -0.1214...
How to force virtualenv to install latest setuptools and pip from pypi?
17,156,912
15
2013-06-17T21:07:56Z
17,157,290
10
2013-06-17T21:37:34Z
[ "python", "virtualenv", "pip", "setuptools", "virtualenvwrapper" ]
Is it possible to force virtualenv to use the latest setuptools and pip available from pypi? Essentially, I'm looking for the ***opposite*** of the `--never-download` flag. Currently, when I make a new virtualenv, it uses the local (old) versions that come bundled with virtualenv. ``` $ v.mk testvenv New python execu...
It's not supported for security reasons. > Using virtualenv.py as an isolated script (i.e. without an associated > virtualenv\_support directory) is no longer supported for security > reasons and will fail with an error. Along with this, --never-download > is now always pinned to True, and is only being maintained in ...
How to force virtualenv to install latest setuptools and pip from pypi?
17,156,912
15
2013-06-17T21:07:56Z
17,495,071
8
2013-07-05T18:40:22Z
[ "python", "virtualenv", "pip", "setuptools", "virtualenvwrapper" ]
Is it possible to force virtualenv to use the latest setuptools and pip available from pypi? Essentially, I'm looking for the ***opposite*** of the `--never-download` flag. Currently, when I make a new virtualenv, it uses the local (old) versions that come bundled with virtualenv. ``` $ v.mk testvenv New python execu...
You can upgrade pip after installing your virtualenv by using `pip install -U pip`. I'm sure you could write a bootstrap-script to automate this step.
Is there a way to set a default parameter equal to another parameter value?
17,157,272
2
2013-06-17T21:36:00Z
17,157,303
8
2013-06-17T21:38:16Z
[ "python", "python-3.x" ]
For example, I have a basic method that will return a list of permutations. ``` import itertools def perms(elements,setLength=elements): data=[] for x in range(elements): data.append(x+1) return(list(itertools.permutations(data,setLength))) ``` Now I understand, that in its current state this code...
No, function keyword parameter defaults are determined when the function is *defined*, not when the function is executed. Set the default to `None` and detect that: ``` def perms(elements, setLength=None): if setLength is None: setLength = elements ``` If you need to be able to specify `None` as a argume...
Get the error code from tweepy exception instance
17,157,753
8
2013-06-17T22:13:09Z
17,168,626
11
2013-06-18T12:16:40Z
[ "python", "python-2.7", "twitter", "tweepy" ]
I'm new to python and I'm trying to use a library. It raises an exception, and I am trying to identify which one. This is what I am trying: ``` except tweepy.TweepError as e: print e print type(e) print e.__dict__ print e.reason print type(e.reason) ``` This is what I am getting: ``` [{u'message'...
How about this? ``` except tweepy.TweepError as e: print e.message[0]['code'] # prints 34 print e.args[0][0]['code'] # prints 34 ```
Centering x-tick labels between tick marks in matplotlib
17,158,382
10
2013-06-17T23:17:09Z
17,158,735
11
2013-06-18T00:03:51Z
[ "python", "matplotlib", "pandas" ]
I want to have the x-tick date labels centered between the tick marks, instead of centered about the tick marks as shown in the photo below. I have read the documentation but to no avail - does anyone know a way to do this? ![enter image description here](http://i.stack.imgur.com/Ea81A.png) Here is everything that I...
One way to do it is to use the minor ticks. The idea is that you set the minor ticks so that they are located halfway between the major ticks, and you manually specify the labels. For example: ``` import matplotlib.ticker as ticker # a is an axes object, e.g. from figure.get_axes() # Hide major tick labels a.xaxis....
What is the way to delete words in Python list which does not have numbers?
17,158,791
3
2013-06-18T00:12:36Z
17,158,807
8
2013-06-18T00:14:52Z
[ "python", "regex" ]
``` a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent'] ``` the above list have words like history, members which do not have numbers in them, so i want to delete them ``` # output would be a = ['in 1978 by', 'June 4th, 1979'...
Keep the ones you want: ``` a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent'] new = [el for el in a if any(ch.isdigit() for ch in el)] # ['in 1978 by', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 19...
Excluding Fields in Django Class Based Views Not Working
17,158,963
5
2013-06-18T00:36:39Z
17,159,030
9
2013-06-18T00:45:23Z
[ "python", "django", "django-forms" ]
Boy, it feels like I've tried EVERYTHING here, and I just can't get this form to render properly (e.g. with a subset of fields). Here's the relevant items (extra items removed): models.py: ``` class Response(models.Model): public = models.BooleanField(default=False) question = models.CharField(max_length=255,...
It looks like you need to specify `form_class` on your view: ``` class ResponseCreate(CreateView): model = Response form_class = ResponseForm ```
Change timezone of date-time column in pandas and add as hierarchical index
17,159,207
13
2013-06-18T01:11:03Z
17,159,276
14
2013-06-18T01:24:42Z
[ "python", "timezone", "dataframe", "pandas", "multi-index" ]
I have data with a time-stamp in UTC. I'd like to convert the timezone of this timestamp to 'US/Pacific' and add it as a hierarchical index to a pandas DataFrame. I've been able to convert the timestamp as an Index, but it loses the timezone formatting when I try to add it back into the DataFrame, either as a column or...
If you set it as the index, it's automatically converted to an Index: ``` In [11]: dat.index = pd.to_datetime(dat.pop('datetime'), utc=True) In [12]: dat Out[12]: label value datetime 2011-07-19 07:00:00 a 0 2011-07-19 08:00:00 a 1 2011-07-19 09:00:00 a 2 2011-07-19 07:...
How to use select_for_update to 'get' a Query in Django?
17,159,471
7
2013-06-18T01:55:37Z
17,159,726
9
2013-06-18T02:36:13Z
[ "python", "django", "django-queryset" ]
As the Django Documentation says, `select_for_update` returns a `Queryset`. But `get` does not. Now I have a query which I am sure is going to return only one tuple. But I also need to acquire locks for this transaction. So I am doing something like: ``` ob = MyModel.objects.select_for_update().filter(some conditions)...
Just call `get`, slice it, etc. and save as usual. The lock is in place through the transaction. ``` ob = MyModel.objects.select_for_update().get(pk=1) ``` Any changes are committed at the end of the transaction (which by default through 1.5 is per-request)
How to create a list of fields in django forms
17,159,567
9
2013-06-18T02:11:17Z
17,159,675
8
2013-06-18T02:26:57Z
[ "python", "django", "django-forms" ]
Is there any way to make a django forms class that actually holds an array of fields? I have a database that will pull up a variable number of questions to ask the user and each question will know how to define it's widget...etc, I just can't seem to hook this up to django forms. I tried this: ``` class MyForm(forms....
You may be able to use [formsets](https://docs.djangoproject.com/en/dev/topics/forms/formsets/) if your forms are identical (including their labels). e.g. Question: ***\_*\_\_*\_*\_\_*\_*\_** Question: ***\_*\_\_*\_*\_\_*\_*\_** Question: ***\_*\_\_*\_*\_\_*\_*\_** etc. I'm assuming each form contains only one fi...
What is the ellipsis [...] in a Python list?
17,160,162
152
2013-06-18T03:38:33Z
17,160,180
83
2013-06-18T03:40:51Z
[ "python", "list" ]
I was playing around in python. I used the following code in IDLE ``` p = [1, 2] p[1:1] = [p] print p ``` The output was ``` [1, [...], 2] ``` What is this […]? Interestingly I could now use this as a list of list of list upto infinity i.e. ``` p[1][1][1].... ``` I could write the above as long as I wanted and...
It means that you created an infinite list nested inside itself, which can not be printed. `p` contains `p` which contains `p` ... and so on. The `[...]` notation is a way to let you know this, and to inform that it can't be represented! Take a look at @6502's answer to see a nice picture showing what's happening. Now...
What is the ellipsis [...] in a Python list?
17,160,162
152
2013-06-18T03:38:33Z
17,162,565
19
2013-06-18T07:06:16Z
[ "python", "list" ]
I was playing around in python. I used the following code in IDLE ``` p = [1, 2] p[1:1] = [p] print p ``` The output was ``` [1, [...], 2] ``` What is this […]? Interestingly I could now use this as a list of list of list upto infinity i.e. ``` p[1][1][1].... ``` I could write the above as long as I wanted and...
To the question "What's its use", here is a concrete example. [Graph reduction](http://en.wikipedia.org/wiki/Graph_reduction) is an evaluation strategy sometime used in order to interpret a computer language. This is a common strategy for lazy evaluation, notably of functional languages. The starting point is to buil...
What is the ellipsis [...] in a Python list?
17,160,162
152
2013-06-18T03:38:33Z
17,163,521
273
2013-06-18T08:00:40Z
[ "python", "list" ]
I was playing around in python. I used the following code in IDLE ``` p = [1, 2] p[1:1] = [p] print p ``` The output was ``` [1, [...], 2] ``` What is this […]? Interestingly I could now use this as a list of list of list upto infinity i.e. ``` p[1][1][1].... ``` I could write the above as long as I wanted and...
This is what your code created ![enter image description here](http://i.stack.imgur.com/mUnTM.png) It's a list where the first and last elements are pointing to two numbers (1 and 2) and where the middle element is pointing to the list itself. In Common Lisp when printing circular structures is enabled such an objec...
Display python unittest results in nice, tabular form
17,162,682
12
2013-06-18T07:12:28Z
17,162,936
15
2013-06-18T07:25:34Z
[ "python", "unit-testing", "testing", "python-unittest", "test-reporting" ]
I am writing a Pythonic tool which validates the correctness of a certain system. Each validation is written as a Python [`unittest`](http://docs.python.org/2/library/unittest.html), and the report looks like: ``` test_exclude_list_not_empty (__main__.TestRepoLists) Assert the the exclude list is not empty ... ok test...
This is not exactly what you are asking, but there are several options for having a readable test output there: * [HTMLTestRunner](http://tungwaiyip.info/software/HTMLTestRunner.html) generates easy to use HTML test reports in a tabular form. [Here](http://tungwaiyip.info/software/sample_test_report.html)'s a sample r...
The for loop with letters instead of numbers
17,163,113
3
2013-06-18T07:36:04Z
17,163,204
7
2013-06-18T07:41:17Z
[ "python" ]
i know the for loop: ``` for i range(2, 6): print i ``` gives this output: ``` 2 3 4 5 ``` can i also do this somehow with letters? for example: ``` # an example for what i'm looking for for i in range(c, h): print i c d f g ```
I think it's nicer to add `1` to `ord('g')` than using `ord('h')` ``` for code in range(ord('c'), ord('g') + 1): print chr(code) ``` because what if you want to go to 'z', you need to know what follows 'z' . I bet you can type `+ 1` faster than you can look it up.
Overwritten Methods don't contain self?
17,164,028
4
2013-06-18T08:27:46Z
17,164,156
8
2013-06-18T08:33:50Z
[ "python", "python-2.7" ]
Here is an example I just played through on my machine: ``` $ python Python 2.7.4 (default, Apr 19 2013, 18:28:01) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. # just a test class >>> class A(object): ... def hi(self): ... print("hi") ... >>> a = A() >>> a.hi() ...
A method in a class referenced via an instance is bound to that instance, in your case: ``` In [3]: a.hi Out[3]: <bound method A.hi of <__main__.A object at 0x218ab10>> ``` Compare to: ``` In [4]: A.hi Out[4]: <unbound method A.hi> ``` So, to achieve the effect you probably want, do ``` In [5]: def hello(self): ...
Regex nested parenthesis in python
17,164,067
4
2013-06-18T08:29:54Z
17,164,919
8
2013-06-18T09:10:40Z
[ "python", "regex", "text" ]
I have something like this: ``` Othername California (2000) (T) (S) (ok) {state (#2.1)} ``` Is there a regex code to obtain: ``` Othername California ok 2.1 ``` I.e. I would like to keep the numbers within round parenthesis which are in turn within {} and keep the text "ok" which is within (). I specifically need t...
## Regex ``` (.+)\s+\(\d+\).+?(?:\(([^)]{2,})\)\s+(?={))?\{.+\(#(\d+\.\d+)\)\} ``` ![Regular expression image](http://www.debuggex.com/i/avRq-wTQtte7T-du.png) ## Text used for test ``` Name1 Name2 Name3 (2000) {Education (#3.2)} Name1 Name2 Name3 (2000) (ok) {edu (#1.1)} Name1 Name2 (2002) {edu (#1.1)} Name1 Name2 ...
How can I make a Django form field contain only alphanumeric characters
17,165,147
10
2013-06-18T09:22:25Z
17,165,415
22
2013-06-18T09:35:56Z
[ "python", "django" ]
I have this model ``` name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=50, unique=True) ``` I want that the user should not be able to use any other characters than alphanumerics in both fields. Is there any way?
You would use a [validator](https://docs.djangoproject.com/en/1.9/ref/validators/) to limit what the field accepts. A [`RegexValidator`](https://docs.djangoproject.com/en/1.9/ref/validators/#regexvalidator) would do the trick here: ``` alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are ...
Most efficient way of finding the next element in a tuple
17,165,167
6
2013-06-18T09:23:28Z
17,165,214
7
2013-06-18T09:25:31Z
[ "python", "tuples", "next" ]
I've got a system in which I often (but not constantly) have to find the next item in a tuple. I'm currently doing this like so: ``` mytuple = (2,6,4,8,7,9,14,3) currentelement = 4 def f(mytuple, currentelement): return mytuple[mytuple.index(currentelement) + 1] nextelement = f(mytuple, currentelement) ``` All el...
Use a dict here, dicts provide `O(1)` lookup compared to `list.index` which is an `O(N)` operation. And this will work for strings as well. ``` >>> lis = (2,6,4,8,7,9,14,3) >>> dic = dict(zip(lis, lis[1:])) >>> dic[4] 8 >>> dic[7] 9 >>> dic.get(100, 'not found') #dict.get can handle key errors 'not found' ``` A memo...
Using Pandas to create DataFrame with Series, resulting in memory error
17,165,340
9
2013-06-18T09:32:02Z
17,169,776
10
2013-06-18T13:11:22Z
[ "python", "numpy", "pandas" ]
I'm using Pandas library for remote sensing time series analysis. Eventually I would like to save my DataFrame to csv by using chunk-sizes, but I run into a little issue. My code generates 6 NumPy arrays that I convert to Pandas Series. Each of these Series contains a lot of items ``` >>> prcpSeries.shape (12626172,) ...
If you know each of these are the same length then you could create the DataFrame directly from the array and then append each column: ``` df = pd.DataFrame(prcpSeries, columns=['prcp']) df['tmax'] = tmaxSeries ... ``` --- Note: you can also use the [`to_frame`](http://pandas.pydata.org/pandas-docs/stable/generated/...
Matplotlib: show labels for minor ticks also
17,165,435
6
2013-06-18T09:37:21Z
17,167,748
10
2013-06-18T11:31:10Z
[ "python", "matplotlib", "plot", "axis-labels" ]
In `matplotlib`, when I use a `log` scale on one axis, it might happen that that axis will have **no major ticks**, **only minor** ones. So this means **no labels** are shown for the whole axis. How can I specify that I need labels also for minor ticks? I tried: ``` plt.setp(ax.get_xticklabels(minor=True), visible=T...
You can use `set_minor_tickformatter` on the corresponding axis: ``` from matplotlib import pyplot as plt from matplotlib.ticker import FormatStrFormatter axes = plt.subplot(111) axes.loglog([3,4,7], [2,3,4]) axes.xaxis.set_minor_formatter(FormatStrFormatter("%.2f")) plt.xlim(1.8, 9.2) plt.show() ``` ![enter image d...
Most efficient way of making an if-elif-elif-else statement when the else is done the most?
17,166,074
62
2013-06-18T10:05:17Z
17,166,144
63
2013-06-18T10:07:53Z
[ "python", "performance", "if-statement" ]
I've got a in if-elif-elif-else statement in which 99% of the time, the else statement is executed: ``` if something == 'this': doThis() elif something == 'that': doThat() elif something == 'there': doThere() else: doThisMostOfTheTime() ``` This construct is done **a lot**, but since it goes over ever...
I'd create a dictionary : ``` options = {'this': doThis,'that' :doThat, 'there':doThere} ``` Now use just: ``` options.get(something, doThisMostOfTheTime)() ``` If `something` is not found in the `options` dict then `dict.get` will return the default value `doThisMostOfTheTime` Some timing comparisons: Script: `...
Most efficient way of making an if-elif-elif-else statement when the else is done the most?
17,166,074
62
2013-06-18T10:05:17Z
17,166,604
58
2013-06-18T10:29:24Z
[ "python", "performance", "if-statement" ]
I've got a in if-elif-elif-else statement in which 99% of the time, the else statement is executed: ``` if something == 'this': doThis() elif something == 'that': doThat() elif something == 'there': doThere() else: doThisMostOfTheTime() ``` This construct is done **a lot**, but since it goes over ever...
The code... ``` options.get(something, doThisMostOfTheTime)() ``` ...looks like it ought to be faster, but it's actually slower than the `if` ... `elif` ... `else` construct, because it has to call a function, which can be a significant performance overhead in a tight loop. Consider these examples... **1.py** ``` ...
Summing across rows of Pandas Dataframe
17,166,601
7
2013-06-18T10:29:17Z
17,166,768
9
2013-06-18T10:37:41Z
[ "python", "pandas" ]
I have a data frame of records that looks something like this: ``` stocks = pd.Series(['A', 'A', 'B', 'C', 'C'], name = 'stock') positions = pd.Series([ 100, 200, 300, 400, 500], name = 'positions') same1 = pd.Series(['AA', 'AA', 'BB', 'CC', 'CC'], name = 'same1') same2 = pd.Series(['AAA', 'AAA', 'BBB', 'CCC', 'CCC'],...
Step 1. Use [['positions']] instead of ['positions']: ``` In [30]: df2 = df.groupby(['stock','same1','same2'])[['positions']].sum() In [31]: df2 Out[31]: positions stock same1 same2 A AA AAA 300 B BB BBB 300 C CC CCC 900 ``` Step ...
python how to "negate" value : if true return false, if false return true
17,168,046
3
2013-06-18T11:47:43Z
17,168,094
13
2013-06-18T11:49:54Z
[ "python", "boolean", "negate" ]
``` if myval == 0: nyval=1 if myval == 1: nyval=0 ``` Is there a better way to do a toggle in python, like a nyvalue = not myval ?
Use the [`not` boolean operator](http://docs.python.org/2/reference/expressions.html#boolean-operations): ``` nyval = not myval ``` `not` returns a *boolean* value (`True` or `False`): ``` >>> not 1 False >>> not 0 True ``` If you must have an integer, cast it back: ``` nyval = int(not myval) ``` However, the pyt...
python sqlite insert named parameters or null
17,169,642
8
2013-06-18T13:05:52Z
17,169,806
11
2013-06-18T13:12:33Z
[ "python", "sqlite3", "named-parameters" ]
I'm trying to insert data from a dictionary into a database using named parameters. I have this working with a simple SQL statement e.g. ``` SQL = "INSERT INTO status (location, arrival, departure) VALUES (:location, :arrival,:departure)" dict = {'location': 'somewhere', 'arrival': '1000', 'departure': '1001'} c.execu...
Use `None` to insert a `NULL`: ``` dict = {'location': 'somewhere', 'arrival': '1000', 'departure': None} ``` You can use a default dictionary and a generator to use this with `executemany()`: ``` defaults = {'location': '', 'arrival': None, 'departure': None} c.executemany(SQL, ({k: d.get(k, defaults[k]) for k in ...
Setting Transparency Based on Pixel Values in Matplotlib
17,170,229
14
2013-06-18T13:31:22Z
17,170,612
20
2013-06-18T13:46:58Z
[ "python", "matplotlib", "python-imaging-library" ]
I am attempting to use matplotlib to plot some figures for a paper I am working on. I have two sets of data in 2D numpy arrays: An ascii hillshade raster which I can happily plot and tweak using: ``` import matplotlib.pyplot as pp import numpy as np hillshade = np.genfromtxt('hs.asc', delimiter=' ', skip_header=6)[:,...
Just mask your "river" array. e.g. ``` rivers = np.ma.masked_where(rivers == 0, rivers) ``` As a quick example of overlaying two plots in this manner: ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm # Generate some data... gray_data = np.arange(10000).reshape(100, 100) masked_dat...
Setting Transparency Based on Pixel Values in Matplotlib
17,170,229
14
2013-06-18T13:31:22Z
17,178,915
8
2013-06-18T21:04:48Z
[ "python", "matplotlib", "python-imaging-library" ]
I am attempting to use matplotlib to plot some figures for a paper I am working on. I have two sets of data in 2D numpy arrays: An ascii hillshade raster which I can happily plot and tweak using: ``` import matplotlib.pyplot as pp import numpy as np hillshade = np.genfromtxt('hs.asc', delimiter=' ', skip_header=6)[:,...
An alternate way to do this with out using masked arrays is to set how the color map deals with clipping values below the minimum of `clim` (shamelessly using Joe Kington's example): ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm # Generate some data... gray_data = np.arange(10000)....
Python OpenCV load image from byte string
17,170,752
11
2013-06-18T13:52:44Z
17,170,855
26
2013-06-18T13:57:15Z
[ "python", "image", "opencv", "byte" ]
I'm trying to load image from string like as PHP function `imagecreatefromstring` How can I do that? I have MySQL blob field image. I'm using **MySQLdb** and don't want create temporary file for working with images in PyOpenCV. NOTE: need cv (not cv2) wrapper function
This is what I normally use to convert images stored in database to OpenCV images in Python. ``` import numpy as np import cv2 from cv2 import cv # Load image as string from file/database fd = open('foo.jpg') img_str = fd.read() fd.close() # CV2 nparr = np.fromstring(img_str, np.uint8) img_np = cv2.imdecode(nparr, c...
Python : split a list dynamically
17,171,823
2
2013-06-18T14:41:42Z
17,171,887
7
2013-06-18T14:44:16Z
[ "python", "python-2.7" ]
I have a list `prodemployees` that looks like this : ``` ['prd1 employe4 employe2', ' prd2 employe2'] ``` I need the values of this list to dynamically create the "where" statement of a query, I need the output to be like this : ``` WHERE (product = 'prd1' AND employe IN ('employe4','employe2')) OR (product = 'prd2'...
You have a list after splitting, you can *slice* that list to get a sublist: ``` for prod_emp in prodemployees: prod_emp = prod_emp.split() prod, emp = prod_emp[0], prod_emp[1:] ``` Here `prod` is set to the first element of your split string, `emp` to a list of all elements but the first: ``` >>> prodemploy...
Why are some Python strings are printed with quotes and some are printed without quotes?
17,171,889
6
2013-06-18T14:44:31Z
17,171,965
13
2013-06-18T14:47:54Z
[ "python", "string", "representation" ]
I have a problem with string representations. I am trying to print my object and I sometimes get single quotes in the output. Please help me to understand why it happens and how can I print out the object without quotes. Here is my code: ``` class Tree: def __init__(self, value, *children): self.value = v...
`repr` on a string gives quotes while `str` does not. e.g.: ``` >>> s = 'foo' >>> print str(s) foo >>> print repr(s) 'foo' ``` Try: ``` def __repr__(self): if len(self.children) == 0: return '%s' %self.value else: childrenStr = ' '.join(map(str, self.children)) #str, not repr! return...
Using Python's multiprocessing.Process class
17,172,878
11
2013-06-18T15:27:43Z
17,220,739
20
2013-06-20T18:09:17Z
[ "python", "class", "multiprocessing" ]
This is a newbie question: A class is an object, so I can create a class called `pippo()` and inside of this add function and parameter, I don't understand if the functions inside of `pippo` are executed from up to down when I assign `x=pippo()` or I must call them as `x.dosomething()` outside of `pippo`. Working wit...
I often wondered why Python's doc page on [multiprocessing](http://docs.python.org/2/library/multiprocessing.html) only shows the "functional" approach (using `target` parameter). Probably because terse, succinct code snippets are best for illustration purposes. For small tasks that fit in one function, I can see how t...
Is a specific timezone using DST right now?
17,173,298
6
2013-06-18T15:46:33Z
17,173,657
8
2013-06-18T16:01:18Z
[ "python", "time", "timezone", "pytz" ]
How would I get my python script to check whether or not a specific timezone that is stored in a variable using DST right now? My server is set to UTC. So I have say for instance ``` zonename = Pacific/Wallis ``` I want to run the query about if it is using DST right now and have the reply come back as either true of...
``` from pytz import timezone from datetime import datetime zonename = "Pacific/Wallis" now = datetime.now(tz=timezone(zonename)) dst_timedelta = now.dst() ### dst_timedelta is offset to the winter time, ### thus timedelta(0) for winter time and timedelta(0, 3600) for DST; ### it returns None if timezone is not set ...
Python issues with return statement
17,173,822
3
2013-06-18T16:08:52Z
17,173,844
9
2013-06-18T16:09:56Z
[ "python", "return" ]
Hello I'm very new to python and was wondering if you could help me with something. I've been playing around with this code and can't seem to get it to work. ``` import math def main(): if isPrime(2,7): print("Yes") else: print("No") def isPrime(i,n): if ((n % i == 0) and (i <= math.s...
You are discarding the return value for the recursive call: ``` def isPrime(i,n): if ((n % i == 0) and (i <= math.sqrt(n))): return False if (i >= math.sqrt(n)): print ("is Prime: ",n) return True else: # No return here isPrime(i+1,n) ``` You want to propagate the v...
Can Alembic Autogenerate column alterations?
17,174,636
10
2013-06-18T16:54:53Z
17,176,843
17
2013-06-18T19:03:41Z
[ "python", "postgresql", "sqlalchemy", "flask", "alembic" ]
I was able to use `alembic --autogenerate` for when adding / removing columns. However, when I wanted to modify for example a "url" column from 200 characters to 2000 characters, it doesn't detect the change. How can I make Alembic (using SQLAlchemy), detect changes and autogenerate scripts to my model's "sizes" of v...
Looks like I found the answer on reddit's /r/flask. <http://www.reddit.com/r/flask/comments/1glejl/alembic_autogenerate_column_changes/cale9o0> Just add "compare\_type=True" to context.configure() parameters inside your env.py's "run\_migrations\_online" function. ``` context.configure( connectio...
Can model views in Flask-Admin hyperlink to other model views?
17,174,707
13
2013-06-18T16:59:30Z
17,184,281
17
2013-06-19T06:28:40Z
[ "python", "flask" ]
Suppose we have a model, Foo, that references another model, User - and Flask-Admin views for both. On the Foo admin view page (e.g. something like the first screenshot at <http://mrjoes.github.io/2012/08/27/flask-admin-102.html> ), I would like the entries in the User column to be link to the corresponding User model...
Use `column_formatters` for this: <https://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.column_formatters> Idea is pretty simple: for a field that you want to display as hyperlink, either generate a HTML string and wrap it with Jinja2 `Markup` class (so it won't be escaped i...
Can model views in Flask-Admin hyperlink to other model views?
17,174,707
13
2013-06-18T16:59:30Z
17,191,125
25
2013-06-19T12:25:29Z
[ "python", "flask" ]
Suppose we have a model, Foo, that references another model, User - and Flask-Admin views for both. On the Foo admin view page (e.g. something like the first screenshot at <http://mrjoes.github.io/2012/08/27/flask-admin-102.html> ), I would like the entries in the User column to be link to the corresponding User model...
Some example code based on Joes' answer: ``` class MyFooView(ModelView): def _user_formatter(view, context, model, name): return Markup( "<a href='%s'>%s</a>" % ( url_for('user.edit_view', id=model.user.id), model.user ) ) if model.user else ...
Python JSON String (containing hex) to HEX
17,175,395
3
2013-06-18T17:37:37Z
17,175,426
7
2013-06-18T17:39:28Z
[ "python", "json", "string", "hex" ]
I'm trying to get random hex value between range of hexes: `random.randint(0xfff000, 0xffffff)` I got the range limits from JSON, as a string. `{"range": "0xfff000,0xffffff"}` How can I convert these strings(after splitting) to hexadecimal values?
Use the built-in [`int()`](http://docs.python.org/2/library/functions.html#int) function with a base of `16`: ``` >>> int('0xfff000', 16) 16773120 >>> int('0xfff000', 16) == 0xfff000 True ```
How can I send a message to a group conversation with Skype4Py in Python
17,176,009
4
2013-06-18T18:15:21Z
17,176,358
8
2013-06-18T18:36:33Z
[ "python", "python-2.7", "group", "sendmessage", "skype4py" ]
I've been trying to get my script to send a message to a group conversation in Skype using the Skype4Py library, the only way I am currently able to send messages is to specific users. ``` import Skype4Py Skype = Skype4Py.Skype() Skype.Attach() Skype.SendMessage('namehere','testmessage') ``` Does anyone know how I ca...
The following little script should work. (Assuming you already have a group chat open) ``` def sendGroupChatMessage(): """ Send Group Chat Messages. """ import Skype4Py as skype skypeClient = skype.Skype() skypeClient.Attach() for elem in skypeClient.ActiveChats: if len(elem.Members...
Python - get all permutation of a list w/o repetitions
17,176,887
4
2013-06-18T19:06:07Z
17,176,932
9
2013-06-18T19:08:50Z
[ "python", "list", "combinations", "permutation", "itertools" ]
I know that I can use itertools.permutation to get all permutation of size r. But, for `itertools.permutation([1,2,3,4],3)` it will return `(1,2,3)` as well as `(1,3,2)`. 1. I want to filter those repetitions (i.e obtain combinations) 2. Is there a simple way to get all permutations (of all lengths)? 3. How can I conv...
Use [`itertools.combinations`](http://docs.python.org/2/library/itertools.html#itertools.combinations) and a simple loop to get combinations of all size. `combinations` return an iterator so you've to pass it to `list()` to see it's content(or consume it). ``` >>> from itertools import combinations >>> lis = [1, 2, 3...
convert xml to python dict
17,177,109
3
2013-06-18T19:19:15Z
17,177,485
10
2013-06-18T19:40:50Z
[ "python", "xml", "parsing", "dictionary", "xml-parsing" ]
I'm trying to make a dict class to process an xml but get stuck, I really run out of ideas. If someone could guide on this subject would be great. code developed so far: ``` class XMLResponse(dict): def __init__(self, xml): self.result = True self.message = '' pass def __setattr__(sel...
You can make use of [`xmltodict`](https://github.com/martinblech/xmltodict) module: ``` import xmltodict message = """<?xml version="1.0"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>""" print xmltodict.parse(message)['note'] ``` which produces an `...
Get worker ID in Celery
17,177,491
6
2013-06-18T19:41:20Z
17,179,198
8
2013-06-18T21:22:35Z
[ "python", "celery" ]
I want to use Celery to run jobs on a GPU server with four Tesla cards. I run the Celery worker with a pool of four workers such that each card always runs one job. My problem is how to instruct the workers to each claim one GPU. Currently I rely on the assumption that the worker processes should all have contiguous p...
If you are using `CELERYD_POOL = 'processes'`, the worker pool is handled by `billiard`, which does happen to expose its 0-based process index: ``` from billiard import current_process from celery import task @task def print_info(): # This will print an int in [0..concurrency[ print current_process().index ``...
How to remove all non-integers from a string? (Python)
17,178,068
3
2013-06-18T20:15:20Z
17,178,086
11
2013-06-18T20:16:22Z
[ "python", "regex", "string" ]
I'm pretty new to python. I have a question. Say for example when I read a line from a file I have a string that looks like this. ``` thestring = '000,5\r\n' ``` How do I remove all non-integers from this string and then convert this string into an integer itself? Thanks!
Using `str.translate`, this is probably the fastest way to do this: ``` >>> strs = '000,5\r\n' >>> from string import ascii_letters, punctuation, whitespace >>> ignore = ascii_letters + punctuation + whitespace >>> strs.translate(None, ignore) '0005' ``` Using `regex`: ``` >>> import re >>> re.sub(r'[^\d]+','',s...
Python (2.7): Why is there a performance difference between the following 2 code snippets that implement the intersection of two dictionaries
17,179,351
3
2013-06-18T21:32:01Z
17,179,441
8
2013-06-18T21:37:12Z
[ "python", "performance", "python-2.7" ]
The following 2 code snippets (A & B) both return the intersection of 2 dictionaries. Both of following 2 code snippets should run in O(n) and output the same results. However code snippet B which is pythonic, seems to run faster. **These code snippets come from the Python Cookbook.** Code Snippet A: ``` def simplew...
They don't quite do the same thing; the first one does a lot more work: * It looks up the `.has_key()` and `.append()` methods each time in the loop, and then calls them. This requires a stack push and pop for each call. * It appends each new element to a list one by one. The Python list has to be grown dynamically to...
How to Swap First and Last Characters from Input in Python
17,179,584
2
2013-06-18T21:47:58Z
17,179,607
8
2013-06-18T21:49:32Z
[ "python", "python-3.x" ]
I am brand new to programming, learning Python3 from an online course. This exercise asks me to write a program which reads a string using `input()`, and outputs the same string but with the first and last character exchanged (example: Fairy becomes yairF). There is likely a simpler way to do this with more advanced fu...
Try this: ``` >>> temp = "abcde" >>> temp[1:-1] 'bcd' >>> temp[-1:] + temp[1:-1] + temp[:1] 'ebcda' >>> ``` In short, python has magnificent string slicing syntax. You can do magic with it.
Python: 'string index out of range'
17,179,808
2
2013-06-18T22:03:04Z
17,179,822
7
2013-06-18T22:04:29Z
[ "python" ]
I had a quick search but couldn't find anything that helped my problem. I'm trying to make a program that takes the first 5 numbers and sources their product, and if that product is the largest found thus far it is set as such. My code is: ``` string = str(integer) x = 0 largest = 0 stringlength = len(string) whil...
``` string = str(integer) x = 0 largest = 0 stringlength = len(string) while x < stringlength-4: # going to -5 would be out of rangue a = int(string[x]) b = int(string[x+1]) c = int(string[x+2]) d = int(string[x+3]) e = int(string[x+4]) if (a*b*c*d*e > largest): largest = a*b*c*d*e ...
Mock vs MagicMock
17,181,687
55
2013-06-19T01:49:02Z
17,182,790
25
2013-06-19T04:16:03Z
[ "python", "mocking" ]
My understanding is that *MagicMock* is a superset of *Mock* that automatically does "magic methods" thus seamlessly providing support for lists, iterations and so on... Then what is the reason for plain *Mock* existing? Isn't that just a stripped down version of *MagicMock* that can be practically ignored? Does *Mock*...
With Mock you *can* mock magic methods but you have to define them. MagicMock has ["default implementations of most of the magic methods."](http://www.voidspace.org.uk/python/mock/magicmock.html#mock.MagicMock). If you don't need to test any magic methods, Mock is adequate and doesn't bring a lot of extraneous things ...
Mock vs MagicMock
17,181,687
55
2013-06-19T01:49:02Z
23,012,876
45
2014-04-11T12:42:33Z
[ "python", "mocking" ]
My understanding is that *MagicMock* is a superset of *Mock* that automatically does "magic methods" thus seamlessly providing support for lists, iterations and so on... Then what is the reason for plain *Mock* existing? Isn't that just a stripped down version of *MagicMock* that can be practically ignored? Does *Mock*...
### What is the reason for plain *Mock* existing? Mock's author, Michael Foord, addressed [a very similar question at Pycon 2011 (31:00)](http://pyvideo.org/video/392/pycon-2011--testing-with-mock): > **Q:** Why was MagicMock made a separate thing rather than just folding the ability into the default mock object? > >...
Mock vs MagicMock
17,181,687
55
2013-06-19T01:49:02Z
27,307,550
8
2014-12-05T01:56:25Z
[ "python", "mocking" ]
My understanding is that *MagicMock* is a superset of *Mock* that automatically does "magic methods" thus seamlessly providing support for lists, iterations and so on... Then what is the reason for plain *Mock* existing? Isn't that just a stripped down version of *MagicMock* that can be practically ignored? Does *Mock*...
To begin with, `MagicMock` is a subclass of `Mock`. ``` class MagicMock(MagicMixin, Mock) ``` As a result, MagicMock provides everything that Mock provides and more. Rather than thinking of Mock as being a stripped down version of MagicMock, think of MagicMock as an extended version of Mock. This should address your ...
How do I iterate through the alphabet in Python, Please?
17,182,656
24
2013-06-19T03:59:17Z
17,182,670
43
2013-06-19T04:00:45Z
[ "python", "python-2.7", "alphabet" ]
Can I simply ++ a char? what is an efficient way of doing this? I want to iterate through urls that have the www.website.com/term/#, www.website.com/term/a, www.website.com/term/b, www.website.com/term/c, www.website.com/term/d ... www.website.com/term/z format
You can use [`string.ascii_lowercase`](http://docs.python.org/2/library/string.html#string.ascii_lowercase) which is simply a convenience string of lowercase letters, ``` >>> from string import ascii_lowercase >>> for c in ascii_lowercase: ... # append to your url ```
How do I iterate through the alphabet in Python, Please?
17,182,656
24
2013-06-19T03:59:17Z
17,182,751
11
2013-06-19T04:10:21Z
[ "python", "python-2.7", "alphabet" ]
Can I simply ++ a char? what is an efficient way of doing this? I want to iterate through urls that have the www.website.com/term/#, www.website.com/term/a, www.website.com/term/b, www.website.com/term/c, www.website.com/term/d ... www.website.com/term/z format
In addition to `string.ascii_lowercase` you should also take a look at the [`ord`](http://docs.python.org/2/library/functions.html#ord) and [`chr`](http://docs.python.org/2/library/functions.html#chr) built-ins. `ord('a')` will give you the ascii value for 'a' and `chr(ord('a'))` will give you the character back. Usin...
SCons- *** No SConstruct file found
17,182,799
3
2013-06-19T04:17:03Z
17,185,787
8
2013-06-19T07:53:35Z
[ "python", "scons" ]
Installed SCons using # cd scons-2.3.0 # python setup.py install After Installation, when i try to run scons , got the below error. scons: *\** No SConstruct file found. File "/usr/local/lib/scons-2.3.0/SCons/Script/Main.py", line 905, in \_main How to overcome this ???
There are 3 ways to specify the SConstruct file when using SCons, as follows: * Execute `scons` from the root of the project, where there should be a SConstruct file. This is the most standard way. * From a subdirectory of the project, where there should be a SConsctruct file at the root, execute `scons` with one of t...
Python repeat string
17,183,259
12
2013-06-19T05:07:38Z
17,183,278
24
2013-06-19T05:09:06Z
[ "python" ]
I am trying string repetition in Python. ``` #!/bin/python str = 'Hello There' print str[:5]*2 ``` **Output** > HelloHello **Required Output** > Hello Hello Can anyone please point me in the right direction . Python version: 2.6.4
``` string = 'Hello There' print ' '.join([string[:5]] * 2) ```
how to remove task from celery with redis broker?
17,184,244
4
2013-06-19T06:25:14Z
17,250,543
13
2013-06-22T12:07:57Z
[ "python", "celery", "celery-task", "celeryd" ]
I Have add some wrong `task` to a `celery` with redis `broker` but now I want to remove the incorrect `task` and I can't find any way to do this Is there some commands or some api to do this ?
I know two ways of doing so: 1) Delete queue directly from broker. In your case it's Redis. There are two commands that could help you: **llen** (to find right queue) and **del** (to delete it). 2) Start celery worker with **--purge** or **--discard** options. Here is help: ``` --purge, --discard Purges all waiti...
Python: get a checkbox - the easiest way
17,185,134
9
2013-06-19T07:19:58Z
17,186,472
7
2013-06-19T08:30:53Z
[ "python", "user-interface", "tkinter" ]
or perhaps the lazy way.. I'm looking for a python module that has some build-in GUI methods to get quick user inputs - a very common programming case. Has to work on windows 7 **My ideal case** ``` import magicGUImodule listOfOptions = ["option 1", "option 2", "option 3"] choosenOptions = magicGUImodule.getChecklis...
Here's a simple example using `Tkinter` (instead of checkboxes `listbox` with multiple selection is used): ``` from Tkinter import * def callback(): print listbox.selection_get() master.destroy() master = Tk() listbox = Listbox(master, selectmode=MULTIPLE) for option in ["option 1", "option 2", "option 3"...
Python: get a checkbox - the easiest way
17,185,134
9
2013-06-19T07:19:58Z
17,330,144
7
2013-06-26T20:46:18Z
[ "python", "user-interface", "tkinter" ]
or perhaps the lazy way.. I'm looking for a python module that has some build-in GUI methods to get quick user inputs - a very common programming case. Has to work on windows 7 **My ideal case** ``` import magicGUImodule listOfOptions = ["option 1", "option 2", "option 3"] choosenOptions = magicGUImodule.getChecklis...
[Easygui](http://easygui.sourceforge.net/) module is **exactly** what you need: ``` import easygui as eg question = "This is your question" title = "This is your window title" listOfOptions = ["option 1", "option 2", "option 3"] choice = eg.multchoicebox(question , title, listOfOptions) ``` `choice` will return a l...
How to run Ansible without specifying the inventory but the host directly?
17,188,147
25
2013-06-19T09:50:23Z
18,255,256
58
2013-08-15T14:48:10Z
[ "python", "ansible" ]
I want to run Ansible in Python without specifying the inventory file through (ANSIBLE\_HOST) but just by: ``` ansible.run.Runner( module_name='ping', host='www.google.com' ) ``` I can actually do this in fabric easily but just wonder how to do this in Python. On the other hand, documentation of the Ansible API f...
Surprisingly, the trick is to append a `,` ``` # Host and IP address ansible all -i example.com, ansible all -i 93.184.216.119, ``` or ``` # Requires 'hosts: all' in your playbook ansible-playbook -i example.com, playbook.yml ``` The host parameter preceding the `,` can be either a hostname or an IPv4/v6 address.
How to run Ansible without specifying the inventory but the host directly?
17,188,147
25
2013-06-19T09:50:23Z
29,315,404
11
2015-03-28T09:07:55Z
[ "python", "ansible" ]
I want to run Ansible in Python without specifying the inventory file through (ANSIBLE\_HOST) but just by: ``` ansible.run.Runner( module_name='ping', host='www.google.com' ) ``` I can actually do this in fabric easily but just wonder how to do this in Python. On the other hand, documentation of the Ansible API f...
I know this question is really old but think that this little trick might helpful for future users who need help for this: ``` ansible-playbook -i '10.254.3.133,' site.yml ``` if you run for local host: ``` ansible-playbook -i 'localhost,' --connection=local site.yml ``` The trick is that after ip address/dns name,...
Subprocess.Popen: cloning stdout and stderr both to terminal and variables
17,190,221
6
2013-06-19T11:38:25Z
17,190,793
8
2013-06-19T12:08:56Z
[ "python", "python-3.x", "subprocess", "popen" ]
Is it possible to modify code below to have printout from 'stdout 'and 'stderr': * printed on the **terminal** (in real time), * and finally stored in **outs** and **errs** variables? The code: ``` #!/usr/bin/python3 # -*- coding: utf-8 -*- import subprocess def run_cmd(command, cwd=None): p = subprocess.Popen...
You could spawn threads to read the stdout and stderr pipes, write to a common queue, and append to lists. Then use a third thread to print items from the queue. ``` import time import Queue import sys import threading import subprocess PIPE = subprocess.PIPE def read_output(pipe, funcs): for line in iter(pipe.r...
Subprocess.Popen: cloning stdout and stderr both to terminal and variables
17,190,221
6
2013-06-19T11:38:25Z
25,960,956
10
2014-09-21T15:49:11Z
[ "python", "python-3.x", "subprocess", "popen" ]
Is it possible to modify code below to have printout from 'stdout 'and 'stderr': * printed on the **terminal** (in real time), * and finally stored in **outs** and **errs** variables? The code: ``` #!/usr/bin/python3 # -*- coding: utf-8 -*- import subprocess def run_cmd(command, cwd=None): p = subprocess.Popen...
To capture and display at the same time both stdout and stderr from a child process line by line in a single thread, you could use asynchronous I/O: ``` #!/usr/bin/env python3 import asyncio import os import sys from asyncio.subprocess import PIPE @asyncio.coroutine def read_stream_and_display(stream, display): "...
How to obtain a gaussian filter in python
17,190,649
8
2013-06-19T12:00:29Z
17,201,686
14
2013-06-19T21:27:45Z
[ "python", "matlab", "numpy", "gaussian" ]
I am using python to create a gaussian filter of size 5x5. I saw this post [here](http://stackoverflow.com/questions/11209115/creating-gaussian-filter-of-required-length-in-python) where they talk about a similar thing but I didn't find the exact way to get equivalent python code to matlab function `fspecial('gaussian'...
In general terms if you really care about getting the the exact same result as MATLAB, the easiest way to achieve this is often by looking directly at the source of the MATLAB function. In this case, `edit fspecial`: ``` ... case 'gaussian' % Gaussian filter siz = (p2-1)/2; std = p3; [x,y] = me...
Google Appengine NDB ancestor vs key query
17,191,471
9
2013-06-19T12:41:10Z
17,192,111
11
2013-06-19T13:11:04Z
[ "python", "google-app-engine", "app-engine-ndb" ]
I am storing a key of an entity as a property of another in order to relate them. We are in a refactor stage at this point in the project so I was thinking about introducing ancestors. Is there a performance difference between the two approaches? Any given advantages that I might gain if we introduce ancestors? ``` cl...
The ancestor query will always be fully consistent. Querying by `book_key`, on the other hand, will not necessarily be consistent: you may find that recent changes will not be shown in that query. On the other hand, introducing an ancestor imposes a limit on the number of updates: you can only do one update per second...
NameError: global name 'xrange' is not defined in Python 3
17,192,158
54
2013-06-19T13:13:04Z
17,192,181
100
2013-06-19T13:14:02Z
[ "python", "python-3.x", "range", "runtimeexception", "xrange" ]
I am getting an error when running a python program: ``` Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 110, in <module> File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 27, in __init__ File "C:\Program Files...
You are trying to run a Python 2 codebase with Python 3. `xrange()` was renamed to `range()` in Python 3. Run the game with Python 2 instead. Don't try to port it unless you know what you are doing, most likely there will be more problems beyond `xrange()` vs. `range()`. For the record, what you are seeing is not a s...
hash function in python
17,192,418
10
2013-06-19T13:24:51Z
17,192,658
17
2013-06-19T13:34:47Z
[ "python", "hash", "sl4a" ]
I believed that `hash()` function works the same in all python interpreters. But it differs when I run it on my mobile using [python for android](https://code.google.com/p/python-for-android/). I get same hash value for hashing strings and numbers but when I hash built-in data types the hash value differs. **PC Python...
`hash()` is randomised by default each time you start a new instance of recent versions (Python3.3+) to [prevent dictionary insertion DOS attacks](http://mail.python.org/pipermail/python-announce-list/2012-March/009394.html) Prior to that, `hash()` was different for 32bit and 64bit builds anyway. If you want somethin...
How to get column by number in Pandas?
17,193,850
7
2013-06-19T14:24:22Z
17,194,149
9
2013-06-19T14:37:41Z
[ "python", "pandas" ]
What's the difference between: ``` Maand['P_Sanyo_Gesloten'] Out[119]: Time 2012-08-01 00:00:11 0 2012-08-01 00:05:10 0 2012-08-01 00:10:11 0 2012-08-01 00:20:10 0 2012-08-01 00:25:10 0 2012-08-01 00:30:09 0 2012-08-01 00:40:10 0 2012-08-01 00:50:09 0 2012-08-01 01:05:10 0 2012-08-01 01:10:...
One is a column (aka Series), while the other is a DataFrame: ``` In [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b']) In [2]: df Out[2]: a b 0 1 2 1 3 4 ``` The column 'b' (aka Series): ``` In [3]: df['b'] Out[3]: 0 2 1 4 Name: b, dtype: int64 ``` The subdataframe with columns (position) in...
Is there any way to show the dependency trees for pip packages?
17,194,301
12
2013-06-19T14:44:50Z
24,903,067
25
2014-07-23T06:10:38Z
[ "python", "pip", "requirements", "requirements.txt" ]
I have a project with multiple package dependencies, the main requirements being listed in `requirements.txt`. When I call `pip freeze` it prints the currently installed packages as plain list. I would prefer to also get their dependency relationships, something like this: ``` Flask==0.9 Jinja2==2.7 Werkzeug==...
You should take a look at [`pipdeptree`](https://pypi.python.org/pypi/pipdeptree/0.3): ``` $ pip install pipdeptree $ pipdeptree -fl Warning!!! Cyclic dependencies found: ------------------------------------------------------------------------ xlwt==0.7.5 ruamel.ext.rtf==0.1.1 xlrd==0.9.3 openpyxl==2.0.4 - jdcal==1....
Using a variable in a try,catch,finally statement without declaring it outside
17,195,569
14
2013-06-19T15:42:21Z
17,195,686
26
2013-06-19T15:48:45Z
[ "python", "scope" ]
I'm pretty new to Python, here is some code I am looking at: ``` try: connection = getConnection(database) cursor = connection.cursor() cursor.execute("some query") except: log.error("Problem.") raise finally: cursor.close() connection.close() ``` Is that being cleaned up properly? In othe...
Python does not have block scope. Anything defined inside the `try` block will be available outside. That said, you would still have a problem: if it is the `getConnection()` call that raises the error, `cursor` will be undefined, so the reference in the `finally` block will error.
Python equivalent of unix "strings" utility
17,195,924
6
2013-06-19T15:59:56Z
17,197,027
7
2013-06-19T16:55:46Z
[ "python", "string", "executable" ]
I'm trying to write a script which will extract strings from an executable binary and save them in a file. Having this file be newline-separated isn't an option since the strings could have newlines themselves. This also means, however, that using the unix "strings" utility isn't an option, since it just prints out all...
Here's a generator that yields all the strings of printable characters >= `min` (4 by default) in length that it finds in `filename`: ``` import string def strings(filename, min=4): with open(filename, errors="ignore") as f: # Python 3.x # with open(filename, "rb") as f: # Python 2.x result...
Extracting table contents from html with python and BeautifulSoup
17,196,018
3
2013-06-19T16:04:56Z
17,196,799
11
2013-06-19T16:43:55Z
[ "python", "beautifulsoup", "screen-scraping" ]
I want to extract certain information out of an html document. E.g. it contains a table (among other tables with other contents) like this: ``` <table class="details"> <tr> <th>Advisory:</th> <td>RHBA-2013:0947-1</td> </tr> <tr> ...
``` >>> from bs4 import BeautifulSoup >>> soup = BeautifulSoup(unicodestring_containing_the_entire_htlm_doc) >>> table = soup.find('table', {'class': 'details'}) >>> th = table.find('th', text='Issued on:') >>> th <th>Issued on:</th> >>> td = th.findNext('td') >>> td <td>2013-06-13</td> >>> td.text u'2013-06-13' ```
Root mean square error in python
17,197,492
24
2013-06-19T17:24:10Z
17,221,808
12
2013-06-20T19:08:39Z
[ "python", "scipy" ]
I know I could implement a root mean squared error function like this: ``` def rmse(predictions, targets): return np.sqrt(((predictions - targets) ** 2).mean()) ``` What I'm looking for if this rmse function is implemented in a library somewhere, perhaps in scipy or scikit-learn?
This is probably faster?: ``` n = len(predictions) rmse = np.linalg.norm(predictions - targets) / np.sqrt(n) ```
Root mean square error in python
17,197,492
24
2013-06-19T17:24:10Z
18,623,635
35
2013-09-04T20:56:57Z
[ "python", "scipy" ]
I know I could implement a root mean squared error function like this: ``` def rmse(predictions, targets): return np.sqrt(((predictions - targets) ** 2).mean()) ``` What I'm looking for if this rmse function is implemented in a library somewhere, perhaps in scipy or scikit-learn?
`sklearn.metrics` has a `mean_squared_error` function. The RMSE is just the square root of whatever it returns. ``` from sklearn.metrics import mean_squared_error from math import sqrt rms = sqrt(mean_squared_error(y_actual, y_predicted)) ```
Is it possible to overload the multiple comparison syntax in python?
17,197,953
8
2013-06-19T17:51:53Z
17,198,023
14
2013-06-19T17:54:51Z
[ "python" ]
I'm wondering if it's possible to overload the multiple comparison syntax in python: ``` a < b < c ``` I know it's possible to overload single comparisons, is it possible to overload these?
Internally it is handled as `a < b and b < c`, so you need to overload only `__lt__`, `__gt__`, etc. From the [docs](http://docs.python.org/2/reference/expressions.html#not-in): > x < y <= z is equivalent to x < y and y <= z, except that y is > evaluated only once (but in both cases z is not evaluated at all when > x...
2D lists generation Python
17,198,414
2
2013-06-19T18:15:13Z
17,198,447
9
2013-06-19T18:16:50Z
[ "python", "list", "loops" ]
I know that to generate a list in Python you can use something like: ``` l = [i**2 for i in range(5)] ``` instead of using for loop like: ``` l = [] for i in range(5): l.append(i**5) ``` Is there a way to do 2D lists without using for loops like this: ``` map = [[]] for x in range(10): row = [] for y ...
Use a list comprehension here too: ``` >>> [ [(x+y)**2 for y in range(10)] for x in range(10)] [[0, 1, 4, 9, 16, 25, 36, 49, 64, 81], [1, 4, 9, 16, 25, 36, 49, 64, 81, 100], [4, 9, 16, 25, 36, 49, 64, 81, 100, 121], [9, 16, 25, 36, 49, 64, 81, 100, 121, 144], [16, 25, 36, 49, 64, 81, 100, 121, 144, 169], [25, 36, 49, ...
None Python error/bug?
17,198,466
15
2013-06-19T18:18:38Z
17,198,511
21
2013-06-19T18:20:45Z
[ "python", "python-2.7", "python-3.x", "types" ]
In Python you have the `None` singleton, which acts pretty oddly in certain circumstances: ``` >>> a = None >>> type(a) <type 'NoneType'> >>> isinstance(a,None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types ``...
You can try: ``` >>> variable = None >>> isinstance(variable,type(None)) True >>> variable = True >>> isinstance(variable,type(None)) False ``` [isinstance](http://docs.python.org/2/library/functions.html#isinstance) takes 2 arguments `isinstance(object, classinfo)` Here, by passing `None` you are setting `classinfo`...
None Python error/bug?
17,198,466
15
2013-06-19T18:18:38Z
17,198,512
18
2013-06-19T18:20:45Z
[ "python", "python-2.7", "python-3.x", "types" ]
In Python you have the `None` singleton, which acts pretty oddly in certain circumstances: ``` >>> a = None >>> type(a) <type 'NoneType'> >>> isinstance(a,None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types ``...
`None` is not a type, it is the singleton instance itself - and the second argument of [`isinstance`](http://docs.python.org/2/library/functions.html#isinstance) must be a type, class or tuple of them. Hence, you need to use `NoneType` from [`types`](http://docs.python.org/2/library/types.html). ``` from types import ...
psycopg2 leaking memory after large query
17,199,113
10
2013-06-19T18:55:55Z
17,203,872
9
2013-06-20T01:20:53Z
[ "python", "postgresql", "psycopg2" ]
I'm running a large query in a python script against my postgres database using psycopg2 (I upgraded to version 2.5). After the query is finished, I close the cursor and connection, and even run gc, but the process still consumes a ton of memory (7.3gb to be exact). Am I missing a cleanup step? ``` import psycopg2 con...
Please see the *next answer* by @joeblog for the better solution. --- First, you shouldn't need all that RAM in the first place. What you should be doing here is fetching *chunks* of the result set. Don't do a `fetchall()`. Instead, use the much more efficient `cursor.fetchmany` method. See [the psycopg2 documentatio...
psycopg2 leaking memory after large query
17,199,113
10
2013-06-19T18:55:55Z
27,940,340
19
2015-01-14T10:08:11Z
[ "python", "postgresql", "psycopg2" ]
I'm running a large query in a python script against my postgres database using psycopg2 (I upgraded to version 2.5). After the query is finished, I close the cursor and connection, and even run gc, but the process still consumes a ton of memory (7.3gb to be exact). Am I missing a cleanup step? ``` import psycopg2 con...
I ran into a similar problem and after a couple of hours of blood, sweat and tears, found the answer simply requires the addition of one parameter. Instead of ``` cursor = conn.cursor() ``` write ``` cursor = conn.cursor(name="my_cursor_name") ``` or simpler yet ``` cursor = conn.cursor("my_cursor_name") ``` The...
Scrapy Vs Nutch
17,199,457
11
2013-06-19T19:14:32Z
17,200,157
16
2013-06-19T19:55:52Z
[ "python", "solr", "web-scraping", "scrapy", "web-crawler" ]
I am planning to use webcrawling in an application i am currently working on. I did some research on Nutch and run some preliminary test using it. But then i came across scrapy. But when i did some preliminary research and went through the documentation about scrapy i found that it can capture only structed data (You h...
`Scrapy` would work perfectly in your case. You are not required to give divs names - you can get anything you want: > Scrapy comes with its own mechanism for extracting data. They’re > called XPath selectors (or just “selectors”, for short) because they > “select” certain parts of the HTML document specifi...
how to use the href attribute in django templates
17,200,389
3
2013-06-19T20:11:22Z
17,200,402
9
2013-06-19T20:12:10Z
[ "python", "django", "url", "href" ]
When I try to use a link in my Django template from `/appname/index/` to get to `/appname/detail/###` I am instead getting to `/appname/index/detail/###` which is not what I'm trying to get so my app can't find it in the urlconf of course. First the urls.py line for the detail page ``` url(r'detail/(?P<jobID>\d+)/$',...
Add `/` at start in `href`: ``` <a href="/appname/detail/{{ job.id }}/">{{ job.name }}</a> ``` And for the `url` tag to work you need to do it like this: ``` <a href="{% url 'appname.views.detail' jobID=job.id %}">{{ job.name }}</a> ```
A logarithmic colorbar in matplotlib scatter plot
17,201,172
30
2013-06-19T20:56:46Z
17,202,196
39
2013-06-19T22:06:07Z
[ "python", "matplotlib" ]
I would like to make the colors of the points on the scatter plot correspond to the value of the void fraction, but on a logarithmic scale to amplify differences. I did this, but now when I do plt.colorbar(), it displays the log of the void fraction, when I really want the actual void fraction. How can I make a log sca...
There is now a section of the documentation describing [how color mapping and normalization works](http://matplotlib.org/devdocs/users/colormapnorms.html) (that is a link to the development documentation, but applies to all versions of mpl. It will be in the mainline documentation 'soon') The way that `matplotlib` doe...
Alembic autogenerates empty Flask-SQLAlchemy migrations
17,201,800
8
2013-06-19T21:35:54Z
17,302,718
19
2013-06-25T16:30:14Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy", "alembic" ]
I'm using Alembic to handle migrations for Flask. `alembic revision --autogenerate` should, in theory, autogenerate a migration based on changes in my database. However, Alembic is simply generating a blank migration with the above command. There's a [question very similar to this one](http://stackoverflow.com/questio...
Here is how I use Alembic with Flask and blueprints. <https://github.com/davidism/basic_flask> I use the application factory pattern and call `db.init_app` within that. After `db = SQLAlchemy()` I import all models that will subclass `db.Model` so that `db.metadata` is aware of them; note this is not done in the `cre...
Can you search backwards from an offset using a Python regular expression?
17,203,604
8
2013-06-20T00:42:12Z
17,203,696
7
2013-06-20T00:56:13Z
[ "python", "regex", "python-2.7" ]
Given a string, and a character offset within that string, can I search backwards using a Python regular expression? The actual problem I'm trying to solve is to get a matching phrase at a particular offset within a string, but I have to match the first instance before that offset. In a situation where I have a regex...
Using positive lookbehind to make sure there are at least 30 characters before a word: ``` # re like: r'.*?(\w+)(?<=.{30})' m = re.match(r'.*?(\w+)(?<=.{%d})' % (offset), my_string) if m: print m.group(1) else: print "no match" ``` For the other example negative lookbehind may help: ``` my_new_string = "Looking feed...
python ftplib specify port
17,204,276
8
2013-06-20T02:15:09Z
17,204,306
10
2013-06-20T02:19:13Z
[ "python", "ftp", "ftplib" ]
I would like to specify the port with python's ftplib client (instead of default port 21). Here is the code: ``` from ftplib import FTP ftp = FTP('localhost') # connect to host, default port ``` Is there an easy way to specify an alternative port?
``` >>> from ftplib import FTP >>> HOST = "localhost" >>> PORT = 12345 # Set your desired port number >>> ftp = FTP() >>> ftp.connect(HOST, PORT) ```
What is {!text!} in Python?
17,204,864
2
2013-06-20T03:39:07Z
17,204,928
8
2013-06-20T03:46:23Z
[ "python" ]
What do {!info!} and {!input!} do in this python code? ``` s += " {!info!}Down Speed: {!input!}%s" % common.fspeed(status["download_payload_rate"]) ``` Taken from: <http://git.deluge-torrent.org/deluge/tree/deluge/ui/console/commands/info.py?h=1.3-stable> Thanks.
They don't mean anything to Python. The string `s` will literally contain `{!info!}`and `{!input!}`. However, that string is later interpreted by Deluge itself to do color formatting — see [ui/console/colors.py](http://git.deluge-torrent.org/deluge/tree/deluge/ui/console/colors.py?h=1.3-stable), specifically `parse_c...
AttributeError: 'NoneType' object has no attribute 'app'
17,206,728
3
2013-06-20T06:31:44Z
17,209,173
7
2013-06-20T08:48:01Z
[ "python", "flask", "xhtml2pdf" ]
The below code gives error: ``` Traceback (most recent call last): File "pdf.py", line 14, in <module> create_pdf(render_template('templates.htm')) File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 123, in render_template ctx.app.update_template_context(context) AttributeError: 'NoneT...
Flask does a whole lot of 'magic' so you don't have to worry about routing or parsing requests. When a Flask application receives a request, it creates a 'context' object before delegating the logic to your view function. In your code, you are calling `render_template` directly without going through Flask, so the cont...
What could be the reason for a socket error "[Errno 9] Bad file descriptor"
17,207,051
5
2013-06-20T06:53:23Z
17,207,158
18
2013-06-20T06:58:38Z
[ "python", "sockets", "python-2.7" ]
I have a complex python (2.7.3) script which is trying to open a socket connection via ``` self.socket.close() # doing something else self.socket.connect((host, port)) ``` but all I get is the following socket error: ``` error: [Errno 9] Bad file descriptor ``` The `host:port` accepts connections as I have verified...
You will need to create a new socket object. Maybe `self.socket = socket.socket()` after closing the previous socket and before connecting.
How to find out where a Python Warning is from
17,208,567
8
2013-06-20T08:15:00Z
17,211,698
7
2013-06-20T10:48:35Z
[ "python", "debugging", "warnings", "pandas" ]
I'm still kinda new with Python, using Pandas, and I've got some issues debugging my Python script. I've got the following warning message : ``` [...]\pandas\core\index.py:756: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal return self._engine...
You can [filter the warnings](http://docs.python.org/2/library/warnings.html#the-warnings-filter) to raise which will enable you to debug (e.g. using pdb): ``` import warnings warnings.filterwarnings('error') ``` \*The [warnings filter](http://docs.python.org/2/library/warnings.html#warnings.filterwarnings) can be ma...
Python: subplot within a loop: first panel appears in wrong position
17,210,646
5
2013-06-20T09:54:26Z
17,211,410
11
2013-06-20T10:34:34Z
[ "python", "matplotlib", "subplot" ]
I am fairly new to Python and come from a more Matlab point of view. I am trying to make a series of 2 x 5 panel contourf subplots. My approach so far has been to convert (to a certain degree) my Matlab code to Python and plot my subplots within a loop. The relavent part of the code looks like this: ``` fig=plt.figure...
Using your code with some random data, this would work: ``` fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k') fig.subplots_adjust(hspace = .5, wspace=.001) axs = axs.ravel() for i in range(10): axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges) axs[i].set_title(str(250+i)...
pip: upgrade package without upgrading particular dependency
17,210,896
5
2013-06-20T10:06:39Z
27,782,019
12
2015-01-05T14:53:32Z
[ "python", "django", "pip" ]
My question is very much similar to [this](http://stackoverflow.com/questions/2861183/pip-upgrade-package-without-upgrading-dependencies) question. But It differs in a way that if i am installing some package i only want to disable upgrade for a particular dependency not for all dependencies. I know there is a flag `--...
This works and lets you be more precise: ``` pip install -U django-rosetta Django==1.4 ```
How to temporarily modify sys.path in Python?
17,211,078
10
2013-06-20T10:16:01Z
17,211,123
8
2013-06-20T10:19:08Z
[ "python", "python-import" ]
In one of my testing scripts in Python I use this pattern several times: ``` sys.path.insert(0, "somedir") mod = __import__(mymod) sys.path.pop(0) ``` Is there a more concise way to temporarily modify the search path?
Appending a value to `sys.path` only modifies it temporarily, i.e for that session only. Permanent modifications are done by changing `PYTHONPATH` and the default installation directory. So, if by temporary you meant for current session only then your approach is okay, but you can remove the `pop` part if `somedir` i...
How to create a timer on python
17,211,188
2
2013-06-20T10:22:30Z
17,211,208
10
2013-06-20T10:23:46Z
[ "python" ]
I am creating a code that requires the program to time how long it runs for and then displays the time. it is basically a timer that runs in the background and I can call upon it to display how long the code has been running for. How do I do this?
You record the start time, then later on calculate the difference between that start time and the current time. Due to platform differences, for precision you want to use the [`timeit.default_timer` callable](http://docs.python.org/2/library/timeit.html#timeit.default_timer): ``` from timeit import default_timer sta...
How can I consume tweets from Twitter's streaming api and store them in mongodb
17,213,991
18
2013-06-20T12:45:27Z
17,231,813
14
2013-06-21T09:27:54Z
[ "python", "mongodb", "twitter", "pymongo", "tweepy" ]
I need to develop an app that lets me track tweets and save them in a mongodb for a research project (as you might gather, I am a noob, so please bear with me). I have found this piece of code that sends tweets streaming through my terminal window: ``` import sys import tweepy consumer_key="" consumer_secret="" acces...
Here's an example: ``` import json import pymongo import tweepy consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) class CustomStreamListener(tweepy.StreamListene...
python format string unused named arguments
17,215,400
14
2013-06-20T13:50:18Z
17,215,533
34
2013-06-20T13:55:49Z
[ "python", "string", "string-formatting" ]
Let's say I have: ``` action = '{bond}, {james} {bond}'.format(bond='bond', james='james') ``` this wil output: ``` 'bond, james bond' ``` Next we have: ``` action = '{bond}, {james} {bond}'.format(bond='bond') ``` this will output: ``` KeyError: 'james' ``` Is there some workaround to prevent this error to ha...
## If you are using Python 3.2+, use can use [str.format\_map()](http://docs.python.org/3/library/stdtypes.html#str.format_map). For `bond, bond`: ``` >>> from collections import defaultdict >>> '{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond')) 'bond, bond' ``` For `bond, {james} bond`: ``` >>> cl...