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
generating permutations with repetitions in python
3,099,987
21
2010-06-23T08:17:14Z
3,100,008
33
2010-06-23T08:20:54Z
[ "python", "permutation", "combinatorics" ]
I know about itertools, but it seems it can only generate permutations without repetitions. for example, I'd like to generate all possible dice rolls for 2 dice. So I need all permutations of size 2 of [1, 2, 3, 4, 5, 6] including repetitions: (1, 1), (1, 2), (2, 1)... etc If possible I don't want to implement this f...
You are looking for the [Cartesian Product](http://en.wikipedia.org/wiki/Cartesian_product). > In mathematics, a Cartesian product (or product set) is the direct product of two sets. In your case, this would be `{1, 2, 3, 4, 5, 6}` x `{1, 2, 3, 4, 5, 6}`. [`itertools`](http://docs.python.org/library/itertools.html) c...
generating permutations with repetitions in python
3,099,987
21
2010-06-23T08:17:14Z
3,100,016
13
2010-06-23T08:21:43Z
[ "python", "permutation", "combinatorics" ]
I know about itertools, but it seems it can only generate permutations without repetitions. for example, I'd like to generate all possible dice rolls for 2 dice. So I need all permutations of size 2 of [1, 2, 3, 4, 5, 6] including repetitions: (1, 1), (1, 2), (2, 1)... etc If possible I don't want to implement this f...
You're not looking for permutations - you want the [Cartesian Product](http://en.wikipedia.org/wiki/Cartesian_product). For this use [product](http://docs.python.org/library/itertools.html#itertools.product) from itertools: ``` from itertools import product for roll in product([1, 2, 3, 4, 5, 6], repeat = 2): prin...
Datetime.now() abnormality - Python
3,100,612
5
2010-06-23T09:59:47Z
3,100,645
10
2010-06-23T10:05:06Z
[ "python", "django", "iis", "datetime", "django-models" ]
**I'm serving a Python app through Django**. Within the app I'm storing the classic "**created**" field within a few tables. This is how the field looks like within the Django form: ``` created = models.DateTimeField(blank=True, default=datetime.now()) ``` --- Unfortunately, **datetime.now() is not accurate.** In f...
This is a common newbie mistake, unfortunately. You have *called* the `datetime.now()` method in the definition - this means the default will be the time at which the definition was executed, ie when your server process starts up. You need to pass the *callable* instead: ``` created = models.DateTimeField(blank=True,...
RegExp - extract value a tag for [python]
3,100,896
2
2010-06-23T10:42:58Z
3,100,903
7
2010-06-23T10:44:36Z
[ "python", "html", "regex" ]
How to get value a tag `<a>` and `<b>`? Use regular expressions. ``` <a href="/model.xml?hid=90971&amp;modelid=4636873&amp;show-uid=678650012772883921" class="b-offers__name"><b>LG</b> X110</a> ``` Ie I want get ``` LG X110 ```
You don't. Regular Expressions are not well suited to deal with the nested structure of HTML. Use an [HTML parser](http://www.crummy.com/software/BeautifulSoup/) instead.
plot with custom text for x axis points
3,100,985
22
2010-06-23T10:59:46Z
3,101,288
51
2010-06-23T11:49:54Z
[ "python", "matplotlib" ]
I am drawing a plot using matplotlib and python like the sample code below. ``` x = array([0,1,2,3]) y = array([20,21,22,23]) plot(x,y) show() ``` As it is the code above on the x axis I will see drawn values `0.0, 0.5, 1.0, 1.5` i.e. the same values of my reference x values. Is there anyway to map each point of x t...
You can manually set xticks (and yticks) using [pylab.xticks](http://matplotlib.sourceforge.net/api/pyplot_api.html?highlight=xticks#matplotlib.pyplot.xticks): ``` import matplotlib.pyplot as plt import numpy as np x = np.array([0,1,2,3]) y = np.array([20,21,22,23]) my_xticks = ['John','Arnold','Mavis','Matt'] plt.xt...
How to pad all the numbers in a string
3,101,778
7
2010-06-23T12:57:42Z
3,101,828
9
2010-06-23T13:04:57Z
[ "python", "string" ]
I've got lots of address style strings and I want to sort them in a rational way. I'm looking to pad all the numbers in a string so that: "Flat 12A High Rise" becomes "Flat 00012A High Rise", there may be multiple numbers in the string. So far I've got: ``` def pad_numbers_in_string(string, padding=5): numbers =...
Instead of changing your data to accommodate your sorting algorithm, change your sorting algorithm to accommodate your data. See [Sorting For Humans: Natural Sort Order](http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html) on [Coding Horror](http://www.codinghorror.com/): ``` import re...
How to pad all the numbers in a string
3,101,778
7
2010-06-23T12:57:42Z
3,101,869
7
2010-06-23T13:10:01Z
[ "python", "string" ]
I've got lots of address style strings and I want to sort them in a rational way. I'm looking to pad all the numbers in a string so that: "Flat 12A High Rise" becomes "Flat 00012A High Rise", there may be multiple numbers in the string. So far I've got: ``` def pad_numbers_in_string(string, padding=5): numbers =...
How about this? ``` re.sub('\d+', lambda x:x.group().zfill(padding), s) ``` Example: ``` >>> s = "Flat 12A High Rise 101B" >>> padding = 5 >>> re.sub('\d+', lambda x:x.group().zfill(padding), s) 'Flat 00012A High Rise 00101B' >>> ```
Python ctypes.WinDLL error , _dlopen(self._name, mode) can't be found
3,101,981
6
2010-06-23T13:22:57Z
3,102,083
7
2010-06-23T13:34:48Z
[ "python", "windows", "dll", "dllimport", "ctypes" ]
``` ctypes.WinDLL("C:\Program Files\AHSDK\bin\ahscript.dll") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\lib\ctypes\__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] The specified module could not be found ``` Ho...
Backslashes are an escape character within strings, as demonstrated in the example below: ``` >>> print "C:\Program Files\AHSDK\bin\ahscript.dll" C:\Program Files\AHSDinhscript.dll ``` You can solve the problem by placing an r before the string, which prevents the backslash from working as an escape character: ``` c...
Why does using threading.Event result in SIGTERM not being caught?
3,102,163
14
2010-06-23T13:44:56Z
3,102,501
13
2010-06-23T14:27:39Z
[ "python", "events", "multithreading", "signals", "daemon" ]
I have a threaded Python daemon. Like any good daemon, it wants to launch all of its worker threads, then wait around until it's told to terminate. The normal signal for termination is `SIGTERM`, and in most languages I'd hold to terminate by waiting on an event or mutex, so using `threading.Event` made sense to me. Th...
From [Python documentation on signals](http://docs.python.org/library/signal.html): > Although Python signal handlers are called asynchronously as far as the Python user is concerned, they can only occur between the “atomic” instructions of the Python interpreter. This means that signals arriving during long calcu...
How to get the system info with Python?
3,103,178
11
2010-06-23T15:42:44Z
3,103,224
18
2010-06-23T15:48:37Z
[ "python", "system-information" ]
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
some of these could be obtained from the [`platform`](http://docs.python.org/library/platform.html) module: ``` >>> import platform >>> platform.machine() 'x86' >>> platform.version() '5.1.2600' >>> platform.platform() 'Windows-XP-5.1.2600-SP2' >>> platform.uname() ('Windows', 'name', 'XP', '5.1.2600', 'x86', 'x86 Fam...
Reading .csv in Python without looping through the whole file?
3,103,327
24
2010-06-23T16:01:14Z
3,103,394
36
2010-06-23T16:10:04Z
[ "python", "csv", "iterator", "next" ]
The only way I've seen Python's csv.reader used is in a for loop, which goes through the whole file without saving past values of the read in variables. I only need to work with 2 consecutive lines of the (enormous) file at a time. Using the csv.reader for loop, I only have 1 line at a time. Is there a way to use Pyth...
There's nothing forcing you to use the reader in a loop. Just read the first line, then read the second line. ``` import csv rdr = csv.reader(open("data.csv")) line1 = rdr.next() # in Python 2, or next(rdr) in Python 3 line2 = rdr.next() ```
How does this Python decorator work?
3,103,463
3
2010-06-23T16:16:47Z
3,103,492
8
2010-06-23T16:21:08Z
[ "python", "decorator" ]
I was looking at some lazy loading property decorators in Python and happened across this example (http://code.activestate.com/recipes/363602-lazy-property-evaluation/): ``` class Lazy(object): def __init__(self, calculate_function): self._calculate = calculate_function def __get__(self, obj, _=None):...
When an attribute named `someprop` is accessed on instance `o` of class `SomeClass`, if `SomeClass` contains a *descriptor* named `o`, then that descriptor's class's `__get__` method is used. For more on descriptors, see [this guide](http://users.rcn.com/python/download/Descriptor.htm). Don't let the fact that `Lazy` i...
Making lxml.objectify ignore xml namespaces?
3,103,661
3
2010-06-23T16:41:51Z
3,104,191
7
2010-06-23T17:51:08Z
[ "python", "xml", "lxml", "xml-namespaces" ]
So I gotta deal with some xml that looks like this: ``` <ns2:foobarResponse xmlns:ns2="http://api.example.com"> <duration>206</duration> <artist> <tracks>...</tracks> </artist> </ns2:foobarResponse> ``` I found lxml and it's [objectify](http://codespeak.net/lxml/objectify.html) module, that lets you travers...
According to the lxml.objectify [documentation](http://codespeak.net/lxml/objectify.html#namespace-handling), attribute lookups default to using the namespace of their parent element. What you probably *want* to work would be: ``` print tree["{}artist"] ``` QName syntax like this would work if your children had a no...
Inverse Distance Weighted (IDW) Interpolation with Python
3,104,781
23
2010-06-23T19:18:38Z
3,114,117
12
2010-06-24T21:45:41Z
[ "python", "numpy", "scipy", "spatial", "interpolation" ]
**The Question:** What is the best way to calculate inverse distance weighted (IDW) interpolation in Python, for point locations? **Some Background:** Currently I'm using RPy2 to interface with R and its gstat module. Unfortunately, the gstat module conflicts with arcgisscripting which I got around by running RPy2 bas...
Edit: @Denis is right, a linear Rbf (e.g. [scipy.interpolate.Rbf](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.Rbf.html) with "function='linear'") isn't the same as IDW... (Note, all of these will use excessive amounts of memory if you're using a large number of points!) Here's a simple examp...
Inverse Distance Weighted (IDW) Interpolation with Python
3,104,781
23
2010-06-23T19:18:38Z
3,119,544
16
2010-06-25T16:02:08Z
[ "python", "numpy", "scipy", "spatial", "interpolation" ]
**The Question:** What is the best way to calculate inverse distance weighted (IDW) interpolation in Python, for point locations? **Some Background:** Currently I'm using RPy2 to interface with R and its gstat module. Unfortunately, the gstat module conflicts with arcgisscripting which I got around by running RPy2 bas...
changed 20 Oct: this class Invdisttree combines inverse-distance weighting and [scipy.spatial.KDTree](http://docs.scipy.org/doc/scipy/reference/spatial.html). Forget the original brute-force answer; this is imho the method of choice for scattered-data interpolation. ``` """ invdisttree.py: inverse-distance-weighted ...
Cross-platform Python GUI suitable for taskbar (Win) and menubar (mac) functionality?
3,104,818
6
2010-06-23T19:21:20Z
3,138,150
10
2010-06-29T05:46:33Z
[ "python", "user-interface", "cross-platform", "taskbar", "menubar" ]
I am fairly new to Python programming, and completely new to cross-platform GUI building (only previous GUI experience is through visual basic and Java). I've written some python code to screen-scrape data from a website, and now I want to build a GUI *that will reside in the Mac OS X menubar, and in Window's task bar ...
Here's an example for PyQt. This works for me on MacOS X; I haven't tried it on other platforms. Note that the `QSystemTrayIcon` class will raise exceptions if it doesn't have an icon – I grabbed the [RSS feed svg from Wiki commons](http://upload.wikimedia.org/wikipedia/commons/4/43/Feed-icon.svg) for my `icon.svg` ...
Python SQLite parameter substitution with wildcards in LIKE
3,105,249
22
2010-06-23T20:25:23Z
3,105,370
41
2010-06-23T20:40:21Z
[ "python", "sqlite", "sql-like" ]
I am attempting to use a parametrized LIKE query with Python's Sqlite library as below: ``` self.cursor.execute("select string from stringtable where string like '%?%' and type = ?", (searchstr,type)) ``` but the ? inside of the wildcard is not being evaluated leaving me with this error: ``` "sqlite3.ProgrammingErro...
The quotes protect either `?` or `:name` from being taken as a place-holder -- they're taken literally. You need to place the percent signs around the string you're passing, and use the plain placeholder without quotes. I.e.: ``` self.cursor.execute( "select string from stringtable where string like ? and type = ?",...
How do you automatically remove the preview window after autocompletion in Vim?
3,105,307
77
2010-06-23T20:31:57Z
3,107,159
89
2010-06-24T04:00:25Z
[ "python", "vim", "autocomplete", "preview" ]
I'm using omnifunc=pythoncomplete. When autocompleting a word (e.g., os.), I get the list of eligible class members and functions, as expected, as well as a scratch buffer preview window with documentation about the selected member or function. This is great, but after selecting the function I want, the preview window ...
Put the following in your vimrc: ``` " If you prefer the Omni-Completion tip window to close when a selection is " made, these lines close it on movement in insert mode or when leaving " insert mode autocmd CursorMovedI * if pumvisible() == 0|pclose|endif autocmd InsertLeave * if pumvisible() == 0|pclose|endif ```
How do you automatically remove the preview window after autocompletion in Vim?
3,105,307
77
2010-06-23T20:31:57Z
13,630,280
15
2012-11-29T16:30:27Z
[ "python", "vim", "autocomplete", "preview" ]
I'm using omnifunc=pythoncomplete. When autocompleting a word (e.g., os.), I get the list of eligible class members and functions, as expected, as well as a scratch buffer preview window with documentation about the selected member or function. This is great, but after selecting the function I want, the preview window ...
If you have the supertab plugin installed, there is an option called `supertab-closepreviewonpopupclose`. Put the following in your .vimrc: ``` let g:SuperTabClosePreviewOnPopupClose = 1 ```
How do you automatically remove the preview window after autocompletion in Vim?
3,105,307
77
2010-06-23T20:31:57Z
26,022,965
45
2014-09-24T17:28:32Z
[ "python", "vim", "autocomplete", "preview" ]
I'm using omnifunc=pythoncomplete. When autocompleting a word (e.g., os.), I get the list of eligible class members and functions, as expected, as well as a scratch buffer preview window with documentation about the selected member or function. This is great, but after selecting the function I want, the preview window ...
Even though there is already an accepted answer I found this directly from the docs which will work for any plugin that is having this issue. ``` autocmd CompleteDone * pclose ```
Google App Engine/Python - Change logging formatting
3,105,521
6
2010-06-23T21:00:14Z
3,105,859
10
2010-06-23T21:55:10Z
[ "python", "google-app-engine", "logging" ]
How can one change the formatting of output from the `logging` module in Google App Engine? I've tried, e.g.: ``` log_format = "* %(asctime)s %(levelname)-8s %(message)s" date_format = "%a, %d %b %Y %H:%M:%S" console = logging.StreamHandler() fr = logging.Formatter(log_format) console.setFormatter(fr) l...
Here is one way you can change the logging format without duplicating output: ``` # directly access the default handler and set its format directly logging.getLogger().handlers[0].setFormatter(fr) ``` This is a bit of a hack because you have to directly access the `handlers` list stored in the root logger. The proble...
Unload a module in Python
3,105,801
42
2010-06-23T21:46:04Z
3,105,828
14
2010-06-23T21:50:07Z
[ "python", "memory-leaks" ]
TL/DR: ``` import gc, sys print len(gc.get_objects()) # 4073 objects in memory # Attempt to unload the module import httplib del sys.modules["httplib"] httplib = None gc.collect() print len(gc.get_objects()) # 6745 objects in memory ``` --- **UPDATE** I've contacted Python developers about this problem and indee...
Python does not support unloading modules. However, unless your program loads an unlimited number of modules over time, that's not the source of your memory leak. Modules are normally loaded once at start up and that's it. Your memory leak most likely lies elsewhere. In the unlikely case that your program really does...
Python "import" scope
3,106,089
4
2010-06-23T22:41:36Z
3,106,123
14
2010-06-23T22:49:35Z
[ "python", "import" ]
I am dealing with some python code automatically generated for me. I want to avoid manually editing these python files & hence this question/issue: foo.py: ``` def foo(): print "foo" ``` boo.py: ``` def boo(): foo.foo() # <-- global name 'foo' not defined print "boo" ``` bar.py: ``` import foo import boo...
> But bar is importing both foo & boo. > Shouldn't foo be automatically > available to boo? No it shouldn't: `import`, like any other way to bind a name, binds that name in a single, specific scope, not "in all scopes you could ever possibly want it in". > Is there a way to do so? As said > boo.py is automatically ge...
How to POST an xml element in python
3,106,459
10
2010-06-24T00:18:42Z
3,106,518
14
2010-06-24T00:34:58Z
[ "python", "xml", "post", "urllib2" ]
Basically I have this xml element (xml.etree.ElementTree) and I want to POST it to a url. Currently I'm doing something like ``` xml_string = xml.etree.ElementTree.tostring(my_element) data = urllib.urlencode({'xml': xml_string}) response = urllib2.urlopen(url, data) ``` I'm pretty sure that works and all, but was wo...
If this is your own API, I would consider POSTing as `application/xml`. The default is `application/x-www-form-urlencoded`, which is meant for HTML form data, not a single XML document. ``` req = urllib2.Request(url=url, data=xml_string, headers={'Content-Type': 'applicati...
Really simple way to deal with XML in Python?
3,106,480
21
2010-06-24T00:24:06Z
3,106,766
7
2010-06-24T01:53:17Z
[ "python", "xml" ]
Musing over a [recently asked question](http://stackoverflow.com/questions/3063319/), I started to wonder if there is a *really simple* way to deal with XML documents in Python. A pythonic way, if you will. Perhaps I can explain best if i give example: let's say the following - which i think is a good example of how X...
You want a thin veneer? That's easy to cook up. Try the following trivial wrapper around ElementTree as a start: ``` # geetree.py import xml.etree.ElementTree as ET class GeeElem(object): """Wrapper around an ElementTree element. a['foo'] gets the attribute foo, a.foo gets the first subelement foo.""" ...
Really simple way to deal with XML in Python?
3,106,480
21
2010-06-24T00:24:06Z
3,106,857
11
2010-06-24T02:27:54Z
[ "python", "xml" ]
Musing over a [recently asked question](http://stackoverflow.com/questions/3063319/), I started to wonder if there is a *really simple* way to deal with XML documents in Python. A pythonic way, if you will. Perhaps I can explain best if i give example: let's say the following - which i think is a good example of how X...
lxml has been mentioned. You might also check out [lxml.objectify](http://codespeak.net/lxml/objectify.html) for some really simple manipulation. ``` >>> from lxml import objectify >>> tree = objectify.fromstring(your_xml) >>> tree.weather.attrib["module_id"] '0' >>> tree.weather.forecast_information.city.attrib["data...
Pointers in Python?
3,106,689
48
2010-06-24T01:28:56Z
3,106,696
21
2010-06-24T01:31:14Z
[ "python", "pointers" ]
I know Python doesn't have pointers, but is there a way to have this yield `2` instead ``` >>> a = 1 >>> b = a # modify this line somehow so that b "points to" a >>> a = 2 >>> b 1 ``` ? --- Here's an example: I want `form.data['field']` and `form.field.value` to always have the same value. It's not completely neces...
There's no way you can do that changing only that line. You can do: ``` a = [1] b = a a[0] = 2 b[0] ``` That creates a list, assigns the reference to a, then b also, uses the a reference to set the first element to 2, then accesses using the b reference variable.
Pointers in Python?
3,106,689
48
2010-06-24T01:28:56Z
3,106,752
24
2010-06-24T01:48:50Z
[ "python", "pointers" ]
I know Python doesn't have pointers, but is there a way to have this yield `2` instead ``` >>> a = 1 >>> b = a # modify this line somehow so that b "points to" a >>> a = 2 >>> b 1 ``` ? --- Here's an example: I want `form.data['field']` and `form.field.value` to always have the same value. It's not completely neces...
It's not a bug, it's a feature :-) When you look at the '=' operator in Python, don't think in terms of assignment. You don't assign things, you bind them. = is a binding operator. So in your code, you are giving the value 1 a name: a. Then, you are giving the value in 'a' a name: b. Then you are binding the value 2 ...
Pointers in Python?
3,106,689
48
2010-06-24T01:28:56Z
3,106,993
7
2010-06-24T03:09:57Z
[ "python", "pointers" ]
I know Python doesn't have pointers, but is there a way to have this yield `2` instead ``` >>> a = 1 >>> b = a # modify this line somehow so that b "points to" a >>> a = 2 >>> b 1 ``` ? --- Here's an example: I want `form.data['field']` and `form.field.value` to always have the same value. It's not completely neces...
From one point of view, *everything* is a pointer in Python. Your example works a lot like the C++ code. ``` int* a = new int(1); int* b = a; a = new int(2); cout << *b << endl; // prints 1 ``` (A closer equivalent would use some type of `shared_ptr<Object>` instead of `int*`.) > Here's an example: I want > form.d...
Pointers in Python?
3,106,689
48
2010-06-24T01:28:56Z
3,107,534
22
2010-06-24T05:58:29Z
[ "python", "pointers" ]
I know Python doesn't have pointers, but is there a way to have this yield `2` instead ``` >>> a = 1 >>> b = a # modify this line somehow so that b "points to" a >>> a = 2 >>> b 1 ``` ? --- Here's an example: I want `form.data['field']` and `form.field.value` to always have the same value. It's not completely neces...
> I want `form.data['field']` and > `form.field.value` to always have the > same value This is feasible, because it involves decorated names and indexing -- i.e., **completely** different constructs from the **barenames** `a` and `b` that you're asking about, and for with your request is utterly impossible. Why ask fo...
Any productive way to install a bunch of packages
3,106,736
2
2010-06-24T01:43:41Z
3,106,793
10
2010-06-24T02:05:18Z
[ "python", "pip" ]
I had one machine with my commonly used python package installed. and i would like to install the same package on another machine or same machine with different python version. I would like to know whether pip or easy-install or some other method can let me install those packages in a batch. When i use perl, it has som...
Pip has some great features for this. It lets you save all requirements from an environment in a file using `pip freeze > reqs.txt` You can then later do : `pip install -r reqs.txt` and you'll get the same exact environnement. You can also bundle several libraries into a `.pybundle` file with the command `pip bundle ...
How do I install M2Crypto on Ubuntu?
3,107,036
13
2010-06-24T03:25:18Z
3,107,169
25
2010-06-24T04:03:02Z
[ "python", "ubuntu", "m2crypto" ]
I'm trying to build and install M2Crypto on Ubuntu 10.04 LTS. I downloaded and untarred M2Crypto-0.20.2.tar, and from the M2Crypto-0.20.2 directory I tried `python setup.py build`. I got an error because I don't have swig. So I ran `sudo apt-get install swig`. Then I tried `python setup.py build` again and got: ``` /u...
You probably need to install the python development packages: ``` sudo apt-get install python-dev ``` Better yet, don't bother building m2crypto yourself. It's already [in the Ubuntu repositories](http://packages.ubuntu.com/search?keywords=python-m2crypto) as a fully supported package. This way, you'll get automatic ...
Python script reading from a csv file
3,107,793
2
2010-06-24T06:55:07Z
3,107,823
9
2010-06-24T07:00:58Z
[ "python", "csv" ]
``` "Type","Name","Description","Designation","First-term assessment","Second-term assessment","Total" "Subject","Nick","D1234","F4321",10,19,29 "Unit","HTML","D1234-1","F4321",18,, "Topic","Tags","First Term","F4321",18,, "Subtopic","Review of representation of HT...
You're importing the [`csv` module](http://docs.python.org/library/csv.html) but never use it. Why? If you do ``` import csv reader = csv.reader(open(file, "rb"), dialect="excel") # Python 2.x # Python 3: reader = csv.reader(open(file, newline=""), dialect="excel") ``` you get a `reader` object that will contain all...
How to read from the serial port in python without using external APIs?
3,107,989
6
2010-06-24T07:37:55Z
3,108,054
7
2010-06-24T07:47:10Z
[ "python", "serial-port" ]
I have to read a stream which is sent from a homemade device over the serial port. The problem is that it should be deployed on a machine where I don't have access to install anything new, which means I have to use the python standard libraries to do this. Is this possible, and if so, how can I manage this. If it turn...
On Unix-like operating systems, the serial port work just like a file, and you simply open it and read or write bytes. There are some extra calls you can make to set the baud rate and whatnot, but that's essentially all there is. On Windows, you open the serial port like a file, but you must use some particular ways o...
Get max key in dictionary
3,108,042
13
2010-06-24T07:45:40Z
3,108,076
23
2010-06-24T07:49:51Z
[ "python" ]
I have a dictionary that looks like this ``` MyCount= {u'10': 1, u'1': 2, u'3': 2, u'2': 2, u'5': 2, u'4': 2, u'7': 2, u'6': 2, u'9': 2, u'8': 2} ``` I need highest key which is 10 but i if try `max(MyCount.keys())` it gives 9 as highest. Same for `max(MyCount)`. The dictionary is created dynamically.
This is because `u'9' > u'10'`, since they are *strings*. To compare numerically, use `int` as a key. ``` max(MyCount.keys(), key=int) ```
Get max key in dictionary
3,108,042
13
2010-06-24T07:45:40Z
3,108,180
12
2010-06-24T08:07:23Z
[ "python" ]
I have a dictionary that looks like this ``` MyCount= {u'10': 1, u'1': 2, u'3': 2, u'2': 2, u'5': 2, u'4': 2, u'7': 2, u'6': 2, u'9': 2, u'8': 2} ``` I need highest key which is 10 but i if try `max(MyCount.keys())` it gives 9 as highest. Same for `max(MyCount)`. The dictionary is created dynamically.
You need to compare the actual numerical values. Currently you're comparing the strings lexigraphically. ``` max(MyCount, key=int) ```
In Python script, how do I set PYTHONPATH?
3,108,285
56
2010-06-24T08:25:55Z
3,108,301
93
2010-06-24T08:28:42Z
[ "python", "linux", "unix", "environment-variables" ]
I know how to set it in my /etc/profile and in my environment variables. But what if I want to set it during a script? Is it import os, sys? How do I do it?
You don't set `PYTHONPATH`, you add entries to [`sys.path`](http://docs.python.org/library/sys.html). It's a list of directories that should be searched for Python packages, so you can just append your directories to that list. ``` sys.path.append('/path/to/whatever') ``` In fact, `sys.path` is initialized by splitti...
In Python script, how do I set PYTHONPATH?
3,108,285
56
2010-06-24T08:25:55Z
3,108,307
19
2010-06-24T08:29:15Z
[ "python", "linux", "unix", "environment-variables" ]
I know how to set it in my /etc/profile and in my environment variables. But what if I want to set it during a script? Is it import os, sys? How do I do it?
You can get and set environment variables via `os.environ`: ``` import os user_home = os.environ["HOME"] os.environ["PYTHONPATH"] = "..." ``` But since your interpreter already runs, this will have no effect. Your better off using ``` import sys sys.path.append("...") ``` which is the array, your `PYTHONPATH` will...
Best way to get xml-rpc and django working together
3,108,507
6
2010-06-24T09:05:03Z
3,108,533
7
2010-06-24T09:08:29Z
[ "python", "django", "xml-rpc" ]
I have worked with Django for a while but I am new to xml-rpc. I have two Django servers running and the first needs to call functions from some modules of second server. I find xml-rpc easiest way to do so but don't want to run a separate server for this only. What options do I have? Can I run Django's web-server and...
Easily - we use <http://code.djangoproject.com/wiki/XML-RPC> to add an xml-rpc server into our django server.
Django signals file, cannot import model names
3,108,694
4
2010-06-24T09:30:41Z
3,108,785
13
2010-06-24T09:44:42Z
[ "python", "django", "django-models" ]
I have such file order: ``` project/ app/ models.py signals.py ``` I am keeping signals inside signals.py as it should be. and at the top of the signals.py file, I include myapp models as I do queries in these signals with ``` from myproject.myapp.models import Foo ``` However it doesnt seem to ...
Most likely you have a circular dependency. Does your models.py import the signals? If so, this can't work as both modules now depend on each other. You may need to import the models within a function in the signals file, rather than at the top level.
how can python function access its own attributes?
3,109,289
28
2010-06-24T10:55:04Z
3,109,542
21
2010-06-24T11:37:25Z
[ "python", "function", "scope", "closures", "attributes" ]
**is it possible to access the python function object attributes from within the function scope?** e.g. let's have ``` def f(): return SOMETHING f._x = "foo" f() # -> "foo" ``` now, what SOMETHING has to be, if we want to have the \_x attribute content "foo" returned? if it's even possible (simply) t...
You could just use a class to do this ``` >>> class F(object): ... def __call__(self, *args, **kw): ... return self._x ... >>> f=F() >>> f._x = "foo" >>> f() 'foo' >>> g=f >>> del f >>> g() 'foo' ```
how can python function access its own attributes?
3,109,289
28
2010-06-24T10:55:04Z
3,200,507
11
2010-07-08T03:30:12Z
[ "python", "function", "scope", "closures", "attributes" ]
**is it possible to access the python function object attributes from within the function scope?** e.g. let's have ``` def f(): return SOMETHING f._x = "foo" f() # -> "foo" ``` now, what SOMETHING has to be, if we want to have the \_x attribute content "foo" returned? if it's even possible (simply) t...
Well, let's look at what function is: ``` >>> def foo(): ... return x ... >>> foo.x = 777 >>> foo.x 777 >>> foo() Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "<interactive input>", line 2, in foo NameError: global name 'x' is not defined >>> dir(foo) ['__call__', '_...
how can python function access its own attributes?
3,109,289
28
2010-06-24T10:55:04Z
3,206,934
8
2010-07-08T18:51:18Z
[ "python", "function", "scope", "closures", "attributes" ]
**is it possible to access the python function object attributes from within the function scope?** e.g. let's have ``` def f(): return SOMETHING f._x = "foo" f() # -> "foo" ``` now, what SOMETHING has to be, if we want to have the \_x attribute content "foo" returned? if it's even possible (simply) t...
As a workaround you could use a factory function to fix your scope: ``` def factory(): def inner(): print inner.x return inner >>> foo=factory() >>> foo.x=11 >>> foo() 11 >>> bar = foo >>> del foo >>> bar() 11 ```
how can python function access its own attributes?
3,109,289
28
2010-06-24T10:55:04Z
3,209,862
40
2010-07-09T04:35:49Z
[ "python", "function", "scope", "closures", "attributes" ]
**is it possible to access the python function object attributes from within the function scope?** e.g. let's have ``` def f(): return SOMETHING f._x = "foo" f() # -> "foo" ``` now, what SOMETHING has to be, if we want to have the \_x attribute content "foo" returned? if it's even possible (simply) t...
## Solution Make one of the function's default arguments be a reference to the function itself. ``` def f(self): return self.x f.func_defaults = (f,) ``` Example usage: ``` >>> f.x = 17 >>> b = f >>> del f >>> b() 17 ``` ## Explanation The original poster wanted a solution that does not require a global name ...
UnicodeEncodeError: 'ascii' codec can't encode character when trying a HTTP POST in Python
3,110,104
9
2010-06-24T12:58:59Z
3,110,164
12
2010-06-24T13:05:46Z
[ "python", "unicode", "ascii", "http-post" ]
I'm trying to do a HTTP POST with a unicode string (u'\xe4\xf6\xfc') as a parameter in Python, but I receive the following error: UnicodeEncodeError: 'ascii' codec can't encode character This is to the code used to make the HTTP POST (with httplib2) ``` http = httplib2.Http() userInfo = [('Name', u'\xe4\xf6\xfc'...
You cannot POST Python Unicode objects directly. You should encode it as a UTF-8 string first: ``` name = u'\xe4\xf6\xfc'.encode('utf-8') userInfo = [('Name', name)] ```
Django Template Ternary Operator
3,110,166
39
2010-06-24T13:05:53Z
3,110,218
20
2010-06-24T13:13:33Z
[ "python", "django", "templates", "ternary-operator" ]
I was wondering if there was a ternary operator (condition ? true-value : false-value) that could be used in a Django template. I see there is a python one (true-value if condition else false-value) but I'm unsure how to use that inside a Django template to display the html given by one of the values. Any ideas?
Why would you need a ternary operator within a template? `{% if %}` and `{% else %}` are all you need. Or you could try the `firstof` tag: ``` {% firstof var1 var2 var3 %} ``` which outputs the first one of var1, var2 or var3 which evaluates to a True value.
Django Template Ternary Operator
3,110,166
39
2010-06-24T13:05:53Z
6,089,283
47
2011-05-22T16:37:37Z
[ "python", "django", "templates", "ternary-operator" ]
I was wondering if there was a ternary operator (condition ? true-value : false-value) that could be used in a Django template. I see there is a python one (true-value if condition else false-value) but I'm unsure how to use that inside a Django template to display the html given by one of the values. Any ideas?
You can use the yesno filter: ``` {{ value|yesno:"yeah,no,maybe" }} ``` <https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#yesno>
Python: Get name of shoutcast/internet radio station from url
3,110,494
2
2010-06-24T13:44:36Z
3,111,024
7
2010-06-24T14:42:54Z
[ "python", "radio", "shoutcast" ]
I've been trying to get the name/title of internet radio stations based on the url in python, but with no luck so far. It seems that internet radio stations use another protocol than HTTP, but please correct me if I'm wrong. For example: <http://89.238.146.142:7030> Has the title: "Ibiza Global Radio" How can i stor...
From a little `curl`, it seems to be using [shoutcast](http://forums.radiotoolbox.com/viewtopic.php?t=74) protocol, so you're looking for an early line starting with `icy-name:` ``` $ curl http://89.238.146.142:7030 | head -5 % Total % Received % Xferd Average Speed Time Time Time Current ...
Why type(classInstance) is returning 'instance'?
3,110,624
9
2010-06-24T13:58:49Z
3,110,640
11
2010-06-24T14:00:38Z
[ "python", "class", "types", "instance" ]
I have a method that accepts a parameter that can be of several types, and has to do one thing or other depending on the type, but if I check the type of said parameter, I don't get the 'real' type, I always get `<type 'instance'>`, and that is messing up with my comparisons. I have something like: ``` from classes i...
Old-style classes do that. Derive your classes from `object` in their definitions.
Why type(classInstance) is returning 'instance'?
3,110,624
9
2010-06-24T13:58:49Z
3,110,654
10
2010-06-24T14:02:09Z
[ "python", "class", "types", "instance" ]
I have a method that accepts a parameter that can be of several types, and has to do one thing or other depending on the type, but if I check the type of said parameter, I don't get the 'real' type, I always get `<type 'instance'>`, and that is messing up with my comparisons. I have something like: ``` from classes i...
you should really use isinstance: ``` In [26]: def foo(param): ....: print type(param) ....: print isinstance(param, Class1) ....: In [27]: foo(x) <type 'instance'> True ``` Type is better for built-in types.
Why type(classInstance) is returning 'instance'?
3,110,624
9
2010-06-24T13:58:49Z
3,110,766
9
2010-06-24T14:16:23Z
[ "python", "class", "types", "instance" ]
I have a method that accepts a parameter that can be of several types, and has to do one thing or other depending on the type, but if I check the type of said parameter, I don't get the 'real' type, I always get `<type 'instance'>`, and that is messing up with my comparisons. I have something like: ``` from classes i...
The fact that `type(x)` returns the same type object for all instances `x` of legacy, aka old-style, classes, is one of many infuriating defects of those kinds of classes -- unfortunately they have to stay (and be the default for a class without base) in Python `2.*` for reasons of backwards compatibility. Nevertheles...
How do I get the client IP of a Tornado request?
3,110,919
24
2010-06-24T14:34:19Z
3,111,656
40
2010-06-24T15:58:13Z
[ "python", "tornado" ]
I have a `RequestHandler` object for incoming `post()`s. How can I find the **IP** of the client making the request? I've browsed most of `RequestHandler`'s methods and properties and seem to have missed something.
`RequestHandler.request.remote_ip` (from RequestHandler's instance) you can inspect the response like: ``` ... class MainHandler(tornado.web.RequestHandler): def get(self): self.write(repr(self.request)) ... ```
How do I get the client IP of a Tornado request?
3,110,919
24
2010-06-24T14:34:19Z
28,959,670
16
2015-03-10T09:04:50Z
[ "python", "tornado" ]
I have a `RequestHandler` object for incoming `post()`s. How can I find the **IP** of the client making the request? I've browsed most of `RequestHandler`'s methods and properties and seem to have missed something.
mykhal's answer is right, however sometimes your application will be behind a proxy, for example if you use nginx and UWSGI and you will always get something like `127.0.0.1` for the remote IP. In this case you need to check the headers too, like: ``` x_real_ip = self.request.headers.get("X-Real-IP") remote_ip = x_rea...
Python performance: Try-except or not in?
3,111,195
2
2010-06-24T15:03:22Z
3,111,386
14
2010-06-24T15:24:43Z
[ "python", "performance" ]
In one of my classes I have a number of methods that all draw values from the same dictionaries. However, if one of the methods tries to access a value that isn't there, it has to call another method to make the value associated with that key. I currently have this implemented as follows, where findCrackDepth(tonnage)...
It's a delicate problem to time this because you need care to avoid "lasting side effects" and the performance tradeoff depends on the % of missing keys. So, consider a `dil.py` file as follows: ``` def make(percentmissing): global d d = dict.fromkeys(range(100-percentmissing), 1) def addit(d, k): d[k] = k def...
Getting tests to parallelize using nose in python
3,111,915
7
2010-06-24T16:32:49Z
3,718,367
12
2010-09-15T14:02:19Z
[ "python", "nose", "nosetests" ]
I have a directory with lots of .py files (say test\_1.py, test\_2.py and so on) Each one of them is written properly to be used with nose. So when I run nosetests script, it finds all the tests in all the .py files and executes them. I now want to parallelize them so that all the tests in all .py files are treated as...
It seems that nose, actually the multiprocess plugin, will make test run in parallel. The caveat is that the way it works, you can end up not executing test on multiple processes. The plugin creates a test queue, spawns multiple processes and then each process consumes the queue concurrently. There is no test dispatch ...
python assert with and without parenthesis
3,112,171
37
2010-06-24T16:59:41Z
3,112,178
51
2010-06-24T17:00:58Z
[ "python", "assert", "parentheses" ]
Here are four simple invocations of assert: ``` >>> assert 1==2 Traceback (most recent call last): File "<stdin>", line 1, in ? AssertionError >>> assert 1==2, "hi" Traceback (most recent call last): File "<stdin>", line 1, in ? AssertionError: hi >>> assert(1==2) Traceback (most recent call last): File "<stdi...
The last `assert` would have given you a warning (`SyntaxWarning: assertion is always true, perhaps remove parentheses?`) if you ran it through a full interpreter, not through IDLE. Because `assert` is a keyword and not a function, you are actually passing in a tuple as the first argument and leaving off the second arg...
python assert with and without parenthesis
3,112,171
37
2010-06-24T16:59:41Z
3,112,196
7
2010-06-24T17:03:17Z
[ "python", "assert", "parentheses" ]
Here are four simple invocations of assert: ``` >>> assert 1==2 Traceback (most recent call last): File "<stdin>", line 1, in ? AssertionError >>> assert 1==2, "hi" Traceback (most recent call last): File "<stdin>", line 1, in ? AssertionError: hi >>> assert(1==2) Traceback (most recent call last): File "<stdi...
`assert 1==2, "hi"` is parsed as `assert 1==2, "hi"` with "hi" as the second parameter for the keyword. Hence why it properly gives an error. `assert(1==2)` is parsed as `assert (1==2)` which is identical to `assert 1==2`, because parens around a single item don't create a tuple unless there's a trailing comma e.g. `(...
Accessing unregistered COM objects from python via a registered TLB
3,112,495
10
2010-06-24T17:42:07Z
3,132,747
7
2010-06-28T13:29:32Z
[ "python", "com", "interop", "assemblies", "win32com" ]
I have three pieces of code that i'm working with at the moment: * A closed source application (Main.exe) * A closed source VB COM object implemented as a dll (comobj.dll) * Code that I am developing in Python comobj.dll hosts a COM object (lets say, 'MainInteract') that I would like to use from Python. I can already...
Here is a method I devised to load a COM object from a DLL. It was based on a lot of reading about COM, etc. I'm not 100% sure about the last lines, specifically d=. I think that only works if IID\_Dispatch is passed in (which you can see if the default param). In addition, I believe this code leaks - for one, the DLL...
Accessing unregistered COM objects from python via a registered TLB
3,112,495
10
2010-06-24T17:42:07Z
6,001,210
8
2011-05-14T10:26:31Z
[ "python", "com", "interop", "assemblies", "win32com" ]
I have three pieces of code that i'm working with at the moment: * A closed source application (Main.exe) * A closed source VB COM object implemented as a dll (comobj.dll) * Code that I am developing in Python comobj.dll hosts a COM object (lets say, 'MainInteract') that I would like to use from Python. I can already...
What I did to access Free Download Manager's type library was the following: ``` import pythoncom, win32com.client fdm = pythoncom.LoadTypeLib('fdm.tlb') downloads_stat = None for index in xrange(0, fdm.GetTypeInfoCount()): type_name = fdm.GetDocumentation(index)[0] if type_name == 'FDMDownloadsStat': ...
os.path.exists() lies
3,112,546
7
2010-06-24T17:48:19Z
3,112,717
8
2010-06-24T18:12:10Z
[ "python" ]
I'm running a number of python scripts on a linux cluster, and the output from one job is generally the input to another script, potentially run on another node. I find that there is some not insignificant lag before python notices files that have been created on other nodes -- os.path.exists() returns false and open()...
`os.path.exists()` just calls the C library's `stat()` function. I believe you're running into a cache in the kernel's NFS implementation. Below is a link to a page that describes the problem as well as some methods to flush the cache. > # File Handle Caching > > **Directories cache file names to file handles mapping...
Classifying Documents into Categories
3,113,428
27
2010-06-24T19:56:42Z
3,113,737
10
2010-06-24T20:45:05Z
[ "python", "machine-learning", "nlp", "bayesian", "nltk" ]
I've got about 300k documents stored in a Postgres database that are tagged with topic categories (there are about 150 categories in total). I have another 150k documents that don't yet have categories. I'm trying to find the best way to programmaticly categorize them. I've been exploring [NLTK](http://www.nltk.org/) ...
How big (number of words) are your documents? Memory consumption at 150K trainingdocs should not be an issue. Naive Bayes is a good choice especially when you have many categories with only a few training examples or very noisy trainingdata. But in general, linear Support Vector Machines do perform much better. Is yo...
Classifying Documents into Categories
3,113,428
27
2010-06-24T19:56:42Z
3,114,191
28
2010-06-24T21:55:16Z
[ "python", "machine-learning", "nlp", "bayesian", "nltk" ]
I've got about 300k documents stored in a Postgres database that are tagged with topic categories (there are about 150 categories in total). I have another 150k documents that don't yet have categories. I'm trying to find the best way to programmaticly categorize them. I've been exploring [NLTK](http://www.nltk.org/) ...
You should start by converting your documents into [TF-log(1 + IDF) vectors](http://en.wikipedia.org/wiki/Vector_space_model): term frequencies are sparse so you should use python dict with term as keys and count as values and then divide by total count to get the global frequencies. Another solution is to use the abs...
Python subprocess Help
3,113,544
8
2010-06-24T20:14:03Z
3,113,627
24
2010-06-24T20:28:16Z
[ "python", "subprocess" ]
I'm testing python subprocess and I keep getting this error: ``` $ python subprocess-test.py Traceback (most recent call last): File "subprocess-test.py", line 3, in <module> p = subprocess.Popen(['rsync', '-azP', 'rsync://cdimage.ubuntu.com/cdimage/daily-live/current/maverick-desktop-amd64.iso', '/home/roaksoa...
Wild guess: you have your own file called subprocess.py which is masking the standard library module. What do you see with this?: ``` import subprocess print subprocess.__file__ ``` This will show what file is being imported as `subprocess`.
PHP vs. Other Languages in Hadoop/MapReduce implementations, and in the Cloud generally
3,113,573
3
2010-06-24T20:18:39Z
3,113,643
11
2010-06-24T20:31:09Z
[ "java", "php", "python", "hadoop", "mapreduce" ]
I'm beginning to learn some Hadoop/MapReduce, coming mostly from a PHP background, with a little bit of Java and Python. But, it seems like most implementations of MapReduce out there are in Java, Ruby, C++ or Python. I've looked, and it looks like there are some Hadoop/MapReduce in PHP, but the overwhelming body of ...
PHP is designed primarily as a language for displaying output to a browser. Most jobs being run on MapReduce/Hadoop clusters have nothing to do with displaying output. They instead tend to lean much more heavily towards data processing. PHP is *not* the most commonly supported language for data processing, by far. Thu...
Is there a nice way to handle exceptions in Python?
3,114,246
6
2010-06-24T22:05:54Z
3,114,274
11
2010-06-24T22:10:28Z
[ "python", "exception" ]
I have a bunch of code that looks similar to this: ``` try: auth = page.ItemAttributes.Author except: try: auth = page.ItemAttributes.Creator except: auth = No...
You can use hasattr to avoid the try/except blocks: ``` auth = None for attrname in ['Author', 'Creator']: if hasattr(page.ItemAttributes, attrname): auth = getattr(page.ItemAttributes, attrname) break ``` An alternate way to write the above is to use the `else` clause of a Python `for` loop: ```...
One-liner to check whether an iterator yields at least one element?
3,114,252
40
2010-06-24T22:06:33Z
3,114,423
13
2010-06-24T22:39:24Z
[ "python", "iterator" ]
Currently I'm doing this: ``` try: something = iterator.next() # ... except StopIteration: # ... ``` But I would like an expression that I can place inside a simple `if` statement. Is there anything built-in which would make this code look less clumsy? `any()` returns `False` if an iterable is empty, but...
This isn't really cleaner, but it shows a way to package it in a function losslessly: ``` def has_elements(iter): from itertools import tee iter, any_check = tee(iter) try: any_check.next() return True, iter except StopIteration: return False, iter has_el, iter = has_elements(iter) if has_el: # ...
One-liner to check whether an iterator yields at least one element?
3,114,252
40
2010-06-24T22:06:33Z
3,114,573
26
2010-06-24T23:12:30Z
[ "python", "iterator" ]
Currently I'm doing this: ``` try: something = iterator.next() # ... except StopIteration: # ... ``` But I would like an expression that I can place inside a simple `if` statement. Is there anything built-in which would make this code look less clumsy? `any()` returns `False` if an iterable is empty, but...
In Python 2.6+, if name `sentinel` is bound to a value which the iterator can't possibly yield, ``` if next(iterator, sentinel) is sentinel: print('iterator was empty') ``` If you have no idea of what the iterator might possibly yield, make your own sentinel (e.g. at the top of your module) with ``` sentinel = o...
One-liner to check whether an iterator yields at least one element?
3,114,252
40
2010-06-24T22:06:33Z
3,114,640
74
2010-06-24T23:28:21Z
[ "python", "iterator" ]
Currently I'm doing this: ``` try: something = iterator.next() # ... except StopIteration: # ... ``` But I would like an expression that I can place inside a simple `if` statement. Is there anything built-in which would make this code look less clumsy? `any()` returns `False` if an iterable is empty, but...
`any` won't go beyond the first element if it's True. In case the iterator yields something false-ish you can write `any(True for _ in iterator)`.
Google App Engine - headers[] and headers.add_header() for cache control
3,114,803
9
2010-06-25T00:16:29Z
3,114,820
10
2010-06-25T00:22:46Z
[ "python", "google-app-engine", "header", "no-cache" ]
What is the proper way to set cache control? Sometimes I see the use of headers[] ``` self.response.headers["Pragma"]="no-cache" self.response.headers["Cache-Control"]="no-cache, no-store, must-revalidate, pre-check=0, post-check=0" self.response.headers["Expires"]="Thu, 01 Dec 1994 16:00:00" ``` Other times, I see ...
The difference is that using `headers[]` will overwrite previous values, while `add_header` won't. From the wsgiref.headers [docs](http://docs.python.org/release/2.5.2/lib/module-wsgiref.headers.html) (referred to by the [GAE docs](http://code.google.com/appengine/docs/python/tools/webapp/responseclass.html#Response_h...
Python: __init__() takes exactly 2 arguments (3 given)
3,115,030
15
2010-06-25T01:38:26Z
3,115,041
12
2010-06-25T01:41:38Z
[ "python" ]
this is my first question on StackOverflow, so please tell me how I can improve it in the comments. I am writing a program to find adapters, and have made a class called 'Adapter'. When I pass in two arguments IDLE gives me an error saying I passed in three! Here is the code and stack trace: ``` #This is the adapter ...
Method calls automatically get a 'self' parameter as the first argument, so make `__init__`() look like: ``` def __init__(self, (pType1,pMF1),(pType2,pMF2)): ``` This is usually implicit in other languages, in Python it must be explicit. Also note that it's really just a way of informing the method of the instance it...
Python: __init__() takes exactly 2 arguments (3 given)
3,115,030
15
2010-06-25T01:38:26Z
3,115,131
17
2010-06-25T02:14:09Z
[ "python" ]
this is my first question on StackOverflow, so please tell me how I can improve it in the comments. I am writing a program to find adapters, and have made a class called 'Adapter'. When I pass in two arguments IDLE gives me an error saying I passed in three! Here is the code and stack trace: ``` #This is the adapter ...
Yes, the OP missed the `self`, but I don't even know what those tuples-as-arguments mean and I'm intentionally not bothering to figure it out, it's just a bad construction. Codysehi, please contrast your code with: ``` class Adapter: def __init__(self, side1, side2): self.side1 = side1 self.side2 ...
Interpreter in Python: Making your own programming language?
3,115,971
6
2010-06-25T06:22:01Z
3,116,011
9
2010-06-25T06:31:01Z
[ "python", "compiler-construction", "parsing", "interpreter" ]
Remember, this is using python. Well, I was fiddling around with an app I made called Pyline, today. It is a command line-like interface, with some cool features. However, I had an idea while making it: Since its like a "OS", wont it have its own language? Well, I have seen some articles online on how to make a interp...
You need some grounding first in order to actually create a programming language. I strongly suggest picking up a copy of [Programming Language Pragmatics](http://rads.stackoverflow.com/amzn/click/0123745144), which is quite readable (much more so than the [Dragon book](http://rads.stackoverflow.com/amzn/click/03214868...
error with parse function in lxml
3,116,269
11
2010-06-25T07:28:30Z
3,116,689
12
2010-06-25T08:48:26Z
[ "python", "windows", "parsing", "lxml" ]
i have installed lxml2.2.2 on windows platform(i m using python version 2.6.5).i tried this simple command: ``` from lxml.html import parse p= parse(‘http://www.google.com’).getroot() ``` but i am getting the following error: ``` Traceback (most recent call last): File “”, line 1, in p=parse(‘http://www.g...
`lxml.html.parse` does not fetch URLs. Here's how to do it with urllib2: ``` >>> from urllib2 import urlopen >>> from lxml.html import parse >>> page = urlopen('http://www.google.com') >>> p = parse(page) >>> p.getroot() <Element html at 1304050> ``` --- **Update** Steven is right. `lxml.etree.parse` should accep...
Should I use Python 32bit or Python 64bit
3,117,626
59
2010-06-25T11:35:11Z
3,117,794
38
2010-06-25T12:03:31Z
[ "python", "32bit-64bit" ]
I have a win7 64bit installation. Must I use Python 64bit? What are the differences between the 32bit and 64bit Python versions anyway? Do different Python packages (such as south, django, mysqldb etc) support only 32bit\64bit?
64 bit version will allow a single process to use more RAM than 32 bit, however you may find that the memory footprint doubles depending on what you are storing in RAM (Integers in particular). For example if your app requires > 2GB of RAM, so you switch from 32bit to 64bit you may find that your app is now requiring ...
How can I use common code in python?
3,118,008
15
2010-06-25T12:35:52Z
3,118,051
16
2010-06-25T12:43:05Z
[ "python", "module" ]
I'm currently maintaining two of my own applications. They both share some common aspects, and as a result, share some code. So far, I've just copied the modules from one project to the other, but now it's becoming a maintenance issue. I'd rather have the common code in one place, outside of both of the projects, which...
There is nothing special you have to do, Python just needs to find your module. This means that you have to put your common module into your `PYTHONPATH`, or you add their location to `sys.path`. [See this.](http://docs.python.org/tutorial/modules.html#the-module-search-path) Say you have ``` ~/python/project1 ~/pyth...
How to write custom python logging handler?
3,118,059
32
2010-06-25T12:43:50Z
7,327,829
39
2011-09-07T01:00:05Z
[ "python", "logging" ]
How to write custom console log function to output only on the console window log messages on a single line (not append) until the first regular log record. ``` progress = ProgressConsoleHandler() console = logging.StreamHandler() logger = logging.getLogger('test') logger.setLevel(logging.DEBUG) logger.addHandler...
``` import logging class ProgressConsoleHandler(logging.StreamHandler): """ A handler class which allows the cursor to stay on one line for selected messages """ on_same_line = False def emit(self, record): try: msg = self.format(record) stream = self.stream ...
Convert HTTP Proxy to HTTPS Proxy in Twisted
3,118,602
7
2010-06-25T14:01:27Z
3,186,044
11
2010-07-06T12:12:13Z
[ "python", "http", "proxy", "https", "twisted" ]
Hey, Recently I have been playing around with the HTTP Proxy in twisted. After much trial and error I think I finally I have something working. What I want to know though, is how, if it is possible, do I expand this proxy to also be able to handle HTTPS pages? Here is what I've got so far: ``` from twisted.internet im...
If you want to connect to an HTTPS website via an HTTP proxy, you need to use the `CONNECT` HTTP verb (because that's how a proxy works for HTTPS). In this case, the proxy server simply connects to the target server and relays whatever is sent by the server back to the client's socket (and vice versa). There's no cachi...
Implementing the decorator pattern in Python
3,118,929
19
2010-06-25T14:45:33Z
3,119,031
24
2010-06-25T15:00:17Z
[ "python", "design-patterns" ]
I want to implement the [decorator pattern](http://en.wikipedia.org/wiki/Decorator_pattern) in Python, and I wondered if there is a way to write a decorator that just implements the function it wants to modify, without writing boiler-plate for all the functions that are just forwarded to the decorated object. Like so: ...
You could use `__getattr__`: ``` class foo(object): def f1(self): print "original f1" def f2(self): print "original f2" class foo_decorator(object): def __init__(self, decoratee): self._decoratee = decoratee def f1(self): print "decorated f1" self._decoratee.f1(...
Implementing the decorator pattern in Python
3,118,929
19
2010-06-25T14:45:33Z
3,371,796
7
2010-07-30T13:19:34Z
[ "python", "design-patterns" ]
I want to implement the [decorator pattern](http://en.wikipedia.org/wiki/Decorator_pattern) in Python, and I wondered if there is a way to write a decorator that just implements the function it wants to modify, without writing boiler-plate for all the functions that are just forwarded to the decorated object. Like so: ...
As an addendum to Philipp's answer; if you need to not only decorate, but preserve the *type* of an object, Python allows you to subclass an instance at runtime: ``` class foo(object): def f1(self): print "original f1" def f2(self): print "original f2" class foo_decorator(object): def __...
datetime issue with xlrd & xlwt python libs
3,118,940
2
2010-06-25T14:47:09Z
3,119,430
8
2010-06-25T15:47:14Z
[ "python", "excel", "datetime", "xlwt", "xlrd" ]
I'm trying to write some dates from one excel spreadsheet to another. Currently, I'm getting a representation in excel that isn't quite what I want such as this: "40299.2501157407" I can get the date to print out fine to the console, however it doesn't seem to work right writing to the excel spreadsheet -- the data mu...
You can write the floating point number directly to the spreadsheet and set the number format of the cell. Set the format using the `num_format_str` of an `XFStyle` object when you write the value. <https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/doc/xlwt.html#xlwt.Worksheet.write-method> The following example wr...
Python global variable insanity
3,119,287
11
2010-06-25T15:29:55Z
3,119,344
11
2010-06-25T15:36:02Z
[ "python" ]
You have three files: main.py, second.py, and common.py common.py ``` #!/usr/bin/python GLOBAL_ONE = "Frank" ``` main.py ``` #!/usr/bin/python from common import * from second import secondTest if __name__ == "__main__": global GLOBAL_ONE print GLOBAL_ONE #Prints "Frank" GLOBAL_ONE = "Bob" print GL...
`global` means global for this module, not for whole program. When you do ``` from lala import * ``` you add all definitions of `lala` as *locals* to this *module*. So in your case you get two copies of `GLOBAL_ONE`
Why do I get TypeError: get() takes exactly 2 arguments (1 given)? Google App Engine
3,119,562
5
2010-06-25T16:04:34Z
3,120,769
7
2010-06-25T19:10:38Z
[ "python", "google-app-engine", "web-applications" ]
I have been trying and trying for several hours now and there must be an easy way to retreive the url. I thought this was the way: ``` #from data.models import Program import basehandler class ProgramViewHandler(basehandler.BaseHandler): def get(self,slug): # query = Program.all() # query.filter('s...
You are getting this error because `ProgramViewHandler.get()` is being called without the `slug` parameter. Most likely, you need to fix the URL mappings in your `main.py` file. Your URL mapping should probably look something like this: ``` application = webapp.WSGIApplication([(r'/(.*)', ProgramViewHandler)]) ``` T...
Python: deepcopy(list) vs new_list = old_list[:]
3,119,901
12
2010-06-25T17:02:03Z
3,119,921
22
2010-06-25T17:04:44Z
[ "python", "list", "copy" ]
I'm doing exercise #9 from <http://openbookproject.net/thinkcs/python/english2e/ch09.html> and have ran into something that doesn't make sense. The exercise suggests using `copy.deepcopy()` to make my task easier but I don't see how it could. ``` def add_row(matrix): """ >>> m = [[0, 0], [0, 0]] >...
You asked two questions: ### Deep vs. shallow copy `matrix[:]` is a **shallow copy** -- it only copies the elements directly stored in it, and doesn't recursively duplicate the elements of arrays or other references within itself. That means: ``` a = [[4]] b = a[:] a[0].append(5) print b[0] # Outputs [4, 5], as a[0]...
Drawing semi-transparent polygons in PIL
3,119,999
10
2010-06-25T17:16:25Z
3,120,700
12
2010-06-25T18:58:30Z
[ "python", "image-processing" ]
How do you draw semi-transparent polygons using the Python Imaging Library?
Can you draw the polygon on a separate RGBA image then use the *Image.paste(image, box, mask)* method? **Edit**: This works. ``` import Image import ImageDraw back = Image.new('RGBA', (512,512), (255,0,0,0)) poly = Image.new('RGBA', (512,512)) pdraw = ImageDraw.Draw(poly) pdraw.polygon([(128,128),(384,384),(128,384),...
Python, subclassing immutable types
3,120,562
11
2010-06-25T18:41:01Z
3,120,650
10
2010-06-25T18:50:14Z
[ "python", "set", "immutability" ]
I've the following class: ``` class MySet(set): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() set.__init__(self, arg) ``` This works as expected (initialising the set with the words of the string rather than the letters). However when I want to do the...
Yes, you need to override `__new__` special method: ``` class MySet(frozenset): def __new__(cls, *args): if args and isinstance (args[0], basestring): args = (args[0].split (),) + args[1:] return super (MySet, cls).__new__(cls, *args) print MySet ('foo bar baz') ``` And the output is...
How do I send an email from a non-gmail account using the appengine
3,120,941
4
2010-06-25T19:43:44Z
3,120,963
7
2010-06-25T19:48:27Z
[ "python", "google-app-engine", "email" ]
I have successfully sent an email using the Google App Engine. However the only email address I can get to work is the gmail address I have listed as the admin of the site. I'm running the app on my own domain (bought and maintained using Google Apps). I would like to send the email from my own domain. Here's the code ...
That's a restriction of [App Engine's mail API](http://code.google.com/appengine/docs/python/mail/sendingmail.html): > The sender address can be either the email address of a registered administrator for the application, or the email address of the current signed-in user (the user making the request that is sending th...
Python threading unexpectedly slower
3,121,109
5
2010-06-25T20:07:15Z
3,121,156
8
2010-06-25T20:16:30Z
[ "python", "multithreading", "parallel-processing" ]
I have decided to learn how multi-threading is done in Python, and I did a comparison to see what kind of performance gain I would get on a dual-core CPU. I found that my simple multi-threaded code actually runs slower than the sequential equivalent, and I cant figure out why. The test I contrived was to generate a la...
1. Python has the GIL. Python bytecode will only be executed by a single processor at a time. Only certain C modules (which don't manage Python state) will be able to run concurrently. 2. The Python GIL has a huge overhead in locking the state between threads. There are fixes for this in newer versions or in developmen...
Error with urlencode in python
3,121,186
24
2010-06-25T20:23:37Z
3,121,311
45
2010-06-25T20:42:24Z
[ "python", "encoding", "urlencode" ]
I have this: ``` a = {'album': u'Metamorphine', 'group': 'monoku', 'name': u'Son Of Venus (Danny\xb4s Song)', 'artist': u'Leandra', 'checksum': '2836e33d42baf947e8c8adef48921f2f76fcb37eea9c50b0b59d7651', 'track_number': 8, 'year': '2008', 'genre': 'Darkwave', 'path': u'/media/data/musik/Leandra/2008. Metamorphine/08. ...
The `urlencode` library expects data in `str` format, and doesn't deal well with Unicode data since it doesn't provide a way to specify an encoding. Try this instead: ``` mp3_data = {'album': u'Metamorphine', 'group': 'monoku', 'name': u'Son Of Venus (Danny\xb4s Song)', 'artist': u'Leandra', 'check...
Error with urlencode in python
3,121,186
24
2010-06-25T20:23:37Z
11,726,437
8
2012-07-30T17:23:56Z
[ "python", "encoding", "urlencode" ]
I have this: ``` a = {'album': u'Metamorphine', 'group': 'monoku', 'name': u'Son Of Venus (Danny\xb4s Song)', 'artist': u'Leandra', 'checksum': '2836e33d42baf947e8c8adef48921f2f76fcb37eea9c50b0b59d7651', 'track_number': 8, 'year': '2008', 'genre': 'Darkwave', 'path': u'/media/data/musik/Leandra/2008. Metamorphine/08. ...
If you are using Django, take a look at Django's QueryDict class, it has a urlencode() method. Or, for the helper function itself you may use [`urlencode`](https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.http.urlencode). It basically does what is described in the other answers as a wrapper around the ori...
Cosine Similarity of Vectors of different lengths?
3,121,217
9
2010-06-25T20:27:51Z
3,145,811
8
2010-06-30T01:00:22Z
[ "python", "nlp", "similarity", "nltk", "tf-idf" ]
[I'm trying to use TF-IDF](http://stackoverflow.com/questions/3113428/classifying-documents-into-categories/3114191#3114191) to sort documents into categories. I've calculated the tf\_idf for some documents, but now when I try to calculate the Cosine Similarity between two of these documents I get a traceback saying: ...
You need multiply the entries for corresponding words in the vector, so there should be a global order for the words. This means that in theory your vectors should be the same length. In practice, if one document was seen before the other, words in the second document may have been added to the global order after the ...
Invoke make from different directory with python script
3,121,555
6
2010-06-25T21:25:38Z
3,121,659
9
2010-06-25T21:46:46Z
[ "python", "linux" ]
I need to invoke make (build a makefile) in a directory different from the one I'm in, from inside a Python script. If I simply do: ``` build_ret = subprocess.Popen("../dir1/dir2/dir3/make", shell = True, stdout = subprocess.PIPE) ``` I get the following: /bin/sh: ../dir1/dir2/dir3/make: No such ...
I'd go with @Philipp's solution of using `cwd`, but as a side note you could also use the `-C` option to make: ``` make -C ../dir1/dir2/dir3/make ``` ### -C *dir*, --directory=*dir* > Change to directory *dir* before reading the makefiles or doing anything else. If multiple -C options are specified, each is interpre...
How to sort (list/tuple) of lists/tuples?
3,121,979
252
2010-06-25T23:01:41Z
3,121,985
467
2010-06-25T23:04:59Z
[ "python", "list", "sorting", "tuples" ]
I have some data either in list contains lists, or list contains tuples. ``` data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] ``` And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I ...
``` sorted_by_second = sorted(data, key=lambda tup: tup[1]) ``` or: ``` data.sort(key=lambda tup: tup[1]) # sorts in place ```
How to sort (list/tuple) of lists/tuples?
3,121,979
252
2010-06-25T23:01:41Z
3,122,110
19
2010-06-25T23:44:26Z
[ "python", "list", "sorting", "tuples" ]
I have some data either in list contains lists, or list contains tuples. ``` data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] ``` And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I ...
[Stephen's answer](http://stackoverflow.com/questions/3121979/python-sort-list-tuple-in-list/3121985#3121985) is the one I'd use. For completeness, here's the DSU (decorate-sort-undecorate) pattern with list comprehensions: ``` decorated = [(tup[1], tup) for tup in data] decorated.sort() undecorated = [tup for second,...
How to sort (list/tuple) of lists/tuples?
3,121,979
252
2010-06-25T23:01:41Z
19,901,707
44
2013-11-11T08:18:15Z
[ "python", "list", "sorting", "tuples" ]
I have some data either in list contains lists, or list contains tuples. ``` data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] ``` And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I ...
``` from operator import itemgetter data.sort(key=itemgetter(1)) ```
How to sort (list/tuple) of lists/tuples?
3,121,979
252
2010-06-25T23:01:41Z
27,001,786
13
2014-11-18T18:53:12Z
[ "python", "list", "sorting", "tuples" ]
I have some data either in list contains lists, or list contains tuples. ``` data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] ``` And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I ...
I just want to add to Stephen's answer if you want to sort the array from high to low, another way other than in the comments above is just to add this to the line: ``` reverse = True ``` and the result will be as follow: ``` data.sort(key=lambda tup: tup[1], reverse=True) ```
How to sort (list/tuple) of lists/tuples?
3,121,979
252
2010-06-25T23:01:41Z
34,375,589
14
2015-12-19T21:27:50Z
[ "python", "list", "sorting", "tuples" ]
I have some data either in list contains lists, or list contains tuples. ``` data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] ``` And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I ...
For sorting by multiple criteria, namely for instance by the second and third elements in a tuple, let ``` data = [(1,2,3),(1,2,1),(1,1,4)] ``` and so define a lambda that returns a tuple that describes priority, for instance ``` sorted(data, key=lambda tup: (tup[1],tup[2]) ) [(1, 1, 4), (1, 2, 1), (1, 2, 3)] ```
Python how to read and split a line to several integers
3,122,121
6
2010-06-25T23:47:48Z
3,122,147
9
2010-06-25T23:55:37Z
[ "python", "file-io" ]
For input file separate by space/tab like: ``` 1 2 3 4 5 6 7 8 9 ``` How to read the line and split the integers, then save into either lists or tuples? Thanks. ``` data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] ```
One way to do this, assuming the sublists are on separate lines: ``` with open("filename.txt", 'r') as f: data = [map(int, line.split()) for line in f] ``` Note that the `with` statement didn't become official until Python 2.6. If you are using an earlier version, you'll need to do ``` from __future__ import wit...
zlib.error: Error -3 while decompressing: incorrect header check
3,122,145
23
2010-06-25T23:55:31Z
22,310,760
42
2014-03-10T20:35:24Z
[ "python", "gzip", "zlib" ]
I have a gzip file and I am trying to read it via Python as below: ``` import zlib do = zlib.decompressobj(16+zlib.MAX_WBITS) fh = open('abc.gz', 'rb') cdata = fh.read() fh.close() data = do.decompress(cdata) ``` it throws this error: ``` zlib.error: Error -3 while decompressing: incorrect header check ``` How can...
You have this error: ``` zlib.error: Error -3 while decompressing: incorrect header check ``` Which is most likely because you are trying to check headers that are not there, e.g. your data follows `RFC 1951` (`deflate` compressed format) rather than `RFC 1950` (`zlib` compressed format) or `RFC 1952` (`gzip` compres...
How to define column headers when reading a csv file in Python
3,122,206
4
2010-06-26T00:18:26Z
3,122,216
26
2010-06-26T00:21:08Z
[ "python", "csv" ]
I have a comma separated value table that I want to read in Python. What I need to do is first tell Python not to skip the first row because that contains the headers. Then I need to tell it to read in the data as a list and not a string because I need to build an array out of the data and the first column is non-integ...
You can use the [`csv` module](http://docs.python.org/library/csv.html) for this sort of thing. It will read in each row as a list of strings representing the different fields. How exactly you'd want to use it depends on how you're going to process the data afterwards, but you might consider making a `Reader` object (...
Python: os.listdir alternative/certain extensions
3,122,514
6
2010-06-26T02:44:26Z
3,122,521
18
2010-06-26T02:50:06Z
[ "python", "operating-system" ]
Is it possible to see files with certain extensions with the os.listdir command? I want it to work so it may show only files or folders with .f at the end. I checked the documentation, and found nothing, so don't ask.
`glob` is good at this: ``` import glob for f in glob.glob("*.f"): print f ```