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
Python nested functions variable scoping
5,218,895
43
2011-03-07T11:05:45Z
19,160,431
10
2013-10-03T13:25:27Z
[ "python", "variables", "scope" ]
I've read almost all the other questions about the topic, but my code still doesn't work. I think I'm missing something about python variable scope. Here is my code: ``` PRICE_RANGES = { 64:(25, 0.35), 32:(13, 0.40), 16:(7, 0.45), 8:(4, 0.5) ...
This is a variation of redman's solution, but using a proper namespace instead of an array to encapsulate the variable: ``` def foo(): class local: counter = 0 def bar(): print(local.counter) local.counter += 1 bar() bar() bar() foo() foo() ``` I'm not sure if using a clas...
Python nested functions variable scoping
5,218,895
43
2011-03-07T11:05:45Z
26,059,224
18
2014-09-26T12:09:08Z
[ "python", "variables", "scope" ]
I've read almost all the other questions about the topic, but my code still doesn't work. I think I'm missing something about python variable scope. Here is my code: ``` PRICE_RANGES = { 64:(25, 0.35), 32:(13, 0.40), 16:(7, 0.45), 8:(4, 0.5) ...
Rather than declaring a special object or map or array, one can also use a function attribute. This makes the scoping of the variable really clear. ``` def sumsquares(x,y): def addsquare(n): sumsquares.total += n*n sumsquares.total = 0 addsquare(x) addsquare(y) return sumsquares.total ``` Of course thi...
How to auto-scroll a gtk.scrolledwindow?
5,218,948
13
2011-03-07T11:11:18Z
5,235,358
14
2011-03-08T16:34:13Z
[ "python", "gtk", "pygtk", "gtktreeview", "scrolledwindow" ]
I have a treeview-widget inside a `ScrolledWindow`, which is populated during runtime. I want the `ScrolledWindow` to auto-scroll to the end of the list. I "solved" the problem, by adjusting the `vadjustment` of the `ScrolledWindow`, everytime a row is inserted into the treeview. e.g: ``` if new_line_in_row: adj = ...
After widening my search-radius, i found a ruby-related answer. since the problem is gtk-related, it should be able to be solved in any language like this: you connect the widget which changes, in my case the treeview, with `gtk.widget`'s 'size-allocate' signal and set the `gtk.scrolledwindow` value to "upper - page\_...
number of all subsets of a set
5,220,087
2
2011-03-07T13:05:29Z
5,220,200
9
2011-03-07T13:17:46Z
[ "python", "algorithm" ]
This is what I came up with to calculate all subsets of length 0, 1, ... , n of a set of length n with doubling single elements. Difficult to describe... ``` def subsets(seq, *args): seqstart = [[seq[i] for i in args], ] if len(args) == 0: for i in range(len(seq)): seqstart += subsets(seq...
The number of multisets of size up to n of a set of size n is equal to the binomial coefficient ``` / 2n \ | | \ n / ``` This follows by summing up the [number of combinations with repetition](http://en.wikipedia.org/wiki/Combinations#Number_of_combinations_with_repetition) for k from 0 to n. For n=14, this yiel...
get key value from a dictionary django/python
5,220,355
4
2011-03-07T13:37:20Z
5,220,413
14
2011-03-07T13:44:42Z
[ "python", "django", "django-templates" ]
How to print the value of a key from the key itself ``` dict={} dict.update({'aa':1}) dict.update({'ab':1}) dict.update({'ac':1}) return render_to_response(t.html, context_instance=RequestContext(request, {'dict':dict})) ``` So in this case i want to print the key `alert('{{dict.aa}}');` i.e,without using any loop c...
Never call a dictionary `dict`, that would overwrite the builtin `dict` type name in the current scope. You can access keys and values in the template like so: ``` {% for item in d.items %} key = {{ item.0 }} value = {{ item.1 }} {% endfor %} ``` or use `d.keys` if you only need the keys.
Change default python coding style
5,220,580
8
2011-03-07T14:00:44Z
5,497,591
16
2011-03-31T09:15:17Z
[ "python", "pylint" ]
In python i'm following **camelCase** Naming style. I checked my code with "pylint" and it gives error for not following **lower\_case\_with\_underscores** style. Also i use netBeans IDE for coding. This IDE gives warning for not following **lower\_case\_with\_underscores** style. How to tell pylint and netBeans that ...
Use `pylint --generate-rcfile > ~/.pylintrc` to get a standard `pylintrc`. Edit the file, go to the [BASIC] section, and change the following regexps: * `function-rgx=_?_?[a-z][A-Za-z0-9]{1,30}$` * `method-rgx=_?_?[a-z][A-Za-z0-9]{1,30}$` * `attr-rgx=_?_?[a-z][A-Za-z0-9]{1,30}$` * `argument-rgx=_?[a-z][A-Za-z0-9]{1,3...
authentication in python script to run as root
5,222,333
15
2011-03-07T16:38:48Z
5,222,710
24
2011-03-07T17:08:58Z
[ "python", "pygtk" ]
I am doing a project in Linux at system level in Python. So that, I want to know that if i am running my code as a normal user and if i am accessing system files then it should have root permissions for it, then how can i prompt for root password and run further code as superuser. I want to know that, how to run python...
The other thing you can do is have your script automatically invoke sudo if it wasn't executed as root: ``` import os import sys euid = os.geteuid() if euid != 0: print "Script not started as root. Running sudo.." args = ['sudo', sys.executable] + sys.argv + [os.environ] # the next line replaces the curre...
python: sys.argv[0] meaning in official documentation
5,222,408
3
2011-03-07T16:44:20Z
5,222,441
9
2011-03-07T16:47:13Z
[ "python", "documentation", "argv", "sys" ]
Quoting from [docs.python.org](http://docs.python.org/py3k/library/sys.html): "`sys.argv` The list of command line arguments passed to a Python script. `argv[0]` is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the `-c` command line option ...
No, if you invoke Python with `-c` to run commands from the command line, your `sys.argv[0]` will be `-c`: ``` C:\Python27>python.exe -c "import sys; print sys.argv[0]" -c ```
Scrapy Crawler in python cannot follow links?
5,223,531
6
2011-03-07T18:22:29Z
5,223,691
30
2011-03-07T18:39:01Z
[ "python", "scrapy" ]
I wrote a crawler in python using the scrapy tool of python. The following is the python code: ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector #from scrapy.item import Item from a11ypi.items import A...
From what I see, it looks like your rule is not an iterable. It looks like you were trying to make rules a tuple, you should [read up on tuples in the python documentation](http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy). To fix your problem, change this line: ``` rules =( ...
PyGTK Entry widget in TreeViewColumn header
5,223,705
6
2011-03-07T18:41:01Z
5,250,289
11
2011-03-09T18:16:59Z
[ "python", "gtk", "pygtk", "gtktreeview", "gtkentry" ]
How can I make a `gtk.Entry` widget focusable or editable within a `gtk.TreeViewColumn` header/title? I've tried this: ``` # Create tree-view. treeview = gtk.TreeView() #... # Create column. renderer = gtk.CellRendererText() column = gtk.TreeViewColumn(None, renderer, text=0) # Set column header. header = gtk.VBox(...
In order to make a `GtkEntry` focusable within a `GtkTreeView` header I had to: 1) Find the header `GtkButton`. ``` def find_closest_ancestor(widget, ancestor_class): if not isinstance(widget, gtk.Widget): raise TypeError("%r is not a gtk.Widget" % widget) ancestor = widget.get_parent() while ance...
python uuid weird bug
5,223,864
2
2011-03-07T18:56:01Z
5,223,970
10
2011-03-07T19:05:08Z
[ "python", "uuid" ]
I first tried with the interpreter to produce uuid's with python's uuid module. I did the following: ``` >>>import uuid >>>uuid.uuid1() UUID('d8904cf8-48ea-11e0-ac43-109add570b60') ``` So far so good. I create a simple little function to produce the uuid's. ``` import uuid def get_guid(): return uuid.uuid1() i...
Your test file name is most likely named `uuid.py` When you went back to the interpreter, you launched the interpreter from the same directory, which by default, will first look for the module name to import in your current working directory. Just change your test file name to something else, i.e. `uuid_test_snippet....
Fastest way to read comma separated files (including datetimes) in python
5,223,967
2
2011-03-07T19:04:50Z
5,224,121
8
2011-03-07T19:17:48Z
[ "python", "numpy" ]
I have data stored in comma delimited txt files. One of the columns represents a datetime. I need to load each column into separate numpy arrays (and decode the date into a python datetime object). What is the fastest way to do this (in terms of run time)? NB. the files are several hundred MB of data and currently t...
First, you should run your sample script with Python's built-in [profiler](http://docs.python.org/library/profile.html#instant-user-s-manual) to see where the problem actually might be. You can do this from the command-line: ``` python -m cProfile myscript.py ``` Secondly, what jumps at me at least, why is that loop ...
Safe decoding in python ('?' symbol instead of exception)
5,224,089
2
2011-03-07T19:14:50Z
5,224,130
10
2011-03-07T19:18:47Z
[ "python" ]
I have code: ``` encoding = guess_encoding() text = unicode(text, encoding) ``` when wrong symbol appears in text UnicodeDecode exception is raised. How can I silently skip exception replacing wrong symbol with '?' ?
Try ``` text = unicode(text, encoding, "replace") ``` From the [documentation](http://docs.python.org/library/functions.html#unicode): > 'replace' causes the official Unicode replacement character, U+FFFD, to be used to replace input characters which cannot be decoded. If you want to use `"?"` instead of the offici...
Python iterable map, range, etc
5,224,373
2
2011-03-07T19:38:18Z
5,224,778
8
2011-03-07T20:19:49Z
[ "python" ]
Why doesn't python have a `__future__` library that replaces `map` with `imap`, `range` with `xrange`, etc.? Is it possible to write one?
There is [`future_builtins`](http://docs.python.org/library/future_builtins.html) module since Python 2.6: ``` from future_builtins import filter, map, zip ```
python copy files to a network location on Windows without mapping a drive
5,224,541
7
2011-03-07T19:55:10Z
5,224,625
19
2011-03-07T20:02:51Z
[ "python", "file", "networking", "copy", "unc" ]
I am running python in a non interactive session on windows and therefore I cannot map a network drive. Most of what I have researched on here and through google everyone suggests mapping a network drive and copying the files that way. On linux I would facilitate this with an smbmount but unfortunately the software I...
Personally, I've never had difficulties getting Python to simply recognize `\\\\<server>\\path\\to\\directory\\`. The annoying part is that for every "\" in the win. path, there needs to be 2 in python.
What is the proper regular expression to match all utf-8/unicode lowercase letter forms
5,224,835
15
2011-03-07T20:25:23Z
5,225,406
8
2011-03-07T21:21:43Z
[ "python", "regex", "unicode", "utf-8" ]
I would like to match **all** lowercase letter forms in the Latin block. The trivial '[a-z]' only matches characters between U+0061 and U+007A, and not all the other lowercase forms. I would like to match all lowercase letters, most importantly, all the accented lowercase letters in the Latin block used in EFIGS langu...
Python does not currently support Unicode properties in regular expressions. See [this answer](http://stackoverflow.com/questions/1832893/python-regex-matching-unicode-properties/1836283#1836283) for a link to the [Ponyguruma library](http://dev.pocoo.org/hg/sandbox/ponyguruma) which does support them. Using such a li...
Turn off a warning in sqlalchemy
5,225,780
16
2011-03-07T22:00:05Z
5,225,951
26
2011-03-07T22:17:48Z
[ "python", "postgresql", "sqlalchemy" ]
I'm using sqlalchemy with reflection, a couple of partial indices in my DB make it dump warnings like this: `SAWarning: Predicate of partial index i_some_index ignored during reflection` into my logs and keep cluttering. It does not hinder my application behavior. I would like to keep these warnings while developing,...
Python's [warning module](http://docs.python.org/library/warnings.html#the-warnings-filter) provides a handy [context manager](http://docs.python.org/library/warnings.html#available-context-managers) that catches warnings for you. Here's how to filter out the SQLAlchemy warning. ``` import warnings from sqlalchemy im...
Installing specific package versions with pip
5,226,311
478
2011-03-07T22:58:13Z
5,226,452
26
2011-03-07T23:13:22Z
[ "python", "mysql", "pip", "pypi", "mysql-python" ]
I'm trying to install version 1.2.2 of the MySQL\_python adaptor. The current version shown in PyPi is [1.2.3](http://pypi.python.org/pypi/MySQL-python/1.2.3). Is there a way to install the older version? I found an article stating that this should do it: ``` pip install MySQL_python==1.2.2 ``` When installed, howeve...
I believe that if you already have a package it installed, pip will not overwrite it with another version. Use `-I` to ignore previous versions.
Installing specific package versions with pip
5,226,311
478
2011-03-07T22:58:13Z
5,226,504
368
2011-03-07T23:18:53Z
[ "python", "mysql", "pip", "pypi", "mysql-python" ]
I'm trying to install version 1.2.2 of the MySQL\_python adaptor. The current version shown in PyPi is [1.2.3](http://pypi.python.org/pypi/MySQL-python/1.2.3). Is there a way to install the older version? I found an article stating that this should do it: ``` pip install MySQL_python==1.2.2 ``` When installed, howeve...
First, I see two issues with what you're trying to do. Since you already have an installed version, you should either uninstall the current existing driver or use `pip install -I MySQL_python==1.2.2` However, you'll soon find out that this doesn't work. If you look at pip's installation log, or if you do a `pip instal...
Installing specific package versions with pip
5,226,311
478
2011-03-07T22:58:13Z
33,812,968
65
2015-11-19T19:42:39Z
[ "python", "mysql", "pip", "pypi", "mysql-python" ]
I'm trying to install version 1.2.2 of the MySQL\_python adaptor. The current version shown in PyPi is [1.2.3](http://pypi.python.org/pypi/MySQL-python/1.2.3). Is there a way to install the older version? I found an article stating that this should do it: ``` pip install MySQL_python==1.2.2 ``` When installed, howeve...
You can even use a version range with `pip install` command. Something like this: ``` pip install 'stevedore>=1.3.0,<1.4.0' ```
Installing specific package versions with pip
5,226,311
478
2011-03-07T22:58:13Z
36,399,566
24
2016-04-04T09:58:18Z
[ "python", "mysql", "pip", "pypi", "mysql-python" ]
I'm trying to install version 1.2.2 of the MySQL\_python adaptor. The current version shown in PyPi is [1.2.3](http://pypi.python.org/pypi/MySQL-python/1.2.3). Is there a way to install the older version? I found an article stating that this should do it: ``` pip install MySQL_python==1.2.2 ``` When installed, howeve...
One way as suggested in [this post](http://stackoverflow.com/questions/13916820/how-to-install-a-specific-version-of-a-package-with-pip) is to mention version in `pip` as `pip install MySQL_python==1.2.2`
Should I be using "global" or "self." for class scope variables in Python?
5,226,572
6
2011-03-07T23:26:46Z
5,226,613
8
2011-03-07T23:31:03Z
[ "python", "class", "variables", "function" ]
Both of these blocks of code work. Is there a "right" way to do this? ``` class Stuff: def __init__(self, x = 0): global globx globx = x def inc(self): return globx + 1 myStuff = Stuff(3) print myStuff.inc() ``` Prints "4" ``` class Stuff: def __init__(self, x = 0): self....
You should use the second way, then every instance has a separate `x` If you use a global variable then you may find you get surprising results when you have more than one instance of `Stuff` as changing the value of one will affect all the others. It's normal to have explicit self's all over your Python code. If you...
write a paragraph to a file
5,226,862
2
2011-03-08T00:06:31Z
5,226,872
15
2011-03-08T00:08:07Z
[ "python" ]
Ok this is simple, I want to write a huge paragraph of text to a file. I know I can do ``` f=open("blah.txt",'w') f.write("blah blah \n") f.write("bla blah blah ") f.close() ``` but what is a little more elegant solution?
``` f.write("""I’ve got a lovely bunch of coconuts There they are all standing in a row Big ones, small ones, some as big as your head Give them a twist a flick of the wrist That’s what the showman said""") ```
'which' equivalent function in Python
5,226,958
25
2011-03-08T00:23:31Z
5,227,009
7
2011-03-08T00:33:01Z
[ "python", "command", "which" ]
I need to setup environment by running 'which abc' command. Is there python equivalent function for 'which' command? This is my code. ``` cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
There's not a command to do that, but you can iterate over `environ["PATH"]` and look if the file exists, which is actually what `which` does. ``` import os def which(file): for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(os.path.join(path, file)): return os.path.join(p...
'which' equivalent function in Python
5,226,958
25
2011-03-08T00:23:31Z
5,227,046
12
2011-03-08T00:38:41Z
[ "python", "command", "which" ]
I need to setup environment by running 'which abc' command. Is there python equivalent function for 'which' command? This is my code. ``` cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
([Similar question](http://stackoverflow.com/questions/775351/os-path-exists-for-files-in-your-path)) See the Twisted implementation: [twisted.python.procutils.which](http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.2.0/twisted/python/procutils.py)
'which' equivalent function in Python
5,226,958
25
2011-03-08T00:23:31Z
15,133,367
41
2013-02-28T10:41:00Z
[ "python", "command", "which" ]
I need to setup environment by running 'which abc' command. Is there python equivalent function for 'which' command? This is my code. ``` cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
There is [distutils.spawn.find\_executable](http://nullege.com/codes/search/distutils.spawn.find_executable).
Python code to read registry
5,227,107
14
2011-03-08T00:50:06Z
5,227,427
16
2011-03-08T01:46:26Z
[ "python", "programming-languages", "registry" ]
``` from _winreg import * """print r"*** Reading from SOFTWARE\Microsoft\Windows\CurrentVersion\Run ***" """ aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE) aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall") for i in range(1024): try: asubkey=EnumKey(aKey,i) val=QueryValu...
[Documentation](http://docs.python.org/library/_winreg.html) says that `EnumKey` returns string with key's name. You have to explicitly open it with `_winreg.OpenKey` function. I've fixed your code snippet: ``` from _winreg import * """print r"*** Reading from SOFTWARE\Microsoft\Windows\CurrentVersion\Run ***" """ aR...
Python code to read registry
5,227,107
14
2011-03-08T00:50:06Z
17,608,059
11
2013-07-12T05:36:55Z
[ "python", "programming-languages", "registry" ]
``` from _winreg import * """print r"*** Reading from SOFTWARE\Microsoft\Windows\CurrentVersion\Run ***" """ aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE) aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall") for i in range(1024): try: asubkey=EnumKey(aKey,i) val=QueryValu...
What about x86 on x64? [Use *64-bit Specific* Types](http://docs.python.org/2/library/_winreg.html#bit-specific) What if there's more than 1024 sub-keys in "Uninstall"? [Use *\_winreg.QueryInfoKey(key)*](http://docs.python.org/2/library/_winreg.html#_winreg.QueryInfoKey) **Python 2:** ``` import errno, os, _winreg p...
What is the maximum number of methods on a Python class?
5,227,198
3
2011-03-08T01:03:55Z
5,227,226
7
2011-03-08T01:09:33Z
[ "python", "unit-testing", "class", "methods" ]
I am automatically generating unit tests for some Python code which number in the thousands. The `unittest` module uses classes to contain the tests however I'm guessing there is an upper limit to the number of methods a class may contain - is this the case?
Methods (and in fact *all* attributes) of a class are stored in a `dict`. There is no limit to the number of items a `dict` can contain, save that each key must be unique.
key corresponding to maximum value in python dictionary
5,227,291
16
2011-03-08T01:21:54Z
5,227,377
22
2011-03-08T01:37:39Z
[ "python" ]
``` a = dict(((1,3),(0,-1),(3,21))) m = max(a, key=a.get) ``` Can someone give me an explanation on why this returns the key corresponding to the maximum value? It's stumped me for quite a while. Thanks!
The dictionary "a" is an iterable structure in python. When you loop through with `for x in a`, you are looping over the keys in the dictionary. In the second line, the max function takes two arguments: An iterable object (a), and an optional "key" function. The Key function is going to be used to evaluate the value o...
conditional evaluation of source file in python
5,227,292
2
2011-03-08T01:22:23Z
5,227,355
7
2011-03-08T01:32:31Z
[ "python" ]
Say I have a file that's only used in pre-production code I want to ensure it gets not run in production code- any calls out to it have to fail. This snippet at the top of the file doesn't work - it breaks the Python grammar, which specifies that `return` must take place in a function. ``` if not __debug__: retur...
``` if not __debug__: raise RuntimeError('This module must not be run in production code.') ```
Why Python does not support record type i.e. mutable namedtuple
5,227,839
39
2011-03-08T03:01:10Z
5,227,863
17
2011-03-08T03:05:12Z
[ "python", "collections", "namedtuple" ]
Why does not Python support a record type natively? It's a matter of having a mutable version of namedtuple. I could use `namedtuple._replace`. But I need to have these records in a collection and since `namedtuple._replace` creates another instance, I also need to modify the collection which becomes messy quickly. Ba...
Is there any reason you can't use a regular dictionary? It seems like the attributes don't have a specific ordering in your particular situation. Alternatively, you could also use a class instance (which has nice attribute access syntax). You could use `__slots__` if you wish to avoid having a `__dict__` created for e...
Why Python does not support record type i.e. mutable namedtuple
5,227,839
39
2011-03-08T03:01:10Z
5,227,940
10
2011-03-08T03:19:23Z
[ "python", "collections", "namedtuple" ]
Why does not Python support a record type natively? It's a matter of having a mutable version of namedtuple. I could use `namedtuple._replace`. But I need to have these records in a collection and since `namedtuple._replace` creates another instance, I also need to modify the collection which becomes messy quickly. Ba...
This can be done using an empty class and instances of it, like this: ``` >>> class a(): pass ... >>> ainstance = a() >>> ainstance.b = 'We want Moshiach Now' >>> ainstance.b 'We want Moshiach Now' >>> ```
Why Python does not support record type i.e. mutable namedtuple
5,227,839
39
2011-03-08T03:01:10Z
5,491,708
32
2011-03-30T20:08:34Z
[ "python", "collections", "namedtuple" ]
Why does not Python support a record type natively? It's a matter of having a mutable version of namedtuple. I could use `namedtuple._replace`. But I need to have these records in a collection and since `namedtuple._replace` creates another instance, I also need to modify the collection which becomes messy quickly. Ba...
## Python <3.3 You mean something like this? ``` class Record(object): __slots__= "attribute1", "attribute2", "attribute3", def items(self): "dict style items" return [ (field_name, getattr(self, field_name)) for field_name in self.__slots__] def __iter__(self): ...
Why Python does not support record type i.e. mutable namedtuple
5,227,839
39
2011-03-08T03:01:10Z
14,338,469
8
2013-01-15T13:08:55Z
[ "python", "collections", "namedtuple" ]
Why does not Python support a record type natively? It's a matter of having a mutable version of namedtuple. I could use `namedtuple._replace`. But I need to have these records in a collection and since `namedtuple._replace` creates another instance, I also need to modify the collection which becomes messy quickly. Ba...
There's a library similar to namedtuple, but mutable, called recordtype. Package home: <http://pypi.python.org/pypi/recordtype> Simple example: ``` from recordtype import recordtype Person = recordtype('Person', 'first_name last_name phone_number') person1 = Person('Trent', 'Steele', '637-3049') person1.last_name =...
Cartesian product of a dictionary of lists
5,228,158
17
2011-03-08T03:57:12Z
5,228,294
20
2011-03-08T04:18:38Z
[ "python", "generator", "combinatorics" ]
I'm trying to write some code to test out the Cartesian product of a bunch of input parameters. I've looked at `itertools`, but its `product` function is not exactly what I want. Is there a simple obvious way to take a dictionary with an arbitrary number of keys *and* an arbitrary number of elements in each value, and...
Ok, thanks to @dfan for telling me I was looking in the wrong place. I've got it now: ``` def my_product(dicts): return (dict(izip(dicts, x)) for x in product(*dicts.itervalues())) ```
python itertools.chain to chain an iter list?
5,229,188
7
2011-03-08T06:37:07Z
5,229,215
11
2011-03-08T06:40:41Z
[ "python", "parameters", "itertools", "chain" ]
code: ``` import itertools def _yield_sample(): it = iter(itertools.combinations('ABCD', 2)) it2 = iter(itertools.combinations('EFGH', 3)) itc = itertools.chain(it,it2) for x in itc: yield x def main(): for x in _yield_sample(): print x ``` This works to print the combinations. `...
[Yes.](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) But [`itertools.chain.from_iterable()`](http://docs.python.org/library/itertools.html#itertools.chain.from_iterable).
Precision in python
5,229,425
7
2011-03-08T07:06:38Z
5,229,434
11
2011-03-08T07:07:48Z
[ "python" ]
How can write a print statement in python that will print exactly 2 digits after decimal?
``` print "{0:.2f}".format(your_number) ``` This is explained in detail in the [Python Documentation](http://docs.python.org/library/string.html#formatstrings).
How is membership testing different for a list and a set?
5,230,522
8
2011-03-08T09:23:27Z
5,230,584
11
2011-03-08T09:29:19Z
[ "python", "list", "set", "member" ]
I'm having trouble with figuring out why the first of these assertions is OK and the second raises an error. ``` subject_list = [Subject("A"), Subject("B"), Subject("C")] subject_set = set() subject_set.add(Subject("A")) subject_set.add(Subject("B")) subject_set.add(Subject("C")) self.assertIn(Subject("A"), subject_l...
The expression ``` Subject("A") in subject_list ``` will compare `Subject("A")` to each entry in `subject_list` using the `Subject.__eq__()` method. If this method is not overwritten, it defaults to always return `False` unless the two operands are the *same object*. The above expression would always return `False` i...
What is the difference between {} and [] in python?
5,230,874
3
2011-03-08T09:58:37Z
5,230,887
11
2011-03-08T10:00:09Z
[ "python", "syntax" ]
What is the difference between `columnNames = {}` and `columnNames = []` in python? How can i iterate each one? using `{% for value in columnNames %}` OR `for idx_o, val_o in enumerate(columnNames):`
* `columnNames = {}` defines an empty `dict` * `columnNames = []` defines an empty `list` These are fundamentally different types. A `dict` is an [associative array](http://en.wikipedia.org/wiki/Associative_array), a `list` is a [standard array](http://en.wikipedia.org/wiki/Array_data_type) with integral indices. I r...
Python-FTP download all files in directory
5,230,966
16
2011-03-08T10:07:35Z
5,313,986
39
2011-03-15T15:28:27Z
[ "python", "ftp" ]
Python newb here so please bear with me. I m putting together a script to download all the files from a directory via FTP. So far I have managed to connect and fetch one file, but I cannot seem to make to work in batch (get all the files from the directory) Here is what I have so far: ``` from ftplib import FTP import...
I've managed to crack this, so now posting the relevant bit of code for future visitors: ``` filenames = ftp.nlst() # get filenames within the directory print filenames for filename in filenames: local_filename = os.path.join('C:\\test\\', filename) file = open(local_filename, 'wb') ftp.retrbinary('RETR '...
Python Last Iteration in For Loop
5,231,040
8
2011-03-08T10:14:21Z
5,231,195
8
2011-03-08T10:27:26Z
[ "python" ]
Is there any simple way to find the Last Iteration of the for Loop in Python? I just want to convert a list to CSV.
actually when a `for` loop in python ends the name that it bound is still accessible and bound to its last value: ``` for i in range(10): if i == 3: break print i # prints 3 ``` i use this trick with `with` like: ``` with Timer() as T: pass # do something print T.format() # prints 0.34 seconds ```
Python Last Iteration in For Loop
5,231,040
8
2011-03-08T10:14:21Z
5,231,235
12
2011-03-08T10:30:37Z
[ "python" ]
Is there any simple way to find the Last Iteration of the for Loop in Python? I just want to convert a list to CSV.
To convert a list to CSV, use the [`join`](http://docs.python.org/library/stdtypes.html#str.join)-function: ``` >>> lst = [1,2,3,4] >>> ",".join(str(item) for item in lst) "1,2,3,4" ``` If the list already contains only string, you just do `",".join(l)`.
Python Last Iteration in For Loop
5,231,040
8
2011-03-08T10:14:21Z
5,231,357
10
2011-03-08T10:43:13Z
[ "python" ]
Is there any simple way to find the Last Iteration of the for Loop in Python? I just want to convert a list to CSV.
To convert a list to csv you could use [`csv`](http://docs.python.org/library/csv.html) module: ``` import csv list_of_lists = ["nf", [1,2]] with open('file', 'wb') as f: csv.writer(f).writerows(list_of_lists) ``` The `'file'` file would be: ``` n,f 1,2 ```
Python Last Iteration in For Loop
5,231,040
8
2011-03-08T10:14:21Z
5,231,547
9
2011-03-08T11:01:34Z
[ "python" ]
Is there any simple way to find the Last Iteration of the for Loop in Python? I just want to convert a list to CSV.
Your best solution is probably to use the csv module, as suggested elsewhere. However, to answer your question as stated: Option 1: count your way through using enumerate() ``` for i, value in enumerate(my_list): print value, if i < len(my_list)-1: print ", followed by" ``` Option 2: handle the final...
Django TemplateSyntaxError Could not parse the remainder: '()'
5,231,171
15
2011-03-08T10:25:02Z
5,231,224
31
2011-03-08T10:29:45Z
[ "python", "django", "django-templates" ]
I'm trying to iterate a dictionary of dictionary in Django template page ``` {% for (key_o, value_o) in f_values.items() %} <tr class="row {% cycle 'odd' 'even' %}"> {% for (key_i, val_i) in value_o.items() %} <td class="tile "> {{ val_i }}...
You don't need to use `()` to call methods in templates. You can just use `f_values.items`. This notation works for list, tuples and functions: ``` lst = ['a', 'b', 'c'] di = {'a': 'a'} class Foo: def bar(self): pass ``` You can do: ``` {{ lst.0 }} {{ di.a }} {{ foo.bar }} ``` So for your code: ``` {% for (ke...
Permission problems when creating a dir with os.makedirs (python)
5,231,901
9
2011-03-08T11:35:16Z
5,231,994
14
2011-03-08T11:44:08Z
[ "python" ]
I'm simply trying to handle an uploaded file and write it in a working dir which name is the system timestamp. The problem is that I want to create that directory with full permission (777) but I CAN'T! Using the following piece of code the created directory has 755 permissions. ``` def handle_uploaded_file(upfile, cT...
According to the official python [documentation](http://docs.python.org/library/os.html) the mode argument of the `os.makedirs` function may be ignored on some systems, and on systems where it is not ignored the current umask valued is masked out. Either way, you can force the mode to 0777 using the `os.chmod` functio...
How to access dictionary values in django template
5,232,236
6
2011-03-08T12:09:41Z
5,232,494
9
2011-03-08T12:32:57Z
[ "python", "django", "django-models", "django-templates", "django-views" ]
How to access the dictionary value in django template? I want to get the value of the variable `a` actually ``` class Emp(models.Model): name = models.CharField(max_length=255, unique=True) address1 = models.CharField(max_length=255) def get_names(self): names = {} names_desc = {} nbl = {} names...
``` {{ emp.get_names.names.a }} will get you 1 in the template {{ emp.get_names.names }} will get you {'A':1} in the template {{ emp.get_names }} will get you {'names_desc': {'b': 2}, 'names': {'a': 1}} in the template ```
Serializing SQLAlchemy models for a REST API while respecting access control?
5,232,461
7
2011-03-08T12:29:03Z
5,249,214
7
2011-03-09T16:51:58Z
[ "python", "design", "serialization", "aop" ]
Currently, the way our, as well as most web frameworks', serialization works is there's some type of method invocation which dumps the model into some type of format. In our case, we have a `to_dict()` method on every model that constructs and returns a key-value dictionary with the key being the field name and the val...
establish the "serialization" contract via a mixin: ``` class Serializer(object): __public__ = None "Must be implemented by implementors" __internal__ = None "Must be implemented by implementors" def to_serializable_dict(self): # do stuff with __public__, __internal__ # ... ``` k...
Lambda and functions in Python
5,232,719
13
2011-03-08T12:52:41Z
5,232,806
17
2011-03-08T13:00:40Z
[ "python" ]
I have beginner two questions 1. What does `*z` or `*foo` or `**foo` mean regarding function in Python. 2. This works - `a = lambda *z :z` But this does not - `a = lambda **z: z`. Because it is supposed to take 0 arguments. What does this actually mean? Thanks and Regards.
`*z` and `**z` in Python refer to args and kwargs. args are positional arguments and kwargs are keyword arguments. lambda `**z` doesn't work in your example because `z` isn't a keyword argument: it's merely positional. Compare these different results: ``` >>> a = lambda z: z >>> b = lambda *z: z >>> c = la...
Python 2.7 on Ubuntu
5,233,536
72
2011-03-08T14:07:16Z
5,233,660
109
2011-03-08T14:16:22Z
[ "python", "ubuntu", "python-2.7" ]
I am new to Python and am working on a Linux machine (Ubuntu 10.10). It is running python 2.6, but I'd like to run 2.7 as it has features I want to use. I have been urged to not install 2.7 and set that as my default python. My question is, how can I install 2.7 and run it side by side with 2.6?
I did it with [pythonbrew](https://github.com/utahta/pythonbrew) on my Ubuntu 10.10 machine. ``` $ python -V Python 2.6.6 $ curl -kL https://raw.github.com/utahta/pythonbrew/master/pythonbrew-install | bash $ . $HOME/.pythonbrew/etc/bashrc $ pythonbrew install 2.7.1 $ pythonbrew switch 2.7.1 Switched to Python-2.7.1 $...
Python 2.7 on Ubuntu
5,233,536
72
2011-03-08T14:07:16Z
8,931,660
11
2012-01-19T18:54:47Z
[ "python", "ubuntu", "python-2.7" ]
I am new to Python and am working on a Linux machine (Ubuntu 10.10). It is running python 2.6, but I'd like to run 2.7 as it has features I want to use. I have been urged to not install 2.7 and set that as my default python. My question is, how can I install 2.7 and run it side by side with 2.6?
I recently backported Python 2.7 to Debian squeeze. Since Ubuntu 10.10 is newer than Debian squeeze, if you can do it on squeeze, you can certainly do it on Ubuntu. I don't have access to a Ubuntu 10.10 system. If I set one up, I'll test on it, and update this answer. So, here instead is a brief sketch of what I did on...
os.walk doesn't walk
5,233,814
2
2011-03-08T14:28:29Z
5,233,855
15
2011-03-08T14:32:00Z
[ "python" ]
While fiddling around to try to automate some process, I ran into this seemingly very strange behavior of Python's `os.walk()`: when I pass it some directory, it just doesn't do anything. However, when I pass the parent directory, it recurses properly in the path that doesn't seem to work when passed directly. For exa...
Your problem is here: ``` for root, _, _ in os.walk('F:\music\test'): print(root) ``` ...when Python parses the string containing your path, it interprets the `\t` as a Tab character. You can either rewrite your path string literal as `'f:\\music\\test'` or as `r'F:\music\test'` (a raw string, which exists for ...
How to take the first N items from a generator or list in Python?
5,234,090
92
2011-03-08T14:53:10Z
5,234,115
59
2011-03-08T14:56:21Z
[ "python", "list", "generator" ]
With [linq](/questions/tagged/linq "show questions tagged 'linq'") I would ``` var top5 = array.Take(5); ``` How to do this with Python?
``` import itertools top5 = itertools.islice(array, 5) ```
How to take the first N items from a generator or list in Python?
5,234,090
92
2011-03-08T14:53:10Z
5,234,170
144
2011-03-08T15:00:56Z
[ "python", "list", "generator" ]
With [linq](/questions/tagged/linq "show questions tagged 'linq'") I would ``` var top5 = array.Take(5); ``` How to do this with Python?
# Slicing a list ``` top5 = array[:5] ``` * To slice a list, there's a simple syntax: `array[start:stop:step]` * You can omit any parameter. These are all valid: `array[start:]`, `array[:stop]`, `array[::step]` # Slicing a generator ``` import itertools top5 = itertools.islice(my_list, 5) # grab the first five el...
How to take the first N items from a generator or list in Python?
5,234,090
92
2011-03-08T14:53:10Z
26,186,228
12
2014-10-03T20:21:13Z
[ "python", "list", "generator" ]
With [linq](/questions/tagged/linq "show questions tagged 'linq'") I would ``` var top5 = array.Take(5); ``` How to do this with Python?
In my taste, it's also very concise to combine zip() with range(n), which works nice on generators as well and seems to be more flexible for changes in general. In Python 3, both zip() and range() are generators. In Python 2, you can still yield the top elements to create a generator. ``` # taking the first n element...
Python Variable Scope (passing by reference or copy?)
5,234,126
5
2011-03-08T14:57:32Z
5,234,274
8
2011-03-08T15:09:28Z
[ "python", "scope" ]
Why does the variable L gets manipulated in the `sorting(L)` function call? In other languages, a copy of L would be passed through to `sorting()` as a copy so that any changes to `x` would not change the original variable? ``` def sorting(x): A = x #Passed by reference? A.sort() def testScope(): L = [5...
Long story short: Python uses pass-by-value, but the things that are passed by value are references. The actual objects have 0 to infinity references pointing at them, and for purposes of mutating that object, it doesn't matter who you are and how you got a reference to the object. Going through your example step by s...
Python Variable Scope (passing by reference or copy?)
5,234,126
5
2011-03-08T14:57:32Z
5,234,279
7
2011-03-08T15:09:53Z
[ "python", "scope" ]
Why does the variable L gets manipulated in the `sorting(L)` function call? In other languages, a copy of L would be passed through to `sorting()` as a copy so that any changes to `x` would not change the original variable? ``` def sorting(x): A = x #Passed by reference? A.sort() def testScope(): L = [5...
Python has the concept of Mutable and [Immutable objects](http://en.wikipedia.org/wiki/Immutable_object). An object like a string or integer is immutable - every change you make creates a new string or integer. Lists are mutable and can be manipulated in place. See below. ``` a = [1, 2, 3] b = [1, 2, 3] c = a print ...
Simple way to toggle fullscreen with F11 in PyGTK
5,234,434
5
2011-03-08T15:22:05Z
5,241,251
17
2011-03-09T04:15:01Z
[ "python", "gtk", "pygtk", "fullscreen" ]
I am not a professional programmer but am regularly using PyGTK and Cairo for data visualization testing and prototyping. I have a standard template of PyGTK that I took from the web, which does the "standard things" GTK needs to work: ``` import pygtk pygtk.require('2.0') import gtk """ lots of stuff """ if __name...
Let's start with how to pick up on the keypress: we need to connect to the [`key-press-event`](http://library.gnome.org/devel/pygtk/stable/class-gtkwidget.html#signal-gtkwidget--key-press-event) signal. But we need something to connect it *to*, of course. This something should keep track of the window state, so it mak...
Using the dig command in python
5,235,569
12
2011-03-08T16:49:22Z
5,237,068
26
2011-03-08T19:07:47Z
[ "python", "dns", "cname", "dig" ]
Just a forewarning, my python skills are almost nonexistent, but I’m trying to learn as I go. I'm doing a few changes via our DNS control panel over the weekend to about 58 CNAMES (just changing the destination) And rather than checking the changes have gone live for each individual record I was wondering if there ...
It's quite possible to invoke **dig** from python, it would probably save you work to just use a python library. Take a look at [dnspython](http://www.dnspython.org/) which will probably do everything easier - plus you don't have to parse the output format. ``` import socket import dns.resolver # Basic query for rdat...
What is the best way to install python 2 on OS X?
5,235,617
2
2011-03-08T16:53:15Z
5,235,708
7
2011-03-08T17:00:18Z
[ "python", "osx", "numpy", "tkinter", "ipython" ]
A colleague of mine wants to use my python 2 code on his OS X (10.6) machine. My code imports several built-in python packages, including Tkinter and shelve, and also uses third-party packages, including numpy, scipy, matplotlib, and ipython. I've encountered a few problems with OS X's built-in python. (IDLE doesn't w...
I use [`brew`](https://github.com/mxcl/homebrew) to install all my libraries/compilers/interpreters. To install `python` try this: ``` brew install python ``` Then add Python's binaries directory to your `$PATH` in your `~/.profile`: ``` export PATH=`brew --prefix python`/bin:$PATH ``` I'd recommend you to install...
How to parallelize list-comprehension calculations in Python?
5,236,364
27
2011-03-08T17:57:12Z
5,237,665
21
2011-03-08T20:04:53Z
[ "python", "parallel-processing", "list-comprehension" ]
Both list comprehensions and map-calculations should -- at least in theory -- be relatively easy to parallelize: each calculation inside a list-comprehension could be done independent of the calculation of all the other elements. For example in the expression ``` [ x*x for x in range(1000) ] ``` each x\*x-Calculation...
As Ken said, no, it can't, but with 2.6's [multiprocessing](http://docs.python.org/library/multiprocessing.html) module, it's pretty easy to parallelize computations. ``` import multiprocessing try: cpus = multiprocessing.cpu_count() except NotImplementedError: cpus = 2 # arbitrary default def square(n): ...
python UnicodeEncodeError > How can I simply remove troubling unicode characters?
5,236,437
6
2011-03-08T18:04:51Z
5,236,869
10
2011-03-08T18:46:28Z
[ "python", "parsing", "unicode", "html-parsing" ]
Heres what I did.. ``` >>> soup = BeautifulSoup (html) >>> soup Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 96953: ordinal not in range(128) >>> >>> soup.find('div') Traceback (most recent call last): File "<st...
Try this way: `soup = BeautifulSoup (html.decode('utf-8', 'ignore'))`
Mocking open(file_name) in unit tests
5,237,693
19
2011-03-08T20:06:37Z
5,237,885
9
2011-03-08T20:23:00Z
[ "python", "unit-testing", "mox" ]
I have a source code that opens a csv file and sets up a header to value association. The source code is given below: ``` def ParseCsvFile(source): """Parse the csv file. Args: source: file to be parsed Returns: the list of dictionary entities; each dictionary contains attribute to value map...
There are two ways that I like to do this, depending on the situation. If your unit test is going to call ParseCsvFile directly I would add a new kwarg to ParseCsvFile: ``` def ParseCsvFile(source, open=open): # ... rack_type_file = open(rack_file) # Need to mock this line. ``` Then your unit test can pass...
Mocking open(file_name) in unit tests
5,237,693
19
2011-03-08T20:06:37Z
6,316,409
13
2011-06-11T14:20:10Z
[ "python", "unit-testing", "mox" ]
I have a source code that opens a csv file and sets up a header to value association. The source code is given below: ``` def ParseCsvFile(source): """Parse the csv file. Args: source: file to be parsed Returns: the list of dictionary entities; each dictionary contains attribute to value map...
To mock built-in function open with mox use `__builtin__` module: ``` import __builtin__ # unlike __builtins__ this must be imported m = mox.Mox() m.StubOutWithMock(__builtin__, 'open') open('ftphelp.yml', 'rb').AndReturn(StringIO("fake file content")) m.ReplayAll() # call the code you want to test that calls `op...
Mocking open(file_name) in unit tests
5,237,693
19
2011-03-08T20:06:37Z
19,663,055
12
2013-10-29T15:48:42Z
[ "python", "unit-testing", "mox" ]
I have a source code that opens a csv file and sets up a header to value association. The source code is given below: ``` def ParseCsvFile(source): """Parse the csv file. Args: source: file to be parsed Returns: the list of dictionary entities; each dictionary contains attribute to value map...
This is admittedly an old question, hence some of the answers are outdated. In the current version of the `mock` library **there is a convenience function designed for precisely this purpose**. Here's how it works: ``` >>> from mock import mock_open >>> m = mock_open() >>> with patch('__main__.open', m, create=True):...
Boost python linking
5,238,160
6
2011-03-08T20:48:35Z
5,238,644
11
2011-03-08T21:38:04Z
[ "c++", "python", "boost", "hyperlink", "cmake" ]
I'm adding boost.python for my Game. I write wrappers for my classes to use them in scripts. The problem is linking that library to my app. I'm using `cmake` build system. Now I have a simple app with 1 file and makefile for it: ``` PYTHON = /usr/include/python2.7 BOOST_INC = /usr/include BOOST_LIB = /usr/lib TARGE...
You are missing your include directory and libs for python in your CMakeList.txt. Use the PythonFindLibs macro or the same find\_package strategy you used for Boost ``` find_package(Boost COMPONENTS filesystem system date_time python REQUIRED) message("Include dirs of boost: " ${Boost_INCLUDE_DIRS} ) message("Libs of ...
Unpickling new-style with kwargs not possible?
5,238,252
3
2011-03-08T20:59:52Z
5,239,396
7
2011-03-08T22:57:39Z
[ "python", "pickle" ]
During instantiation of my class, I initialize some fields that are not picklable. Thus, in order to be able to (un)pickle my classes correctly, I would like my **init** method to be called on unpickling. This is, it seems, the way it worked with old-style classes. With new style classes, I need to use `__new__` and `...
The pickle protocol 2 wants to call `cls.__new__(cls, *args)` by default, but there is a way around this. If you use `__reduce__` you can return a function which will map your arguments to `__new__`. I was able to modify your example to get `**kwargs` to work: ``` import cPickle class Blubb(object): def __init__...
(Only) generate SQL-Code with SqlAlchemy
5,238,275
8
2011-03-08T21:02:01Z
5,239,102
7
2011-03-08T22:22:19Z
[ "python", "orm", "sqlalchemy" ]
Can i use the SqlAlchemy ORM-Mapper to only generate the SQL-Code? With simple tables i can use code like ``` print users_table.select() print users_table.insert() print users_table.update() print users_table.delete() ``` But with the ORM i have only found a way for SELECT-Statements: ``` TestUser = User("John", "D...
Perhaps you want the SQLAlchemy core expression language, instead of the ORM? <http://www.sqlalchemy.org/docs/core/index.html> The ORM is designed to be very tightly data-bound, and thus to not really be decoupled from its DB sessions. The expression language, on the other hand, can be directly translated to SQL. (Ju...
adding characters to a string in python 3
5,238,389
3
2011-03-08T21:13:11Z
5,238,418
14
2011-03-08T21:15:36Z
[ "python", "string", "python-3.x" ]
I currently have a string that I want to edit by adding spaces between each character, so I currently have `s = 'abcdefg'` and I want it to become `s = 'a b c d e f g'`. Is there any easy way to do this using loops?
``` >>> ' '.join('abcdefg') 'a b c d e f g' ```
Equivalent of ruby obj.send in python
5,238,785
8
2011-03-08T21:52:18Z
5,238,817
14
2011-03-08T21:55:37Z
[ "python", "send" ]
In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax obj.send(funcname) Is there something similar in python. The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it at the end of the switch statement.
``` getattr(obj, "name")(args) ``` ​​​​
Equivalent of ruby obj.send in python
5,238,785
8
2011-03-08T21:52:18Z
5,238,840
7
2011-03-08T21:58:06Z
[ "python", "send" ]
In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax obj.send(funcname) Is there something similar in python. The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it at the end of the switch statement.
hmmm... getattr(obj, funcname)(\*args, \*\*kwargs) ? ``` >>> s = "Abc" >>> s.upper() 'ABC' >>> getattr(s, "upper")() 'ABC' >>> getattr(s, "lower")() 'abc' ```
problem compiling libjingle
5,238,953
8
2011-03-08T22:09:11Z
5,239,583
22
2011-03-08T23:23:17Z
[ "python", "google-code", "libjingle" ]
I downloaded and installed libjingle-0.5.2.zip, and according to the README also downloaded and installed swtoolkit.0.9.1.zip, scons-local-2.1.0.alpha.20101125.tar.gz, and expat-2.0.1.tar.gz, and got nrtp by cvs download. After overwriting my Makefile twice, attempting to follow the rather poorly-written README, I came...
I'm not familiar with the project, but think I have a fix to get you past that point. You need to cast those `Dir` instances using `str()` in swtoolkit/site\_scons/site\_init.py. That way they can safely be evaluated by `path.endswith('/')`. Odd that such an issue would exist for very long in the main part of the build...
creating one string from two in python
5,239,071
5
2011-03-08T22:19:40Z
5,239,076
7
2011-03-08T22:20:34Z
[ "python", "string", "python-3.x" ]
Is there any way to add one string to the end of another in python? e.g. String1 = 'A' String2 = 'B' and i want String3 == 'AB'
String concatenation in python is straightforward ``` a = "A" b = "B" c = a + b print c > AB ``` I benchmarked the three operations, performing 1m of each: ``` c = a + b c = '%s%s' % (a,b) c = "{0}{1}".format(a, b) ``` And the results are: ``` +: 0.232225275772 %s: 0.42436670365 {}: 0.683854960343 ``` Even with...
Finding the most popular words in a list
5,239,781
6
2011-03-08T23:49:00Z
5,239,831
7
2011-03-08T23:56:08Z
[ "python", "string", "list", "words" ]
I have a list of words: ``` words = ['all', 'awesome', 'all', 'yeah', 'bye', 'all', 'yeah'] ``` And I want to get a list of tuples: ``` [(3, 'all'), (2, 'yeah'), (1, 'bye'), (1, 'awesome')] ``` where each tuple is... ``` (number_of_occurrences, word) ``` The list should be sorted by the number of occurrences. Wh...
You can use the [counter](http://docs.python.org/library/collections.html#collections.Counter) for this. ``` import collections words = ['all', 'awesome', 'all', 'yeah', 'bye', 'all', 'yeah'] counter = collections.Counter(words) print(counter.most_common()) >>> [('all', 3), ('yeah', 2), ('bye', 1), ('awesome', 1)] ```...
foggy on asterisk in python
5,239,856
70
2011-03-08T23:58:47Z
5,239,873
110
2011-03-09T00:01:16Z
[ "python", "operators" ]
I'm using itertools.chain to "flatten" a list of lists in this fashion: ``` uniqueCrossTabs = list(itertools.chain(*uniqueCrossTabs)) ``` how is this different than saying: ``` uniqueCrossTabs = list(itertools.chain(uniqueCrossTabs)) ```
`*` is the "splat" operator: It takes a list as input, and expands it into actual positional arguments in the function call. So if `uniqueCrossTabs` was `[ [ 1, 2 ], [ 3, 4 ] ]`, then `itertools.chain(*uniqueCrossTabs)` is the same as saying `itertools.chain([ 1, 2 ], [ 3, 4 ])` This is obviously different from passi...
foggy on asterisk in python
5,239,856
70
2011-03-08T23:58:47Z
5,239,879
46
2011-03-09T00:01:59Z
[ "python", "operators" ]
I'm using itertools.chain to "flatten" a list of lists in this fashion: ``` uniqueCrossTabs = list(itertools.chain(*uniqueCrossTabs)) ``` how is this different than saying: ``` uniqueCrossTabs = list(itertools.chain(uniqueCrossTabs)) ```
It splits the sequence into separate arguments for the function call. ``` >>> def foo(a, b=None, c=None): ... print a, b, c ... >>> foo([1, 2, 3]) [1, 2, 3] None None >>> foo(*[1, 2, 3]) 1 2 3 >>> def bar(*a): ... print a ... >>> bar([1, 2, 3]) ([1, 2, 3],) >>> bar(*[1, 2, 3]) (1, 2, 3) ```
foggy on asterisk in python
5,239,856
70
2011-03-08T23:58:47Z
32,908,288
9
2015-10-02T13:30:00Z
[ "python", "operators" ]
I'm using itertools.chain to "flatten" a list of lists in this fashion: ``` uniqueCrossTabs = list(itertools.chain(*uniqueCrossTabs)) ``` how is this different than saying: ``` uniqueCrossTabs = list(itertools.chain(uniqueCrossTabs)) ```
Just an alternative way of explaining the concept/using it. ``` import random def arbitrary(): return [x for x in range(1, random.randint(3,10))] a, b, *rest = arbitrary() # a = 1 # b = 2 # rest = [3,4,5] ```
Map list by partial function vs lambda
5,240,427
16
2011-03-09T01:35:34Z
5,240,556
16
2011-03-09T02:04:07Z
[ "python" ]
I was wondering whether for most examples it is more 'pythonic' to use [`lambda`](http://docs.python.org/reference/expressions.html#lambda) or the [`partial`](http://docs.python.org/library/functools.html#functools.partial) function? For example, I might want to apply [`imap`](http://docs.python.org/library/itertools....
To be truly equivalent to `imap`, use a generator expression: ``` (x + 3 for x in mylist) ``` Like `imap`, this doesn't immediately construct an entire new list, but instead computes elements of the resulting sequence on-demand (and is thus much more efficient than a list comprehension if you're chaining the result i...
Detect if a model has changed before calling save in Django
5,240,670
18
2011-03-09T02:31:56Z
5,246,227
9
2011-03-09T13:08:15Z
[ "python", "django", "django-models" ]
I have a database model that is being updated based on changes in remote data (via an HTML scraper). I want to maintain a field called `changed` - a timestamp denoting when the last time that model's values changed from what they were previously (note that this is different from `auto_now` as these fields are updated ...
<http://code.activestate.com/pypm/django-dirtyfields/> Tracks dirty/changed fields on a django model instance.
Detect if a model has changed before calling save in Django
5,240,670
18
2011-03-09T02:31:56Z
5,246,846
34
2011-03-09T14:00:36Z
[ "python", "django", "django-models" ]
I have a database model that is being updated based on changes in remote data (via an HTML scraper). I want to maintain a field called `changed` - a timestamp denoting when the last time that model's values changed from what they were previously (note that this is different from `auto_now` as these fields are updated ...
If you save your instance through a form, you can check `form.has_changed()`.
Web.py on dotcloud with wsgi
5,241,291
8
2011-03-09T04:26:59Z
5,242,223
13
2011-03-09T06:35:39Z
[ "python", "wsgi", "web.py" ]
I'm trying to deploy my web.py app on dotcloud, but can't figure out how to do it. I went through this tutorial fine: <http://docs.dotcloud.com/static/tutorials/firststeps/> And then I looked at <http://docs.dotcloud.com/static/components/python/> ... > The python service can host any python > web application compat...
I am fellow user of web.py and I work at DotCloud by the way :-) We use uWSGI to run your WSGI application. The point is that uWSGI is looking for a variable named "application". Here is what I usually do: ``` app = web.application(urls, globals()) if __name__ == '__main__': app.run() else: web.config.debug...
Cython - implementing callbacks
5,242,051
8
2011-03-09T06:09:49Z
12,809,191
8
2012-10-09T22:12:43Z
[ "c++", "python", "cython" ]
I have been working with Cython in an attempt to interface with a library written in c++. So far things are going pretty good, and I can effectively use MOST functions within the library. My only problem lies within implementing callbacks. The library has 4 function definitions that look a little something like this: ...
I've recently been in the situation where I also had to interface an existing C++ library with Python using Cython, making an intensive use of events/callbacks. It was not that easy to find sources about this and I would like to put all of this together here : First of all, the wrapping C++ callback class (based on 'd...
"Segmentation fault" during "import cv" on Mac OS
5,242,257
5
2011-03-09T06:39:45Z
6,222,493
7
2011-06-03T02:49:29Z
[ "python", "osx", "opencv", "macports" ]
Trying to compile opencv on my Mac from source. I have following CMakeCache.txt: <http://pastebin.com/KqPHjBx0> I make `ccmake ..`, press `c`, then `g`. Than I make `sudo make -j8`: <http://pastebin.com/cJyr1cEd> Than I make `sudo make install`: <http://pastebin.com/W77syYBj> And than I make `import cv` in python a...
I had a same situation and resolved the following steps. In ccmake(`ccmake -G "Unix Makefiles" .`), toggle to the advanced mode pressing `t`. change `PYTHON_LIBRARY` value to `/opt/local/lib/libpython2.6.dylib` and `PYTHON_INCLUDE_DIR` to `/opt/local/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6`...
python: union keys from multiple dictionary?
5,242,311
6
2011-03-09T06:47:34Z
5,242,329
8
2011-03-09T06:49:47Z
[ "python", "dictionary", "lambda", "reduce" ]
I have 5 dictionaries and I want a union of their keys. ``` alldict = [dict1, dict2, dict3, dict4, dict5] ``` I tried ``` allkey = reduce(lambda x, y: set(x.keys()).union(y.keys()), alldict) ``` but it gave me an error ``` AttributeError: 'set' object has no attribute 'keys' ``` Am I doing it wrong ? I using nor...
Your solution works for the first two elements in the list, but then `dict1` and `dict2` got reduced into a set and that set is put into your lambda as the `x`. So now `x` does not have the method `keys()` anymore. The solution is to make x be a set from the very beginning by initializing the reduction with an empty s...
python: union keys from multiple dictionary?
5,242,311
6
2011-03-09T06:47:34Z
5,243,192
24
2011-03-09T08:42:12Z
[ "python", "dictionary", "lambda", "reduce" ]
I have 5 dictionaries and I want a union of their keys. ``` alldict = [dict1, dict2, dict3, dict4, dict5] ``` I tried ``` allkey = reduce(lambda x, y: set(x.keys()).union(y.keys()), alldict) ``` but it gave me an error ``` AttributeError: 'set' object has no attribute 'keys' ``` Am I doing it wrong ? I using nor...
I think @chuck already answered the question why it doesn't work, but a simpler way to do this would be to remember that the `union` method can take multiple arguments: ``` allkey = set().union(*alldict) ``` does what you want without any loops or lambdas.
Django: how to read the db_column name of a model field
5,243,222
6
2011-03-09T08:44:37Z
5,244,198
13
2011-03-09T10:09:39Z
[ "python", "django" ]
I need to know the db\_column name of various model fields. On a few models the name is explicitly set by "db\_column='foo'", but most of the models/fields have the name automatically generated by Django. How can I retrieve the column\_name for **all** fields from within a model's instance?
There is an undocumented `_meta` API that's widely used throughout Django for introspecting models. It stores your model options on the type and provides about two dozen methods and attributes to inspect your model and it's fields. You can use it to get all the model fields and then from the fields you can get the colu...
Python SQL query string formatting
5,243,596
40
2011-03-09T09:20:08Z
5,244,019
8
2011-03-09T09:55:12Z
[ "python", "sql", "string-formatting" ]
I'm trying to find the best way to format an sql query string. When I'm debugging my application I'd like to log to file all the sql query strings, and it is important that the string is properly formated. **Option 1** ``` def myquery(): sql = "select field1, field2, field3, field4 from table where condition1=1 a...
You've obviously considered lots of ways to write the SQL such that it prints out okay, but how about changing the 'print' statement you use for debug logging, rather than writing your SQL in ways you don't like? Using your favourite option above, how about a logging function such as this: ``` def debugLogSQL(sql): ...
Python SQL query string formatting
5,243,596
40
2011-03-09T09:20:08Z
9,433,548
51
2012-02-24T15:42:20Z
[ "python", "sql", "string-formatting" ]
I'm trying to find the best way to format an sql query string. When I'm debugging my application I'd like to log to file all the sql query strings, and it is important that the string is properly formated. **Option 1** ``` def myquery(): sql = "select field1, field2, field3, field4 from table where condition1=1 a...
Sorry for posting to such an old thread -- but as someone who also shares a passion for pythonic 'best', I thought I'd share our solution. The solution is to build SQL statements using python's String Literal Concatenation ([http://docs.python.org/](http://docs.python.org/reference/lexical_analysis.html#string-literal...
How do I add "Reply To" to this in Django?
5,243,757
4
2011-03-09T09:34:00Z
5,243,781
14
2011-03-09T09:35:35Z
[ "python", "django" ]
``` msg = EmailMessage(subject, body, from_email, [to_email]) msg.content_subtype = "html" msg.send() ``` How do I add the "reply to" header?
You'll want to add a `Reply-To` header to the `EmailMessage`. ``` headers = {'Reply-To': reply_email} msg = EmailMessage(subject, body, from_email, [to_email], headers=headers) msg.content_subtype = "html" msg.send() ```
Why is 00100 = 64 in python?
5,243,968
2
2011-03-09T09:50:53Z
5,243,986
9
2011-03-09T09:52:37Z
[ "python", "int" ]
Why, like in the following python code, does `00100` equal `64`? ``` >>> i = 00100 >>> i 64 >>> type(00100) <type 'int'> >>> str(00100) '64' >>> str("00100") '00100' >>> int(str("00100")) 100 >>> ```
its an octal value because of leading zeros <http://www.translatorscafe.com/cafe/units-converter/numbers/calculator/octal-to-decimal/> ^calculator (hard to summarize)
Python code-folding in emacs?
5,244,485
27
2011-03-09T10:34:34Z
17,775,868
22
2013-07-21T19:10:02Z
[ "python", "emacs", "editor", "folding" ]
I have many classes and def ... I want have + and - key before class and def for collapse class or open it ( toggle it ) how i can do this?
Hideshow works out of the box and folds python code. It is built-in my version of emacs (24.3.1) I have never needed more than these commands: ``` M-x hs-minor-mode M-x hs-hide-all M-x hs-show-all ``` To toggle use C-c @ C-c which probably needs rebinding. You might also want to setup a hook in your .emacs file for ...
python: Appending a dictionary to a list - I see a pointer like behavior
5,244,810
23
2011-03-09T11:02:53Z
5,244,854
35
2011-03-09T11:05:45Z
[ "python", "list", "dictionary" ]
I tried the following in the python interpreter: ``` >>> >>> a = [] >>> b = {1:'one'} >>> a.append(b) >>> a [{1: 'one'}] >>> b[1] = 'ONE' >>> a [{1: 'ONE'}] >>> ``` Here, after appending the dictionary 'b' to the list 'a', I'm changing the value corresponding to the key 1 in dictionary 'a'. Somehow this change gets r...
You are correct in that your list contains a *reference* to the original dictionary. `a.append(b.copy())` should do the trick. Bear in mind that this makes a shallow copy. An alternative is to use [`copy.deepcopy(b)`](http://docs.python.org/library/copy.html), which makes a deep copy.
python: Appending a dictionary to a list - I see a pointer like behavior
5,244,810
23
2011-03-09T11:02:53Z
5,245,358
9
2011-03-09T11:50:13Z
[ "python", "list", "dictionary" ]
I tried the following in the python interpreter: ``` >>> >>> a = [] >>> b = {1:'one'} >>> a.append(b) >>> a [{1: 'one'}] >>> b[1] = 'ONE' >>> a [{1: 'ONE'}] >>> ``` Here, after appending the dictionary 'b' to the list 'a', I'm changing the value corresponding to the key 1 in dictionary 'a'. Somehow this change gets r...
Also with **dict** ``` a = [] b = {1:'one'} a.append(dict(b)) print a b[1]='iuqsdgf' print a ``` result ``` [{1: 'one'}] [{1: 'one'}] ```
Modifiying CSV export in scrapy
5,245,047
5
2011-03-09T11:21:30Z
5,245,959
11
2011-03-09T12:43:08Z
[ "python", "csv", "scrapy" ]
I seem to be missing something very simple. All i want to do is use `;` as a delimiter in the CSV exporter instead of `,`. I know the CSV exporter passes kwargs to csv writer, but i cant seem to figure out how to pass this the delimiter. I am calling my spider like so: ``` scrapy crawl spidername --set FEED_URI=outp...
In `contrib/feedexport.py`, ``` class FeedExporter(object): ... def open_spider(self, spider): file = TemporaryFile(prefix='feed-') exp = self._get_exporter(file) # <-- this is where the exporter is instantiated exp.start_exporting() self.slots[spider] = SpiderSlot(file, exp)...
Python: Filter lines from a text file which contain a particular word
5,245,058
5
2011-03-09T11:22:16Z
5,245,216
10
2011-03-09T11:37:03Z
[ "python", "filter", "line" ]
In Python, I want to write a program which filters the lines from my text file which contain the word "apple" and write those lines into a new text file. What I have tried just writes the word "apple" in my new text file, whereas I want whole lines. I am a beginner in Python, so kindly reply to my question, as I really...
Use can get all lines containing 'apple' using a list-comprehension: ``` [ line for line in open('textfile') if 'apple' in line] ``` So - also in one code-line - you can create the new textfile: ``` open('newfile','w').writelines([ line for line in open('textfile') if 'apple' in line]) ```
Python: Filter lines from a text file which contain a particular word
5,245,058
5
2011-03-09T11:22:16Z
5,245,426
7
2011-03-09T11:58:10Z
[ "python", "filter", "line" ]
In Python, I want to write a program which filters the lines from my text file which contain the word "apple" and write those lines into a new text file. What I have tried just writes the word "apple" in my new text file, whereas I want whole lines. I am a beginner in Python, so kindly reply to my question, as I really...
``` from itertools import ifilter with open('source.txt','rb') as f,open('new.txt','wb') as g: g.writelines( ifilter(lambda line: 'apple' in line, f)) ```
Removing duplicate element from a list and the element itself
5,245,872
2
2011-03-09T12:36:42Z
5,246,229
10
2011-03-09T13:08:17Z
[ "python", "list", "unique" ]
I know this question has been asked lots of times, but I am not asking how to remove duplicate elements from a list only, I want to remove the duplicated element as well. For example, if I have a list: ``` x = [1, 2, 5, 3, 4, 1, 5] ``` I want the list to be: ``` x = [2, 3, 4] # removed 1 and 5 since they were repea...
This should be done with a [Counter](http://docs.python.org/library/collections.html#counter-objects) object. It's trivial. ``` from collections import Counter x = [k for k, v in Counter([1, 2, 5, 3, 4, 1, 5]).iteritems() if v == 1] print x ``` Output: ``` [2, 3, 4] ```
Python Fabric gives: Fatal error: No existing session
5,246,416
10
2011-03-09T13:23:34Z
13,273,980
17
2012-11-07T16:29:53Z
[ "python", "fabric" ]
I have the following simple fabfile.py from the docs: ``` from fabric.api import run def host_type(): run('uname -s') ``` I try to run it using: ``` fab -H 192.168.0.201 host_type ``` But get the error: ``` me@ubuntu:~/me$ fab -H 192.168.0.201 host_type [192.168.0.201] run: uname -s Password for me@192.168.0....
Short answer: try the '-k' and '-a' command-line flags if you have more than one SSH public key and want to use password authentication. When I encountered this error, it was the result of a very unique situation. I have many different public keys in ~/.ssh. I also have many of those public keys added to my SSH agent....
How did Python implement the built-in function pow()?
5,246,856
30
2011-03-09T14:01:18Z
5,246,975
29
2011-03-09T14:11:18Z
[ "python", "algorithm", "math" ]
I have to write a program to calculate `a**b % c` where `b` and `c` are both very large numbers. If I just use `a**b % c`, it's really slow. Then I found that the built-in function `pow()` can do this really fast by calling `pow(a, b, c)`. I'm curious to know how does Python implement this? Or where could I find the ...
If `a`, `b` and `c` are integers, the implementation can be made more efficient by [binary exponentiation](http://en.wikipedia.org/wiki/Exponentiation_by_squaring) and reducing modulo `c` in each step, including the first one (i.e. reducing `a` modulo `c` before you even start). This is what [the implementation of `lon...