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
Easier way to enable verbose logging
14,097,061
21
2012-12-31T03:19:20Z
28,611,921
15
2015-02-19T16:42:19Z
[ "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) ...
Here is a more concise method, that does bounds checking, and will list valid values in help: ``` parser = argparse.ArgumentParser(description='This is a demo.') parser.add_argument("-l", "--log", dest="logLevel", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help="Set the logging level") args = parser.p...
Concatenating two range function results
14,099,872
12
2012-12-31T09:34:12Z
14,099,894
19
2012-12-31T09:36:22Z
[ "python", "python-3.x", "range", "concatenation" ]
Does range function allows concatenation ? Like i want to make a `range(30)` & concatenate it with `range(2000, 5002)`. So my concatenated range will be `0, 1, 2, ... 29, 2000, 2001, ... 5001` Code like this does not work on my latest python (ver: 3.3.0) ``` range(30) + range(2000, 5002) ```
You can use [`itertools.chain`](http://docs.python.org/3/library/itertools.html#itertools.chain) for this: ``` from itertools import chain concatenated = chain(range(30), range(2000, 5002)) for i in concatenated: ... ``` It works for arbitrary iterables. Note that there's a difference in behavior of [`range()`](...
Concatenating two range function results
14,099,872
12
2012-12-31T09:34:12Z
14,100,069
13
2012-12-31T09:52:18Z
[ "python", "python-3.x", "range", "concatenation" ]
Does range function allows concatenation ? Like i want to make a `range(30)` & concatenate it with `range(2000, 5002)`. So my concatenated range will be `0, 1, 2, ... 29, 2000, 2001, ... 5001` Code like this does not work on my latest python (ver: 3.3.0) ``` range(30) + range(2000, 5002) ```
Can be done using [list-comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions). ``` >>> [i for j in (range(10), range(15, 20)) for i in j] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 16, 17, 18, 19] ``` Works for your request, but it is a long answer so I will not post it here. note: can be...
Formatting a date with Mako templates
14,101,045
5
2012-12-31T11:35:16Z
14,101,090
10
2012-12-31T11:38:57Z
[ "python", "pyramid", "mako" ]
In my mako template I have: ``` <p>${item.addDate}</p> ``` It returns: > 2012-12-27 19:50:00 but I would like to get: > 27/12/2012 19:50 Have mako any nifty filters, format functions?
According to [google](https://github.com/ralsina/nikola/issues/101), `strftime` should do the job: ``` ${post.date.strftime('%Y/%m/%d %H:%M') ``` Also, according to google: ``` <%! from time import strftime as time %> It is the ${"%d of %B" | time} ```
Pandas column addition/subtraction
14,102,195
9
2012-12-31T13:28:27Z
14,102,891
13
2012-12-31T14:41:17Z
[ "python", "pandas" ]
I am using a pandas/python dataframe. I am trying to do a lag subtraction. I am currently using: ``` newCol = df.col - df.col.shift() ``` This leads to a NaN in the first spot: ``` NaN 45 63 23 ... ``` First question: Is this the best way to do a subtraction like this? Second: If I want to add a column (same numb...
I think your method of of computing lags is just fine: ``` import pandas as pd df = pd.DataFrame(range(4), columns = ['col']) print(df['col'] - df['col'].shift()) # 0 NaN # 1 1 # 2 1 # 3 1 # Name: col print(df['col'] + df['col'].shift()) # 0 NaN # 1 1 # 2 3 # 3 5 # Name: col ``` If you w...
Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol
14,102,416
42
2012-12-31T13:51:58Z
14,146,031
33
2013-01-03T19:45:42Z
[ "python", "openssl", "httprequest", "python-requests", "ubuntu-12.10" ]
I'm on Ubuntu 12.10 with OpenSSL 1.0.1c, python 2.7.3, [Requests](http://www.python-requests.org/en/latest/) 1.0.3 and 1.0.4 (tried both), and when attempting to connect to the website in the url variable with the following code. ``` def SendInitialRequest(xmlmessage, redirecturl): url = 'https://centineltest.card...
Reposting this here for others from [the requests issue page](https://github.com/kennethreitz/requests/issues/1083#issuecomment-11853729): Requests' does not support doing this before version 1. Subsequent to version 1, you are expected to subclass the HTTPAdapter, like so: ``` from requests.adapters import HTTPAdapt...
Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol
14,102,416
42
2012-12-31T13:51:58Z
24,166,498
28
2014-06-11T15:10:55Z
[ "python", "openssl", "httprequest", "python-requests", "ubuntu-12.10" ]
I'm on Ubuntu 12.10 with OpenSSL 1.0.1c, python 2.7.3, [Requests](http://www.python-requests.org/en/latest/) 1.0.3 and 1.0.4 (tried both), and when attempting to connect to the website in the url variable with the following code. ``` def SendInitialRequest(xmlmessage, redirecturl): url = 'https://centineltest.card...
Setting verify=False only skips verifying the server certificate, but will not help to resolve SSL protocol errors. This issue is likely due to SSLv2 being disabled on the web server, but Python 2.x tries to establish a connection with PROTOCOL\_SSLv23 by default. This happens at <https://github.com/python/cpython/blo...
There's one line of Reddit's code (the ranking feature) made me confused
14,102,819
3
2012-12-31T14:34:58Z
14,102,882
7
2012-12-31T14:40:13Z
[ "python", "reddit" ]
The code is from this page: <https://github.com/reddit/reddit/blob/master/r2/r2/lib/db/_sorts.pyx> Here is the code snippet: ``` cpdef double epoch_seconds(date): """Returns the number of seconds from the epoch to date. Should match the number returned by the equivalent function in postgres.""" td = date - epoc...
Your assumptions are wrong and that is why this seams weird. `td.days` contains the number of days since the epoch as you correctly assumed, but `td.seconds` and `td.microseconds` contains the number of seconds since the start of the day and the number of microseconds since the start of the second respectively. Thus th...
Length-wise-sorted list but, same length in alphabetical-order in a step
14,103,620
5
2012-12-31T15:59:59Z
14,103,631
9
2012-12-31T16:01:07Z
[ "python", "python-2.6" ]
My Python List of string is something like `x` but long enough: ``` x = ['aaa','ab','aa','c','a','b','ba'] ``` I wants to sort this list as: `['a', 'b', 'c', 'aa', 'ab', 'ba', 'aaa']` and I did as follows in **two** steps: ``` >>> x.sort() >>> x.sort(key=len) >>> x ['a', 'b', 'c', 'aa', 'ab', 'ba', 'aaa'] `...
You got the order of the tuple the wrong way round. When Python sorts on tuples, the first value is the *main* sort, with the second being the subsort, etc... - your code presumes the opposite order. You want to sort by length, *then* alphabetically: ``` >>> x.sort(key=lambda item: (len(item), item)) >>> x ['a', 'b',...
__init__ or __call__?
14,103,903
6
2012-12-31T16:32:16Z
14,103,919
14
2012-12-31T16:34:35Z
[ "python" ]
When should I use `__init__` and when `__call__` method ? I am confused about whether should I use the first or the second. At the moment I can use them both, but I don't know which is more appropriate.
These two are completely different. `__init__()` is the constructor, it is run on new instances of the object. `__call__()` is run when you try to call an instance of an object as if it were a function. E.g: Say we have a class, `Test`: ``` a = Test() #This will call Test.__init__() (among other things) a() #This w...
__init__ or __call__?
14,103,903
6
2012-12-31T16:32:16Z
14,103,925
9
2012-12-31T16:35:24Z
[ "python" ]
When should I use `__init__` and when `__call__` method ? I am confused about whether should I use the first or the second. At the moment I can use them both, but I don't know which is more appropriate.
A quick test shows the difference between them ``` class Foo(object): def __init__(self): print "init" def __call__(self): print "call" f = Foo() # prints "init" f() # prints "call" ``` In no way are these interchangeable
Set execute bit for a file using python
14,104,778
7
2012-12-31T18:07:53Z
14,104,799
14
2012-12-31T18:10:21Z
[ "python", "osx", "file-io" ]
Using python on Mac OS, I would like to open a file for writing and put some shell commands into it. Later to be run in terminal. ``` with open("my_script.sh", "w") as fd: fd.write("#!/bin/sh\n") fd.write("echo $PATH\n") ``` This will create the file, but I could not figure how to set the execute bit so when ...
``` import os os.chmod("my_script.sh", 0744) ``` Pick the value properly though. Some values might not be safe.
What is the cause of the Bad Request Error when submitting form in Flask application?
14,105,452
31
2012-12-31T19:36:26Z
14,113,958
56
2013-01-01T20:28:22Z
[ "python", "forms", "post", "flask", "bad-request" ]
After reading many similar sounding problems and the relevant Flask docs, I cannot seem to figure out what is generating the following error upon submitting a form: > 400 Bad Request > > The browser (or proxy) sent a request that this server could not understand. While the form always displays properly, the bad reque...
The solution was simple and uncovered in the comments. As addressed in this question, [Form sending error, Flask](http://stackoverflow.com/questions/8552675/form-sending-error-flask), and pointed out by [Sean Vieira](http://stackoverflow.com/users/135978/sean-vieira), > ...the issue is that Flask raises an HTTP error ...
Compressing `x if x else y` statement in Python
14,105,500
12
2012-12-31T19:44:01Z
14,105,516
16
2012-12-31T19:46:15Z
[ "python", "variable-assignment", "ternary-operator", "user-friendly" ]
I'm quite acquainted with Python's ternary operator approach: ``` value = foo if something else bar ``` My question is very simple: without prior assignments, is there anyway to reference the term being evaluated in (`if ...`) from one of the return operands (`... if` or `else ...`)? The motivation here is that some...
Don't use `if ... else` at all. Instead, take advantage of Python's coalescing operators. ``` value = info.findNext("b") or "Oompa Loompa" ```
Compressing `x if x else y` statement in Python
14,105,500
12
2012-12-31T19:44:01Z
14,105,612
13
2012-12-31T20:01:17Z
[ "python", "variable-assignment", "ternary-operator", "user-friendly" ]
I'm quite acquainted with Python's ternary operator approach: ``` value = foo if something else bar ``` My question is very simple: without prior assignments, is there anyway to reference the term being evaluated in (`if ...`) from one of the return operands (`... if` or `else ...`)? The motivation here is that some...
There is no way to do this, and that's intentional. The ternary if is only supposed to be used for trivial cases. If you want to use the result of a computation twice, put it in a temporary variable: ``` value = info.findNext("b") value = value if value else "Oompa Loompa" ``` Once you do this, it becomes clear that...
postgres and python
14,106,388
13
2012-12-31T22:03:49Z
14,682,316
7
2013-02-04T07:41:29Z
[ "python", "postgresql", "plpython" ]
In postgres 9.2 I am trying to create a python program that can be a trigger. I want to run an external program (an exe on the local disk) so I am using python to run it. When I try to create a simple program like this: ``` CREATE FUNCTION one () RETURNS int AS $$ # PL/Python function body $$ LANGUAGE plpythonu; ``` ...
I have just solved this problem, literally a few days back. The solution is quite involved. Here it goes. 1. Install python 3.2.\* version only on your system. 2. In Postgresql use the 'CREATE LANGUAGE plpython3u' command to install Python 3 language support. More often than not, it will give the following error "unab...
Python, subprocess, call(), check_call and returncode to find if a command exists
14,106,720
12
2012-12-31T23:14:13Z
14,106,797
15
2012-12-31T23:30:30Z
[ "python", "command-line", "call", "subprocess", "file-exists" ]
I've figured out how to use call() to get my python script to run a command: ``` import subprocess mycommandline = ['lumberjack', '-sleep all night', '-work all day'] subprocess.call(mycommandline) ``` This works but there's a problem, what if users don't have lumberjack in their command path? It would work if lumbe...
A simple snippet: ``` try: subprocess.check_call(['executable']) except subprocess.CalledProcessError: pass # handle errors in the called executable except OSError: pass # executable not found ```
Is this an acceptable algorithm?
14,106,736
2
2012-12-31T23:17:08Z
14,107,094
10
2013-01-01T00:45:27Z
[ "python", "lcs" ]
I've designed an algorithm to find the longest common subsequence. these are steps: * Pick the first letter in the first string. * Look for it in the second string and if its found, Add that letter to `common_subsequence` and store its position in `index`, Otherwise compare the length of `common_subsequence` with ...
If your professor wants you to invent your own LCS algorithm, you're done. Your algorithm is not the most optimal one ever created, but it's in the right complexity class, you clearly understand it, and you clearly didn't copy your implementation from the internet. You might want to be prepared to defend your algorithm...
Python Sqlite3: INSERT INTO table VALUE(dictionary goes here)
14,108,162
7
2013-01-01T05:55:25Z
14,108,554
12
2013-01-01T06:59:21Z
[ "python", "dictionary", "parameters", "sqlite3", "insert" ]
I would like to use a dictionary to insert values into a table, how would I do this? ``` import sqlite3 db = sqlite3.connect('local.db') cur = db.cursor() cur.execute('DROP TABLE IF EXISTS Media') cur.execute('''CREATE TABLE IF NOT EXISTS Media( id INTEGER PRIMARY KEY, title TEXT, t...
If you're trying to use a `dict` to specify both the column names and the values, you can't do that, at least not directly. That's really inherent in SQL. If you don't specify the list of column names, you have to specify them in `CREATE TABLE` order—which you can't do with a `dict`, because a `dict` has no order. I...
pyserial: No module named tools
14,108,428
15
2013-01-01T06:35:38Z
14,109,679
17
2013-01-01T10:34:36Z
[ "python", "python-2.7", "serial-port", "pyserial" ]
I have installed the latest pySerial on my Ubuntu box with python 2.7.2, and it works fine for most things, but whenever I try to import the 'tools' package, it says that it can't find 'tools'. The [documentation for pySerial](http://pyserial.sourceforge.net/shortintro.html?highlight=list#listing-ports) explicitly refe...
Use `pip` to install `pyserial`. First install pip: ``` sudo apt-get install python-pip ``` After that install `pyserial`: ``` sudo pip install pyserial ```
How to change Pandas dataframe index value?
14,110,721
10
2013-01-01T13:05:42Z
14,110,955
13
2013-01-01T13:40:39Z
[ "python", "pandas" ]
I have a `df` : ``` >>> df sales cash STK_ID RPT_Date 000568 20120930 80.093 57.488 000596 20120930 32.585 26.177 000799 20120930 14.784 8.157 ``` And want to change first row's index value from `('000568','20120930')` to `('000999','20121231')` . Final result wil...
With this setup: ``` import pandas as pd import io text = '''\ STK_ID RPT_Date sales cash 000568 20120930 80.093 57.488 000596 20120930 32.585 26.177 000799 20120930 14.784 8.157 ''' df = pd.read_csv(io.BytesIO(text), delimiter = ' ', converters = {0:str}) df.set_index(['STK_ID','RPT_Date'], inplac...
Convert a string to a whitespace separated list w/quoted elements
14,111,580
2
2013-01-01T15:16:17Z
14,111,590
11
2013-01-01T15:17:26Z
[ "python" ]
Is there a simple way in Python to convert a string to a list using whitespaces as separators, but ignoring the whitespace within quoted text? IE: each word is treated as a separate search term, but any quoted text is treated as one term.
Yes, by using the [`shlex.split()` function](http://docs.python.org/2/library/shlex.html#shlex.split): ``` >>> import shlex >>> shlex.split('Some whitespace "separated string"') ['Some', 'whitespace', 'separated string'] ```
Displaying a grayscale Image
14,111,705
5
2013-01-01T15:32:31Z
14,111,762
10
2013-01-01T15:41:23Z
[ "python", "matplotlib", "python-imaging-library" ]
My aim: 1. Read an image into the PIL format. 2. Convert it to grayscale. 3. Plot the image using pylab. Here is the code i'm using: ``` from PIL import Image from pylab import * import numpy as np inputImage='C:\Test\Test1.jpg' ##outputImage='C:\Test\Output\Test1.jpg' pilImage=Image.open(inputImage) pilImage.draf...
You want to over-ride the default color map: ``` imshow(imageArray, cmap="Greys_r") ``` [Here's a page on plotting images and pseudocolor in matplotlib](http://matplotlib.org/users/image_tutorial.html) .
Using __class__ to create instances
14,112,179
5
2013-01-01T16:41:16Z
14,112,406
10
2013-01-01T17:08:10Z
[ "python", "python-3.x", "code-duplication" ]
Is it a good idea to use `__class__` to create new instances within the class? The following code is an example of doing this: ``` from collections import namedtuple _Position = namedtuple('Position', ['x', 'y']) class Position(_Position): def __add__(self, other): return __class__(self.x + other.x, self...
To support the zero-argument form of [`super()`](http://docs.python.org/3/library/functions.html#super), the compiler adds an implicit reference to the class if `__class__` or `super()` are being used in a class method. See [Creating the class object](http://docs.python.org/3/reference/datamodel.html#creating-the-class...
Numpy's ones and zeros array creation--how to do the same for an arbitrary value?
14,112,235
3
2013-01-01T16:48:35Z
14,112,342
9
2013-01-01T17:01:11Z
[ "python", "numpy", "scipy" ]
How do I create an array where every entry is the same value--I know numpy.ones() and numpy.zeros() do this for 1's and 0's, but what about -1 for example: ``` >>import numpy as np >>np.zeros((3,3)) array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) >>np.ones((2,5)) array([[ 1., 1., 1., 1., ...
I don't know if there's a nice one-liner without an arithmetic operation, but probably the fastest approach is to create an uninitialized array using `empty` and then use `.fill()` to set the values. For comparison: ``` >>> timeit m = np.zeros((3,3)); m += -1 100000 loops, best of 3: 6.9 us per loop >>> timeit m = np....
Flask request and application/json content type
14,112,336
14
2013-01-01T17:00:10Z
14,112,400
30
2013-01-01T17:07:31Z
[ "python", "json", "dictionary", "flask", "mime-types" ]
I have a flask app with the following view: ``` @menus.route('/', methods=["PUT", "POST"]) def new(): return jsonify(request.json) ``` However, this only works if the request's content type is set to `application/json`, otherwise the dict `request.json` is None. I know that `request.data` has the request body as...
As of [Flask 0.10](https://flask.readthedocs.org/en/latest/changelog/#version-0-10), you can use [`request.get_json()`](https://flask.readthedocs.org/en/latest/api/#flask.Request.get_json) and set `force` to `True`: ``` @menus.route('/', methods=["PUT", "POST"]) def new(): return jsonify(request.get_json(force=Tru...
Flask request and application/json content type
14,112,336
14
2013-01-01T17:00:10Z
19,590,680
9
2013-10-25T13:03:21Z
[ "python", "json", "dictionary", "flask", "mime-types" ]
I have a flask app with the following view: ``` @menus.route('/', methods=["PUT", "POST"]) def new(): return jsonify(request.json) ``` However, this only works if the request's content type is set to `application/json`, otherwise the dict `request.json` is None. I know that `request.data` has the request body as...
the `request` object already has a method `get_json` which can give you the json regardless of the content-type if you execute it with `force=True` so your code would be something like the following: ``` @menus.route('/', methods=["PUT", "POST"]) def new(): return jsonify(request.get_json(force=True)) ``` in fact...
How do you set a conditional in python based on datatypes?
14,113,187
2
2013-01-01T18:45:00Z
14,113,197
14
2013-01-01T18:46:08Z
[ "python", "types", "conditional" ]
This question seems mind-boggling simple, yet I can't figure it out. I know you can check datatypes in python, but how can you set a conditional based on the datatype? For instance, if I have to write a code that sorts through a dictionary/list and adds up all the integers, how do I isolate the search to look for only ...
How about, ``` if isinstance(x, int): ``` but a cleaner way would simply be ``` sum(z for z in y if isinstance(z, int)) ```
Why does Flask's url_for throw an error when using a decorator on that item in Python?
14,114,296
2
2013-01-01T21:14:50Z
14,114,606
8
2013-01-01T21:57:08Z
[ "python", "flask", "decorator", "build-error" ]
I am creating a Python Flask app and created the decorator and views below. The decorator works great when viewing the index, but when you logout and it redirects using the `url_for` index it throws a builderror. Why would ``` def logged_in(fn): def decorator(): if 'email' in session: return fn...
The problem here is that `decorator()` function which you return has different name than the function it is decorating, so the URL builder can't find your `index` view. You need to use `wraps()` decorator from `functools` module to copy the name of the original function. Another problem (which you still have to encount...
Finding centre of a polygon using limited data
14,114,610
3
2013-01-01T21:57:43Z
14,115,494
14
2013-01-02T00:11:50Z
[ "python", "voronoi" ]
I'm implementing Voronoi tesselation followed by smoothing. For the smoothing I was going to do Lloyd relaxation, but I've encountered a problem. I'm using following module for calculation of Voronoi sides: <https://bitbucket.org/mozman/geoalg/src/5bbd46fa2270/geoalg/voronoi.py> For the smoothing I need to know the ...
For finding a centroid, you can use [the formula described on wikipedia](http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon): ``` import math def area_for_polygon(polygon): result = 0 imax = len(polygon) - 1 for i in range(0,imax): result += (polygon[i]['x'] * polygon[i+1]['y']) - (polygon[...
Complex list slice/index in python
14,114,621
7
2013-01-01T21:59:35Z
14,114,633
15
2013-01-01T22:01:20Z
[ "python", "list", "slice" ]
I have a list that looks like this: ``` lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] ``` I'd like to generate a filtered list that looks like this: ``` filtered_lst = [2, 6, 7, 9, 10, 13] ``` Does Python provide a convention for custom slicing. Something such as: ``` lst[1, 5, 6, 8, 9, 12] # slice a list by i...
Use [`operator.itemgetter()`](http://docs.python.org/2/library/operator.html#operator.itemgetter): ``` from operator import itemgetter itemgetter(1, 5, 6, 8, 9, 12)(lst) ``` Demo: ``` >>> from operator import itemgetter >>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] >>> itemgetter(1, 5, 6, 8, 9, 12)(lst) (2,...
Creating a folder with timestamp
14,115,254
3
2013-01-01T23:32:23Z
14,115,286
9
2013-01-01T23:37:56Z
[ "python" ]
Currently am creating files using the below code,I want to create a directory based on the timestamp at that point in the cwd,save the directory location to a variable and then create the file in the newly created directory,does anyone have ideas on how can this be done? ``` def filecreation(list, filename): #prin...
You mean, something like this? ``` import os, datetime mydir = os.path.join(os.getcwd(), datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')) os.makedirs(mydir) with open(os.path.join(mydir, 'filename.txt'), 'w') as d: pass # ... etc ... ``` ## Complete function ``` import os, datetime def filecreation(list, ...
Create Django model or update if exists
14,115,318
34
2013-01-01T23:43:22Z
14,115,332
79
2013-01-01T23:46:07Z
[ "python", "django", "django-models" ]
I want to create a model object, like Person, if person's id doesn't not exist, or I will get that person object. The code to create a new person as following: ``` class Person(models.Model): identifier = models.CharField(max_length = 10) name = models.CharField(max_length = 20) objects = PersonManager() ...
If you're looking for "update if exists else create" use case, please refer to [@Zags excellent answer](http://stackoverflow.com/a/26286864/2800876) --- Django already has a `get_or_create`, <https://docs.djangoproject.com/en/1.9/ref/models/querysets/#get-or-create> For you it could be : ``` id = 'some identifier' ...
Create Django model or update if exists
14,115,318
34
2013-01-01T23:43:22Z
26,286,864
19
2014-10-09T19:52:49Z
[ "python", "django", "django-models" ]
I want to create a model object, like Person, if person's id doesn't not exist, or I will get that person object. The code to create a new person as following: ``` class Person(models.Model): identifier = models.CharField(max_length = 10) name = models.CharField(max_length = 20) objects = PersonManager() ...
It's unclear whether your question is asking for the [get\_or\_create](https://docs.djangoproject.com/en/1.7/ref/models/querysets/#get-or-create) method (available from at least Django 1.3) or the [update\_or\_create](https://docs.djangoproject.com/en/1.7/ref/models/querysets/#update-or-create) method (new in Django 1....
Pygame installation for Python 3.3
14,115,440
20
2013-01-02T00:03:18Z
14,752,347
26
2013-02-07T13:32:08Z
[ "python", "pygame" ]
I am trying to import [Pygame](https://en.wikipedia.org/wiki/Pygame) to use for my version of [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), 3.3. The downloads on the Pygame website only have Python 3.1 and 3.2. I cannot seem to be able to import Pygame though I thought I had it installed in ...
The main Pygame page seems to be rarely updated. You can download Pygame releases direct from [Bitbucket](http://en.wikipedia.org/wiki/Bitbucket) at <https://bitbucket.org/pygame/pygame/downloads>.
Python regular expression question mark operator not working?
14,115,922
9
2013-01-02T01:26:05Z
14,116,188
13
2013-01-02T02:16:50Z
[ "python", "regex", "capture", "optional" ]
``` import re str='abc defg' m1 = re.match(".*(def)?",str) m2 = re.match(".*(def)",str) print (m1.group(1),m2.group(1)) ``` The output of the above is: > (None, 'def') What is going on? Even with a non-greedy repetition operator, the optional capture group `(def)?` is not matched.
Here's what happens when the regex engine tries to match `.*(def)` against `abc defg`: * First, the engine starts trying to match the regex at the beginning of the string. * The greedy subpattern `.*` initially tries to match as many times as it can, matching the entire string. * Since this causes the rest of the matc...
Swap two lists in python
14,116,893
3
2013-01-02T04:37:32Z
14,116,905
9
2013-01-02T04:39:47Z
[ "python", "list" ]
I have a list of 2 lists, which are of equal size, in python like: ``` list_of_lists = [list1, list2] ``` In a for loop after doing some processing on both `list1` and `list2`, I have to swap them so that `list1` becomes `list2` and `list2` becomes a list initialized to all zeros. So at the end of the iteration the l...
It sounds like you are mainly working with `list1` and `list2` inside the loop. So you could just reassign their values: ``` list1 = list2 list2 = [0]*len(list2) ``` Python also allows you to shorten this to a one-liner: ``` list1, list2 = list2, [0]*len(list2) ``` but in this case I find the two-line version more ...
In Python, using argparse, allow only positive integers
14,117,415
55
2013-01-02T05:47:21Z
14,117,511
69
2013-01-02T05:58:04Z
[ "python", "argparse" ]
The title pretty much summarizes what I'd like to have happen. Here is what I have, and while the program doesn't blow up on a nonpositive integer, I want the user to be informed that a nonpositive integer is basically nonsense. ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("-g", "--games...
This should be possible utilizing `type`. You'll still need to define an actual method that decides this for you: ``` def check_positive(value): ivalue = int(value) if ivalue <= 0: raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value) return ivalue parser = argparse.Argu...
In Python, using argparse, allow only positive integers
14,117,415
55
2013-01-02T05:47:21Z
14,117,567
24
2013-01-02T06:05:32Z
[ "python", "argparse" ]
The title pretty much summarizes what I'd like to have happen. Here is what I have, and while the program doesn't blow up on a nonpositive integer, I want the user to be informed that a nonpositive integer is basically nonsense. ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("-g", "--games...
`type` would be the recommended option to handle conditions/checks, as in Yuushi's answer. In your specific case, you can also use the `choices` parameter if your upper limit is also known: ``` parser.add_argument('foo', type=int, choices=xrange(5, 10)) ```
Too many different Python versions on my system and causing problems
14,117,945
23
2013-01-02T06:47:39Z
14,174,029
15
2013-01-05T16:51:00Z
[ "python", "osx", "path", "installation", "uninstall" ]
During the past years, I have installed many Python libraries with various Python versions. To make them ready to work immediately, I installed them blindly without control. Currently they're causing problems when I tried to install [pynest](http://nest-initiative.org/index.php/Software%3aDocumentation) which invokes n...
## **Why did it get messed up?** There're a couples of different way to install Python, as the update of OP says, and they locate files in different locations. For example, `macports` puts things into `/opt/local/`, while `homebrew` puts things into `/usr/local/`. Also, Mac OS X brings a few python versions with itsel...
How to convert unicode accented characters to pure ascii without accents?
14,118,352
6
2013-01-02T07:28:42Z
14,121,678
16
2013-01-02T12:00:43Z
[ "python", "unicode", "wget", "normalization", "unicode-normalization" ]
I'm trying to download some content from a dictionary site like <http://dictionary.reference.com/browse/apple?s=t> The problem I'm having is that the original paragraph has all those squiggly lines, and reverse letters, and such, so when I read the local files I end up with those funny escape characters like \x85, \xa...
> how do i convert all those escape characters into their respective characters like if there is an unicode **Ã**, how do i convert that into a standard **a**? When I pull the dictionary reference with `wget`, I don't see unicode... perhaps this has to do with me using `wget` in linux instead of windows?? Regardless....
How does __slots__ avoid a dictionary lookup?
14,118,564
7
2013-01-02T07:49:56Z
14,119,024
12
2013-01-02T08:37:51Z
[ "python", "slots", "python-internals" ]
I've heard that `__slots__` makes objects faster by avoiding a dictionary lookup. My confusion comes from Python being a dynamic language. In a static language, we avoid a dictionary lookup for `a.test` by doing a compile-time optimisation to save the index in the instruction we run. Now, in Python, `a` could just as ...
`__slots__` does not (significantly) speed up attribute access: ``` >>> class Foo(object): ... __slots__ = ('spam',) ... def __init__(self): ... self.spam = 'eggs' ... >>> class Bar(object): ... def __init__(self): ... self.spam = 'eggs' ... >>> import timeit >>> timeit.timeit('t.spam', '...
Scraperwiki + lxml. How to get the href attribute of a child of an element with a class?
14,119,590
2
2013-01-02T09:30:31Z
14,136,852
8
2013-01-03T10:17:59Z
[ "python", "web-scraping", "lxml", "scraperwiki" ]
On the link that contains 'alpha' in the URL has many links(hrefs) which I would like to collect from 20 different pages and paste onto the end of the general url(second last line). The href are found in a table which class is mys-elastic mys-left for the td and the a is obviously the element which contains the href at...
No need to muck about with javascript - it's all there in the html: ``` import scraperwiki import lxml.html html = scraperwiki.scrape('http://ahr13.mapyourshow.com/5_0/exhibitor_results.cfm? alpha=%40&type=alpha&page=1') root = lxml.html.fromstring(html) # get the links hrefs = root.xpath('//td[@class="mys-elastic ...
Python 4D linear interpolation on a rectangular grid
14,119,892
14
2013-01-02T09:51:41Z
14,122,491
10
2013-01-02T12:58:03Z
[ "python", "numpy", "scipy", "interpolation" ]
I need to interpolate temperature data linearly in 4 dimensions (latitude, longitude, altitude and time). The number of points is fairly high (360x720x50x8) and I need a fast method of computing the temperature at any point in space and time within the data bounds. I have tried using `scipy.interpolate.LinearNDInter...
In the same ticket you have linked, there is an example implementation of what they call *tensor product interpolation*, showing the proper way to nest recursive calls to `interp1d`. This is equivalent to quadrilinear interpolation if you choose the default `kind='linear'` parameter for your `interp1d`'s. While this m...
IOError: [Errno 13] file not accessible GAE
14,121,726
4
2013-01-02T12:03:53Z
14,121,855
8
2013-01-02T12:14:11Z
[ "python", "google-app-engine" ]
I want to access a file in my computer from a google app engine application. If I put the file in the src folder of the application there is no problem but I need this file to be out of that folder. When I try to access this file I get the next error: ``` Traceback (most recent call last): File "C:\Program Files ...
Put the file in the same directory as the rest of your applications files (i.e. where the app.yaml is). All the files you want your application to access have to be in the same place, under your main application directory. GAE can't access arbitrary files somewhere on your computer, just like it cannot access files s...
Is there any type for function in Cython?
14,124,049
15
2013-01-02T14:47:49Z
14,182,799
21
2013-01-06T13:54:41Z
[ "python", "callback", "cython" ]
Is there any way to tell Cython compiler that param is function. Something like ``` cpdef float calc_class_re(list data, func callback) ```
Should be self-explanatory..? :) ``` # Define a new type for a function-type that accepts an integer and # a string, returning an integer. ctypedef int (*f_type)(int, str) # Extern a function of that type from foo.h cdef extern from "foo.h": int do_this(int, str) # Passing this function will not work. cpdef int ...
elementtree register namespace error
14,124,311
6
2013-01-02T15:10:10Z
14,124,492
12
2013-01-02T15:23:08Z
[ "python", "elementtree" ]
I tried to register namespace with this: ``` ET.register_namespace("inv", "http://www.stormware.cz/schema/version_2/invoice.xsd") ``` but it doesn't work: ``` Traceback (most recent call last): File "C:\tutorial\temp_xml2.py", line 34, in module> for listInvoice in root.findall('inv:invoiceHeader'): File "C:...
It looks like the documentation hasn't been updated on how to use namespaces and `.findall()`. The `.findall()` function (as well as `.find()`, `.findtext() and`.iterfind()`) takes a`namespaces` argument which is supposed to be a mapping. That is the only structure consulted when finding tags: ``` root.findall('inv:i...
Python multiprocessing shared memory
14,124,588
25
2013-01-02T15:28:51Z
14,135,569
19
2013-01-03T08:50:13Z
[ "python", "multiprocessing", "shared-memory", "large-data" ]
I have three large lists. First contains bitarrays (module bitarray 0.8.0) and the other two contain arrays of integers. ``` l1=[bitarray 1, bitarray 2, ... ,bitarray n] l2=[array 1, array 2, ... , array n] l3=[array 1, array 2, ... , array n] ``` These data structures take quite a bit of RAM (~16GB total). If i sta...
Generally speaking, there are two ways to share the same data: * Multithreading * Shared memory Python's multithreading is not suitable for CPU-bound tasks (because of the GIL), so the usual solution in that case is to go on `multiprocessing`. However, with this solution you need to explicitly share the data, using [...
Python list comprehension expensive
14,124,610
3
2013-01-02T15:30:11Z
14,124,639
15
2013-01-02T15:32:32Z
[ "python", "list-comprehension" ]
Im trying to find the effeciency of list comprehension but it look like its more expensive than a normal function operation. Can someone explain? ``` def squares(values): lst = [] for x in range(values): lst.append(x*x) return lst def main(): t = timeit.Timer(stmt="lst = [x*x for x in range(10...
You are never *calling* your `squares` function, so it is not doing anything. List comprehensions *are* in fact faster: ``` >>> import timeit >>> def squares(values): ... lst = [] ... for x in range(values): ... lst.append(x*x) ... return lst ... >>> def squares_comp(values): ... return [x*x ...
Allocating a chunk of memory and immediately freeing it in C fails
14,125,294
2
2013-01-02T16:12:05Z
14,125,412
8
2013-01-02T16:19:31Z
[ "python", "c" ]
In part of the code of a C module I am integrating with Python, I have a char\*\* (array of strings) which is repeatedly allocated, filled with allocated strings, then freed and allocated again. The general pattern is that when a certain function is called (from Python) supplying the new contents of the array (as a lis...
Here ``` staticWords[i] = malloc(sizeof(char) * strlen(word)); strcpy(staticWords[i], word); ``` you are missing to allocate the `0`-termination for the "strings". So any operation on those character arrays as strings, most likely will lead to undefined behaviour. Do it this way: ``` { int isNull = !word; stat...
Python coding style on function call with multiple parameters
14,126,153
6
2013-01-02T17:11:12Z
14,126,184
10
2013-01-02T17:12:35Z
[ "python" ]
This may sound like a newbie question, but I really need some help with this. I don't even know how to tag it, but I assume is just a Python question. I need to use a function that receives 5 parameters and returns 5 values: ``` a, b, c, d, e = function (input1, input2, input3, input4, input5) ``` The problem is that...
You can nest lines like this ``` my_function(test, this, out, like, so, something, indent) ``` You can expand lists into args like so ``` a = [1,2,3,4,5] my_function(*a) ``` You can even do this ``` result = my_function(big, long, list, of, args) a,b,c,d = result ``` > Al...
Python 2.7 gives ValueError list.remove(x) x not in list
14,126,726
2
2013-01-02T17:51:19Z
14,126,786
8
2013-01-02T17:54:57Z
[ "python", "list", "dictionary" ]
Every time I run the program Python throws `ValueError list.remove(x) x not in list`. Here is the code: ``` def manage_collide(bolts, aliens): #Check if a bolt collides with any alien(s) for b in bolts: for a in aliens: if b['rect'].colliderect(a['rect']): for a in aliens: ...
You should not remove items from a list you are looping over. Create a copy instead: ``` for a in aliens[:]: ``` and ``` for b in bolts[:]: ``` Modifying a list while looping over it, affects the loop: ``` >>> lst = [1, 2, 3] >>> for i in lst: ... print i ... lst.remove(i) ... 1 3 >>> lst [2] ``` Removin...
Killing child process when parent crashes in python
14,128,410
9
2013-01-02T20:04:03Z
14,128,476
16
2013-01-02T20:09:11Z
[ "python", "process", "subprocess" ]
I am trying to write a python program to test a server written in C. The python program launches the compiled server using the `subprocess` module: ``` pid = subprocess.Popen(args.server_file_path).pid ``` This works fine, however if the python program terminates unexpectedly due to an error, the spawned process is l...
I would [`atexit.register`](http://docs.python.org/2/library/atexit.html) a function to terminate the process: ``` import atexit process = subprocess.Popen(args.server_file_path) atexit.register(process.terminate) pid = process.pid ``` Or maybe: ``` import atexit process = subprocess.Popen(args.server_file_path) @at...
How to find the overlap between 2 sequences, and return it
14,128,763
5
2013-01-02T20:34:55Z
14,128,891
8
2013-01-02T20:45:30Z
[ "python", "algorithm" ]
I am new in Python, and have already spend to many hours with this problem, hope somebody can help me. I need to find the overlap between 2 sequences. The overlap is in the left end of the first sequences and the right end of the second one. I want the function to find the overlap, and return it. My sequences are: ``...
You could use [`difflib.SequenceMatcher`](http://docs.python.org/2/library/difflib.html#sequencematcher-objects): ``` d = difflib.SequenceMatcher(None,s1,s2) >>> match = max(d.get_matching_blocks(),key=lambda x:x[2]) >>> match Match(a=8, b=0, size=39) >>> i,j,k = match >>> d.a[i:i+k] 'GGCTCCCCACGGGGTACCCATAACTTGACAGTA...
How to find the overlap between 2 sequences, and return it
14,128,763
5
2013-01-02T20:34:55Z
14,128,905
7
2013-01-02T20:46:53Z
[ "python", "algorithm" ]
I am new in Python, and have already spend to many hours with this problem, hope somebody can help me. I need to find the overlap between 2 sequences. The overlap is in the left end of the first sequences and the right end of the second one. I want the function to find the overlap, and return it. My sequences are: ``...
Have a look at the [`difflib`](http://docs.python.org/3.3/library/difflib.html) library and more precisely at [`find_longest_match()`](http://docs.python.org/3.3/library/difflib.html#difflib.SequenceMatcher.find_longest_match): ``` import difflib def get_overlap(s1, s2): s = difflib.SequenceMatcher(None, s1, s2) ...
Django: foreign key value in a list display admin
14,130,174
8
2013-01-02T22:22:06Z
14,130,269
16
2013-01-02T22:29:26Z
[ "python", "django", "django-admin" ]
I'm trying to display the foreign key 'company name' in the admin list view. However, the list view just shows (None) for the company. What I'm I doing wrong? **admin.py** ``` class CampaignAdmin(admin.ModelAdmin): #fields = ['name', 'Company_name', 'active', 'modified', 'created'] list_display = ['name', 're...
Your `Campaign` model has no `Company` attribute - the ForeignKey is the field `companyid`. You'd need to change your function to ``` def related_company(self, obj): return obj.companyid.name related_company.short_description = 'Company' ``` And since the `__unicode__()` method of the company object returns the n...
matplotlib not working anymore due to interactive issue
14,130,527
6
2013-01-02T22:51:32Z
14,132,653
9
2013-01-03T03:31:54Z
[ "python", "matplotlib" ]
I was working with python and matplotlib but my script crashed so I had to turn off the terminal (Ubuntu 12.04, matplotib-1.1.0, python2.7). Now if I try to run any script it crashes on the line ``` import matplotlib.pyplot as plt ``` with the following error ``` Traceback (most recent call last): File "new.py", l...
If you read through files in the stack trace, `new.py`-> `/matplotlib/__init__.py` -> `matplotlib/rcsetup.py`, `/matplotlib/colors.py` -> `/matplotlib/cbook.py` --> **/home/federico/Documents/../new.py** -> `matplotlib/pyplot.py` You have named your module `new` which is shadowing with an import in `matplolib.cbook`,...
Python multi-threading file processing
14,130,642
2
2013-01-02T23:04:25Z
14,130,790
18
2013-01-02T23:19:38Z
[ "python" ]
I have few files that resides on a server, im trying to implement a multi threading process to improve the performance, I read a tutorial but have few questions implementing it, Here are the files, ``` filelistread = ['h:\\file1.txt', \ 'h:\\file2.txt', \ 'h:\\file3.txt', \ ...
You're mixing up two different solutions. If you want to create a dedicated worker thread for each file, you don't need a queue for anything. If you want to create a threadpool and a queue of files, you don't *want* to pass `inpfile` and `outfile` to the `run` method; you want to put them in each job on the queue. Ho...
better one-liner to flip keys and values of a dictionary
14,131,089
5
2013-01-02T23:51:38Z
14,131,104
13
2013-01-02T23:52:57Z
[ "python" ]
I've written a one-liner to accomplish this: ``` vocab_tag = dict(zip(*reversed(zip(*tag_vocab.items())))) ``` Can anybody write one that's more comprehensible/direct?
A readable and short [dict comprehension](http://www.youtube.com/watch?v=pShL9DCSIUw) is probably the best one can do: ``` vocab_tage = {value: key for key, value in tag_vocab.items()} ``` Pre 2.7, dictionary comprehensions don't exist, but we can replace them trivially with `dict()` and a generator expression: ``` ...
in a Flask unit-test, how can I mock objects on the request-global `g` object?
14,131,494
3
2013-01-03T00:39:41Z
14,146,151
9
2013-01-03T19:52:44Z
[ "python", "unit-testing", "mocking", "flask", "werkzeug" ]
I have a flask application that is setting up a database connection in a `before_filter`, very similar to [this](http://flask.pocoo.org/docs/tutorial/dbcon/): ``` @app.before_request def before_request(): g.db = connect_db() ``` Now: I am writing some unit-tests and I do *not* want them to hit the database. I wan...
This works `test_app.py` ``` from flask import Flask, g app = Flask(__name__) def connect_db(): print 'I ended up inside the actual function' return object() @app.before_request def before_request(): g.db = connect_db() @app.route('/') def root(): return 'Hello, World' ``` `test.py` ``` from mo...
Possible to append multiple lists at once? (Python)
14,131,615
9
2013-01-03T00:54:32Z
14,131,646
15
2013-01-03T00:57:58Z
[ "python", "list", "append" ]
I have a bunch of lists I want to append to a single list that is sort of the "main" list in a program I'm trying to write. Is there a way to do this in one line of code rather than like 10? I'm a beginner so I have no idea... For a better picture of my question, what if I had these lists: ``` x = [1, 2, 3] y = [4, 5...
``` x.extend(y+z) ``` should do what you want or ``` x += y+z ``` or even ``` x = x+y+z ```
Possible to append multiple lists at once? (Python)
14,131,615
9
2013-01-03T00:54:32Z
14,131,753
9
2013-01-03T01:09:26Z
[ "python", "list", "append" ]
I have a bunch of lists I want to append to a single list that is sort of the "main" list in a program I'm trying to write. Is there a way to do this in one line of code rather than like 10? I'm a beginner so I have no idea... For a better picture of my question, what if I had these lists: ``` x = [1, 2, 3] y = [4, 5...
Extending my comment ``` In [1]: x = [1, 2, 3] In [2]: y = [4, 5, 6] In [3]: z = [7, 8, 9] In [4]: from itertools import chain In [5]: print list(chain(x,y,z)) [1, 2, 3, 4, 5, 6, 7, 8, 9] ```
itertools.accumulate() versus functools.reduce()
14,132,545
7
2013-01-03T03:15:43Z
14,132,618
11
2013-01-03T03:26:32Z
[ "python", "itertools", "python-3.3", "functools" ]
In Python 3.3, [`itertools.accumulate()`](http://docs.python.org/3.3/library/itertools.html#itertools.accumulate), which normally repeatedly applies an addition operation to the supplied iterable, can now take a function argument as a parameter; this means it now overlaps with [`functools.reduce()`](http://docs.python....
It seems that `accumulate` keeps the previous results, whereas `reduce` (which is known as fold in other languages) does not necessarily. e.g. `list(accumulate([1,2,3], operator.plus))` would return `[1,3,6]` whereas a plain fold would return `6` Also (just for fun, don't do this) you can define `accumulate` in terms...
Relative imports for the billionth time
14,132,789
103
2013-01-03T03:50:40Z
14,132,912
184
2013-01-03T04:06:37Z
[ "python", "python-2.7", "relative", "import" ]
I've been here * <http://www.python.org/dev/peps/pep-0328/> * <http://docs.python.org/2/tutorial/modules.html#packages> * [Python packages: relative imports](http://stackoverflow.com/questions/10059002/python-packages-relative-imports) * [python relative import example code does not work](http://stackoverflow.com/ques...
**Script vs. Module** Here's an explanation. The short version is that there is a big difference between directly running a Python file, and importing that file from somewhere else. **Just knowing what directory a file is in does not determine what package Python thinks it is in.** That depends, additionally, on how y...
How to read UWSGI parameters in python/flask passed from nginx
14,133,460
9
2013-01-03T05:19:00Z
14,133,533
15
2013-01-03T05:27:29Z
[ "python", "nginx", "flask", "uwsgi" ]
I set up python/flask/uwsgi+nginx web app and it works fine. I want to use geoip, I set it up on nginx side: ``` location / { include uwsgi_params; uwsgi_pass unix:/tmp/qbaka-visit.sock; ... uwsgi_param GEOIP_COUNTRY_CODE $geoip_country_code; } ``...
`uwsgi_param` sets a wsgi `environ` key of the given name to the application. You can use this for headers, which follow the CGI convention of using an `HTTP_` prefix. the equivalent of your `proxy_set_header` would be: ``` uwsgi_param HTTP_X_GEOIP_COUNTRY $geoip_country_code; ``` note that the header name must be in...
Why is pow(a, d, n) so much faster than a**d % n?
14,133,806
97
2013-01-03T06:00:16Z
14,133,837
149
2013-01-03T06:03:13Z
[ "python", "performance", "pypy" ]
I was trying to implement a [Miller-Rabin primality test](http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test), and was puzzled why it was taking so long (> 20 seconds) for midsize numbers (~7 digits). I eventually found the following line of code to be the source of the problem: ``` x = a**d % n ``` (wh...
See the Wikipedia article on [modular exponentiation](http://en.wikipedia.org/wiki/Modular_exponentiation). Basically, when you do `a**d % n`, you actually have to calculate `a**d`, which could be quite large. But there are ways of computing `a**d % n` without having to compute `a**d` itself, and that is what `pow` doe...
Why is pow(a, d, n) so much faster than a**d % n?
14,133,806
97
2013-01-03T06:00:16Z
14,133,884
10
2013-01-03T06:07:30Z
[ "python", "performance", "pypy" ]
I was trying to implement a [Miller-Rabin primality test](http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test), and was puzzled why it was taking so long (> 20 seconds) for midsize numbers (~7 digits). I eventually found the following line of code to be the source of the problem: ``` x = a**d % n ``` (wh...
There are shortcuts to doing modular exponentiation: for instance, you can find `a**(2i) mod n` for every `i` from `1` to `log(d)` and multiply together (mod `n`) the intermediate results you need. A dedicated modular-exponentiation function like 3-argument `pow()` can leverage such tricks because it knows you're doing...
Why is pow(a, d, n) so much faster than a**d % n?
14,133,806
97
2013-01-03T06:00:16Z
14,133,966
35
2013-01-03T06:17:16Z
[ "python", "performance", "pypy" ]
I was trying to implement a [Miller-Rabin primality test](http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test), and was puzzled why it was taking so long (> 20 seconds) for midsize numbers (~7 digits). I eventually found the following line of code to be the source of the problem: ``` x = a**d % n ``` (wh...
BrenBarn answered your main question. For your aside: > why is it almost twice as fast when run with Python 2 or 3 than PyPy, when usually PyPy is much faster? If you read PyPy's [performance page](http://pypy.org/performance.html), this is exactly the kind of thing PyPy is not good at—in fact, the very first examp...
writing data from a python list to csv row-wise
14,134,237
11
2013-01-03T06:45:10Z
14,134,281
19
2013-01-03T06:49:43Z
[ "python", "csv" ]
Using python, i am writing data from a list to a .csv file, row-wise. Code: ``` writer=csv.writer(open(filepath,'wb')) header=['type','id','numberOfUpdates','isPingEnabled','lastUpdated'] length_list=len(header) i=0 while i!=length_list : data=header[i] print data i=i+1 writer.writerow(data) ``` Res...
Change `writer.writerow(data)` to `writer.writerow([data])`. `.writerow` takes an iterable and uses each element of that iterable for each column. If you use a list with only one element it will be placed in a single column. You should also restructure your loop: ``` for word in header: writer.writerow([word]) `...
Convert image from PIL to openCV format
14,134,892
11
2013-01-03T07:44:03Z
14,140,796
20
2013-01-03T14:26:13Z
[ "python", "image-processing", "opencv", "python-imaging-library" ]
I'm trying to convert image from `PIL` to `OpenCV` format. I'm using `OpenCV 2.4.3`. here is what I've attempted till now. ``` >>> from PIL import Image >>> import cv2 as cv >>> pimg = Image.open('D:\\traffic.jpg') #PIL Image >>> cimg = cv.cv.CreateImageHeader(pimg.size,cv.IPL_DEPTH_8U,3) ...
use this: ``` pil_image = PIL.Image.open('Image.jpg').convert('RGB') open_cv_image = numpy.array(pil_image) # Convert RGB to BGR open_cv_image = open_cv_image[:, :, ::-1].copy() ```
Convert image from PIL to openCV format
14,134,892
11
2013-01-03T07:44:03Z
32,264,327
7
2015-08-28T06:05:07Z
[ "python", "image-processing", "opencv", "python-imaging-library" ]
I'm trying to convert image from `PIL` to `OpenCV` format. I'm using `OpenCV 2.4.3`. here is what I've attempted till now. ``` >>> from PIL import Image >>> import cv2 as cv >>> pimg = Image.open('D:\\traffic.jpg') #PIL Image >>> cimg = cv.cv.CreateImageHeader(pimg.size,cv.IPL_DEPTH_8U,3) ...
This is the shortest version I could find,saving/hiding an extra conversion: ``` pil_image = PIL.Image.open('image.jpg') opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR) ``` If reading a file from a URL: ``` import cStringIO import urllib file = cStringIO.StringIO(urllib.urlopen(r'http://stackov...
An alternative to global in Python
14,135,345
5
2013-01-03T08:30:02Z
14,135,363
7
2013-01-03T08:31:34Z
[ "python", "global" ]
I currently have code like this: ``` cache = 1 def foo(): global cache # many # lines # of code cache = 2 ``` However, this may lead to hard-to-find-bugs in the future, because the reader may not notice that `global cache` appears somewhere above `cache = 2`. Alternatively, a contributor may mista...
``` cache = 1 def foo(): return 2 cache = foo() ``` or ``` d = {'cache': 1} def foo(x): x['cache'] = 2 foo(d) ```
An alternative to global in Python
14,135,345
5
2013-01-03T08:30:02Z
14,135,517
10
2013-01-03T08:45:12Z
[ "python", "global" ]
I currently have code like this: ``` cache = 1 def foo(): global cache # many # lines # of code cache = 2 ``` However, this may lead to hard-to-find-bugs in the future, because the reader may not notice that `global cache` appears somewhere above `cache = 2`. Alternatively, a contributor may mista...
``` class Cache: myvar = 1 def foo(): Cache.myvar = 2 ``` This way, `Cache.myvar` is practically a "global". It's possible to read/write to it from anywhere. I prefer this over the dictionary alternative, because it allows for auto-complete of the variable names.
How is tuple implemented in CPython?
14,135,542
14
2013-01-03T08:47:31Z
14,135,865
18
2013-01-03T09:12:21Z
[ "python", "data-structures", "tuples", "cpython", "python-internals" ]
I've been trying to learn how CPython is implemented under the scenes. It's great that Python is high level, but I don't like treating it like a black box. With that in mind, how are tuples implemented? I've had a look at [the source (tupleobject.c)](https://bitbucket.org/python_mirrors/cpython/src/d81d4b3059e4e5dca67...
Because in the course of normal operations Python will create and destroy a *lot* of small tuples, Python keeps an internal cache of small tuples for that purpose. This helps cut down on a lot of memory allocation and deallocation churn. For the same reasons small integers from -5 to 255 are interned (made into singlet...
How is tuple implemented in CPython?
14,135,542
14
2013-01-03T08:47:31Z
14,135,893
18
2013-01-03T09:14:26Z
[ "python", "data-structures", "tuples", "cpython", "python-internals" ]
I've been trying to learn how CPython is implemented under the scenes. It's great that Python is high level, but I don't like treating it like a black box. With that in mind, how are tuples implemented? I've had a look at [the source (tupleobject.c)](https://bitbucket.org/python_mirrors/cpython/src/d81d4b3059e4e5dca67...
As a caveat, everything in this answer is based on what I've gleaned from looking over the implementation you linked. It seems that the standard implementation of a tuple is simply as an array. However, there are a bunch of optimizations in place to speed things up. First, if you try to make an empty tuple, CPython i...
how to set the QTableView header name in Pyqt4
14,135,543
5
2013-01-03T08:47:32Z
14,154,912
8
2013-01-04T10:01:07Z
[ "python", "header", "pyqt4", "qtableview" ]
I want to know how can i set the custom header names in QTableview when i create a QTableview i get the column and row header names as 1,2,3,4. I want to know how can i set my own column and header titles. --- I got the [solution](http://pastebin.com/he125QmB) as required, Hope it could help some one who comes acros...
If you're using a `QTableView` with your own model you need to implement the [`headerData()`](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qabstractitemmodel.html#headerData) method in the model to return data for the header. Here's a snippet to show just column headings - change the `header_labels` value...
What is the proper way to handle (in python) IOError: [Errno 4] Interrupted system call, raised by multiprocessing.Queue.get
14,136,195
9
2013-01-03T09:36:38Z
14,262,151
11
2013-01-10T16:08:05Z
[ "python", "error-handling", "queue", "multiprocessing", "ioerror" ]
When I use multiprocessing.Queue.get I sometimes get an exception due to EINTR. I know definitely that sometimes this happens for no good reason (I open another pane in a tmux buffr), and in such a case I would want to continue working and retry the operation. I can imagine that in some other cases The error would be...
The `EINTR` error can be returned from many system calls when the application receives a signal while waiting for other input. Typically these signals can be quite benign and already handled by Python, but the underlying system call still ends up being interrupted. When doing C/C++ coding this is one reason why you can...
Python bug? Lazy objects have hidden state
14,136,871
2
2013-01-03T10:18:49Z
14,136,889
7
2013-01-03T10:19:51Z
[ "python", "lazy-evaluation", "enumerate" ]
Consider this (Python 3.3): ``` a=enumerate([2,3,5]) print(list(a)) print(list(a)) ``` Do you really expect two print calls to print different things? Neither did I. The same thing happens if you replace list with `set`, `tuple` or `dict`. It also happens if you replace `enumerate` object with `map` or `filter`, but...
`enumerate()` returns an iterator, as do the other calls.. You can only loop through an iterator once; it is then exhausted. You can create such an iterator yourself with a generator function: ``` def somelist_generator(): somelist = [1, 2, 3] while somelist: yield somelist.pop() ``` If you were to l...
Django admin save error: get_db_prep_value() got an unexpected keyword argument 'connection'
14,138,586
5
2013-01-03T12:04:05Z
14,138,696
8
2013-01-03T12:11:39Z
[ "python", "django", "django-admin" ]
When I try and save (using the Django standard admin interface) I get the following error... ``` TypeError at /admin/web/campaign/dc6eb21f-87fa-462f-88af-416cf6be37f6/ get_db_prep_value() got an unexpected keyword argument 'connection' ``` Could someone explain this to me, why and maybe a possible solution? I'm assu...
Yes, that would be a fair assumption. As you can see from [the source code](https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L287), the signature of that method is `def get_db_prep_value(self, value, connection, prepared=False)`, so any subclass needs to either expect the same arguments ...
Django admin save error: get_db_prep_value() got an unexpected keyword argument 'connection'
14,138,586
5
2013-01-03T12:04:05Z
14,766,741
7
2013-02-08T06:12:37Z
[ "python", "django", "django-admin" ]
When I try and save (using the Django standard admin interface) I get the following error... ``` TypeError at /admin/web/campaign/dc6eb21f-87fa-462f-88af-416cf6be37f6/ get_db_prep_value() got an unexpected keyword argument 'connection' ``` Could someone explain this to me, why and maybe a possible solution? I'm assu...
Daniel Roseman pretty much answered this, but I will state it in another way and use more words so that you hopefully understand. For custom fields in Django 1.4.x, your custom field's get\_db\_prep\_value function **MUST NOW ACCEPT** 4 parameters. In Django 1.2, the Django developers introduced multiple database suppo...
How to get line breaks in e-mail sent using Python's smtplib?
14,139,165
11
2013-01-03T12:41:16Z
14,139,320
17
2013-01-03T12:51:10Z
[ "python", "email", "python-2.7", "smtplib" ]
I have written a script that writes a message to a text file and also sends it as an email. Everything goes well, except the email finally appears to be all in one line. I add line breaks by `\n` and it works for the text file but not for the email. Do you know what could be the possible reason? --- Here's my code: ...
Unfortunately for us all, not every type of program or application uses the same standardization that python does. Looking at your question i notice your header is: `"Content-Type: text/html"` Which means you need to use HTML style tags for your new-lines, these are called line-breaks. `<br>` Your text should be: `...
How to get line breaks in e-mail sent using Python's smtplib?
14,139,165
11
2013-01-03T12:41:16Z
14,139,800
7
2013-01-03T13:23:29Z
[ "python", "email", "python-2.7", "smtplib" ]
I have written a script that writes a message to a text file and also sends it as an email. Everything goes well, except the email finally appears to be all in one line. I add line breaks by `\n` and it works for the text file but not for the email. Do you know what could be the possible reason? --- Here's my code: ...
Also have a look at the [email package](http://docs.python.org/2/library/email.html). There are some classes that can simplify the definition of E-Mail messages for you ([with examples](http://docs.python.org/2/library/email-examples.html)). For example you could try (untested): ``` import smtplib from email.mime.tex...
How to make a nice matrix from a dictionary
14,139,258
7
2013-01-03T12:46:44Z
14,139,403
15
2013-01-03T12:56:33Z
[ "python", "dictionary", "matrix" ]
I would like to make a matrix that makes a list of nested dictionaries. But I can't find out how to make a matrix, end even less how to put my values into it. My dictionary looks like: ``` {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29}, '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1}, '2': {'1': 13, '3': 1...
`import`**[`pandas`](http://pandas.pydata.org)**`as pd` ``` a = pd.DataFrame({'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29}, '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1}, '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0}, '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6':...
Run a particular Python function in C# with IronPython
14,139,766
5
2013-01-03T13:21:33Z
14,141,311
8
2013-01-03T14:57:15Z
[ "c#", "python", "dynamic", "ironpython" ]
So far I have a simple class that wraps a python engine (IronPython) for my use. Although code looks big it's really simple so I copy it here to be more clear with my issue. Here's the code: ``` public class PythonInstance { ScriptEngine engine; ScriptScope scope; ScriptSource source; public PythonIn...
Thanks to suggestion in comments I was able to figure out how to use it. Here's what I have now: ``` public class PythonInstance { private ScriptEngine engine; private ScriptScope scope; private ScriptSource source; private CompiledCode compiled; private object pythonClass; public PythonInstan...
How to add a line parallel to y axis in matplotlib?
14,139,793
4
2013-01-03T13:23:14Z
14,139,878
8
2013-01-03T13:28:39Z
[ "python", "matplotlib" ]
I want to draw a line at `x=x'`. This should be pretty straightforward, but how can I do it?
You can use [`matplotlib.pyplot.axvline()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.axvline). ``` import matplotlib.pyplot as plt plt.figure() plt.axvline(x=0.2) plt.axvline(x=0.5) plt.show() ``` ![enter image description here](http://i.imgur.com/ryru1.png)
python: in pdb is it possible to enable a breakpoint only after n hit counts?
14,139,817
12
2013-01-03T13:24:34Z
14,139,882
11
2013-01-03T13:28:57Z
[ "python", "debugging", "pdb" ]
In eclipse (and several other IDE's as well) there is an option to turn on the breakpoint only after a certain number of hits. In Python's `pdb` there is a hit count for breakpoints and there is the `condition` command. How do I connect them?
Conditional Breakpoints can be set in 2 ways - **FIRST:** specify the condition when the breakpoint is set using `break` ``` python -m pdb pdb_break.py > .../pdb_break.py(7)<module>() -> def calc(i, n): (Pdb) break 9, j>0 Breakpoint 1 at .../pdb_break.py:9 (Pdb) break Num Type Disp Enb Where 1 breakpoint...
python: in pdb is it possible to enable a breakpoint only after n hit counts?
14,139,817
12
2013-01-03T13:24:34Z
14,140,339
8
2013-01-03T13:59:18Z
[ "python", "debugging", "pdb" ]
In eclipse (and several other IDE's as well) there is an option to turn on the breakpoint only after a certain number of hits. In Python's `pdb` there is a hit count for breakpoints and there is the `condition` command. How do I connect them?
I found the answer. It's pretty easy actually, there's a command called `ignore` let's say you want to break at breakpoint in line 9 after 1000 hits: ``` b 9 Breakpoint 2 at ... ignore 1 1000 Will ignore next 1000 crossings of breakpoint 1. c ```
Celery - Programmatically list workers
14,142,150
9
2013-01-03T15:41:42Z
14,192,360
15
2013-01-07T08:37:11Z
[ "python", "celery" ]
How can I programmatically, using Python code, list current workers and their corresponding `celery.worker.consumer.Consumer` instances?
You can use [celery.control.inspect](http://docs.celeryproject.org/en/master/userguide/workers.html#inspecting-workers) to inspect the running workers: ``` >>> import celery >>> celery.current_app.control.inspect().ping() {u'celery@host': {u'ok': u'pong'}} ```
Is there a GUI design app for the Tkinter / grid geometry?
14,142,194
25
2013-01-03T15:44:18Z
14,142,360
14
2013-01-03T15:53:31Z
[ "python", "grid", "tkinter" ]
Does anyone know of a GUI design app that lets you choose/drag/drop the widgets, and then turn that layout into Python code with the appropriate Tkinter calls & arrangement using the `grid` geometry manager? So far I've turned up a couple of pretty nice options that I may end up using, but they generate code using eith...
You have **VisualTkinter** also known as Visual Python. Development seems not active. You have [sourceforge](http://sourceforge.net/projects/visualtkinter/files/?source=navbar) and [googlecode](http://code.google.com/p/visualtkinter/downloads/list) sites. Web site [is here](http://visualtkinter.sourceforge.net/download...
Is there a GUI design app for the Tkinter / grid geometry?
14,142,194
25
2013-01-03T15:44:18Z
14,144,121
11
2013-01-03T17:34:04Z
[ "python", "grid", "tkinter" ]
Does anyone know of a GUI design app that lets you choose/drag/drop the widgets, and then turn that layout into Python code with the appropriate Tkinter calls & arrangement using the `grid` geometry manager? So far I've turned up a couple of pretty nice options that I may end up using, but they generate code using eith...
The best tool for doing layouts using grid, IMHO, is graph paper and a pencil. I know you're asking for some type of program, but it really does work. I've been doing Tk programming for a couple of decades so layout comes quite easily for me, yet I still break out graph paper when I have a complex GUI. Another thing t...
Is there a GUI design app for the Tkinter / grid geometry?
14,142,194
25
2013-01-03T15:44:18Z
29,053,928
18
2015-03-14T20:39:13Z
[ "python", "grid", "tkinter" ]
Does anyone know of a GUI design app that lets you choose/drag/drop the widgets, and then turn that layout into Python code with the appropriate Tkinter calls & arrangement using the `grid` geometry manager? So far I've turned up a couple of pretty nice options that I may end up using, but they generate code using eith...
Apart from the options already given in other answers, there's a current more active, recent and open-source project called [`pygubu`](https://github.com/alejandroautalan/pygubu). This is the first description by the author taken from the github repository: > Pygubu is a RAD tool to enable quick & easy development of...
Why does matplotlib fill_between draw edgelines only on a PDF?
14,143,092
10
2013-01-03T16:35:18Z
14,143,593
9
2013-01-03T17:04:39Z
[ "python", "pdf", "matplotlib", "png" ]
In python's `matplotlib.fill_between` the following minimal working example below draws correctly to the screen, and to the `.png`. In the resulting `.pdf` however, the edge lines are still drawn. How can I fix this? ``` from numpy import * import pylab as plt # Sample data X = linspace(0,2*pi,1000) Y0 = sin(X) Y1 =...
It's not perfect, but I've found a solution (and will accept a better one if it comes). [Apparently](http://permalink.gmane.org/gmane.comp.python.matplotlib.general/996) postscript might be to blame: > ... note that interpreting a linewidth of zero as a 1 > pixel wide line is what PostScript does. So the only way to >...
Compare list of datetimes with datetime in Python
14,143,100
7
2013-01-03T16:35:48Z
14,143,148
8
2013-01-03T16:39:00Z
[ "python", "numpy" ]
I have a list of datetime objects and would like to find the ones which are within a certain time frame: ``` import datetime dates = [ datetime.datetime(2007, 1, 2, 0, 1), datetime.datetime(2007, 1, 3, 0, 2), datetime.datetime(2007, 1, 4, 0, 3), datetime.datetime(2007, 1, 5, 0, 4), ...
You can mask a [`numpy.array`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html) in the syntax you describe *(but not a list)*: ``` import numpy as np date1 = np.array(dates) mask = (dates1 > datetime.datetime(2007,1,3)) & \ (dates1 < datetime.datetime(2007,1,6)) In [14]: mask Out[14]: arr...
Compare list of datetimes with datetime in Python
14,143,100
7
2013-01-03T16:35:48Z
14,143,152
8
2013-01-03T16:39:15Z
[ "python", "numpy" ]
I have a list of datetime objects and would like to find the ones which are within a certain time frame: ``` import datetime dates = [ datetime.datetime(2007, 1, 2, 0, 1), datetime.datetime(2007, 1, 3, 0, 2), datetime.datetime(2007, 1, 4, 0, 3), datetime.datetime(2007, 1, 5, 0, 4), ...
If your `dates` list is in sorted order, you can use the [`bisect` module](http://docs.python.org/2/library/bisect.html): ``` >>> import bisect >>> bisect.bisect_right(dates, datetime.datetime(2007,1,3)) 1 >>> bisect.bisect_left(dates, datetime.datetime(2007,1,6)) 4 ``` The `.bisect_*` functions return indices into t...
Python 2.7+: What's the correct way to format a float in non-scientific notation with certain precision?
14,143,211
3
2013-01-03T16:42:00Z
14,143,229
7
2013-01-03T16:43:08Z
[ "python", "floating-point" ]
I hope I am making sense with this question. Sometimes if I print a small float it'll look like `6.1248979238e-05` or something similar. I want to be able to say "No matter what, output 10 digits precision like so": `0.abcdefghij`
``` >>> '%0.10f'% 6.1248979238e-05 '0.0000612490' ``` This is "string interpolation" or [printf-style formatting](http://docs.python.org/3.3/library/stdtypes.html#printf-style-string-formatting) which is still widely supported and used. Another option is the [newer style string formatting](http://docs.python.org/3.3/...
Line is too long. Django PEP8
14,143,284
9
2013-01-03T16:46:21Z
14,143,393
17
2013-01-03T16:53:12Z
[ "python", "django", "pep8" ]
PEP8 info: ``` models.py:10:80: E501 line too long (83 > 79 characters) ``` Models.py: ``` field = TreeForeignKey('self', null=True, blank=True, related_name='abcdefgh') ``` How to correctly write this line?
It's "correct", PEP8 just flags lines over 79 characters long. But if you're concerned about that, you could write it like this: ``` field = TreeForeignKey('self', null=True, blank=True, related_name='abcdefgh') ``` Or this: ``` field = TreeForeign...
Line is too long. Django PEP8
14,143,284
9
2013-01-03T16:46:21Z
14,143,691
10
2013-01-03T17:09:54Z
[ "python", "django", "pep8" ]
PEP8 info: ``` models.py:10:80: E501 line too long (83 > 79 characters) ``` Models.py: ``` field = TreeForeignKey('self', null=True, blank=True, related_name='abcdefgh') ``` How to correctly write this line?
I just found this neat program called autopep8! <https://github.com/hhatto/autopep8> ``` pip install autopep8 autopep8 -i models.py ``` You can also do (recursively): ``` autopep8 -ri package/ ``` Auto PEP8 only makes safe changes to the files, only changing layout, not code logic.
Merge two arrays by collections of two elements
14,144,516
2
2013-01-03T18:00:36Z
14,144,582
8
2013-01-03T18:05:40Z
[ "python", "arrays" ]
I have an array containing an even number of integers. The array represents a pairing of an identifier and a count. The tuples have already been sorted by the identifier. I would like to merge a few of these arrays together. I have thought of a few ways to do it but they are fairly complicated and I feel there might be...
It would be better to store these as dictionaries than as lists (not just for this purpose, but for other use cases, such as extracting the value of a single ID): ``` x1 = [14, 1, 16, 4, 153, 21] x2 = [14, 2, 16, 3, 18, 9] # turn into dictionaries (could write a function to convert) d1 = dict([(x1[i], x1[i + 1]) for ...
== and is in python
14,144,707
12
2013-01-03T18:14:26Z
14,144,740
22
2013-01-03T18:15:49Z
[ "python" ]
Its been a couple of days since I started learning python, at which point I stumbled across the `==` and `is`. Coming from a java background I assumed `==` does a comparison by object id and `is` by value, however doing ``` >>> a = (1,2) >>> b = (1,2) >>> a is b False >>> a == b True ``` Seems like `is` is equi...
* '==' checks for equality, * 'is' checks for identity See also [Python '==' vs 'is' comparing strings, 'is' fails sometimes, why?](http://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why)
== and is in python
14,144,707
12
2013-01-03T18:14:26Z
14,144,816
16
2013-01-03T18:20:19Z
[ "python" ]
Its been a couple of days since I started learning python, at which point I stumbled across the `==` and `is`. Coming from a java background I assumed `==` does a comparison by object id and `is` by value, however doing ``` >>> a = (1,2) >>> b = (1,2) >>> a is b False >>> a == b True ``` Seems like `is` is equi...
`is` checks that both operands are the same object. `==` calls [`__eq__()`](http://docs.python.org/2/reference/datamodel.html#object.__eq__) on the left operand, passing the right. Normally this method implements equality comparison, but it is *possible* to write a class that uses it for other purposes (but it never sh...