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
Finding the index of a list in a loop
3,549,959
3
2010-08-23T17:14:20Z
3,549,968
10
2010-08-23T17:15:03Z
[ "python", "loops" ]
I have a simple question. If I have a for loop in python as follows: ``` for name in nameList: ``` How do I know what the index is for the element name? I know I can some something like: ``` i = 0 for name in nameList: i= i + 1 if name == "something": nameList[i] = "something else" ``` I just feel t...
Use the built in function [`enumerate`](http://docs.python.org/library/functions.html#enumerate). ``` for index, name in enumerate(nameList): ... ```
Comparing two objects
3,550,336
10
2010-08-23T18:05:06Z
3,550,500
7
2010-08-23T18:24:41Z
[ "python" ]
Is there any way to check if two objects have the same values, other than to iterate through their attributes and manually compare their values? Thanks in advance!
@Joe Kington's solutions works if there is a `__dict__` (some objects, including builtins, don't have one) and `__eq__` works for all values of both dicts (a badly written `__eq__` mayraise exceptions etc). But it is horribly unpythonic. It doesn't even handle nominal subtypes properly... much less structural subtypes ...
Numpy index slice without losing dimension information
3,551,242
19
2010-08-23T20:06:22Z
3,551,837
7
2010-08-23T21:26:12Z
[ "python", "numpy" ]
I'm using numpy and want to index a row without losing the dimension information. ``` import numpy as np X = np.zeros((100,10)) X.shape # >> (100, 10) xslice = X[10,:] xslice.shape # >> (10,) ``` In this example xslice is now 1 dimension, but I want it to be (1,10). In R, I would use X[10,:,drop=F]. Is there...
I found a few reasonable solutions. 1) use `numpy.take(X,[10],0)` 2) use this strange indexing `X[10:11:, :]` Ideally, this should be the default. I never understood why dimensions are ever dropped. But that's a discussion for numpy...
Numpy index slice without losing dimension information
3,551,242
19
2010-08-23T20:06:22Z
3,551,859
15
2010-08-23T21:30:22Z
[ "python", "numpy" ]
I'm using numpy and want to index a row without losing the dimension information. ``` import numpy as np X = np.zeros((100,10)) X.shape # >> (100, 10) xslice = X[10,:] xslice.shape # >> (10,) ``` In this example xslice is now 1 dimension, but I want it to be (1,10). In R, I would use X[10,:,drop=F]. Is there...
It's probably easiest to do `x[10,:,None]` or equivalently (but more readable) `x[10,:,np.newaxis]`. As far as why it's not the default, personally, I find that constantly having arrays with singleton dimensions gets annoying very quickly. I'd guess the numpy devs felt the same way. Also, numpy handle broadcasting ar...
Numpy index slice without losing dimension information
3,551,242
19
2010-08-23T20:06:22Z
18,183,182
16
2013-08-12T09:05:36Z
[ "python", "numpy" ]
I'm using numpy and want to index a row without losing the dimension information. ``` import numpy as np X = np.zeros((100,10)) X.shape # >> (100, 10) xslice = X[10,:] xslice.shape # >> (10,) ``` In this example xslice is now 1 dimension, but I want it to be (1,10). In R, I would use X[10,:,drop=F]. Is there...
Another solution is to do ``` X[[10],:] ``` or ``` I = array([10]) X[I,:] ``` The dimensionality of an array is preserved when indexing is performed by a list (or an array) of indexes. This is nice because it leaves you with the choice between keeping the dimension and squeezing.
How to make wx.TextEntryDialog larger and resizable
3,551,249
5
2010-08-23T20:07:28Z
3,551,477
8
2010-08-23T20:36:24Z
[ "python", "wxpython", "wxwidgets", "wx" ]
I create a [`wx.TextEntryDialog`](http://www.wxpython.org/docs/api/wx.TextEntryDialog-class.html) as follows: ``` import wx dlg = wx.TextEntryDialog(self, 'Rules:', 'Edit rules', style=wx.TE_MULTILINE|wx.OK|wx.CANCEL) dlg.SetValue(self.rules_text.Value) if dlg.ShowModal() == wx.ID_OK: â€...
Time to learn how to write your own dialogs! ;-) The built-in dialogs such as `TextEntryDialog` are only for the most basic programs. If you need much customization, you need to write your own dialogs. Here's an example, this should work for you. ``` import wx class TextEntryDialog(wx.Dialog): def __init__(self...
How to disable formatting for FloatField in template for Django
3,551,257
21
2010-08-23T20:08:00Z
5,551,043
52
2011-04-05T11:25:30Z
[ "python", "django", "templates" ]
i just can't seem to find a definitive answer to this issue, and django's irc needs auth to services... So my question is : how can you force some kind of formatting for FloatFields in template when you're using Django ? The problem is simple i need simple dot separated numbers like this : 42547.34 And i end up with c...
``` {{ float_var|stringformat:"f" }} ```
How to disable formatting for FloatField in template for Django
3,551,257
21
2010-08-23T20:08:00Z
28,574,292
8
2015-02-18T01:17:25Z
[ "python", "django", "templates" ]
i just can't seem to find a definitive answer to this issue, and django's irc needs auth to services... So my question is : how can you force some kind of formatting for FloatFields in template when you're using Django ? The problem is simple i need simple dot separated numbers like this : 42547.34 And i end up with c...
You can now force the value to be printed without localization. ``` {% load l10n %} {{ value|unlocalize }} ``` Taken from <https://docs.djangoproject.com/en/1.7/topics/i18n/formatting/#std:templatefilter-unlocalize>
python: comparing two strings
3,551,423
9
2010-08-23T20:29:52Z
3,551,701
15
2010-08-23T21:06:18Z
[ "python", "string" ]
I would like to know if there is a library that will tell me approximately how similar two strings are I am not looking for anything specific, but in this case: ``` a = 'alex is a buff dude' b = 'a;exx is a buff dud' ``` we could say that `b` and `a` are approximately 90% similar. Is there a library which can do th...
``` import difflib >>> a = 'alex is a buff dude' >>> b = 'a;exx is a buff dud' >>> difflib.SequenceMatcher(None, a, b).ratio() 0.89473684210526316 ```
Django, automatic HTML "sanitizing" when putting HTML to template, how to stop it?
3,551,599
4
2010-08-23T20:51:06Z
3,551,699
8
2010-08-23T21:05:47Z
[ "python", "html", "django", "templates", "html-sanitizing" ]
I'm kind of confused by this because it seems that Django templates have optional HTML filters but this seems to be happening automatically.. I am making this demo app where the user will do an action that calls a python script which retrieves a url, I then want to display this in a new window.. its all fine except whe...
Use the safe filter: ``` {{ myvariable|safe }} ``` If you need large parts of your template treated like this (that is, if you find yourself using `|safe` over and over), you can disable the autoescaping whole-sale: ``` {% autoescape off %} blah {{myvariable}} blah {{myothervariable}} {% endautoescape %} ```
Xorg, Python, and Current Window Title
3,551,754
3
2010-08-23T21:14:53Z
3,552,462
12
2010-08-23T23:28:39Z
[ "python", "linux", "title", "xorg", "wiimote" ]
After stackoverflow answered my previous question on here about my Wiimote left/right click issue, Not only can I move the mouse cursor, I can now left/right click on things. I now have one more question. What do I use in python to get the title of the current active window? After googling 'X11 Python Window Title', '...
**EDIT** best way: ``` import gtk import wnck import glib class WindowTitle(object): def __init__(self): self.title = None glib.timeout_add(100, self.get_title) def get_title(self): try: title = wnck.screen_get_default().get_active_window().get_name() if self....
combine list elements
3,551,797
2
2010-08-23T21:21:13Z
3,551,808
12
2010-08-23T21:22:43Z
[ "python" ]
How can I merge/combine two or three elements of a list. For instance, if there are two elements, the list 'l' ``` l = [(a,b,c,d,e),(1,2,3,4,5)] ``` is merged into ``` [(a,1),(b,2),(c,3),(d,4),(e,5)] ``` however if there are three elements ``` l = [(a,b,c,d,e),(1,2,3,4,5),(I,II,II,IV,V)] ``` the list is converted...
Use [zip](http://docs.python.org/library/functions.html#zip): ``` l = [('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, 5)] print zip(*l) ``` Result: ``` [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] ```
Custom classes in python: does a method HAVE to be called with an instance?
3,552,045
2
2010-08-23T21:59:34Z
3,552,063
8
2010-08-23T22:02:33Z
[ "python", "datetime", "class", "instance" ]
I'm processing data from an application that has a few quirks in how it keeps time. One of the simpler quirks is that it uses "day of year" (Jan 1 is 1, Febuary 1 is 32, etc) instead of month + day. So I want to make my own date class that inherits from the default datetime class and has a few custom methods. I'm calli...
You want @classmethod decorator. Then your method gets the class instead of object instance as the first argument. It's customary to call it cls: ``` @classmethod def from_file(cls, f): return cls(f.read()) ```
Python: Upload a photo to photobucket
3,552,102
2
2010-08-23T22:11:06Z
3,553,293
8
2010-08-24T03:06:08Z
[ "python", "photobucket" ]
Can a Python script upload a photo to photo bucket and then retrieve the URL for it? Is so how? I found a script at this link: <http://www.democraticunderground.com/discuss/duboard.php?az=view_all&address=240x677> But I just found that confusing. many thanks, Phil
Yes, you can. Photobucket has a well-documented [API](http://photobucket.com/developer/documentation), and someone wrote a [wrapper](http://code.google.com/p/photobucket-api-py/) around it. Download the it and put it into your Python path, then download httplib2 (you can use easy\_install or pip for this one). Then, ...
how do i set a timeout value for python's mechanize?
3,552,928
12
2010-08-24T01:22:22Z
3,554,146
11
2010-08-24T07:03:40Z
[ "python", "timeout", "mechanize" ]
How do i set a timeout value for python's mechanize?
Alex is correct: `mechanize.urlopen` takes a `timeout` argument. Therefore, just insert a number of [seconds in floating point](http://docs.python.org/library/socket.html#socket.socket.settimeout): `mechanize.urlopen('http://url/', timeout=30.0)`. The background, from the source of `mechanize.urlopen`: ``` def urlope...
How do you "concatenate" two 32 bits int to get a 64 bits long in Python?
3,553,354
4
2010-08-24T03:22:09Z
3,553,367
9
2010-08-24T03:25:04Z
[ "python", "timestamp", "bit-manipulation", "math", "uniqueidentifier" ]
I want to generate 64 bits long int to serve as unique ID's for documents. One idea is to combine the user's ID, which is a 32 bit int, with the Unix timestamp, which is another 32 bits int, to form an unique 64 bits long integer. A scaled-down example would be: Combine two 4-bit numbers `0010` and `0101` to form th...
Left shift the first number by the number of bits in the second number, then add (or bitwise OR - replace `+` with `|` in the following examples) the second number. ``` result = (user_id << 32) + timestamp ``` With respect to your scaled-down example, ``` >>> x = 0b0010 >>> y = 0b0101 >>> (x << 4) + y 37 >>> 0b00100...
What is the Python equivalent of Ruby's "inspect"?
3,553,740
12
2010-08-24T05:13:42Z
3,553,773
13
2010-08-24T05:22:23Z
[ "python" ]
I just want to quickly see the properties and values of an object in Python, how do I do that in the terminal on a mac (very basic stuff, never used python)? Specifically, I want to see what `message.attachments` are in [this Google App Engine MailHandler example](http://pastie.org/680280) (images, videos, docs, etc.)...
use the `getmembers` attribute of the `inspect` module It will return a list of `(key, value)` tuples. It gets the value from `obj.__dict__` if available and uses `getattr` if the the there is no corresponding entry in `obj.__dict__`. It can save you from writing a few lines of code for this purpose.
What is the Python equivalent of Ruby's "inspect"?
3,553,740
12
2010-08-24T05:13:42Z
3,553,775
15
2010-08-24T05:23:21Z
[ "python" ]
I just want to quickly see the properties and values of an object in Python, how do I do that in the terminal on a mac (very basic stuff, never used python)? Specifically, I want to see what `message.attachments` are in [this Google App Engine MailHandler example](http://pastie.org/680280) (images, videos, docs, etc.)...
If you want to dump the entire object, you can use the [`pprint`](http://docs.python.org/library/pprint.html) module to get a pretty-printed version of it. ``` from pprint import pprint pprint(my_object) # If there are many levels of recursion, and you don't want to see them all # you can use the depth parameter to ...
Transform tuple to dict
3,553,949
5
2010-08-24T06:20:50Z
3,553,960
16
2010-08-24T06:23:43Z
[ "python", "dictionary", "tuples" ]
How can I transform tuple like this: ``` ( ('a', 1), ('b', 2) ) ``` to dict: ``` { 'a': 1, 'b': 2 } ```
[Dict](http://docs.python.org/library/stdtypes.html#dict) constructor can do this for you. ``` dict(( ('a', 1), ('b', 2) )) ```
What is Ruby equivalent of Python's `s= "hello, %s. Where is %s?" % ("John","Mary")`
3,554,344
97
2010-08-24T07:34:52Z
3,554,363
15
2010-08-24T07:37:34Z
[ "python", "ruby", "string-formatting" ]
In Python, this idiom for string formatting is quite common ``` s = "hello, %s. Where is %s?" % ("John","Mary") ``` What is the equivalent in Ruby?
Almost the same way: ``` irb(main):003:0> "hello, %s. Where is %s?" % ["John","Mary"] => "hello, John. Where is Mary?" ```
What is Ruby equivalent of Python's `s= "hello, %s. Where is %s?" % ("John","Mary")`
3,554,344
97
2010-08-24T07:34:52Z
3,554,373
9
2010-08-24T07:38:51Z
[ "python", "ruby", "string-formatting" ]
In Python, this idiom for string formatting is quite common ``` s = "hello, %s. Where is %s?" % ("John","Mary") ``` What is the equivalent in Ruby?
Actually almost the same ``` s = "hello, %s. Where is %s?" % ["John","Mary"] ```
What is Ruby equivalent of Python's `s= "hello, %s. Where is %s?" % ("John","Mary")`
3,554,344
97
2010-08-24T07:34:52Z
3,554,380
159
2010-08-24T07:39:30Z
[ "python", "ruby", "string-formatting" ]
In Python, this idiom for string formatting is quite common ``` s = "hello, %s. Where is %s?" % ("John","Mary") ``` What is the equivalent in Ruby?
The easiest way is [string interpolation](http://ruby.about.com/od/rubyfeatures/ss/strings.htm). You can inject little pieces of Ruby code directly into your strings. ``` name1 = "John" name2 = "Mary" "hello, #{name1}. Where is #{name2}?" ``` You can also do format strings in Ruby. ``` "hello, %s. Where is %s?" % ...
What is Ruby equivalent of Python's `s= "hello, %s. Where is %s?" % ("John","Mary")`
3,554,344
97
2010-08-24T07:34:52Z
11,156,289
33
2012-06-22T12:35:58Z
[ "python", "ruby", "string-formatting" ]
In Python, this idiom for string formatting is quite common ``` s = "hello, %s. Where is %s?" % ("John","Mary") ``` What is the equivalent in Ruby?
In Ruby 1.9 you can do this: ``` s = "hello, %{name1}. Where is %{name2} ?" % { :name1 => 'John', :name2 => 'Mary' } ``` Edit: added missing ':'s Reference: <http://ruby-doc.org/core-1.9.3/String.html>
Given a list and a bitmask, how do I return the values at the indices that are True?
3,555,375
7
2010-08-24T10:11:30Z
3,555,387
8
2010-08-24T10:12:41Z
[ "python", "list", "sequence", "tuples", "bitmask" ]
I start with the following list `s` and bitmask `b`: ``` s = ['baa', 'baa', 'black', 'sheep', 'have', 'you', 'any', 'wool'] b = [1, 0, 0, 0, 1, 1, 1, 0] # or any iterable with boolean values ``` How do I write some function `apply_bitmask(s, b)` so that it returns ``` ['baa', 'have', 'you', 'any'] ```
``` [ item for item, flag in zip( s, b ) if flag == 1 ] ```
Given a list and a bitmask, how do I return the values at the indices that are True?
3,555,375
7
2010-08-24T10:11:30Z
3,555,397
7
2010-08-24T10:14:35Z
[ "python", "list", "sequence", "tuples", "bitmask" ]
I start with the following list `s` and bitmask `b`: ``` s = ['baa', 'baa', 'black', 'sheep', 'have', 'you', 'any', 'wool'] b = [1, 0, 0, 0, 1, 1, 1, 0] # or any iterable with boolean values ``` How do I write some function `apply_bitmask(s, b)` so that it returns ``` ['baa', 'have', 'you', 'any'] ```
You can use [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` newList = [word for (word, mask) in zip(s,b) if mask] # Note: Could also use 'if mask == blah', if mask is not a boolean-compatible type. ``` This first takes the original two lists, and [zips](http://docs....
Given a list and a bitmask, how do I return the values at the indices that are True?
3,555,375
7
2010-08-24T10:11:30Z
3,555,490
15
2010-08-24T10:31:23Z
[ "python", "list", "sequence", "tuples", "bitmask" ]
I start with the following list `s` and bitmask `b`: ``` s = ['baa', 'baa', 'black', 'sheep', 'have', 'you', 'any', 'wool'] b = [1, 0, 0, 0, 1, 1, 1, 0] # or any iterable with boolean values ``` How do I write some function `apply_bitmask(s, b)` so that it returns ``` ['baa', 'have', 'you', 'any'] ```
Python 3.1 [itertools.compress](http://docs.python.org/py3k/library/itertools.html#itertools.compress) (or [Python 2.7's](http://docs.python.org/library/itertools.html#itertools.compress) if you haven't upgraded yet) does exactly that (the list comprehension is a real close second): ``` import itertools filtered = ite...
python win32 filename length workaround
3,555,527
4
2010-08-24T10:35:43Z
3,557,977
11
2010-08-24T15:14:06Z
[ "python", "windows" ]
I have found out that you can't `open(filepath)` when filepath length is greater than 255 characters even if the filename itself is 10 characters long (the remaining part is the directory path). Any idea to work around this issue? (python 2.6 on win32)
The most general approach to this is to prefix the path with `\\\\?\\` ([reference](http://msdn.microsoft.com/en-us/library/aa365247.aspx#maxpath)). Be aware that this disables certain pre-processing on the path, but nothing major IMO. Also I can note that on 32-bit Windows Server 2003 with Python 2.7 I had to use pre...
Why does pip install matplotlib version 0.91.1 when PyPi shows version 1.0.0?
3,555,551
25
2010-08-24T10:38:48Z
3,556,318
18
2010-08-24T12:20:08Z
[ "python", "matplotlib", "pip", "pypi" ]
## Update Oct 15, 2012 PyPi is now showing matplotlib at 1.1.0 so this issue is resolved. Install matplotlib via: `pip install matplotlib` # Outdated Information Below [PyPi](http://www.pypi.org) shows [matplotlib 1.0.0](http://pypi.python.org/pypi/matplotlib/1.0.0). However, when I install matplotlib via [pip](htt...
I've experienced the same problem. I have no idea why it happens, but I do have a fix; use the -f option in pip to tell it where to find the matplotlib sources. (This works in requirements.txt as well). ``` pip install -f http://downloads.sourceforge.net/project/matplotlib/matplotlib/matplotlib-1.0/matplotlib-1.0.0.ta...
Why does pip install matplotlib version 0.91.1 when PyPi shows version 1.0.0?
3,555,551
25
2010-08-24T10:38:48Z
3,558,580
11
2010-08-24T16:16:44Z
[ "python", "matplotlib", "pip", "pypi" ]
## Update Oct 15, 2012 PyPi is now showing matplotlib at 1.1.0 so this issue is resolved. Install matplotlib via: `pip install matplotlib` # Outdated Information Below [PyPi](http://www.pypi.org) shows [matplotlib 1.0.0](http://pypi.python.org/pypi/matplotlib/1.0.0). However, when I install matplotlib via [pip](htt...
This happens because the download link for matplotlib 1.0 on PyPI points to a URL that doesn't appear to pip to be a file in a known format (the URL ends with /download rather than a filename). See this [bug filed on pip](http://bitbucket.org/ianb/pip/issue/162/pip-installs-an-old-version-of-matplotlib). oyvindio's wo...
Why does pip install matplotlib version 0.91.1 when PyPi shows version 1.0.0?
3,555,551
25
2010-08-24T10:38:48Z
5,812,947
8
2011-04-28T02:32:40Z
[ "python", "matplotlib", "pip", "pypi" ]
## Update Oct 15, 2012 PyPi is now showing matplotlib at 1.1.0 so this issue is resolved. Install matplotlib via: `pip install matplotlib` # Outdated Information Below [PyPi](http://www.pypi.org) shows [matplotlib 1.0.0](http://pypi.python.org/pypi/matplotlib/1.0.0). However, when I install matplotlib via [pip](htt...
I followed @oyvindio's and @elaichi's advice, but was still getting version 0.91.1, for some unknown reason. This was then failing to compile (with the error `src/mplutils.cpp:17: error: ‘vsprintf’ was not declared in this scope`): Installing matplotlib directly from git worked for me: ``` pip install -e git+git@...
Is there a way of having a GUI for bash scripts?
3,556,027
3
2010-08-24T11:41:58Z
3,556,051
7
2010-08-24T11:45:29Z
[ "python", "user-interface", "bash" ]
I have some bash scripts, some simple ones to copy, search, write lines to files and so on. I am an Ubuntu. and I've searched in google, but it seems that everybody is doing that on python. I could do these on python, but since I am not a python programmer, I just know the basics. I have no idea of how calling a sh sc...
> Is there a way of having a GUI for bash scripts? You can try using [Zenity](http://live.gnome.org/Zenity). > a tool that allows you to display GTK dialog boxes in commandline and shell scripts. --- > I have no idea of how calling a sh script from a GUI written on python. You can do this using [`subprocess`](http...
Better way, than this, to rename files using Python
3,556,175
3
2010-08-24T12:01:50Z
3,556,335
8
2010-08-24T12:21:57Z
[ "python", "file-io" ]
I am python newbie and am still discovering its wonders. I wrote a script which renames a number of files : from **Edison\_03-08-2010-05-02-00\_PM.7z** to **Edison\_08-03-2010-05-02-00\_PM.7z** "**03-08**-2010" is changed to "**08-03**-2010" The script is: ``` import os, os.path location = "D:/codebase/_Backups" fi...
`datetime`'s [`strptime` (parse time string) and `strftime` (format time string)](http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior) will do most of the heavy lifting for you: ``` import datetime _IN_FORMAT = 'Edison_%d-%m-%Y-%I-%M-%S_%p.7z' _OUT_FORMAT = 'Edison_%m-%d-%Y-%I-%M-%S_%p.7z' ol...
How can I get the final redirect URL when using urllib2.urlopen?
3,556,266
13
2010-08-24T12:12:08Z
3,556,287
21
2010-08-24T12:15:12Z
[ "python", "urllib2" ]
I'm using the `urllib2.urlopen` method to open a URL and fetch the markup of a webpage. Some of these sites redirect me using the 301/302 redirects. I would like to know the final URL that I've been redirected to. How can I get this?
Call the `.geturl()` method of the file object returned. Per the [`urllib2` docs](https://docs.python.org/2.7/library/urllib2.html): > `geturl()` — return the URL of the resource retrieved, commonly used to determine if a redirect was followed Example: ``` import urllib2 response = urllib2.urlopen('http://tinyurl....
How to retrieve table names in a mysql database with Python and MySQLdb?
3,556,305
11
2010-08-24T12:18:02Z
3,556,313
7
2010-08-24T12:19:18Z
[ "python", "mysql", "mysql-python" ]
I have an SQL database and am wondering what command you use to just get a list of the table names within that database.
SHOW tables 15 chars
How to retrieve table names in a mysql database with Python and MySQLdb?
3,556,305
11
2010-08-24T12:18:02Z
3,556,316
8
2010-08-24T12:20:01Z
[ "python", "mysql", "mysql-python" ]
I have an SQL database and am wondering what command you use to just get a list of the table names within that database.
`show tables` will help. [Here is the documentation](http://dev.mysql.com/doc/refman/5.0/en/show-tables.html).
How to retrieve table names in a mysql database with Python and MySQLdb?
3,556,305
11
2010-08-24T12:18:02Z
8,363,828
30
2011-12-02T23:09:12Z
[ "python", "mysql", "mysql-python" ]
I have an SQL database and am wondering what command you use to just get a list of the table names within that database.
To be a bit more complete: ``` import MySQLdb connection = MySQLdb.connect( host = 'localhost', user = 'myself', passwd = 'mysecret') # create the connection cursor = connection.cursor() # get the cursor cursor.execute("USE mydatabase") # select the database cu...
Python binary search-like function to find first number in sorted list greater than a specific value
3,556,496
2
2010-08-24T12:42:35Z
3,556,527
16
2010-08-24T12:46:11Z
[ "python", "binary-search" ]
I'm trying to write a function in Python that finds the first number in a sorted list greater than a specific value that I pass in as an argument. I've found examples online that use simple list comprehensions to achieve this, but for my purposes I need to be performing this operation frequently and on large lists, so ...
Have you tried the [`bisect` module](http://docs.python.org/library/bisect.html)? ``` def find_ge(a, key): '''Find smallest item greater-than or equal to key. Raise ValueError if no such item exists. If multiple keys are equal, return the leftmost. ''' i = bisect_left(a, key) if i == len(a): ...
Where can I find a full reference of wxpython?
3,556,716
4
2010-08-24T13:10:19Z
3,557,189
7
2010-08-24T13:56:02Z
[ "python", "wxpython" ]
Sorry the question may sound stupid, but I do need one. Right now I'm just adding a wx.TextCtrl in my GUI program, and I want to know what styles can I add (such as style=wx.TE\_MULTILINE|wx.TE\_PROCESS\_ENTER), so I googled and end up reading this page: <http://www.wxpython.org/docs/api/wx.TextCtrl-class.html>. It mus...
I find Andrea Gavana's (creator of wx.lib.agw ) documentation more comprehensive then the offical wxpython docs. [<http://xoomer.virgilio.it/infinity77/wxPython/APIMain.html>](http://xoomer.virgilio.it/infinity77/wxPython/APIMain.html) [Heres](http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.TextCtrl.html) th...
Printing objects and unicode, what's under the hood ? What are the good guidelines?
3,557,095
6
2010-08-24T13:46:09Z
3,557,431
8
2010-08-24T14:21:11Z
[ "python", "unicode", "printing", "stdout" ]
I'm struggling with print and unicode conversion. Here is some code executed in the 2.5 windows interpreter. ``` >>> import sys >>> print sys.stdout.encoding cp850 >>> print u"é" é >>> print u"é".encode("cp850") é >>> print u"é".encode("utf8") ├® >>> print u"é".__repr__() u'\xe9' >>> class A(): ... def __...
Python doesn't have *many* semantic type constraints on given functions and methods, but it has *a few*, and here's one of them: `__str__` (in Python 2.\*) must return a byte string. As usual, if a unicode object is found where a byte string is required, the current default encoding (usually `'ascii'`) is applied in th...
Reading a Turtle/N3 RDF File with Python
3,557,561
7
2010-08-24T14:33:08Z
3,557,815
9
2010-08-24T14:58:12Z
[ "python", "debugging", "semantic-web", "rdflib", "turtle-rdf" ]
I'm trying to encode some botanical data in [Turtle](http://en.wikipedia.org/wiki/Turtle_%28syntax%29) format, and read this data from Python using [RDFLib](http://www.rdflib.net/). However, I'm having trouble, and I'm not sure if it's because my Turtle is malformed or I'm [misusing](http://code.google.com/p/rdflib/wik...
I think the first problem is w/the *uppercase* `PREFIX`-- if you lowercase those it gets past that point. Not sure if it's a bug in rdflib or in the Turtle `.ttl`, but the [Turtle Validator](http://www.rdfabout.com/demo/validator/) online demo seems to agree it's a problem with the `.ttl` (says `Validation failed: The ...
How to apply __str__ function when printing a list of objects in python
3,558,474
7
2010-08-24T16:04:30Z
3,558,507
12
2010-08-24T16:08:03Z
[ "python", "list", "object", "printing", "string" ]
Well this interactive python console snippet will tell everything: ``` >>> class Test: ... def __str__(self): ... return 'asd' ... >>> t = Test() >>> print t asd >>> l = [Test(), Test(), Test()] >>> print l [__main__.Test instance at 0x00CBC1E8, __main__.Test instance at 0x00CBC260, __main__.Test inst...
Try: ``` class Test: def __repr__(self): return 'asd' ``` And read this [documentation link](http://docs.python.org/reference/datamodel.html#object.__repr__):
How to apply __str__ function when printing a list of objects in python
3,558,474
7
2010-08-24T16:04:30Z
3,558,544
7
2010-08-24T16:11:59Z
[ "python", "list", "object", "printing", "string" ]
Well this interactive python console snippet will tell everything: ``` >>> class Test: ... def __str__(self): ... return 'asd' ... >>> t = Test() >>> print t asd >>> l = [Test(), Test(), Test()] >>> print l [__main__.Test instance at 0x00CBC1E8, __main__.Test instance at 0x00CBC260, __main__.Test inst...
The suggestion in other answers to implement `__repr__` is definitely one possibility. If that's unfeasible for whatever reason (existing type, `__repr__` needed for reasons other than aesthetic, etc), then just do ``` print [str(x) for x in l] ``` or, as some are sure to suggest, `map(str, l)` (just a bit more compa...
Pass each element of a list to a function that takes multiple arguments in Python?
3,558,593
6
2010-08-24T16:18:29Z
3,558,606
19
2010-08-24T16:20:03Z
[ "python", "function", "arguments" ]
For example, if I have `a=[['a','b','c'],[1,2,3],['d','e','f'],[4,5,6]]` How can I get each element of `a` to be an argument of say, `zip` without having to type `zip(a[0],a[1],a[2],a[3])`?
Using sequence unpacking (thanks to delnan for the name): ``` zip(*a) ```
How do I pickle an object?
3,558,718
6
2010-08-24T16:34:22Z
3,558,772
16
2010-08-24T16:39:16Z
[ "python", "debugging", "pickle" ]
Here is the code I have: ``` import pickle alist = ['here', 'there'] c = open('config.pck', 'w') pickle.dump(alist, c) ``` and this is the error I receive: ``` Traceback (most recent call last): File "C:\pickle.py", line 1, in ? import pickle File "C:\pickle.py", line 6, in ? pickle.dump(alist, c) AttributeEr...
Don't call your file pickle.py. It conflicts with the python standard libary module of the same name. So your `import pickle` is not picking up the python module.
If you import yourself in Python, why don't you get an infinite loop?
3,558,842
6
2010-08-24T16:48:14Z
3,558,872
10
2010-08-24T16:51:34Z
[ "python", "import", "infinite-loop" ]
This question is a response to the following SO post: <http://stackoverflow.com/questions/3558718/how-do-i-pickle-an-object/3558783#3558783> In that thread, the OP accidentally imports his own module at the top of the same module. Why doesn't this cause an infinite loop?
Modules are imported only once. Python realizes it already has been imported, so does not do it again. See: <http://docs.python.org/tutorial/modules.html#more-on-modules>
are there dictionaries in javascript like python?
3,559,070
61
2010-08-24T17:15:18Z
3,559,184
40
2010-08-24T17:26:37Z
[ "javascript", "python" ]
i need to make a dictionary in javascript like this i dont remember the exact notation, but it was something like: ``` states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ } ``` is there such a thing in javascript?
There are no real associative arrays in Javascript. You can try using objects: ``` var x = new Object(); x["Key"] = "Value"; ``` However with objects it is not possible to use typical array properties or methods like array.length. At least it is possible to access the "object-array" in a for-in-loop.
are there dictionaries in javascript like python?
3,559,070
61
2010-08-24T17:15:18Z
11,789,703
82
2012-08-03T05:19:26Z
[ "javascript", "python" ]
i need to make a dictionary in javascript like this i dont remember the exact notation, but it was something like: ``` states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ } ``` is there such a thing in javascript?
This is an old post, but I thought I should provide an illustrated answer anyway. Use javascript's object notation. Like so: ``` states_dictionary={ "CT":["alex","harry"], "AK":["liza","alex"], "TX":["fred", "harry"] }; ``` And to access the values: ``` states_dictionary.AK[0] //which is liza ``` ...
are there dictionaries in javascript like python?
3,559,070
61
2010-08-24T17:15:18Z
18,535,013
9
2013-08-30T14:10:40Z
[ "javascript", "python" ]
i need to make a dictionary in javascript like this i dont remember the exact notation, but it was something like: ``` states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ } ``` is there such a thing in javascript?
Have created a simple dictionary in JS here: ``` function JSdict() { this.Keys = []; this.Values = []; } // Check if dictionary extensions aren't implemented yet. // Returns value of a key if (!JSdict.prototype.getVal) { JSdict.prototype.getVal = function (key) { if (key == null) { ret...
Dissecting a line of (obfuscated?) Python
3,559,124
8
2010-08-24T17:20:34Z
3,559,218
11
2010-08-24T17:29:50Z
[ "python", "obfuscation", "execution", "flow" ]
I was reading another question on Stack Overflow ([Zen of Python](http://stackoverflow.com/questions/228181/zen-of-python)), and I came across this line in Jaime Soriano's answer: ``` import this "".join([c in this.d and this.d[c] or c for c in this.s]) ``` Entering the above in a Python shell prints: ``` "The Zen o...
The operators in the list comprehension line associate like this: ``` "".join([(((c in this.d) and this.d[c]) or c) for c in this.s]) ``` Removing the list comprehension: ``` result = [] for c in this.s: result.append(((c in this.d) and this.d[c]) or c) print "".join(result) ``` Removing the `and`/`or` boolean t...
how in python to generate a random list of fixed length of values from given range?
3,559,337
13
2010-08-24T17:43:10Z
3,559,360
7
2010-08-24T17:45:59Z
[ "python", "random", "list", "sample" ]
How to generate a random (but unique and sorted) list of a fixed given length out of numbers of a given range in python? Something like that: ``` >>>> list_length = 4 >>>> values_range = [1,30] >>>> random_list(list_length,values_range) [1,6,17,29] >>>> random_list(list_length,values_range) [5,6,22,24] >>>> rando...
A combination of [random.randrange](http://docs.python.org/library/random.html#random.randrange) and list comprehension would work. ``` import random [random.randrange(1, 10) for _ in range(0, 4)] ```
how in python to generate a random list of fixed length of values from given range?
3,559,337
13
2010-08-24T17:43:10Z
3,559,364
24
2010-08-24T17:46:24Z
[ "python", "random", "list", "sample" ]
How to generate a random (but unique and sorted) list of a fixed given length out of numbers of a given range in python? Something like that: ``` >>>> list_length = 4 >>>> values_range = [1,30] >>>> random_list(list_length,values_range) [1,6,17,29] >>>> random_list(list_length,values_range) [5,6,22,24] >>>> rando...
A random sample like this returns list of unique items of sequence. Don't confuse this with random integers in the range. ``` >>> import random >>> random.sample(range(30), 4) [3, 1, 21, 19] ```
Calculating e (base of the natural log) to high precision in Python?
3,559,548
11
2010-08-24T18:05:38Z
3,559,567
19
2010-08-24T18:07:52Z
[ "python", "math", "numpy", "floating-point", "scipy" ]
Is it possible to calculate the value of the mathematical constant, ***e*** with high precision (2000+ decimal places) using [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)? I am particularly interested in a solution either in or that integrates with [NumPy](http://en.wikipedia.org/wiki/NumPy)...
You can set the precision you want with the [decimal](http://docs.python.org/library/decimal.html) **built-in module**: ``` from decimal import * getcontext().prec = 40 Decimal(1).exp() ``` This returns: ``` Decimal('2.718281828459045235360287471352662497757') ```
Calculating e (base of the natural log) to high precision in Python?
3,559,548
11
2010-08-24T18:05:38Z
3,559,642
7
2010-08-24T18:16:25Z
[ "python", "math", "numpy", "floating-point", "scipy" ]
Is it possible to calculate the value of the mathematical constant, ***e*** with high precision (2000+ decimal places) using [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)? I am particularly interested in a solution either in or that integrates with [NumPy](http://en.wikipedia.org/wiki/NumPy)...
This can also be done with [sympy](http://code.google.com/p/sympy/) using [numerical evaluation](http://docs.sympy.org/modules/evalf.html): ``` import sympy print sympy.N(sympy.E, 100) ```
Calculating e (base of the natural log) to high precision in Python?
3,559,548
11
2010-08-24T18:05:38Z
3,559,797
7
2010-08-24T18:34:31Z
[ "python", "math", "numpy", "floating-point", "scipy" ]
Is it possible to calculate the value of the mathematical constant, ***e*** with high precision (2000+ decimal places) using [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)? I am particularly interested in a solution either in or that integrates with [NumPy](http://en.wikipedia.org/wiki/NumPy)...
Using a series sum you could calculate it: ``` getcontext().prec = 2000 e = Decimal(0) i = 0 while True: fact = math.factorial(i) e += Decimal(1)/fact i += 1 if fact > 10**2000: break ``` But that's not really necessary, as what Mermoz did agrees just fine with it: ``` >>> e Decimal('2.7182818284590...
How to delete a character from a string using python?
3,559,559
185
2010-08-24T18:06:31Z
3,559,576
35
2010-08-24T18:09:21Z
[ "python", "string" ]
There is a string, for example `EXAMPLE` How can I remove the middle character i.e. `M` from it. I don't need the code, what I want to know is * Do strings in python end in any special character? * Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string...
This is probably the best way: ``` original = "EXAMPLE" removed = original.replace("M", "") ``` Don't worry about shifting characters and such. Most python takes place on a much higher level of abstraction.
How to delete a character from a string using python?
3,559,559
185
2010-08-24T18:06:31Z
3,559,592
20
2010-08-24T18:10:59Z
[ "python", "string" ]
There is a string, for example `EXAMPLE` How can I remove the middle character i.e. `M` from it. I don't need the code, what I want to know is * Do strings in python end in any special character? * Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string...
To replace a specific position: ``` s = s[:pos] + s[(pos+1):] ``` To replace a specific character: ``` s = s.replace('M','') ```
How to delete a character from a string using python?
3,559,559
185
2010-08-24T18:06:31Z
3,559,600
271
2010-08-24T18:11:46Z
[ "python", "string" ]
There is a string, for example `EXAMPLE` How can I remove the middle character i.e. `M` from it. I don't need the code, what I want to know is * Do strings in python end in any special character? * Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string...
In Python, strings are immutable, so you have to create a new string. You have a few options of how to create the new string. If you want to remove the 'M' wherever it appears: ``` newstr = oldstr.replace("M", "") ``` If you want to remove the central character: ``` midlen = len(oldstr)/2 newstr = oldstr[:midlen] + ...
How to delete a character from a string using python?
3,559,559
185
2010-08-24T18:06:31Z
3,559,635
7
2010-08-24T18:15:56Z
[ "python", "string" ]
There is a string, for example `EXAMPLE` How can I remove the middle character i.e. `M` from it. I don't need the code, what I want to know is * Do strings in python end in any special character? * Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string...
> How can I remove the middle character You can't, because strings in Python are [immutable](http://en.wikipedia.org/wiki/Immutable_object). > Do strings in python end in any special character? No. They are similar to lists of characters; the length of the list defines the length of the string, and no character acts...
How to delete a character from a string using python?
3,559,559
185
2010-08-24T18:06:31Z
3,561,091
18
2010-08-24T21:14:13Z
[ "python", "string" ]
There is a string, for example `EXAMPLE` How can I remove the middle character i.e. `M` from it. I don't need the code, what I want to know is * Do strings in python end in any special character? * Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string...
Strings are immutable. But you can convert them to a list, which is mutable, and then convert the list back to a string after you've changed it. ``` s = "this is a string" l = list(s) # convert to list l[1] = "" # "delete" letter h (the item actually still exists but is empty) l[1:2] = [] # really delete letter...
How to delete a character from a string using python?
3,559,559
185
2010-08-24T18:06:31Z
19,259,168
7
2013-10-08T21:55:25Z
[ "python", "string" ]
There is a string, for example `EXAMPLE` How can I remove the middle character i.e. `M` from it. I don't need the code, what I want to know is * Do strings in python end in any special character? * Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string...
I didn't see see the [`translate()`](http://docs.python.org/2/library/string.html#string.translate) method mentioned, so here goes: ``` >>> s = 'EXAMPLE' >>> s.translate(None, 'M') 'EXAPLE' ```
PHP equivalent to Python's enumerate()?
3,560,757
9
2010-08-24T20:29:58Z
3,560,772
9
2010-08-24T20:32:40Z
[ "php", "python", "iteration" ]
In Python I can write: ``` for i, val in enumerate(lst): print i, val ``` The only way I know how to do this in PHP is: ``` for($i = 0; $i < count(lst); $i++){ echo "$i $val\n"; } ``` Is there a cleaner way in PHP?
Use [`foreach`](http://pl.php.net/manual/en/control-structures.foreach.php): ``` foreach ($lst as $i => $val) { echo $i, $val; } ```
PHP equivalent to Python's enumerate()?
3,560,757
9
2010-08-24T20:29:58Z
3,561,009
19
2010-08-24T21:02:16Z
[ "php", "python", "iteration" ]
In Python I can write: ``` for i, val in enumerate(lst): print i, val ``` The only way I know how to do this in PHP is: ``` for($i = 0; $i < count(lst); $i++){ echo "$i $val\n"; } ``` Is there a cleaner way in PHP?
Don't trust PHP arrays, they are like Python dicts. If you want safe code consider this: ``` <?php $lst = array('a', 'b', 'c'); // Removed a value to prove that keys are preserved unset($lst[1]); // So this wont work foreach ($lst as $i => $val) { echo "$i $val \n"; } echo "\n"; // Use array_values to rese...
Problems defining install-platlib in pydistutils.cfg --
3,560,865
6
2010-08-24T20:44:05Z
3,560,946
7
2010-08-24T20:53:57Z
[ "python" ]
According to the [docs](http://docs.python.org/install/#custom-installation) I should be able to simply define this in my ~/.pydistutils.cfg and be off and running. ``` [install] install-base=$HOME install-purelib=python/lib install-platlib=python/lib.$PLAT install-scripts=python/scripts install-data=python/data ``` ...
You MUST include this.. ``` install-headers=python/?? ``` So the final looks like this.. ``` [install] install-base=$HOME install-purelib=python/lib install-platlib=python/lib.$PLAT install-scripts=python/scripts install-headers=python/include install-data=python/data ```
Learn Python the Hard Way Exercise 17 Extra Question(S)
3,561,279
19
2010-08-24T21:41:51Z
3,561,299
18
2010-08-24T21:44:45Z
[ "python", "python-2.x" ]
I'm doing Zed Shaw's fantastic [Learn Python The Hard Way](http://learnpythonthehardway.com/), but an extra question has me stumped: Line 9--10 could be written in one line, how? I've tried some different thoughts, but to no avail. I could move on, but what would the fun in that be? ``` from sys import argv from os.pa...
``` indata = open(from_file).read() ```
Learn Python the Hard Way Exercise 17 Extra Question(S)
3,561,279
19
2010-08-24T21:41:51Z
3,561,437
7
2010-08-24T22:09:52Z
[ "python", "python-2.x" ]
I'm doing Zed Shaw's fantastic [Learn Python The Hard Way](http://learnpythonthehardway.com/), but an extra question has me stumped: Line 9--10 could be written in one line, how? I've tried some different thoughts, but to no avail. I could move on, but what would the fun in that be? ``` from sys import argv from os.pa...
[shutil](http://docs.python.org/library/shutil.html) is the way to do one-liner file copies in Python: ``` shutil.copy(sys.argv[1], sys.argv[2]) ``` Putting the `import shutil, sys` on the same line as this one (with a semicolon in-between, of course) would however be stylistically goofy;-).
python: SyntaxError: EOL while scanning string literal
3,561,691
45
2010-08-24T23:04:26Z
3,561,704
63
2010-08-24T23:07:50Z
[ "python" ]
I have the above mentioned error in `s1="some very long string............"` Anyone know what i am doing wrong?
you are not putting a `"` before the end of the line. use ``` """ a very long string ...... ....that can span multiple lines """ ``` if you want to do this.
python: SyntaxError: EOL while scanning string literal
3,561,691
45
2010-08-24T23:04:26Z
3,561,840
10
2010-08-24T23:36:10Z
[ "python" ]
I have the above mentioned error in `s1="some very long string............"` Anyone know what i am doing wrong?
(Assuming you don't have/want line breaks in your string...) How long is this string really? I suspect there is a limit to how long a line read from a file or from the commandline can be, and because the end of the line gets choped off the parser sees something like `s1="some very long string..........` (without an e...
python: SyntaxError: EOL while scanning string literal
3,561,691
45
2010-08-24T23:04:26Z
5,141,611
32
2011-02-28T11:52:19Z
[ "python" ]
I have the above mentioned error in `s1="some very long string............"` Anyone know what i am doing wrong?
I had this problem - I eventually worked out that the reason was that I'd included `\` characters in the string. If you have any of these, "escape" them with `\\` and it should work fine.
How can you get the SSH return code using Paramiko?
3,562,403
50
2010-08-25T02:14:06Z
3,563,211
35
2010-08-25T05:59:38Z
[ "python", "ssh", "paramiko" ]
``` client = paramiko.SSHClient() stdin, stdout, stderr = client.exec_command(command) ``` Is there any way to get the command return code? It's hard to parse all stdout/stderr and know whether the command finished successfully or not.
SSHClient is a simple wrapper class around the more lower-level functionality in Paramiko. The [API documentation](http://docs.paramiko.org/en/latest/index.html) lists a [recv\_exit\_status()](http://docs.paramiko.org/en/latest/api/channel.html#paramiko.channel.Channel.recv_exit_status) method on the Channel class. A ...
How can you get the SSH return code using Paramiko?
3,562,403
50
2010-08-25T02:14:06Z
14,631,412
131
2013-01-31T17:14:35Z
[ "python", "ssh", "paramiko" ]
``` client = paramiko.SSHClient() stdin, stdout, stderr = client.exec_command(command) ``` Is there any way to get the command return code? It's hard to parse all stdout/stderr and know whether the command finished successfully or not.
Much easier example that doesn't involve invoking the channel class directly: ``` import paramiko client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect('blahblah.com') stdin, stdout, stderr = client.exec_command("uptime") print stdout.channel.recv_exit_status() ...
URL encoding/decoding with Python
3,563,126
45
2010-08-25T05:42:07Z
3,565,460
68
2010-08-25T11:48:13Z
[ "python", "url-encoding" ]
I am trying to encode and store, and decode arguments in Python and getting lost somewhere along the way. Here are my steps: 1) I use google toolkit's `gtm_stringByEscapingForURLArgument` to convert an NSString properly for passing into HTTP arguments. 2) On my server (python), I store these string arguments as somet...
url encoding a "raw" unicode doesn't really make sense. What you need to do is `.encode("utf8")` first so you have a known byte encoding and then `.quote()` that. The output isn't very pretty but it should be a correct uri encoding. ``` >>> s = u'1234567890-/:;()$&@".,?!\'[]{}#%^*+=_\|~<>\u20ac\xa3\xa5\u2022.,?!\'' >...
stored procedures with sqlAlchemy
3,563,738
20
2010-08-25T07:34:20Z
3,564,604
12
2010-08-25T09:48:17Z
[ "python", "sql-server", "stored-procedures", "sqlalchemy" ]
How can I call stored procedures of sql server with sqlAlchemy?
Engines and Connections have an `execute()` method you can use for arbitrary sql statements, and so do Sessions. For example: ``` results = sess.execute('myproc ?, ?', [param1, param2]) ``` You can use `outparam()` to create output parameters if you need to (or for bind parameters use `bindparam()` with the `isoutpar...
stored procedures with sqlAlchemy
3,563,738
20
2010-08-25T07:34:20Z
12,899,763
8
2012-10-15T16:19:30Z
[ "python", "sql-server", "stored-procedures", "sqlalchemy" ]
How can I call stored procedures of sql server with sqlAlchemy?
Supposing you already have session created with sessionmaker(), you can use following function: ``` def exec_procedure(session, proc_name, params): sql_params = ",".join(["@{0}={1}".format(name, value) for name, value in params.items()]) sql_string = """ DECLARE @return_value int; EXEC @retu...
Python in OpenOffice 3
3,564,394
9
2010-08-25T09:20:07Z
3,564,452
9
2010-08-25T09:28:22Z
[ "python", "scripting", "spreadsheet", "openoffice.org", "openoffice-basic" ]
I have a heap of Lotus 123 spreadsheets (not written by me) with Lotus Scripts in them doing an awful lot of leg work (moving data from one spreadsheet to another, and other things like that). I am making the consideration of moving it all away from Lotus 98 and going to something a little more open, like OpenOffice. ...
> Starting point Start here: [Python as a macro language](http://wiki.services.openoffice.org/wiki/Python_as_a_macro_language) > Examples Use the [Python category](http://wiki.services.openoffice.org/wiki/Category%3aPython) in the wiki. > Is there a better scripting language? Python has by far the best syntax. I'd...
Python, mechanize, proper syntax for setting multiple headers?
3,564,509
7
2010-08-25T09:35:21Z
3,564,557
9
2010-08-25T09:41:02Z
[ "python", "http-headers", "mechanize", "webautomation" ]
I can't seem to find how to do this anywere, I am trying to set multiple headers with python's mechanize module, such as: ``` br.addheaders = [('user-agent', ' Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3')] br.addheaders = [('accept', 'text/html,application/x...
According to <http://wwwsearch.sourceforge.net/mechanize/doc.html#adding-headers>, the syntax would be ``` br.addheaders = [('user-agent', ' Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3'), ('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q...
Which is most accurate way to distinguish one of 8 colors?
3,565,108
4
2010-08-25T10:54:32Z
3,565,191
9
2010-08-25T11:06:58Z
[ "python", "rgb" ]
Imagine we how some basic colors: ``` RED = Color ((196, 2, 51), "RED") ORANGE = Color ((255, 165, 0), "ORANGE") YELLOW = Color ((255, 205, 0), "YELLOW") GREEN = Color ((0, 128, 0), "GREEN") BLUE = Color ((0, 0, 255), "BLUE") VIOLET = Color ((127, 0, 255), "VIOLET") BLACK = Color ((0, 0, 0), "BLACK") WHITE = Color ((2...
Short answer: use the Euclidean distance in a device independent color space (source: [Color difference](http://en.wikipedia.org/wiki/Color_difference) article in Wikipedia). Since RGB is device-dependent, you should first map your colors to one of the device-independent color spaces. I suggest to convert RGB to [L\*a...
Google App Engine : Cursor Versus Offset
3,566,462
19
2010-08-25T13:46:22Z
3,566,878
27
2010-08-25T14:26:38Z
[ "python", "google-app-engine" ]
Do you know which is the best approach for fetching chunks of result from a query? # 1.Cursor ``` q = Person.all() last_cursor = memcache.get('person_cursor') if last_cursor: q.with_cursor(last_cursor) people = q.fetch(100) cursor = q.cursor() memcache.set('person_cursor', cursor) ``` # 2.Offset ``` q = Person....
While it's hard to measure precise and reliably, I'd be astonished if the cursor didn't run rings around the offset approach at soon as a sufficiently large set of Person entities are getting returned. As [the docs](http://code.google.com/appengine/docs/python/datastore/queryclass.html#Query_fetch) say very clearly and...
Python Pythonpath Modules install
3,566,546
4
2010-08-25T13:54:52Z
3,566,965
8
2010-08-25T14:34:24Z
[ "python", "installation", "pythonpath" ]
I am kind of annoyed by the installation of modules in python and had a lot of trouble with it, so it would be fantastic to find a good solution for it. Here are my issues: 1. PYTHONPATH: How can I tell easy\_install/Python where to install my packages? Even though I put: `/Library/Python/2.6/site-packages` in my `.b...
Based on the path (`/Library/Frameworks/Python.framework/Versions/2.6`) in your question, you appear to have installed an additional Python besides the ones supplied by Apple. That's the standard installation path for the python.org OS X installer. The trick to getting `easy_install` to install to the right Python sit...
Using arbitrary methods or attributes as fields on Django ModelAdmin objects?
3,566,772
7
2010-08-25T14:17:31Z
3,568,539
13
2010-08-25T17:17:48Z
[ "python", "django", "django-admin" ]
Using Django 1.1: The [Django admin docs describe](http://docs.djangoproject.com/en/1.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display) using arbitrary methods or attributes on a ModelAdmin object in the `list_display` class attribute. This is a great mechanism for displaying arbitrary information in ...
Add the method to the 'readonly\_fields' tuple as well.
How can I specify an exact output size for my networkx graph?
3,567,018
3
2010-08-25T14:39:26Z
8,379,435
7
2011-12-04T23:27:32Z
[ "python", "image", "networkx" ]
![http://imgur.com/7wiRw.png](http://i.stack.imgur.com/F4XKW.png) The above is the output of my current graph. However, I have yet to manage what I am trying to achieve. I need to output my graph in a larger size so that each node/edge can be viewed with ease. I've tried `nx.draw(G, node_size=size)`, but that only in...
You could try either smaller nodes/fonts or larger canvas. Here is a way to do both: ``` import matplotlib.pyplot as plt import networkx as nx G = nx.cycle_graph(80) pos = nx.circular_layout(G) # default plt.figure(1) nx.draw(G,pos) # smaller nodes and fonts plt.figure(2) nx.draw(G,pos,node_size=60,font_size=8) # lar...
Threaded Tkinter script crashes when creating the second Toplevel widget
3,567,238
6
2010-08-25T14:59:13Z
3,567,284
20
2010-08-25T15:03:11Z
[ "python", "multithreading", "tkinter" ]
I have a Python script which uses Tkinter for the GUI. My little script should create a Toplevel widget every X seconds. When I run my code, the first Toplevel widget is created successfully, but when it tries to create a second one the program crashes. What I am doing is using the after method to call the function st...
Tkinter is designed to run from the main thread, only. See [the docs](http://effbot.org/zone/tkinter-threads.htm): > Just run all UI code in the main > thread, and let the writers write to a > Queue object; e.g. ...and a substantial example follows, showing secondary threads writing requests to a queue, and the main ...
geodjango syncdb errors. From geodjango tutorial
3,567,352
3
2010-08-25T15:09:48Z
3,575,365
21
2010-08-26T13:13:02Z
[ "python", "django", "postgresql", "gis", "geodjango" ]
**I have followed the geodjango installation(windows XP) and tutorial to perfection I am running django 1.2 When I get to syncdb and run I receive the following.** ``` raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured:'django.db.backends.postgis' isn an available database backend. T...
The problem is, in `settings.py` ``` 'django.db.backends.postgis' ``` it is supposed to be ``` django.contrib.gis.db.backends.postgis ``` that should do it.
Calling python script from excel/vba
3,567,365
6
2010-08-25T15:10:56Z
3,569,988
12
2010-08-25T20:34:15Z
[ "python", "excel", "vba", "excel-vba" ]
I have a python code that reads 3 arguments (scalars) and a text files and then returns me a vector of double. I want to write a macro in vba to call this python code and write the results in one of the same excel sheet. I wanted to know what was the easiest way to do it, here are some stuffs that I found: * call the ...
Follow these steps carefully 1. Go to Activestate and get [ActivePython 2.5.7](http://www.activestate.com/activepython/downloads) MSI installer. I had DLL hell problems with 2.6.x 2. Install in your Windows machine 3. once install is complete open Command Prompt and go to > C:\Python25\lib\site-packages\win32...
How to use named parameters in Python methods that are defaulting to a class level value?
3,567,618
4
2010-08-25T15:32:04Z
3,567,689
8
2010-08-25T15:38:59Z
[ "python", "named-parameters" ]
Usage scenario: ``` # case #1 - for classes a = MyClass() # default logger is None a = MyClass(logger="a") # set the default logger to be "a" a.test(logger="b") # this means that logger will be "b" only inside this method a.test(logger=None) # this means that logger will be None but only inside this method a.test() # ...
``` _sentinel = object() class MyClass(object): def __init__(self, logger=None): self.logger = logger def test(self, logger=_sentinel): if logger is _sentinel: logger = self.logger # in case you want to use this inside a function from your module use: _sentinel = object() logger = None def test(logger=_se...
How to read lines from a file in python starting from the end
3,568,833
11
2010-08-25T17:55:14Z
3,568,878
16
2010-08-25T18:01:57Z
[ "python", "file-io" ]
I need to know how to read lines from a file in python so that I read the last line first and continue in that fashion until the cursor reach's the beginning of the file. Any idea's?
The general approach to this problem, reading a text file in reverse, line-wise, can be solved by at least three methods. The general problem is that since each line can have a different length, you can't know beforehand where each line starts in the file, nor how many of them there are. This means you need to apply s...
ctypes behaving strangely in Python interpreter
3,568,867
4
2010-08-25T18:00:31Z
3,568,905
8
2010-08-25T18:05:37Z
[ "python", "ctypes" ]
I am having a funny issue with ctypes; while it seems to work in regular python scripts, when I use it in the interpreter with printf() it prints the length of the string after the string itself. A demo: ``` Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or ...
From the printf(3) man page: > Upon successful return, these functions return the number of characters printed (not including the trailing `’\0’` used to end output to strings). The python interpreter is displaying the return code of `printf()` after you call it. Since you don't have a newline `\n` at the end of ...
Why doesn't Pylint like built-in functions?
3,569,134
61
2010-08-25T18:37:37Z
3,569,304
83
2010-08-25T19:01:00Z
[ "python", "list-comprehension", "pylint" ]
I have a line like this: ``` filter(lambda x: x == 1, [1, 1, 2]) ``` Pylint is showing a warning: ``` W: 3: Used builtin function 'filter' ``` Why is that? is a list comprehension the recommended method? Of course I can rewrite this like this: ``` [x for x in [1, 1, 2] if x == 1] ``` And I get no warnings, but ...
Pylint often chatters on about stuff it shouldn't. You can disable the warning in a .pylintrc file. This page <http://pylint-messages.wikidot.com/messages:w0141> indicates the problem is that filter and map have been superseded by list comprehensions. A line like this in your pylintrc file will quiet the warning: ``...
Parsing HTML with Lxml
3,569,152
9
2010-08-25T18:39:24Z
3,569,555
14
2010-08-25T19:33:56Z
[ "python", "html", "parsing", "lxml" ]
I need help parsing out some text from a page with lxml. I tried beautifulsoup and the html of the page I am parsing is so broken, it wouldn't work. So I have moved on to lxml, but the docs are a little confusing and I was hoping someone here could help me. [Here](http://www.keelshield.com/store_locator.html?&cHash=8e...
``` import lxml.html as lh import urllib2 def text_tail(node): yield node.text yield node.tail url='http://bit.ly/bf1T12' doc=lh.parse(urllib2.urlopen(url)) for elt in doc.iter('td'): text=elt.text_content() if text.startswith('Additional Info'): blurb=[text for node in elt.itersiblings('td')...
Python mechanize, following link by url and what is the nr parameter?
3,569,622
17
2010-08-25T19:43:52Z
3,569,707
47
2010-08-25T19:53:46Z
[ "python", "mechanize" ]
I'm sorry to have to ask something like this but python's mechanize documentation seems to really be lacking and I can't figure this out.. they only give one example that I can find for following a link: ``` response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1) ``` But I don't want to use a regex, I just want...
`br.follow_link` takes either a `Link` object or a keyword arg (such as `nr=0`). `br.links()` lists all the links. `br.links(url_regex='...')` lists all the links whose urls matches the regex. `br.links(text_regex='...')` lists all the links whose link text matches the regex. `br.follow_link(nr=num)` follows the `n...
Python mechanize, following link by url and what is the nr parameter?
3,569,622
17
2010-08-25T19:43:52Z
3,570,232
16
2010-08-25T21:10:27Z
[ "python", "mechanize" ]
I'm sorry to have to ask something like this but python's mechanize documentation seems to really be lacking and I can't figure this out.. they only give one example that I can find for following a link: ``` response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1) ``` But I don't want to use a regex, I just want...
I found this way to do it, for reference for anyone who doesn't want to use regex: ``` r = br.open("http://www.somewebsite.com") br.find_link(url='http://www.somewebsite.com/link1.html') req = br.click_link(url='http://www.somewebsite.com/link1.html') br.open(req) print br.response().read() ``` Or, it will work by th...
Django count related objects
3,569,975
2
2010-08-25T20:32:32Z
3,570,235
8
2010-08-25T21:10:36Z
[ "python", "django" ]
How can I count related objects in Django (in less than *N* queries, where *N* is number of object). To clarify, let's say I have tables *A* and *B*. Every *B* is connected to exactly one *A*. Approach I tried: ``` A.objects.select_related().filter(attr=val) A[i].B_set.count() ``` Of course, for every *A[i]* I want ...
Have not tried how many queries are executed, but the djano way should be using `annotate()` something like: ``` q = A.objects.select_related().annotate(num_B=Count('B')) print A[0].num_B ```
In wxPython how do you bind a EVT_KEY_DOWN event to the whole window?
3,570,254
14
2010-08-25T21:13:29Z
3,570,391
16
2010-08-25T21:33:31Z
[ "python", "user-interface", "wxpython" ]
I can bind an event to a textctrl box np. The problem is I have to be clicked inside of the textctrl box to "catch" this event. I am hoping to be able to catch anytime someone presses the Arrow keys while the main window has focus. **NOT WORKING:** ``` wx.EVT_KEY_DOWN(self, self.OnKeyDown) ``` **WORKING:** ``` sel...
Instead try binding to `wx.EVT_CHAR_HOOK` e.g.. ``` self.Bind(wx.EVT_CHAR_HOOK, self.onKey) ... def onKey(self, evt): if evt.GetKeyCode() == wx.WXK_DOWN: print "Down key pressed" else: evt.Skip() ```
Does Python's reduce() short circuit?
3,570,624
12
2010-08-25T22:09:51Z
3,570,636
20
2010-08-25T22:12:04Z
[ "python" ]
If I do: ``` result = reduce(operator.and_, [False] * 1000) ``` Will it stop after the first result? (since `False & anything == False`) Similarly: ``` result = reduce(operator.or_, [True] * 1000) ```
It doesn't. Your alternative in this case is [any](http://docs.python.org/library/functions.html#any) and [all](http://docs.python.org/library/functions.html#all). ``` result = reduce(operator.and_, [False] * 1000) result = reduce(operator.or_, [True] * 1000) ``` can be replaced by ``` result = all([False] * 1000) r...
Why use Abstract Base Classes in Python?
3,570,796
99
2010-08-25T22:43:01Z
3,570,868
13
2010-08-25T22:58:14Z
[ "python", "abc" ]
Being used to the old ways of duck typing in Python, I failed to understand the need for ABC (abstract base classes). The [help](https://docs.python.org/2/library/abc.html) is good on how to use them. I tried to read the rationale in the [PEP](https://www.python.org/dev/peps/pep-3119/), but it went over my head. If I ...
It will make determining whether an object supports a given protocol without having to check for presence of all the methods in the protocol or without triggering an exception deep in "enemy" territory due to non-support much easier.
Why use Abstract Base Classes in Python?
3,570,796
99
2010-08-25T22:43:01Z
3,571,946
76
2010-08-26T03:59:12Z
[ "python", "abc" ]
Being used to the old ways of duck typing in Python, I failed to understand the need for ABC (abstract base classes). The [help](https://docs.python.org/2/library/abc.html) is good on how to use them. I tried to read the rationale in the [PEP](https://www.python.org/dev/peps/pep-3119/), but it went over my head. If I ...
Short version: ABCs offer a higher level of semantic contract between clients and the implemented classes. Long version: There is a contract between a class and its callers. The class promises to do certain things and have certain properties. There are different levels to the contract. At a very low level, the cont...
Why use Abstract Base Classes in Python?
3,570,796
99
2010-08-25T22:43:01Z
19,328,146
96
2013-10-11T22:20:29Z
[ "python", "abc" ]
Being used to the old ways of duck typing in Python, I failed to understand the need for ABC (abstract base classes). The [help](https://docs.python.org/2/library/abc.html) is good on how to use them. I tried to read the rationale in the [PEP](https://www.python.org/dev/peps/pep-3119/), but it went over my head. If I ...
@Oddthinking's answer is not wrong, but I think it misses the *real*, *practical* reason Python has ABCs in a world of duck-typing. Abstract methods are neat, but in my opinion they don't really fill any use-cases not already covered by duck typing. Abstract base classes' real power lies in [the way they allow you to ...
Why use Abstract Base Classes in Python?
3,570,796
99
2010-08-25T22:43:01Z
30,328,931
22
2015-05-19T14:46:33Z
[ "python", "abc" ]
Being used to the old ways of duck typing in Python, I failed to understand the need for ABC (abstract base classes). The [help](https://docs.python.org/2/library/abc.html) is good on how to use them. I tried to read the rationale in the [PEP](https://www.python.org/dev/peps/pep-3119/), but it went over my head. If I ...
A handy feature of ABCs is that if you don't implement all necessary methods (and properties) you get an error upon instantiation, rather than an [`AttributeError`](https://docs.python.org/2/library/exceptions.html#exceptions.AttributeError), potentially much later, when you actually try to use the missing method. ```...
Static method vs module function in python
3,570,823
8
2010-08-25T22:48:38Z
3,573,180
7
2010-08-26T08:08:23Z
[ "python", "global", "static-methods" ]
So I have a class in a module that has some static methods. A couple of these static methods just do crc checks and stuff, and they're not really useful outside of the class (I would just make them private static methods in java or C++). I'm wondering if I should instead make them global class functions (outside of the...
Prefixing the function names with a single underscore is a convention to say that they are private, and it will also prevent them from being imported with a `from module import *`. Another technique is to specify an [`__all__`](http://docs.python.org/tutorial/modules.html#importing-from-a-package) list in the module -...
Python: Why should 'from <module> import *' be prohibited?
3,571,514
22
2010-08-26T01:46:33Z
3,571,558
15
2010-08-26T01:59:42Z
[ "python", "namespaces", "module" ]
If you happen to have ``` from <module> import * ``` in the middle of your program (or module), you would get the warning: ``` /tmp/foo:100: SyntaxWarning: import * only allowed at module level ``` I understand why `import *` is discouraged in general (namespace invisibility), but there are many situations where it...
I believe by "in the middle of your program" you are talking about an import *inside* a function definition: ``` def f(): from module import * # not allowed ``` This is not allowed because it would make optimizing the body of the function too hard. The Python implementation wants to know all of the names of fu...
Python: Why should 'from <module> import *' be prohibited?
3,571,514
22
2010-08-26T01:46:33Z
3,571,569
11
2010-08-26T02:02:13Z
[ "python", "namespaces", "module" ]
If you happen to have ``` from <module> import * ``` in the middle of your program (or module), you would get the warning: ``` /tmp/foo:100: SyntaxWarning: import * only allowed at module level ``` I understand why `import *` is discouraged in general (namespace invisibility), but there are many situations where it...
The [release notes for Python 2.1](http://docs.python.org/dev/whatsnew/2.1.html) seem to explain why this limitation exists: > One side effect of the change is that > the from module import \* and exec > statements have been made illegal > inside a function scope under certain > conditions. The Python reference > manu...