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
Get domain name from URL
9,626,535
48
2012-03-08T23:12:38Z
9,626,596
102
2012-03-08T23:17:43Z
[ "python", "django" ]
In my django app, I need to get the domain name from the referer in `request.META.get('HTTP_REFERER')` along with its protocol so that from URLs like: * <https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1> * <http://stackoverflow.com/questions/1234567/blah-blah-blah-blah> * <http://www.domain.com> *...
You should be able to do it with: ``` from urlparse import urlparse parsed_uri = urlparse( 'http://stackoverflow.com/questions/1234567/blah-blah-blah-blah' ) domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri) print domain # gives 'http://stackoverflow.com/' ``` UPDATE: Python [docs on urlparse](http://d...
Get domain name from URL
9,626,535
48
2012-03-08T23:12:38Z
9,627,628
22
2012-03-09T01:16:50Z
[ "python", "django" ]
In my django app, I need to get the domain name from the referer in `request.META.get('HTTP_REFERER')` along with its protocol so that from URLs like: * <https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1> * <http://stackoverflow.com/questions/1234567/blah-blah-blah-blah> * <http://www.domain.com> *...
<https://github.com/john-kurkowski/tldextract> This is a more verbose version of urlparse. It detects domains and subdomains for you. From their documentation: ``` >>> import tldextract >>> tldextract.extract('http://forums.news.cnn.com/') ExtractResult(subdomain='forums.news', domain='cnn', suffix='com') >>> tldext...
Get domain name from URL
9,626,535
48
2012-03-08T23:12:38Z
20,728,813
15
2013-12-22T11:20:29Z
[ "python", "django" ]
In my django app, I need to get the domain name from the referer in `request.META.get('HTTP_REFERER')` along with its protocol so that from URLs like: * <https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1> * <http://stackoverflow.com/questions/1234567/blah-blah-blah-blah> * <http://www.domain.com> *...
### Python3 using [urlsplit](http://docs.python.org/3/library/urllib.parse#urllib.parse.urlsplit): ``` from urllib.parse import urlsplit url = "http://stackoverflow.com/questions/9626535/get-domain-name-from-url" base_url = "{0.scheme}://{0.netloc}/".format(urlsplit(url)) print(base_url) # http://stackoverflow.com/ ``...
Get domain name from URL
9,626,535
48
2012-03-08T23:12:38Z
32,214,840
8
2015-08-25T22:02:51Z
[ "python", "django" ]
In my django app, I need to get the domain name from the referer in `request.META.get('HTTP_REFERER')` along with its protocol so that from URLs like: * <https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1> * <http://stackoverflow.com/questions/1234567/blah-blah-blah-blah> * <http://www.domain.com> *...
``` >>> import urlparse >>> url = 'http://stackoverflow.com/questions/1234567/blah-blah-blah-blah' >>> urlparse.urljoin(url, '/') 'http://stackoverflow.com/' ```
Problems installing South with Django (south_migrationhistory tables do not get created)
9,626,979
4
2012-03-09T00:00:06Z
9,627,145
17
2012-03-09T00:20:01Z
[ "python", "django", "migration", "django-south" ]
I cannot seem to get this working. I need South to do migrations for a bunch of apps. 1. Downloaded south 0.7.3 2. Unzipped, ran setup.py develop (as it says in the turorial) 3. Double checked to see if it south is where it should be by going to python interpreter and doing (no errors) > import south 4. I do > `...
It seems to me like a bug in South. Also this may be cause by doing wrong thigs like: running `schemamigration --auto south` and etc. My suggestion would be install it by running `python setup.py install` or through **easy\_install** or **pip** South documentation says: "Once South is added in, you’ll need to run ....
Plotting dates on the x-axis with Python's matplotlib
9,627,686
24
2012-03-09T01:23:54Z
9,627,942
11
2012-03-09T01:58:22Z
[ "python", "datetime", "matplotlib" ]
I am trying to plot information against dates. I have a list of dates in the format "01/02/1991". I converted them by doing the following: ``` x = parser.parse(date).strftime('%Y%m%d')) ``` which gives `19910102` Then I tried to use num2date ``` import matplotlib.dates as dates new_x = dates.num2date(x) ``` Plott...
As @KyssTao has been saying, `help(dates.num2date)` says that the `x` has to be a float giving the number of days since 0001-01-01 plus one. Hence, `19910102` is not 2/Jan/1991, because if you counted 19910101 days from 0001-01-01 you'd get something in the year 54513 or similar (divide by 365.25, number of days in a y...
Plotting dates on the x-axis with Python's matplotlib
9,627,686
24
2012-03-09T01:23:54Z
9,627,970
50
2012-03-09T02:02:35Z
[ "python", "datetime", "matplotlib" ]
I am trying to plot information against dates. I have a list of dates in the format "01/02/1991". I converted them by doing the following: ``` x = parser.parse(date).strftime('%Y%m%d')) ``` which gives `19910102` Then I tried to use num2date ``` import matplotlib.dates as dates new_x = dates.num2date(x) ``` Plott...
You can do this more simply using `plot()` instead of `plot_date()`. First, convert your strings to instances of Python `datetime.date`: ``` import datetime as dt dates = ['01/02/1991','01/03/1991','01/04/1991'] x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates] y = range(len(x)) # many thanks to Kyss Ta...
(Python) Counting lines in a huge (>10GB) file as fast as possible
9,629,179
13
2012-03-09T05:05:53Z
9,631,635
13
2012-03-09T09:24:14Z
[ "python", "enumerate", "line-count" ]
I have a really simple script right now that counts lines in a text file using `enumerate()`: ``` i = 0 f = open("C:/Users/guest/Desktop/file.log", "r") for i, line in enumerate(f): pass print i + 1 f.close() ``` This takes around 3 and a half minutes to go through a 15GB log file with ~30 million lines. It wou...
[Ignacio's answer](http://stackoverflow.com/questions/9629179/python-counting-lines-in-a-huge-10gb-file-as-fast-as-possible/9629202#9629202) is correct, but might fail if you have a 32 bit process. But maybe it could be useful to read the file block-wise and then count the `\n` characters in each block. ``` def block...
Python Mixin for __str__and Method Resolution Order
9,631,716
6
2012-03-09T09:30:03Z
9,632,395
11
2012-03-09T10:20:36Z
[ "python", "mixins" ]
I find that many classes I write in Python contain a small set of variables I actually would like to see when I call `str()`, and that rewriting `__str__(self)` for each is rather cumbersome. Thus, I cooked up the following mixin, ``` class StrMixin(object): ''' Automatically generate __str__ and __repr__ ''' ...
When you define: ``` class StrMixin(object): ... ``` The compiler knows that `StrMixin` comes before `object` in the class's MRO. When you do: ``` class C(object, StrMixin): pass ``` You have told the compiler that `object` comes before `StrMixin` in the MRO. But `object` also has to come after `StrMixin` so...
What does locals()['_[1]'] mean in Python?
9,631,777
10
2012-03-09T09:34:12Z
9,631,961
9
2012-03-09T09:49:36Z
[ "python", "list", "syntax" ]
I saw a one liner code that is claimed to [remove duplicates from a sequence](http://www.testingreflections.com/node/view/5241): ``` u = [x for x in seq if x not in locals()['_[1]']] ``` I tried that code in ipython (with Python 2.7), it gave `KeyError: '_[1]'` Does `['_[1]']` mean something special in Python?
`locals()['_[1]']` is a way to access a reference to list comprehension (or generator) current result inside that list comprehension. It is quite an evil, but can produce funny results: ``` >> [list(locals()['_[1]']) for x in range(3)] [[], [[]], [[], [[]]]] ``` See more details here: [the-secret-name-of-list-compre...
What does locals()['_[1]'] mean in Python?
9,631,777
10
2012-03-09T09:34:12Z
9,632,177
7
2012-03-09T10:04:34Z
[ "python", "list", "syntax" ]
I saw a one liner code that is claimed to [remove duplicates from a sequence](http://www.testingreflections.com/node/view/5241): ``` u = [x for x in seq if x not in locals()['_[1]']] ``` I tried that code in ipython (with Python 2.7), it gave `KeyError: '_[1]'` Does `['_[1]']` mean something special in Python?
It is a temporary name used in a list comprehension by Python 2.6 and earlier. Python 2.7 and Python 3.x fixed this wart: the list being created is no longer accessible until creation has finished. Or in short it was an implementation detail that nobody should ever have relied on. Here you can see that Python 2.7 lea...
Django - Handling "enum models"
9,632,521
9
2012-03-09T10:28:18Z
9,633,015
8
2012-03-09T11:07:23Z
[ "python", "django", "django-models" ]
Is there any best practice in handling "support tables" in Django? I dislike `Field.choices`, as it doesn't really enforce integrity (it doesn't even create check constraints), so I prefer creating a full-blown model (and often, I find myself adding additional fields in the support table). Now, if I use a full model,...
Django ORM checks integrity if you specify choices attribute (when you insert/update data via user forms). You also can set validation logic to database level and use database ENUM field if you db support this. **UPD**: ``` class EnumField(models.Field): def __init__(self, *args, **kwargs): super(EnumFi...
Django logging of custom management commands
9,632,873
8
2012-03-09T10:56:46Z
9,635,649
11
2012-03-09T14:27:25Z
[ "python", "django", "logging" ]
I have an app named `main` in my Django project. This app has a several management commands that I want to log, but nothing is showing up in stdout with the following configuration: ``` LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'log_to_stdout': { 'level'...
you need to namespace your logger. currently you are logging to the root logger, which isn't caught by your handler, which is looking for `main` rather than `logging.debug("message")`, you want ``` logger = logging.getLogger('main') logger.debug("message") ```
How do I look up for a specific part / extension of file name?
9,633,214
2
2012-03-09T11:20:44Z
9,633,256
7
2012-03-09T11:23:47Z
[ "python" ]
I want to look for the extension of a filename, and the extension can only be 3 characters long. it is something like, ``` filename = str(input("Please enter filename: ")) ``` then I want to execute a task to look for the extension, and if the extension doesn't fulfill the requirement (i.e. 3 characters long), I'll ...
``` len(os.path.splitext('/foo/file.png')[1]) - 1 == 3 ```
UserWarning: Module matplotlib was already imported
9,635,014
2
2012-03-09T13:43:46Z
9,636,380
9
2012-03-09T15:13:57Z
[ "python", "matplotlib" ]
I get the following warning whenever running a script: ``` /usr/lib/pymodules/python2.6/mpl_toolkits/__init__.py:2: UserWarning: Module matplotlib was already imported from /usr/local/lib/python2.6/dist-packages/matplotlib/__init__.pyc, but /usr/lib/pymodules/python2.6 is being added to sys.path __import__('pkg_reso...
The "problem" is with your installation of matplotlib - or rather, your two installations of it - not with the program you're trying to run. From the message, I can infer that you have one version of matplotlib installed in /usr/local - perhaps a newer version that you installed yourself without using OS package manag...
Convert string date to timestamp in Python
9,637,838
86
2012-03-09T16:47:56Z
9,637,904
17
2012-03-09T16:52:48Z
[ "python", "datetime" ]
How to convert a string in the format `"%d/%m/%Y"` to timestamp? ``` "01/12/2011" -> 1322697600 ```
``` >>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s")) 1322683200 ```
Convert string date to timestamp in Python
9,637,838
86
2012-03-09T16:47:56Z
9,637,908
138
2012-03-09T16:53:05Z
[ "python", "datetime" ]
How to convert a string in the format `"%d/%m/%Y"` to timestamp? ``` "01/12/2011" -> 1322697600 ```
``` >>> import time >>> import datetime >>> s = "01/12/2011" >>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple()) 1322697600.0 ```
Convert string date to timestamp in Python
9,637,838
86
2012-03-09T16:47:56Z
9,637,927
7
2012-03-09T16:54:25Z
[ "python", "datetime" ]
How to convert a string in the format `"%d/%m/%Y"` to timestamp? ``` "01/12/2011" -> 1322697600 ```
First you must the [strptime](http://docs.python.org/library/time.html#time.strptime) class to convert the string to a struct\_time format. Then just use [mktime](http://docs.python.org/library/time.html#time.mktime) from there to get your float.
Convert string date to timestamp in Python
9,637,838
86
2012-03-09T16:47:56Z
16,102,056
9
2013-04-19T10:01:07Z
[ "python", "datetime" ]
How to convert a string in the format `"%d/%m/%Y"` to timestamp? ``` "01/12/2011" -> 1322697600 ```
The answer depends also on your input date timezone. If your date is a local date, then you can use mktime() like katrielalex said - only I don't see why he used datetime instead of this shorter version: ``` >>> time.mktime(time.strptime('01/12/2011', "%d/%m/%Y")) 1322694000.0 ``` But observe that my result is differ...
Convert string date to timestamp in Python
9,637,838
86
2012-03-09T16:47:56Z
20,035,328
18
2013-11-17T19:50:34Z
[ "python", "datetime" ]
How to convert a string in the format `"%d/%m/%Y"` to timestamp? ``` "01/12/2011" -> 1322697600 ```
To convert the string into a date object: ``` from datetime import date, datetime date_string = "01/12/2011" date_object = date(*map(int, reversed(date_string.split("/")))) assert date_object == datetime.strptime(date_string, "%d/%m/%Y").date() ``` The way to convert the date object into POSIX timestamp depends on t...
Is there any Python equivalent to partial classes?
9,638,446
22
2012-03-09T17:30:43Z
9,638,593
7
2012-03-09T17:43:50Z
[ "python", "partial-classes" ]
Using "new" style classes (I'm in python 3.2) is there a way to split a class over multiple files? I've got a large class (which really should be a single class from an object-oriented design perspective, considering coupling, etc, but it'd be nice to split over a few files just for ease of editing the class.
Class definitions containing hundreds of lines do occur "in the wild" (I have seen some in popular open-source Python-based frameworks), but I believe that if you ponder what the methods are doing, it will be possible to reduce the length of most classes to a manageable point. Some examples: * Look for places where mo...
Is there any Python equivalent to partial classes?
9,638,446
22
2012-03-09T17:30:43Z
9,638,653
24
2012-03-09T17:48:49Z
[ "python", "partial-classes" ]
Using "new" style classes (I'm in python 3.2) is there a way to split a class over multiple files? I've got a large class (which really should be a single class from an object-oriented design perspective, considering coupling, etc, but it'd be nice to split over a few files just for ease of editing the class.
If your problem really is just working with a large class in an editor, the first solution I'd actually look for is a better way to break down the problem. The second solution would be a better editor, preferably one with code folding. That said, there are a couple of ways you might break up a class into multiple file...
Plot a black-and-white binary map in matplotlib
9,638,826
13
2012-03-09T18:05:00Z
9,638,926
21
2012-03-09T18:13:26Z
[ "python", "matplotlib" ]
I'm using python to simulate some automation models, and with the help of matplotlib I'm producing plots like the one shown below. ![enter image description here](http://i.stack.imgur.com/SUeE2.png) I'm currently plotting with the following command: ``` ax.imshow(self.g, cmap=map, interpolation='nearest') ``` where...
You can change the color map you are using via the `cmap` keyword. The color map `'Greys'` provides the effect you want. You can find a list of [available maps on the scipy website](http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps). ``` import matplotlib.pyplot as plt import numpy as np np.random.seed(101) g =...
Python Remove last char from string and return it
9,639,754
14
2012-03-09T19:20:05Z
9,639,869
24
2012-03-09T19:31:21Z
[ "python" ]
While I know that there is the possibility: ``` >>> a = "abc" >>> result = a[-1] >>> a = a[:-1] ``` Now I also know that strings are immutable and therefore something like this: ``` >>> a.pop() c ``` is not possible. But is this really the preferred way?
Strings are "immutable" for good reason: It really saves a lot of headaches, more often than you'd think. It also allows python to be very smart about optimizing their use. If you want to process your string in increments, you can pull out part of it with `split()` or separate it into two parts using indices: ``` a = ...
jinja2 filesystemloader load all subdirectories
9,641,317
4
2012-03-09T21:35:09Z
9,644,828
12
2012-03-10T07:46:31Z
[ "python", "jinja2" ]
I currently have templates in multiple different sub directories and I would like to load all of the templates in jinja2. It appears that just pointing the FileSystemLoader directory at the top of the tree doesn't pick up anything in the sub folders. Is there a way to get jinja2 to load all of the sub directories (jus...
Jinja does take the subfolders into account, but templates must be referenced with paths relative to the root folder. If we have mydir/foo/bar.html, this works: ``` template_env = jinja2.Environment(loader=jinja2.FileSystemLoader('mydir')) template_env.get_template('foo/bar.html') ```
Convert from ASCII string encoded in Hex to plain ASCII?
9,641,440
71
2012-03-09T21:47:30Z
9,641,593
29
2012-03-09T22:01:05Z
[ "python", "hex", "ascii" ]
How can I convert from hex to plain ASCII in Python? Note that, for example, I want to convert "0x7061756c" to "paul".
``` >>> txt = '7061756c' >>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])]) 'paul' ``` i'm just having fun, but the important parts are: ``` >>> int('0a',16) # parse hex 10 >>> ''.join(['a', 'b']) # join characters 'ab' >>> 'abcd'[0::2] # alternates 'ac' >>> zip('abc', '123') ...
Convert from ASCII string encoded in Hex to plain ASCII?
9,641,440
71
2012-03-09T21:47:30Z
9,641,622
140
2012-03-09T22:03:09Z
[ "python", "hex", "ascii" ]
How can I convert from hex to plain ASCII in Python? Note that, for example, I want to convert "0x7061756c" to "paul".
A slightly simpler solution: ``` >>> "7061756c".decode("hex") 'paul' ```
Convert from ASCII string encoded in Hex to plain ASCII?
9,641,440
71
2012-03-09T21:47:30Z
27,519,487
15
2014-12-17T06:22:25Z
[ "python", "hex", "ascii" ]
How can I convert from hex to plain ASCII in Python? Note that, for example, I want to convert "0x7061756c" to "paul".
No need to import any library: ``` >>> bytearray.fromhex("7061756c").decode() 'paul' ```
Is it possible to get a list of keywords in Python?
9,642,087
22
2012-03-09T22:55:22Z
9,642,128
8
2012-03-09T23:00:58Z
[ "python", "list", "syntax" ]
I'd like to get a list of all of Pythons keywords as strings. It would also be rather nifty if I could do a similar thing for built in functions. Something like this : ``` import syntax print syntax.keywords # prints ['print', 'if', 'for', etc...] ```
The built-in functions are in a module called `__builtins__`, so: ``` dir(__builtins__) ```
Is it possible to get a list of keywords in Python?
9,642,087
22
2012-03-09T22:55:22Z
9,642,137
42
2012-03-09T23:02:19Z
[ "python", "list", "syntax" ]
I'd like to get a list of all of Pythons keywords as strings. It would also be rather nifty if I could do a similar thing for built in functions. Something like this : ``` import syntax print syntax.keywords # prints ['print', 'if', 'for', etc...] ```
You asked about **statements**, while showing **keywords** in your output example. If you're looking for **keywords**, they're all listed in the [`keyword`](http://docs.python.org/library/keyword.html) module: ``` >>> import keyword >>> keyword.kwlist ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del'...
Python files - import from each other
9,642,451
10
2012-03-09T23:41:14Z
9,642,488
21
2012-03-09T23:46:04Z
[ "python", "import", "compilation", "package", "importerror" ]
I would like for two of my python files to import some methods from each other. This seems to be giving me import errors. **Example:** file\_A.py: ``` from file_B import do_B_stuff ``` file\_B.py: ``` from file_A import do_A_stuff ``` The reason I am trying to do this is because I would like to organize my projec...
Don't use the names within the other module directly. ### file\_A.py ``` import file_B def something(): file_B.do_B_stuff ``` ### file\_B.py ``` import file_A def something(): file_A.do_A_stuff ```
argparse help without duplicate ALLCAPS
9,642,692
8
2012-03-10T00:15:50Z
9,643,173
7
2012-03-10T01:37:17Z
[ "python", "argparse" ]
I'd like to display argparse help for my options the same way the default `-h`,`--help` and `-v`,`--version` are, without the ALLCAPS text after the option, or at least without the duplicated CAPS. ``` import argparse p = argparse.ArgumentParser("a foo bar dustup") p.add_argument('-i', '--ini', help="use alternate ini...
You could customize `usage` and assign `metavar` to an empty string: ``` import argparse p = argparse.ArgumentParser("a foo bar dustup", usage='%(prog)s [-h] [-i INI]') p.add_argument('-i', '--ini', help="use alternate ini file", metavar='') p.print_help() ``` ### Output ``` usage: a foo bar dustup [-h] [-i INI] o...
Import json file to Django model
9,643,291
8
2012-03-10T02:02:05Z
12,896,841
9
2012-10-15T13:39:00Z
[ "python", "django", "json" ]
I have a file in json format, with such a structure: ``` { "Admiralty Islands": [ [ "Up to 1 kg", "5.00" ], [ "1 - 10 kg", "10.00" ], ], "Afghanistan": [ [ "Up to 1 kg", "15.00" ], ...
Use manage.py to import fixtures: ``` python manage.py loaddata fixture.json ```
64-bit Integer vs. 64-bit Float: which one has more values?
9,643,526
3
2012-03-10T02:48:32Z
9,643,558
7
2012-03-10T02:55:24Z
[ "python" ]
Which has more values, a 64-bit integer or a 64-bit float? My answer is that float has more value because its more accurate. But isn't integer is always greater than a float ?
There are more *unique values* in a 64-bit integer (2^64 for a two's complement machine). However, a 64-bit float has *much larger range* of values. This can be trivially reasoned about because a 64-bit integer *has a unique bit pattern for each unique value* (it is "100% efficient") while a 64-bit float has a dedica...
Python - 'ascii' codec can't decode byte
9,644,099
69
2012-03-10T05:10:46Z
9,644,115
36
2012-03-10T05:14:14Z
[ "python", "unicode", "python-unicode" ]
I'm really confused. I tried to encode but the error said `can't decode...`. What is Python doing under the hood? ``` >>> "你好".encode("utf8") Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128) ```
Always *encode* from unicode to bytes. In this direction, **you get to choose the encoding**. ``` >>> u"你好".encode("utf8") '\xe4\xbd\xa0\xe5\xa5\xbd' >>> print _ 你好 ``` The other way is to decode from bytes to unicode. In this direction, **you have to know what the encoding is**. ``` >>> bytes = '\xe4\xb...
Python - 'ascii' codec can't decode byte
9,644,099
69
2012-03-10T05:10:46Z
9,644,206
109
2012-03-10T05:34:51Z
[ "python", "unicode", "python-unicode" ]
I'm really confused. I tried to encode but the error said `can't decode...`. What is Python doing under the hood? ``` >>> "你好".encode("utf8") Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128) ```
``` "你好".encode('utf-8') ``` `encode` converts a unicode object to a `string` object. But here you have invoked it on a `string` object (because you don't have the u). So python has to convert the `string` to a `unicode` object first. So it does the equivalent of ``` "你好".decode().encode('utf-8') ``` But the...
Python - 'ascii' codec can't decode byte
9,644,099
69
2012-03-10T05:10:46Z
34,591,774
22
2016-01-04T13:00:19Z
[ "python", "unicode", "python-unicode" ]
I'm really confused. I tried to encode but the error said `can't decode...`. What is Python doing under the hood? ``` >>> "你好".encode("utf8") Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128) ```
**You can try this** ``` import sys reload(sys) sys.setdefaultencoding("utf-8") ``` Or **You can also try following** Add following line at top of your .py file. ``` # -*- coding: utf-8 -*- ```
Difference between parsing a text file in r and rb mode
9,644,110
25
2012-03-10T05:13:05Z
9,644,141
13
2012-03-10T05:19:50Z
[ "python", "file-io", "text-parsing" ]
What makes parsing a text file in 'r' mode more convenient than parsing it in 'rb' mode? Especially when the text file in question may contain non-ASCII characters.
from the [documentation](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files): > On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters...
Difference between parsing a text file in r and rb mode
9,644,110
25
2012-03-10T05:13:05Z
9,644,285
24
2012-03-10T05:53:11Z
[ "python", "file-io", "text-parsing" ]
What makes parsing a text file in 'r' mode more convenient than parsing it in 'rb' mode? Especially when the text file in question may contain non-ASCII characters.
This depends a little bit on what version of Python you're using. In Python 2, [Chris Drappier's answer](http://stackoverflow.com/a/9644141/779200) applies. In Python 3, its a different (and more consistent) story: in text mode (`'r'`), Python will parse the file according to the text encoding you give it (or, if you ...
Python: -mno -cygwin
9,645,004
6
2012-03-10T08:21:38Z
9,646,031
17
2012-03-10T11:24:10Z
[ "python", "gcc", "cygwin" ]
i'm trying to learn a lot of python on windows and that includes installing several packages, however everytime i invoke python setup.py install i have a problem with -mno -cygwin for gcc. i've have read already a lot of articles and it seems they want that these individual packages to wait for the fix on their own bu...
I had this problem too, and this is a bug in the Python code. The only way I found to fix it was to edit the file `C:\Python27\Lib\distutils\cygwinccompiler.py`. In this file you must remove every occurence of `-mno-cygwin`. The same goes for GCC installed through MinGW.
How can I create byte values from integers in Python?
9,645,188
3
2012-03-10T09:02:14Z
9,645,209
8
2012-03-10T09:05:07Z
[ "python", "serial-port", "arduino", "pyserial" ]
Background: I need to send a numerical value as a byte to an external device, but I have run into a problem. My code is: ``` ser=serial.Serial("COM3",9600, timeout=0) ser.write(value) ``` where "value" is an int that I read have read. The problem is, when I send this, it sends the character value, not the actual valu...
Use the built-in function [`chr()`](http://docs.python.org/library/functions.html#chr). If you have a list of such integers you need to send, you might consider using a [`bytearray()`](http://docs.python.org/library/functions.html#bytearray). Alternatively, in newer versions of Python you can simply use a `byte` type...
How to determine path to php.exe on windows - search default paths?
9,645,545
9
2012-03-10T09:59:59Z
9,645,756
20
2012-03-10T10:41:39Z
[ "php", "python", "windows", "path", "sublimetext" ]
I'm currently developing a couple of plugins for Sublime Text 2 on OS X and I would like to make them cross platform, meaning I have to find out if and where `php.exe` is installed. Right now I call `/usr/bin/php` in Python, which obviously works only on OS X and Linux: ``` phppath = '/usr/bin/php'<br> pluginpath = s...
If the user has defined added PHP's bin folder to the system `PATH` then you should just be able to try and execute `php -v` to check that it's present. If you want to obtain the full path to the php executable and the target system is Windows 2003 or later (so Vista, and 7) then you could use the `WHERE` command, ie:...
Django project at Heroku cannot install dependencies with pip
9,645,924
2
2012-03-10T11:07:45Z
9,653,491
7
2012-03-11T08:22:17Z
[ "python", "django", "heroku", "virtualenv", "pip" ]
i'm trying to deploy a django project on Heroku. I use virtualenv and pip to manage dependencies. The virtualenv version is 1.7.1 and pip that comes with it it's 1.1. I tried to force the --no-site-packages but it prompts that it's the default behavior now. Also i'm sure that i install everything within the virtual env...
It seems that the problem it is in the requirements.txt, i created it using powershell and "pip.exe freeze > requirements.txt" command, which creates a file with a name that has nullbytes in it. I was able to get around this problem by downloading a requirements.txt from an example project on github and modifying it. T...
Python objects - avoiding creation of attribute with unknown name
9,646,015
10
2012-03-10T11:20:45Z
9,646,051
14
2012-03-10T11:27:32Z
[ "python", "object", "attributes" ]
Wishing to avoid a situation like this: ``` >>> class Point: x = 0 y = 0 >>> a = Point() >>> a.X = 4 #whoops, typo creates new attribute capital x ``` I created the following object to be used as a superclass: ``` class StrictObject(object): def __setattr__(self, item, value): if item in dir(self): ...
Much better ways. The most common way is "we're all consenting adults". That means, you don't do any checking, and you leave it up to the user. Any checking you do makes the code less flexible in it's use. But if you really want to do this, there is [`__slots__`](http://docs.python.org/reference/datamodel.html#slots)...
How to copy a member function of another class into myclass in python?
9,646,187
6
2012-03-10T11:51:53Z
9,646,242
8
2012-03-10T12:00:06Z
[ "python", "reflection" ]
I have a utility class from which I want to use one of the member function in another class. I don't want to inherit from that class. I just want to re-use the code from one of the member function of the other class. Kind of partial inheritance. ``` class HugeClass(): def interestedFunc(self,arg1): doSomethin...
You can do what you want ie.: ``` class Foo(object): def foo(self): print self.a class Bar(object): foo = Foo.__dict__['foo'] b = Bar() b.a = 1 b.foo() ``` But are you sure that this is good idea?
What does ECONNABORTED mean when trying to connect a socket?
9,646,550
5
2012-03-10T12:49:51Z
9,650,977
10
2012-03-10T23:06:19Z
[ "python", "sockets" ]
I'm using python 2.7 on an ubuntu machine. The client tries to connect to the server. I get a EINPROGRESS which is expected for non-blocking sockets. To check whether or not the connection succeeded, I do what the man page for {connect} suggest: ``` # EINPROGRESS The socket is nonblocking and the connection cannot b...
`ECONNABORTED` is set in two places of the Linux Kernel Source Socket Code. As per the `errno` man page and **/include/asm-generic/errno.h** `#define ECONNABORTED 103 /* Software caused connection abort */` The [first](http://lxr.free-electrons.com/source/net/socket.c#L1533) is in the function that defines the sysca...
"outsourcing" exception-handling to a decorator
9,647,021
23
2012-03-10T14:01:41Z
9,647,491
14
2012-03-10T15:11:57Z
[ "python", "exception-handling", "decorator", "python-2.6" ]
Many try/except/finally-clauses not only "uglify" my code, but often i find myself using identical exception-handling for different tasks. So i was considering reducing redundancy by "outsourcing" them to a ... decorator. Because i was sure not to be the 1st one to come to this conclusion, I googled and found this - i...
The biggest reason to keep the try/except/finally blocks in the code itself is that error recovery is usually an integral part of the function. For example, if we had our own `int()` function: ``` def MyInt(text): return int(text) ``` What should we do if `text` cannot be converted? Return `0`? Return `None`? I...
Ordinal numbers replacement
9,647,202
17
2012-03-10T14:27:49Z
20,007,730
45
2013-11-15T18:07:32Z
[ "python", "nlp", "nltk", "ordinals" ]
I am currently looking for the way to replace words like first, second, third,...with appropriate ordinal number representation (1st, 2nd, 3rd). I have been googling for the last week and I didn't find any useful standard tool or any function from NLTK. So is there any or should I write some regular expressions manual...
Here's a terse solution taken from [Gareth on codegolf](http://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd#answer-4712): ``` ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) ``` Works on any number: ``` print [ordinal(n) for n in range(1,32)] ['1st', '2...
Getting a request parameter in Jinja2
9,647,586
21
2012-03-10T15:25:55Z
16,875,941
31
2013-06-01T18:30:29Z
[ "python", "flask", "jinja2" ]
How can I retrieve a request param `a` in Jinja2 template? ``` http://foo.bar?a=1 ```
I'm a bit late with this answer, but the other solutions don't really account for your use of Flask. The fact that you're using Flask with Jinja2 makes your situation a bit different from other frameworks. Flask actually makes some global variables available to you in all Jinja2 templates without requiring you to pass...
Linking QLineEdit's "enter" event to a slot?
9,647,801
2
2012-03-10T15:54:34Z
9,647,837
8
2012-03-10T15:59:26Z
[ "python", "qt4", "pyqt" ]
I do have the following code: ``` def init_widgets(self): mainLayout = QtGui.QGridLayout() self.label1 = QtGui.QLabel("Enter a song name: ") self.search_lineEdit = QtGui.QLineEdit() self.search_button = QtGui.QPushButton("&Search") # QCommandLinkButton self.search_button.clicke...
`QLineEdit` has a [`returnPressed`](http://qt-project.org/doc/qt-4.8/qlineedit.html#returnPressed) signal. You can connect that signal from `search_lineEdit` to your custom slot. Not familiar with the PyQt syntax, but should be something like: ``` self.search_lineEdit.returnPressed.connect(self.search_slot) ```
PyPi download counts seem unrealistic
9,648,015
61
2012-03-10T16:23:14Z
9,649,144
9
2012-03-10T18:46:30Z
[ "python", "web-crawler", "pypi" ]
I put [a package on PyPi](http://pypi.python.org/pypi/powerlaw) for the first time ~2 months ago, and have made some version updates since then. I noticed this week the download count recording, and was surprised to see it had been downloaded hundreds of times. Over the next few days, I was more surprised to see the do...
You also have to take into account that virtualenv is getting more popular. If your package is something like a core library that people use in many of their projects, they will usually download it multiple times. Consider a single user has 5 projects where he uses your package and each lives in its own virtualenv. Us...
PyPi download counts seem unrealistic
9,648,015
61
2012-03-10T16:23:14Z
14,726,265
69
2013-02-06T10:05:29Z
[ "python", "web-crawler", "pypi" ]
I put [a package on PyPi](http://pypi.python.org/pypi/powerlaw) for the first time ~2 months ago, and have made some version updates since then. I noticed this week the download count recording, and was surprised to see it had been downloaded hundreds of times. Over the next few days, I was more surprised to see the do...
This is kind of an old question at this point, but I noticed the same thing about a package I have on PyPI and investigated further. It turns out PyPI keeps reasonably detailed [download statistics](http://pypi.python.org/stats/), including (apparently slightly anonymised) user agents. From that, it was apparent that m...
PyPi download counts seem unrealistic
9,648,015
61
2012-03-10T16:23:14Z
15,584,542
10
2013-03-23T07:47:19Z
[ "python", "web-crawler", "pypi" ]
I put [a package on PyPi](http://pypi.python.org/pypi/powerlaw) for the first time ~2 months ago, and have made some version updates since then. I noticed this week the download count recording, and was surprised to see it had been downloaded hundreds of times. Over the next few days, I was more surprised to see the do...
Starting with Cairnarvon's summarizing statement: > "It looks like the main reason PyPI needs mirrors is because it has them." I would slightly modify this: > It might be more the **way** PyPI actually works and thus has to be mirrored, that might contribute an additional bit (or two :-) to the *real* traffic. At t...
Python cdecimal InvalidOperation
9,648,650
9
2012-03-10T17:38:13Z
9,649,536
12
2012-03-10T19:35:50Z
[ "python", "decimal", "invalidoperationexception" ]
I am trying to read financial data and store it. The place I get the financial data from stores the data with incredible precision, however I am only interested in 5 figures after the decimal point. Therefore, I have decided to use t = .quantize(cdecimal.Decimal('.00001'), rounding=cdecimal.ROUND\_UP) on the Decimal I ...
decimal version gives a better description of the error: ``` Python 2.7.2+ (default, Feb 16 2012, 18:47:58) >>> import decimal >>> s = '45.2091000080109' >>> decimal.getcontext().prec = 5 >>> decimal.Decimal(s).quantize(decimal.Decimal('.00001'), rounding=decimal.ROUND_UP) Traceback (most recent call last): File "<...
dendrogram in python
9,648,685
9
2012-03-10T17:44:34Z
9,648,746
8
2012-03-10T17:50:49Z
[ "python", "dendrogram" ]
I am wanting to write code to draw a dendrogram in python. is there a simple way of going about it. I have written code that identifies clusters in a point dataset and want to produce a dendrogram that shows the amount of clusters produced for each iteration for example when i run my code on this dataset i get 1 clus...
[SciPy does clustering](http://docs.scipy.org/doc/scipy/reference/cluster.hierarchy.html#module-scipy.cluster.hierarchy) and comes with [a function to turn such clusterings into dendrograms](http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.dendrogram.html#scipy.cluster.hierarchy.dendrogram). ...
Why is it possible to iterate along a string?
9,649,103
14
2012-03-10T18:39:30Z
9,649,139
9
2012-03-10T18:46:00Z
[ "python" ]
I'm trying to understand why I can iterate along the string. What I see in the documentation is: > One method needs to be defined for container objects to provide > iteration support: > > container.**\_\_*iter*\_\_**() > > Return an iterator object. The object is required > to support the iterator protocol described b...
Iterators were new in Python 2.2. The old method was the sequence protocol (implements `__getitem__` with 0-based indices) and still works.
My matplotlib.pyplot legend is being cut off
9,651,092
19
2012-03-10T23:27:01Z
9,651,897
14
2012-03-11T03:27:08Z
[ "python", "matplotlib" ]
I'm attempting to create a plot with a legend to the side of it using matplotlib. I can see that the plot is being created, but the image bounds do not allow the entire legend to be displayed. ``` lines = [] ax = plt.subplot(111) for filename in args: lines.append(plt.plot(y_axis, x_axis, colors[colorcycle], lines...
As pointed by Adam, you need to make space on the side of your graph. If you want to fine tune the needed space, you may want to look at the [add\_axes](http://matplotlib.sourceforge.net/api/figure_api.html?highlight=add_axes#matplotlib.figure.Figure.add_axes) method of matplotlib.pyplot.artist. Below is a rapid examp...
Is there an equivalent of PHP's hash_hmac in Python/Django?
9,652,124
10
2012-03-11T03:19:27Z
9,652,135
25
2012-03-11T03:21:53Z
[ "php", "python", "django", "sha256" ]
I want to forward my visitors to a 3rd party paysite. This 3rd party will process their payment and POST to me a 64 character token generated from a unique order number and shared password using PHP's [hash\_hmac](http://php.net/manual/en/function.hash-hmac.php) using the sha256 algorithm, like so: ``` $token = hash_h...
You want [`hmac`](http://docs.python.org/library/hmac.html). ``` hmac.new("sharedpassword", "12345", hashlib.sha256).hexdigest() ```
Is there any way to list queues in a rabbitmq via pika?
9,652,295
8
2012-03-11T03:56:15Z
9,652,322
11
2012-03-11T04:01:44Z
[ "python", "queue", "rabbitmq", "pika" ]
I know that we can do this to list queue in a rabbitmq. ``` rabbitmqctl list_queues ``` but how can I do this via pika?
No. Pika is an AMQP library. If you want to manage an MQ Broker, then you need an MQ Broker management tool. Fortunately, RabbitMQ comes with such a tool if you install a recent version of RabbitMQ such as 2.7.1 and you install the RabbitMQ management plugins. That gives you a web GUI as well as a RESTful API that yo...
How to I load a tsv file into a Pandas DataFrame?
9,652,832
23
2012-03-11T06:00:56Z
9,652,858
34
2012-03-11T06:06:56Z
[ "python", "pandas", "tsv" ]
I'm new to python and pandas. I'm trying to get a `tsv` file loaded into a pandas `DataFrame`. This is what I'm trying and the error I'm getting: ``` >>> df1 = DataFrame(csv.reader(open('c:/~/trainSetRel3.txt'), delimiter='\t')) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> df1 = ...
The documentation lists a [.from\_csv](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.from_csv.html) function that appears to do what you want: ``` DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t') ``` If you have a header, you can pass `header=0`. ``` DataFrame.from_csv('c:/~/trainSetRel3.t...
How to I load a tsv file into a Pandas DataFrame?
9,652,832
23
2012-03-11T06:00:56Z
9,656,288
29
2012-03-11T15:34:23Z
[ "python", "pandas", "tsv" ]
I'm new to python and pandas. I'm trying to get a `tsv` file loaded into a pandas `DataFrame`. This is what I'm trying and the error I'm getting: ``` >>> df1 = DataFrame(csv.reader(open('c:/~/trainSetRel3.txt'), delimiter='\t')) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> df1 = ...
Use `read_table(filepath)`. The default separator is tab
How to I load a tsv file into a Pandas DataFrame?
9,652,832
23
2012-03-11T06:00:56Z
34,548,894
11
2015-12-31T16:13:36Z
[ "python", "pandas", "tsv" ]
I'm new to python and pandas. I'm trying to get a `tsv` file loaded into a pandas `DataFrame`. This is what I'm trying and the error I'm getting: ``` >>> df1 = DataFrame(csv.reader(open('c:/~/trainSetRel3.txt'), delimiter='\t')) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> df1 = ...
As of 17.0 [`from_csv`](http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.from_csv.html) is discouraged. Use `pd.read_csv(fpath, sep='\t')` or `pd.read_table(fpath)`.
Metaclasses and __slots__?
9,654,133
9
2012-03-11T10:23:17Z
9,654,228
11
2012-03-11T10:39:12Z
[ "python" ]
So, I am reading a bit about metaclasses in Python, and how `type()`'s three-argument alter-ego is used to dynamically create classes. However, the third argument is usually a `dict` that initializes the to-be created class' `__dict__` variable. If I want to dynamically create classes based on a metaclass that uses `_...
You can't create a type with a non-empty \_\_slots\_\_ attribute. What you can do is insert a \_\_slots\_\_ attribute into the new class's dict, like this: ``` class Meta(type): def __new__(cls, name, bases, dctn): dctn['__slots__'] = ( 'x', ) return type.__new__(cls, name, bases, dctn) class ...
Why does foo = function() run the function in Python?
9,655,725
7
2012-03-11T14:22:01Z
9,655,781
14
2012-03-11T14:28:57Z
[ "python", "function", "variables" ]
I'm up to Exercise 41 in Learn Python the Hard Way, and I'm having a really hard time wrapping my brain around the fact that the entire thing hinges on a function running just because it's been assigned as a value to a variable. I wrote up a little script to confirm that this is how it works, and it does: ``` def pant...
When you use the parentheses `()` the function gets called. If you want to assign the function to the variable to reuse it you should remove there parentheses. Example: ``` def pants(): print "Put on some pants!" def shorts(): print "And don't forget your underwear!" zap = pants thing = shorts ``` And then...
Initializing matrix in Python using "[[0]*x]*y" creates linked rows?
9,658,459
3
2012-03-11T20:10:57Z
9,658,522
8
2012-03-11T20:17:55Z
[ "python", "matrix" ]
Initializing a matrix as so seems to link the rows so that when one row changes, they all change: ``` >>> grid = [[0]*5]*5 >>> grid [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> grid[2][2] = 1 >>> grid [[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0...
``` grid = [[0]*5 for i in range(5)] ``` Note: [int]\*5 copies the int 5 times (but when you copy an int you just copy the value). [list]\*5 copies the reference to the same list 5 times. (when you copy a list you copy the reference that points to the list in memory).
python check if word is in certain elements of a list
9,659,494
4
2012-03-11T22:25:39Z
9,659,532
7
2012-03-11T22:29:51Z
[ "python", "list", "word" ]
I was wondering if there was a better way to put: ``` if word==wordList[0] or word==wordList[2] or word==wordList[3] or word==worldList[4] ```
``` word in wordList ``` Or, if you want to check the 4 first, ``` word in wordList[:4] ```
Why does my code work from interactive shell, but not when run from a file?
9,659,585
2
2012-03-11T22:36:59Z
9,659,603
9
2012-03-11T22:38:37Z
[ "python", "python-module", "pprint", "python-interactive" ]
I am trying to use the `pprint` module to check out some vars in Python, which I can happily do using the interactive shell and the code below: ``` import pprint pp = pprint.PrettyPrinter() stuff = ['cakes','bread','mead'] pp.pprint(stuff) ``` However, when I put the above into `pprint.py` and run it using `python pp...
You named your program pprint.py, so at the line `import pprint` it tries to import itself. It succeeds, but *your* pprint.py doesn't contain anything called PrettyPrinter. Change your code's name. [And, to be clear, delete any pprint.pyc or pprint.pyo files..]
Python permutations with constraints
9,660,085
10
2012-03-11T23:46:47Z
9,660,395
12
2012-03-12T00:37:46Z
[ "python", "permutation", "itertools" ]
I am using python 3 and I am trying to find a way to get all the permutations of a list while enforcing some constraints. For instance, I have a list `L=[1, 2, 3, 4, 5, 6, 7]` I want to find all permutations. However, My constraints are: * 1 should always come before 2. * 3 should come before 4 which in turn should ...
This approach filters permutations using a simple filter. ``` import itertools groups = [(1,2),(3,4,5),(6,7)] groupdxs = [i for i, group in enumerate(groups) for j in range(len(group))] old_combo = [] for dx_combo in itertools.permutations(groupdxs): if dx_combo <= old_combo: # as simple filter continue ...
python opencv imwrite ... can't find params
9,661,512
6
2012-03-12T03:48:03Z
9,661,581
23
2012-03-12T04:00:41Z
[ "python", "opencv" ]
I am using opencv with python. I wanted to do an cv2.imwrte: ``` cv2.imwrite('myimage.png', my_im) ``` The only problem is that opencv does not recognize the params constants: ``` cv2.imwrite('myimage.png', my_im, cv2.CV_IMWRITE_PNG_COMPRESSION, 0) ``` It cannot find CV\_IMWRITE\_PNG\_COMPRESSION at all. Any ideas?
I can't find key `CV_XXXXX` in the `cv2` module: 1. Try `cv2.XXXXX` 2. Failing that, use `cv2.cv.CV_XXXXX` In your case, `cv2.cv.CV_IMWRITE_PNG_COMPRESSION`. --- ### More info. The docs for OpenCV (cv2 interface) are a bit confusing. Usually parameters that look like `CV_XXXX` are actually `cv2.XXXX`. I use the ...
How to create a multiline entry with tkinter?
9,661,854
9
2012-03-12T04:44:17Z
9,662,139
7
2012-03-12T05:27:31Z
[ "python", "input", "tkinter", "multiline", "entry" ]
`Entry` widgets seem only to deal with single line text. I need a multiline entry field to type in email messages. Anyone has any idea how to do that?
You could use the [Text](http://www.tkdocs.com/tutorial/morewidgets.html#text) widget: ``` from tkinter import * root = Tk() text = Text(root) text.pack() root.mainloop() ``` Or with scrolling bars using [ScrolledText](http://docs.python.org/library/scrolledtext.html): ``` from tkinter import * from tkinter.scrolle...
What is the proper pattern in Python for implementing lazy getters?
9,662,164
6
2012-03-12T05:31:37Z
9,662,214
7
2012-03-12T05:38:33Z
[ "python", "design-patterns", "getter" ]
Sometimes I like to write getter attributes for an object such that the first time they are called, the heavy lifting is done once, and that value is saved and returned on future calls. In objective-c I would use an ivar or a static variable to hold this value. Something like: ``` - (id)foo { if ( _foo == nil ) ...
Use a [lazy property](http://stackoverflow.com/questions/3012421/python-lazy-property-decorator) instead. Getters are [so 1990's](http://www.archive.org/details/SeanKellyRecoveryfromAddiction).
Class does not have a table or tablename specified and does not inherit from an existing table-mapped class
9,662,271
14
2012-03-12T05:45:52Z
9,662,453
12
2012-03-12T06:09:02Z
[ "python", "mysql", "sqlalchemy", "flask-sqlalchemy" ]
When I tried to add a new table to python/flask - ``` class UserRemap(db.Model): name = db.Column(db.String(40)) email = db.Column(db.String(255)) password = db.Column(db.String(64)) flag = db.Column(db.String(1)) def __init__(self, name, email, password): self.email = email self.n...
You have to mention `__tablename__` or `__table__` to notify sqlalchemy for table in database. ``` class UserRemap(db.Model): __tablename__ = 'UserRemap' name = db.Column(db.String(40)) email = db.Column(db.String(255)) password = db.Column(db.String(64)) flag = db.Column(db.String(1)) def __i...
Class does not have a table or tablename specified and does not inherit from an existing table-mapped class
9,662,271
14
2012-03-12T05:45:52Z
14,595,840
75
2013-01-30T02:44:52Z
[ "python", "mysql", "sqlalchemy", "flask-sqlalchemy" ]
When I tried to add a new table to python/flask - ``` class UserRemap(db.Model): name = db.Column(db.String(40)) email = db.Column(db.String(255)) password = db.Column(db.String(64)) flag = db.Column(db.String(1)) def __init__(self, name, email, password): self.email = email self.n...
Per the Flask-SQLAlchemy [docs](http://packages.python.org/Flask-SQLAlchemy/models.html) inheriting from db.Model will automatically setup the table name for you. The reason you are seeing this message is because you don't have a primary key defined for that table. The error message is kind of unhelpful, but adding a ...
matplotlib: change title and colorbar text and tick colors
9,662,995
4
2012-03-12T07:10:49Z
9,666,308
10
2012-03-12T11:36:34Z
[ "python", "matplotlib" ]
I wanted to know how to change the color of the ticks in the colorbar and how to change the font color of the title and colorbar in a figure. For example, things obviously are visible in temp.png but not in temp2.png: ``` import matplotlib.pyplot as plt import numpy as np from numpy.random import randn fig = plt.figu...
This can be done by inspecting and setting properties for object handler in matplotlib. I edited your code and put some explanation in comment: ``` import matplotlib.pyplot as plt import numpy as np from numpy.random import randn fig = plt.figure() data = np.clip(randn(250,250),-1,1) cax = plt.imshow(data, interpola...
what is difference between __init__ and __call__ in python?
9,663,562
111
2012-03-12T08:09:45Z
9,663,597
9
2012-03-12T08:13:24Z
[ "python" ]
I want to know what is difference between `__init__` and `__call__` methods? For example : ``` class test: def __init__(self): self.a = 10 def __call__(self): b = 20 ```
`__init__` would be treated as Constructor where as `__call__` methods can be called with objects any number of times. Both `__init__` and `__call__` functions do take default arguments.
what is difference between __init__ and __call__ in python?
9,663,562
111
2012-03-12T08:09:45Z
9,663,601
150
2012-03-12T08:13:42Z
[ "python" ]
I want to know what is difference between `__init__` and `__call__` methods? For example : ``` class test: def __init__(self): self.a = 10 def __call__(self): b = 20 ```
The first is used to initialise newly created object, and receives arguments used to do that: ``` class foo: def __init__(self, a, b, c): # ... x = foo(1, 2, 3) # __init__ ``` The second implements function call operator. ``` class foo: def __call__(self, a, b, c): # ... x = foo() x(1, 2, 3...
what is difference between __init__ and __call__ in python?
9,663,562
111
2012-03-12T08:09:45Z
9,663,704
65
2012-03-12T08:21:30Z
[ "python" ]
I want to know what is difference between `__init__` and `__call__` methods? For example : ``` class test: def __init__(self): self.a = 10 def __call__(self): b = 20 ```
Defining a custom `__call__()` method in the meta-class allows the class's instance to be called as a function, not always modifying the instance itself. ``` In [1]: class A: ...: def __init__(self): ...: print "init" ...: ...: def __call__(self): ...: print "call" .....
what is difference between __init__ and __call__ in python?
9,663,562
111
2012-03-12T08:09:45Z
22,879,086
19
2014-04-05T09:32:47Z
[ "python" ]
I want to know what is difference between `__init__` and `__call__` methods? For example : ``` class test: def __init__(self): self.a = 10 def __call__(self): b = 20 ```
``` >>> class A: ... def __init__(self): ... print "init" ... ... def __call__(self): ... print "call" ... >>> >>> A() init >>> A()() init call ```
what is difference between __init__ and __call__ in python?
9,663,562
111
2012-03-12T08:09:45Z
29,727,916
13
2015-04-19T09:12:08Z
[ "python" ]
I want to know what is difference between `__init__` and `__call__` methods? For example : ``` class test: def __init__(self): self.a = 10 def __call__(self): b = 20 ```
In Python, functions are first-class objects, this means: function references can be passed in inputs to other functions and/or methods, and executed from inside them. *Instances of Classes* (aka Objects), can be treated as if they were functions: pass them to other methods/functions and call them. In order to achieve...
Apply a method to an object of another class
9,663,849
5
2012-03-12T08:35:23Z
9,663,900
9
2012-03-12T08:41:11Z
[ "python" ]
Given two non-related classes A and B, how to call `A.method` with an object of B as `self`? ``` class A: def __init__(self, x): self.x = x def print_x(self): print self.x class B: def __init__(self, x): self.x = x a = A('spam') b = B('eggs') a.print_x() #<-- spam <magic>(A.prin...
In Python 3.x you can simply do what you want: ``` A.print_x(b) #<-- 'eggs' ``` If you only have an instance of 'A', then get the class first: ``` a.__class__.print_x(b) #<-- 'eggs' ``` In Python 2.x (which the OP uses) this doesn't work, as noted by the OP and explained by Amber in the comments: > *This is a diff...
Need a good beginner's WSGI guide
9,663,980
2
2012-03-12T08:46:51Z
9,664,122
8
2012-03-12T09:00:10Z
[ "python", "wsgi" ]
I have an almost complete simple web app written as a Python CGI script. I would like to change it to use WSGI, but I can't find documentation that helps me make sense of what WSGI actually is (one only repeatedly finds calls with start\_response etc. but there doesn't seem to be much explanation fo rwhat these calls a...
WSGI is [PEP 333](http://www.python.org/dev/peps/pep-0333/) (and [PEP3333](http://www.python.org/dev/peps/pep-3333/) for Python 3), a.k.a. Web Server Gateway Interface. It has three parts, but the part you're interested in is how you write a WSGI application. And WSGI app is a callable object that takes two arguments a...
Python 2.6.1: Checking if imports exist
9,664,361
3
2012-03-12T09:18:47Z
13,163,067
7
2012-10-31T16:59:38Z
[ "python", "osx", "python-module", "python-import" ]
I have written a utility script for some of my colleagues' Mac OSX with Python 2.6.1. Since they don't have all the required modules installed, I have a try-except import clause: ``` try: import argparse except ImportError: print "argparse module missing: Please run 'sudo easy_install argparse'" sys.exit(1...
Your best shot is to freeze your python code with all modules needed and distribute it as binary; it worked for me with Windows and Linux, however on Linux, make sure you have a compatible glibc version There are some freeze tools for Mac OS X, but I have not used them. I only used Windows and Linux tools. check out ...
Port ASP to Django or ASP.NET
9,665,002
3
2012-03-12T10:02:18Z
9,670,524
8
2012-03-12T16:03:35Z
[ "asp.net", "python", "django", "asp-classic" ]
We use Asp Classic with VBScript and SQL Server 2005. Websites are hosted on Windows Server. I have managed to replace VBScript with Python and this has been a great improvement. I'm wondering what the next step might be. The original developer is a fan of Microsoft products, however he is impressed by Python. I on t...
Wow, this is exactly what we (as a company) have been through. We actually still have a big classic ASP web application running. We have circumvented the fact that plain classic ASP code can be spaghetti code by using WSCs (Windows script components, or scriptlets) to get separation of concern, which actually works gr...
How to update SQLAlchemy row entry?
9,667,138
30
2012-03-12T12:37:12Z
9,667,308
38
2012-03-12T12:49:05Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
Assume table has three columns: `username`, `password` and `no_of_logins`. When user tries to login its checked for an entry with query like ``` user=User.query.filter_by(username=form.username.data).first() ``` If password matches, he proceeds further. What I would like to do is to count how many time the user logg...
``` user.no_of_logins += 1 session.commit() ```
How to update SQLAlchemy row entry?
9,667,138
30
2012-03-12T12:37:12Z
26,920,108
61
2014-11-13T23:02:43Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
Assume table has three columns: `username`, `password` and `no_of_logins`. When user tries to login its checked for an entry with query like ``` user=User.query.filter_by(username=form.username.data).first() ``` If password matches, he proceeds further. What I would like to do is to count how many time the user logg...
There are several ways to `UPDATE` using `sqlalchemy` ``` 1) user.no_of_logins += 1 session.commit() 2) session.query().\ filter(User.username == form.username.data).\ update({"no_of_logins": (User.no_of_logins +1)}) session.commit() 3) conn = engine.connect() stmt = User.update().\ val...
All possible permutations of dictionaries combinations out of 2 lists
9,668,705
3
2012-03-12T14:15:12Z
9,668,825
10
2012-03-12T14:21:44Z
[ "python", "dictionary", "permutation" ]
Suppose I have 2 lists in python : ``` keys = [1, 2, 3, 4, 5, 6] values = [7, 8, 9] ``` I want to get all permutations out of those 2 lists something like: ``` d = [{1:7, 2:8, 3:9}, {1:8, 2:9, 3:7}, ....... ] ``` How could I achieve that?
Do you mean something like this? ``` >>> import itertools >>> keys = [1, 2, 3, 4, 5, 6] >>> values = [7, 8, 9] >>> d = [dict(zip(kperm, values)) for kperm in itertools.permutations(keys, len(values))] >>> len(d) 120 >>> d[:10] [{1: 7, 2: 8, 3: 9}, {1: 7, 2: 8, 4: 9}, {1: 7, 2: 8, 5: 9}, {1: 7, 2: 8, 6: 9}, {1: 7, 2: 9...
multiprocessing python
9,669,686
5
2012-03-12T15:13:30Z
9,669,720
7
2012-03-12T15:15:26Z
[ "python", "multiprocessing", "scientific-computing" ]
What are the simplest way to use all cores off a computer for a python program ? In particular, I would want to parallelize a numpy function (which already exists). Is there something like openmp under fortran in python ?
Check out the [multiprocessing](http://docs.python.org/dev/library/multiprocessing.html) library. It even allows to spread work across multiple computers.
How to efficiently calculate distance to nearest 1 in mask in numpy?
9,669,841
5
2012-03-12T15:22:40Z
9,670,048
9
2012-03-12T15:35:32Z
[ "python", "algorithm", "numpy", "scipy" ]
In numpy I have a 2d array of 1s and 0s. I need to calculate a new array (same dimensions) where each element contains the distance to the nearest 1 from the corresponding point in the mask array. e.g. ``` a=np.array( [[1,1,0], [1,0,0], [1,0,0]]) ``` I need b to look like this: ``` array([[0,0,1], [0,1,1.41]...
You're looking for the equivalent of MATLAB's [`bwdist`](http://www.mathworks.com/help/toolbox/images/ref/bwdist.html) ; check out [this SO question](http://stackoverflow.com/q/5260232/71131) for more details. The short answer is to use [`scipy.ndimage.morphology.distance_transform_edt`](http://docs.scipy.org/doc/scipy...
proper way python mock __init__() method that returns a fake class
9,670,032
2
2012-03-12T15:34:36Z
9,670,102
7
2012-03-12T15:39:12Z
[ "python", "unit-testing", "mocking" ]
Trying to mock out calls to pyazure library for django testing, but I can't figure out how to mock out the PyAzure class constructor so that it doesn't cause a TypeError. Is there a better way to approach mocking out an access library that generates a connection object? Anything I've tried other than None generates a ...
You seem to have a misconception about what `__init__()` does. Its purpose is to initialise an instance that was already created earlier. The first argument to `__init__()` is `self`, which is the instance, so you can see it was already allocated when `__init__()` is called. There is a method `__new__()` that is calle...
Multiprocessing on Windows breaks
9,670,926
6
2012-03-12T16:26:31Z
9,671,030
7
2012-03-12T16:32:53Z
[ "python", "multiprocessing", "pickle", "traceback" ]
I develop with Python on Linux and have never really seen this sort of problem with Windows. I'm using the `multiprocessing` library to speed up computations, which works very well for me on Linux. On Windows, however, things don't run as smoothly: ``` * [INFO] Parsing 1 file using 2 threads Traceback (most recent ...
There are restrictions on Windows, here is the relevant parts to the errors you are seeing: [Since Windows lacks os.fork() it has a few extra restrictions:](http://docs.python.org/library/multiprocessing.html#windows) More picklability > Ensure that all arguments to `Process.__init__()` are picklable. This > means, ...
A fast python HTML parser
9,670,948
6
2012-03-12T16:27:43Z
9,671,197
11
2012-03-12T16:44:46Z
[ "python", "html", "xml", "beautifulsoup" ]
I wrote a python script that processes a large amount of downloaded webpages HTML(120K pages). I need to parse them and extract some information from there. I tried using BeautifulSoup, which is easy and intuitive, but it seems to run super slowly. As this is something that will have to run routinely on a weak machine ...
lxml is a fast xml and html parser: <http://lxml.de/parsing.html>
scipy large sparse matrix
9,671,150
3
2012-03-12T16:40:58Z
9,671,621
9
2012-03-12T17:13:45Z
[ "python", "scipy" ]
I'm trying to use large 10^5x10^5 sparse matrices but seem to be running up against scipy: ``` n = 10 ** 5 x = scipy.sparse.rand(n, n, .001) ``` gets ``` ValueError: Trying to generate a random sparse matrix such as the product of dimensions is greater than 2147483647 - this is not supported on this machine ...
This is a limitation which results from the way `scipy.sparse.rand()` is implemented. You can roll your own random matrix generation to circumvent this limitation: ``` n = 10 ** 5 density = 1e-3 ij = numpy.random.randint(n, size=(2, n * n * density)) data = numpy.random.rand(n * n * density) matrix = scipy.sparse.coo....
Maximum value of a tuple
9,673,633
4
2012-03-12T19:37:47Z
9,673,688
7
2012-03-12T19:41:22Z
[ "python" ]
I've this tuple: ``` lpfData = ((0.0, 0.0), (0.100000001490116, 0.0879716649651527), ..., (1.41875004768372, 0.481221735477448),..., (45.1781234741211, 0.11620718985796)) ``` and I want to find the maximum value of the second column. So I use: ``` maxLPFt = max(lpfData) maxLPF = maxLPFt[1] ``` But I get always the ...
You can pass a function as `key` argument to extract the value you want to compareâ€: ``` import operator maxLPFt = max(lpfData, key=operator.itemgetter(1)) ``` This will use the second element of each tuple for the calculation. **Reference**: [`max`](http://docs.python.org/library/functions.html#max), [`operator.it...
Interacting with bash from python
9,673,730
6
2012-03-12T19:43:25Z
9,673,783
10
2012-03-12T19:47:01Z
[ "python", "bash", "subprocess" ]
I've been playing around with Python's `subprocess` module and I wanted to do an "interactive session" with bash from python. I want to be able to read bash output/write commands from Python just like I do on a terminal emulator. I guess a code example explains it better: ``` >>> proc = subprocess.Popen(['/bin/bash'])...
[pexpect](http://www.noah.org/wiki/pexpect#Examples) is designed specifically for this kind of task. It's pure Python and it's inspired by [expect](http://en.wikipedia.org/wiki/Expect), the venerable TCL tool.
Interacting with bash from python
9,673,730
6
2012-03-12T19:43:25Z
9,674,162
8
2012-03-12T20:17:21Z
[ "python", "bash", "subprocess" ]
I've been playing around with Python's `subprocess` module and I wanted to do an "interactive session" with bash from python. I want to be able to read bash output/write commands from Python just like I do on a terminal emulator. I guess a code example explains it better: ``` >>> proc = subprocess.Popen(['/bin/bash'])...
Try with this example: ``` import subprocess proc = subprocess.Popen(['/bin/bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout = proc.communicate('ls -lash') print stdout ``` You have to read more about stdin, stdout and stderr. This looks like good lecture: <http://www.doughellmann.com/PyMOTW/subprocess...
Extracting text after tag in Python's ElementTree
9,673,906
7
2012-03-12T19:58:06Z
9,674,097
13
2012-03-12T20:11:32Z
[ "python", "text", "elementtree" ]
Here is a part of XML: ``` <item><img src="cat.jpg" /> Picture of a cat</item> ``` Extracting the tag is easy. Just do: ``` et = xml.etree.ElementTree.fromstring(our_xml_string) img = et.find('img') ``` But how do to get the text immediately after it (*Picture of a cat*)? Doing the following returns a blank string:...
Elements have a `tail` attribute -- so instead of `element.text`, you're asking for `element.tail`. ``` >>> import lxml.etree >>> root = lxml.etree.fromstring('''<root><foo>bar</foo>baz</root>''') >>> root[0] <Element foo at 0x145a3c0> >>> root[0].tail 'baz' ``` Or, for your example: ``` >>> et = lxml.etree.fromstri...
Intraday candlestick charts using MatPlotLib
9,673,988
11
2012-03-12T20:03:42Z
9,713,447
36
2012-03-15T03:05:15Z
[ "python", "charts", "matplotlib" ]
I've been having some difficulty with MatPlotLib's finance charting. Seems like their candlestick charts work best with daily data and I am having a hard time making them work with intraday (every 5 minutes, between 9:30 and 4pm) data. I have pasted sample data in pastebin, top is what I get from the database, bottom ...
If I understand well, one of your major concern is the gaps between the daily data. To get rid of them, one method is to artificially 'evenly space' your data (but of course you will loose any temporal indication intra-day). Anyways, doing this way, you will be able to obtain a chart that looks like the one you have p...
Python subprocess interaction, why does my process work with Popen.communicate, but not Popen.stdout.read()?
9,674,511
4
2012-03-12T20:41:32Z
9,674,559
7
2012-03-12T20:45:01Z
[ "python", "stdout", "popen", "subprocess" ]
I am trying to communicate with a command-line chat bot with Python using the `subprocess` module. (http://howie.sourceforge.net/ using the compiled win32 binary, I have my reasons!) This works: ``` proc = Popen('Howie/howie.exe', stdout=PIPE,stderr=STDOUT,stdin=PIPE) output = proc.communicate() ``` But `Popen.commu...
One major difference between the two is that communicate() closes stdin after sending the data. I don't know about your particular case, but in many cases this means that if a process is awaiting the end of the user input, he will get it when communicate() is used, and will never get it when the code blocks on read() o...
django icontains with __in lookup
9,674,688
11
2012-03-12T20:56:21Z
9,674,801
21
2012-03-12T21:05:09Z
[ "python", "django" ]
So I want to find any kind of matching given some fields, so for example, this is what I would like to do: ``` possible_merchants = ["amazon", "web", "services"] # Possible name --> "Amazon Service" Companies.objects.filter(name__icontains__in=possible_merchants) ``` sadly it is not possible to mix icontains and the ...
You can create querysets [with the `Q` constructor](https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects) and combine them with the `|` operator to get their union: ``` from django.db.models import Q def companies_matching(merchants): """ Return a queryset for companies whos...
TypeError: Error when calling the metaclass bases a new-style class can't have only classic bases
9,677,163
8
2012-03-13T01:27:58Z
9,677,219
12
2012-03-13T01:37:12Z
[ "python", "oop", "typeerror", "new-style-class" ]
A collection of classes defined as: ``` class A(): @staticmethod def call(): print('a') class C(type): def __repr__(self): return 'somename' class B(A): __metaclass__ = C @staticmethod def call(): print('b') def boundcall(self): print('bound') ``` When r...
The problem is the line ``` class A(): ``` It should be: ``` class A(object): ``` That way, you make A a new style class. The empty parens make no sense whatsoever, and still, I continue to see them on stackoverflow and everywhere. Why, oh why?