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
Parsing Meaning from Text
1,140,908
9
2009-07-17T00:05:09Z
1,141,386
8
2009-07-17T03:58:18Z
[ "python", "parsing", "nlp", "lexical-analysis" ]
I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like: "Manny Ramirez makes his return for the Dodgers today against the Houston Astros", what's a light-weight/ easy way of getting t...
Use the [NLTK](http://www.nltk.org/), in particular [chapter 7 on Information Extraction.](http://www.nltk.org/book/ch07.html) You say you want to extract meaning, and there are modules for semantic analysis, but I think IE is all you need--and honestly one of the only areas of NLP computers can handle right now. See...
What's a quick one-liner to remove empty lines from a python string?
1,140,958
29
2009-07-17T00:21:12Z
1,140,966
52
2009-07-17T00:25:15Z
[ "python", "string", "line-endings" ]
I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this? Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. Thanks!
How about: ``` text = os.linesep.join([s for s in text.splitlines() if s]) ``` where `text` is the string with the possible extraneous lines?
What's a quick one-liner to remove empty lines from a python string?
1,140,958
29
2009-07-17T00:21:12Z
1,140,967
10
2009-07-17T00:25:18Z
[ "python", "string", "line-endings" ]
I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this? Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. Thanks!
``` "\n".join([s for s in code.split("\n") if s]) ``` Edit2: ``` text = "".join([s for s in code.splitlines(True) if s.strip("\r\n")]) ``` I think that's my final version. It should work well even with code mixing line endings. I don't think that line with spaces should be considered empty, but if so then simple s.s...
What's a quick one-liner to remove empty lines from a python string?
1,140,958
29
2009-07-17T00:21:12Z
1,141,893
10
2009-07-17T07:46:23Z
[ "python", "string", "line-endings" ]
I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this? Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. Thanks!
``` filter(None, code.splitlines()) filter(str.strip, code.splitlines()) ``` are equivalent to ``` [s for s in code.splitlines() if s] [s for s in code.splitlines() if s.strip()] ``` and might be useful for readability
Why was the 'thread' module renamed to '_thread' in Python 3.x?
1,141,047
8
2009-07-17T01:04:20Z
1,141,058
7
2009-07-17T01:10:56Z
[ "python", "multithreading", "python-3.x" ]
Python 3.x renamed the low-level module 'thread' to '\_thread' -- I don't see why in the documentation. Does anyone know?
I think the old `thread` module is deprecated in favour of the higher level [`threading`](http://docs.python.org/library/threading.html) module.
Why was the 'thread' module renamed to '_thread' in Python 3.x?
1,141,047
8
2009-07-17T01:04:20Z
1,141,059
8
2009-07-17T01:11:12Z
[ "python", "multithreading", "python-3.x" ]
Python 3.x renamed the low-level module 'thread' to '\_thread' -- I don't see why in the documentation. Does anyone know?
It looks like the thread module became obsolete in 3.x in favor of the threading module. See [PEP 3108](http://www.python.org/dev/peps/pep-3108/#obsolete).
Why was the 'thread' module renamed to '_thread' in Python 3.x?
1,141,047
8
2009-07-17T01:04:20Z
1,141,115
10
2009-07-17T01:43:48Z
[ "python", "multithreading", "python-3.x" ]
Python 3.x renamed the low-level module 'thread' to '\_thread' -- I don't see why in the documentation. Does anyone know?
It's been quite a long time since the low-level `thread` module was informally deprecated, with all users heartily encouraged to use the higher-level `threading` module instead; now with the ability to introduce backwards incompatibilities in Python 3, we've made that deprecation rather more than just "informal", that'...
Python networking library for a simple card game
1,141,130
3
2009-07-17T01:51:34Z
1,141,183
8
2009-07-17T02:11:10Z
[ "python", "networking" ]
I'm trying to implement a fairly simple [card game](http://www.sirlin.net/yomi) in Python so that two players can play together other the Internet. I have no problem with doing the GUI, but I don't know the first thing about how to do the networking part. A couple libraries I've found so far: * [PyRO](http://pyro.sour...
Both of those libraries are very good and would work perfectly for your card game. Pyro might be easier to learn and use, but Twisted will scale better if you ever want to move into a very large number of players. Twisted can be daunting at first but there are some books to help you get over the hump. The are some o...
Name this python/ruby language construct (using array values to satisfy function parameters)
1,141,504
18
2009-07-17T05:20:29Z
1,141,520
10
2009-07-17T05:26:05Z
[ "python", "ruby", "syntax", "language-features" ]
What is this language construct called? In Python I can say: ``` def a(b,c): return b+c a(*[4,5]) ``` and get 9. Likewise in Ruby: ``` def a(b,c) b+c end a(*[4,5]) ``` What is this called, when one passes a single array to a function which otherwise requires multiple arguments? What is the name of the `*` operato...
In ruby, it is often called "splat". Also in ruby, you can use it to mean 'all of the other elements in the list'. ``` a, *rest = [1,2,3,4,5,6] a # => 1 rest # => [2, 3, 4, 5, 6] ``` It can also appear on either side of the assignment operator: ``` a = d, *e ``` In this usage, it is a bit like scheme's cdr, ...
Name this python/ruby language construct (using array values to satisfy function parameters)
1,141,504
18
2009-07-17T05:20:29Z
1,141,556
25
2009-07-17T05:44:12Z
[ "python", "ruby", "syntax", "language-features" ]
What is this language construct called? In Python I can say: ``` def a(b,c): return b+c a(*[4,5]) ``` and get 9. Likewise in Ruby: ``` def a(b,c) b+c end a(*[4,5]) ``` What is this called, when one passes a single array to a function which otherwise requires multiple arguments? What is the name of the `*` operato...
The Python docs call this [Unpacking Argument Lists](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists). It's a pretty handy feature. In Python, you can also use a double asterisk (\*\*) to unpack a dictionary (hash) into keyword arguments. They also work in reverse. I can define a function like...
How to modify the local namespace in python
1,142,068
3
2009-07-17T08:43:24Z
1,144,561
8
2009-07-17T17:07:52Z
[ "python", "namespaces", "local" ]
How can I modify the local namespace of a function in python? I know that locals() returns the local namespace of the function when called inside it, but I want to do something like this (I have a reason why I want to do this where g is not accessible to f, but it's quicker to give a trivial, stupid example to illustra...
You've a couple of options. First, note that g in your example isn't actually a local to the function (ie. not assigned within it), it's a global (ie hasn't been assigned to a local variable). This means that it will be looked up in the module the function is defined in. This is fortunate, as there's no way of altering...
Python @property versus method performance - which one to use?
1,142,133
11
2009-07-17T08:58:39Z
1,142,186
18
2009-07-17T09:11:49Z
[ "python", "performance", "properties" ]
I have written some code that uses attributes of an object: ``` class Foo: def __init__(self): self.bar = "baz" myFoo = Foo() print (myFoo.bar) ``` Now I want to do some fancy calculation to return `bar`. I could use `@property` to make methods act as the attribute `bar`, or I could refactor my code to us...
If it's logically a property/attribute of the object, I'd say keep it as a property. If it's likely to become parametrised, by which I mean you may want to invoke `myFoo.bar(someArgs)` then bite the bullet now and make it a method. Under most circumstances, performance is unlikely to be an issue.
Python @property versus method performance - which one to use?
1,142,133
11
2009-07-17T08:58:39Z
1,143,856
15
2009-07-17T15:06:38Z
[ "python", "performance", "properties" ]
I have written some code that uses attributes of an object: ``` class Foo: def __init__(self): self.bar = "baz" myFoo = Foo() print (myFoo.bar) ``` Now I want to do some fancy calculation to return `bar`. I could use `@property` to make methods act as the attribute `bar`, or I could refactor my code to us...
Wondering about performance is needless when it's so easy to measure it: ``` $ python -mtimeit -s'class X(object): > @property > def y(self): return 23 > x=X()' 'x.y' 1000000 loops, best of 3: 0.685 usec per loop $ python -mtimeit -s'class X(object): def y(self): return 23 x=X()' 'x.y()' 1000000 loops, best of ...
Django: Why do some model fields clash with each other?
1,142,378
147
2009-07-17T09:59:08Z
1,142,473
259
2009-07-17T10:20:48Z
[ "python", "django", "django-models" ]
I want to create an object that contains 2 links to Users. For example: ``` class GameClaim(models.Model): target = models.ForeignKey(User) claimer = models.ForeignKey(User) isAccepted = models.BooleanField() ``` but I am getting the following errors when running the server: * > Accessor for field 'targe...
You have two foreign keys to User. Django automatically creates a reverse relation from User back to GameClaim, which is usually `gameclaim_set`. However, because you have two FKs, you would have two `gameclaim_set` attributes, which is obviously impossible. So you need to tell Django what name to use for the reverse r...
python + Spreadsheet
1,142,730
4
2009-07-17T11:34:59Z
8,532,699
9
2011-12-16T10:14:08Z
[ "python", "google-app-engine", "google-spreadsheet" ]
Can anybody please tell me is there any possible way to connect to spreadsheet from python? I want to store some data from a form and submit it to google spreadsheet. Please help on this issue. What steps do I have to follow? Thanks in advance...
The easiest way to connect to Google Spreadsheet is by using this [spreadsheet library](http://burnash.github.com/gspread). These are the steps you need to follow: ``` import gspread # Login with your Google account gc = gspread.login('[email protected]','password') # Spreadsheets can be opened by their title in Goo...
Merge some list items in a Python List
1,142,851
11
2009-07-17T12:03:05Z
1,142,876
20
2009-07-17T12:07:51Z
[ "python", "list", "concatenation" ]
Say I have a list like this: ``` [a, b, c, d, e, f, g] ``` How do modify that list so that it looks like this? ``` [a, b, c, def, g] ``` I would much prefer that it modified the existing list directly, not created a new list.
That example is pretty vague, but maybe something like this? ``` items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] items[3:6] = [''.join(items[3:6])] ``` It basically does a splice (or [assignment to a slice](http://docs.python.org/tutorial/introduction.html#lists)) operation. It removes items 3 to 6 and inserts a new...
Merge some list items in a Python List
1,142,851
11
2009-07-17T12:03:05Z
1,142,879
26
2009-07-17T12:08:15Z
[ "python", "list", "concatenation" ]
Say I have a list like this: ``` [a, b, c, d, e, f, g] ``` How do modify that list so that it looks like this? ``` [a, b, c, def, g] ``` I would much prefer that it modified the existing list directly, not created a new list.
On what basis should the merging take place? Your question is rather vague. Also, I assume a, b, ..., f are supposed to be strings, that is, 'a', 'b', ..., 'f'. ``` >>> x = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> x[3:6] = [''.join(x[3:6])] >>> x ['a', 'b', 'c', 'def', 'g'] ``` Check out the documentation on [sequence...
Create NTFS junction point in Python
1,143,260
8
2009-07-17T13:27:31Z
1,143,329
8
2009-07-17T13:38:16Z
[ "python", "windows", "ntfs", "junction" ]
Is there a way to create an NTFS junction point in Python? I know I can call the `junction` utility, but it would be better not to rely on external tools.
you can use python win32 API modules e.g. ``` import win32file win32file.CreateSymbolicLink(srcDir, targetDir, 1) ``` see <http://docs.activestate.com/activepython/2.5/pywin32/win32file__CreateSymbolicLink_meth.html> for more details if you do not want to rely on that too, you can always use ctypes and directly cal...
Removing duplicates from list of lists in Python
1,143,379
7
2009-07-17T13:45:48Z
1,143,432
24
2009-07-17T13:54:27Z
[ "python", "list" ]
Can anyone suggest a good solution to remove duplicates from nested lists if wanting to evaluate duplicates based on first element of each nested list? The main list looks like this: ``` L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]] ``` If there is another list with the same element at fir...
Do you care about preserving order / which duplicate is removed? If not, then: ``` dict((x[0], x) for x in L).values() ``` will do it. If you want to preserve order, and want to keep the first one you find then: ``` def unique_items(L): found = set() for item in L: if item[0] not in found: ...
Python sorting list of dictionaries by multiple keys
1,143,671
55
2009-07-17T14:36:48Z
1,143,719
18
2009-07-17T14:44:47Z
[ "python" ]
I have a list of dicts: ``` b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'To...
``` def sortkeypicker(keynames): negate = set() for i, k in enumerate(keynames): if k[:1] == '-': keynames[i] = k[1:] negate.add(k[1:]) def getit(adict): composite = [adict[k] for k in keynames] for i, (k, v) in enumerate(zip(keynames, composite)): if...
Python sorting list of dictionaries by multiple keys
1,143,671
55
2009-07-17T14:36:48Z
1,144,405
51
2009-07-17T16:35:39Z
[ "python" ]
I have a list of dicts: ``` b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'To...
This answer works for any kind of column in the dictionary -- the negated column need not be a number. ``` def multikeysort(items, columns): from operator import itemgetter comparers = [((itemgetter(col[1:].strip()), -1) if col.startswith('-') else (itemgetter(col.strip()), 1)) for col in col...
Python sorting list of dictionaries by multiple keys
1,143,671
55
2009-07-17T14:36:48Z
12,925,750
13
2012-10-17T01:15:02Z
[ "python" ]
I have a list of dicts: ``` b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'To...
<http://stygianvision.net/updates/python-sort-list-object-dictionary-multiple-key/> has a nice rundown on various techniques for doing this. If your requirements are simpler than "full bidirectional multikey", take a look. It's clear the accepted answer and the blog post I just referenced influenced each other in some ...
Python sorting list of dictionaries by multiple keys
1,143,671
55
2009-07-17T14:36:48Z
29,849,371
8
2015-04-24T13:54:15Z
[ "python" ]
I have a list of dicts: ``` b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'To...
I know this is a rather old question, but none of the answers mention that Python guarantees a stable sort order for its sorting routines such as `list.sort()` and `sorted()`, which means items that compare equal retain their original order. This means that the equivalent of `ORDER BY name ASC, age DESC` (using SQL no...
How do I convert (or scale) axis values and redefine the tick frequency in matplotlib?
1,143,848
20
2009-07-17T15:05:17Z
1,144,137
30
2009-07-17T15:49:08Z
[ "python", "matplotlib" ]
I am displaying a jpg image (I rotate this by 90 degrees, if this is relevant) and of course the axes display the pixel coordinates. I would like to convert the axis so that instead of displaying the pixel number, it will display my unit of choice - be it radians, degrees, or in my case an astronomical coordinate. I kn...
It looks like you're dealing with the `matplotlib.pyplot` interface, which means that you'll be able to bypass most of the dealing with artists, axes, and the like. You can control the values and labels of the tick marks by using the [`matplotlib.pyplot.xticks`](http://matplotlib.sourceforge.net/api/pyplot_api.html#mat...
Change python file in place
1,145,286
8
2009-07-17T19:41:37Z
1,145,434
7
2009-07-17T20:11:07Z
[ "python", "file" ]
I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files? Thanks!
Say you want to split the file into N pieces, then simply start reading from the back of the file (more or less) and repeatedly call [truncate](http://docs.python.org/library/stdtypes.html?highlight=truncate#file.truncate): > Truncate the file's size. If the optional size argument is present, the file is truncated to ...
Difference between "inspect" and "interactive" command line flags in Python
1,145,428
4
2009-07-17T20:09:49Z
1,145,777
7
2009-07-17T21:28:21Z
[ "python", "command-line", "interpreter" ]
What is the difference between "inspect" and "interactive" flags? The [sys.flags function](http://docs.python.org/library/sys.html#sys.flags) prints both of them. How can they both have "-i" flag according to the documentation of sys.flags? How can I set them separately? If I use "python -i", both of them will be set...
According to [pythonrun.c](http://svn.python.org/view/python/trunk/Python/pythonrun.c?view=markup) corresponding `Py_InspectFlag` and `Py_InteractiveFlag` are used as follows: ``` int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */ /* snip */ static void handle_system_exit(void) { PyObject...
py2exe: Compiled Python Windows Application won't run because of DLL
1,145,662
6
2009-07-17T21:01:13Z
1,145,725
8
2009-07-17T21:14:48Z
[ "python", "wxpython", "py2exe" ]
I will confess I'm very new to Python and I don't really know what I'm doing yet. Recently I created a very small Windows application using Python 2.6.2 and wxPython 2.8. And it works great; I'm quite pleased with how well it works normally. By normally I mean when I invoke it directly through the Python interpreter, l...
You can't just copy msvcr\*.dll - they need to be set up using the rules for side-by-side assemblies. You can do this by installing the redistributable package as Sam points out, or you can put them alongside your executables as long as you obey the rules. See the section "Deploying Visual C++ library DLLs as private ...
Simulating Pointers in Python
1,145,722
42
2009-07-17T21:13:59Z
1,145,747
19
2009-07-17T21:20:22Z
[ "python", "pointers" ]
I'm trying to cross compile an in house language(ihl) to Python. One of the ihl features is pointers and references that behave like you would expect from C or C++. For instance you can do this: ``` a = [1,2]; // a has an array b = &a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); //...
You may want to read [*Semantics of Python variable names from a C++ perspective*](http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/). The bottom line: **All variables are references**. More to the point, don't think in terms of variables, but in terms of objects which can b...
Simulating Pointers in Python
1,145,722
42
2009-07-17T21:13:59Z
1,145,848
66
2009-07-17T21:49:07Z
[ "python", "pointers" ]
I'm trying to cross compile an in house language(ihl) to Python. One of the ihl features is pointers and references that behave like you would expect from C or C++. For instance you can do this: ``` a = [1,2]; // a has an array b = &a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); //...
This can be done explicitly. ``` class ref: def __init__(self, obj): self.obj = obj def get(self): return self.obj def set(self, obj): self.obj = obj a = ref([1, 2]) b = a print a.get() # => [1, 2] print b.get() # => [1, 2] b.set(2) print a.get() # => 2 print b.get() # => 2 ```
Simulating Pointers in Python
1,145,722
42
2009-07-17T21:13:59Z
1,145,884
11
2009-07-17T22:01:56Z
[ "python", "pointers" ]
I'm trying to cross compile an in house language(ihl) to Python. One of the ihl features is pointers and references that behave like you would expect from C or C++. For instance you can do this: ``` a = [1,2]; // a has an array b = &a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); //...
If you're compiling a C-like language, say: ``` func() { var a = 1; var *b = &a; *b = 2; assert(a == 2); } ``` into Python, then all of the "everything in Python is a reference" stuff is a misnomer. It's true that everything in Python is a reference, but the fact that many core types (ints, strings) ...
Simulating Pointers in Python
1,145,722
42
2009-07-17T21:13:59Z
14,000,962
7
2012-12-22T07:32:38Z
[ "python", "pointers" ]
I'm trying to cross compile an in house language(ihl) to Python. One of the ihl features is pointers and references that behave like you would expect from C or C++. For instance you can do this: ``` a = [1,2]; // a has an array b = &a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); //...
Almost exactly like [ephemient](http://stackoverflow.com/users/20713/ephemient) [answer](http://stackoverflow.com/a/1145848/1020470), which I voted up, you could use Python's builtin [property](http://docs.python.org/2/library/functions.html#property) function. It will do something nearly similar to the `ref` class in ...
SQLAlchemy: Scan huge tables using ORM?
1,145,905
26
2009-07-17T22:07:02Z
1,145,941
36
2009-07-17T22:23:39Z
[ "python", "performance", "orm", "sqlalchemy" ]
I am currently playing around with SQLAlchemy a bit, which is really quite neat. For testing I created a huge table containing my pictures archive, indexed by SHA1 hashes (to remove duplicates :-)). Which was impressingly fast... For fun I did the equivalent of a `select *` over the resulting SQLite database: ``` se...
Okay, I just found a way to do this myself. Changing the code to ``` session = Session() for p in session.query(Picture).yield_per(5): print(p) ``` loads only 5 pictures at a time. It seems like the query will load all rows at a time by default. However, I don't yet understand the disclaimer on that method. Quote...
SQLAlchemy: Scan huge tables using ORM?
1,145,905
26
2009-07-17T22:07:02Z
1,217,947
21
2009-08-02T01:28:45Z
[ "python", "performance", "orm", "sqlalchemy" ]
I am currently playing around with SQLAlchemy a bit, which is really quite neat. For testing I created a huge table containing my pictures archive, indexed by SHA1 hashes (to remove duplicates :-)). Which was impressingly fast... For fun I did the equivalent of a `select *` over the resulting SQLite database: ``` se...
here's what I usually do for this situation: ``` def page_query(q): offset = 0 while True: r = False for elem in q.limit(1000).offset(offset): r = True yield elem offset += 1000 if not r: break for item in page_query(Session.query(Picture)): ...
Create instance of a python class , declared in python, with C API
1,147,452
5
2009-07-18T12:38:40Z
1,147,840
15
2009-07-18T15:41:44Z
[ "python", "c", "python-c-api" ]
I want to create an instance of a Python class defined in the `__main__` scope with the C API. For example, the class is called `MyClass` and is defined as follows: ``` class MyClass: def __init__(self): pass ``` The class type lives under `__main__` scope. Within the C application, I want to create an ...
I believe the simplest approach is: ``` /* get sys.modules dict */ PyObject* sys_mod_dict = PyImport_GetModuleDict(); /* get the __main__ module object */ PyObject* main_mod = PyMapping_GetItemString(sys_mod_dict, "__main__"); /* call the class inside the __main__ module */ PyObject* instance = PyObject_CallMethod(mai...
Difference in SHA512 between python hashlib and sha512sum tool
1,147,875
4
2009-07-18T15:56:13Z
1,147,880
14
2009-07-18T15:59:05Z
[ "python", "digest", "sha512", "hashlib" ]
I am getting different message digests from the linux 'sha512sum' tool and the python hashlib library. Here is what I get on my Ubuntu 8.10: ``` $ echo test | sha512sum 0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123 - $ python Python ...
I think the difference is that echo adds a newline character to its output. Try echo -n test | sha512sum
Difference in SHA512 between python hashlib and sha512sum tool
1,147,875
4
2009-07-18T15:56:13Z
1,147,883
10
2009-07-18T16:00:09Z
[ "python", "digest", "sha512", "hashlib" ]
I am getting different message digests from the linux 'sha512sum' tool and the python hashlib library. Here is what I get on my Ubuntu 8.10: ``` $ echo test | sha512sum 0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123 - $ python Python ...
`echo` is adding a newline: ``` $ python -c 'import hashlib; print hashlib.sha512("test\n").hexdigest()' 0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123 ``` To avoid that, use `echo -n`.
Python socket accept blocks - prevents app from quitting
1,148,062
8
2009-07-18T17:23:39Z
1,148,126
9
2009-07-18T17:49:38Z
[ "python", "sockets" ]
I've written a very simple python class which waits for connections on a socket. The intention is to stick this class into an existing app and asyncronously send data to connecting clients. The problem is that when waiting on an socket.accept(), I cannot end my application by pressing ctrl-c. Neither can I detect when...
Add `self.setDaemon(True)` to the `__init__` before `self.start()`. (In Python 2.6 and later, `self.daemon = True` is preferred). The key idea is explained [here](http://docs.python.org/library/threading.html#threading.Thread.daemon): > The entire Python program exits when > no alive non-daemon threads are left. So...
How can I use Sphinx' Autodoc-extension for private methods?
1,149,280
18
2009-07-19T05:07:51Z
6,106,855
8
2011-05-24T07:02:59Z
[ "python", "documentation", "python-sphinx" ]
I am using Sphinx for documenting my python project. I have the autodoc extension enabled and have the following in my docs. ``` .. autoclass:: ClassName :members: ``` The problem is, it only documents the [non-private methods](http://sphinx.pocoo.org/ext/autodoc.html) in the class. How do I include the private me...
One way to get around this is to explicitly force Sphinx to document private members. You can do this by appending `automethod` to the end of the class level docs: ``` class SmokeMonster(object): """ A large smoke monster that protects the island. """ def __init__(self,speed): """ :param speed:...
How can I use Sphinx' Autodoc-extension for private methods?
1,149,280
18
2009-07-19T05:07:51Z
7,740,295
18
2011-10-12T12:47:28Z
[ "python", "documentation", "python-sphinx" ]
I am using Sphinx for documenting my python project. I have the autodoc extension enabled and have the following in my docs. ``` .. autoclass:: ClassName :members: ``` The problem is, it only documents the [non-private methods](http://sphinx.pocoo.org/ext/autodoc.html) in the class. How do I include the private me...
if you are using sphinx 1.1 or above, from the sphinx documentation site at <http://sphinx.pocoo.org/ext/autodoc.html>, ``` :special-members: :private-members: ```
Exploring and decompiling python bytecode
1,149,513
12
2009-07-19T08:59:47Z
1,149,590
7
2009-07-19T10:00:58Z
[ "python", "decompiling" ]
Lets say I have: ``` >>> def test(a): >>> print a ``` Now, I want to explore see how test looks like in its compiled form. ``` >>> test.func_code.co_code '|\x00\x00GHd\x00\x00S' ``` I can get the disassembled form using the **dis** module: ``` >>> import dis >>> dis.dis(test) 2 0 LOAD_FAST ...
**UnPyc** <http://sourceforge.net/projects/unpyc/> It is a maintained fork of the old decompyle updated to work with 2.5 and 2.6.
python and ruby - for what to use it?
1,149,581
8
2009-07-19T09:56:34Z
1,149,595
11
2009-07-19T10:08:03Z
[ "python", "ruby" ]
I'm thinking about learning ruby and python a little bit, and it occurred to me, for what ruby/python is good for? When to use ruby and when python, or for what ruby/python is not for? :) What should I do in these languages? thanks
They are good for mostly for rapid prototyping, quick development, dynamic programs, web applications and scripts. They're general purpose languages, so you can use them for pretty much everything you want. You'll have smaller development times (compared to, say, Java or C++), but worse performance and less static erro...
Pythonic Swap?
1,149,802
13
2009-07-19T12:29:16Z
1,149,804
15
2009-07-19T12:31:08Z
[ "python", "swap" ]
I found that i have to perform a swap in python and i write something like this. ``` arr[first], arr[second] = arr[second], arr[first] ``` I suppose this is not so pythonic. Does somebody know how to do a swap in python more elegent? **EDIT:** I think another example will show my doubts ``` self.memberlist[someinde...
``` a, b = b, a ``` [Is a perfectly Pythonic idiom.](http://love-python.blogspot.com/2008/02/swap-values-python-way.html) It is short and readable, as long as your variable names are short enough.
Pythonic Swap?
1,149,802
13
2009-07-19T12:29:16Z
1,150,272
12
2009-07-19T16:36:43Z
[ "python", "swap" ]
I found that i have to perform a swap in python and i write something like this. ``` arr[first], arr[second] = arr[second], arr[first] ``` I suppose this is not so pythonic. Does somebody know how to do a swap in python more elegent? **EDIT:** I think another example will show my doubts ``` self.memberlist[someinde...
The one thing I might change in your example code: if you're going to use some long name such as `self.memberlist` over an over again, it's often more readable to alias ("assign") it to a shorter name first. So for example instead of the long, hard-to-read: ``` self.memberlist[someindexA], self.memberlist[someindexB] ...
Can I create a Python extension module in D (instead of C)
1,150,093
14
2009-07-19T15:10:18Z
1,150,107
14
2009-07-19T15:21:32Z
[ "python", "module", "d" ]
I hear D is link-compatible with C. I'd like to use D to create an extension module for Python. Am I overlooking some reason why it's never going to work?
Wait? Something like this <http://pyd.dsource.org/>
Generating random sentences from custom text in Python's NLTK?
1,150,144
5
2009-07-19T15:41:58Z
1,481,492
7
2009-09-26T15:50:57Z
[ "python", "random", "nltk" ]
I'm having trouble with the NLTK under Python, specifically the .generate() method. > generate(self, length=100) > > Print random text, generated using a trigram language model. > > Parameters: > > ``` > * length (int) - The length of text to generate (default=100) > ``` Here is a simplified version of what I am a...
You should be "training" the Markov model with multiple sequences, so that you accurately sample the starting state probabilities as well (called "pi" in Markov-speak). If you use a single sequence then you will always start in the same state. In the case of Orwell's 1984 you would want to use sentence tokenization fi...
Source interface with Python and urllib2
1,150,332
29
2009-07-19T17:05:12Z
1,150,408
22
2009-07-19T17:36:44Z
[ "python", "urllib2" ]
How do i set the source IP/interface with Python and urllib2?
This seems to work. ``` import urllib2, httplib, socket class BindableHTTPConnection(httplib.HTTPConnection): def connect(self): """Connect to the host and port specified in __init__.""" self.sock = socket.socket() self.sock.bind((self.source_ip, 0)) if isinstance(self.timeout, float): s...
Source interface with Python and urllib2
1,150,332
29
2009-07-19T17:05:12Z
1,150,423
44
2009-07-19T17:43:41Z
[ "python", "urllib2" ]
How do i set the source IP/interface with Python and urllib2?
Unfortunately the stack of standard library modules in use (urllib2, httplib, socket) is somewhat badly designed for the purpose -- at the key point in the operation, `HTTPConnection.connect` (in httplib) delegates to `socket.create_connection`, which in turn gives you no "hook" whatsoever between the creation of the s...
Source interface with Python and urllib2
1,150,332
29
2009-07-19T17:05:12Z
14,669,175
9
2013-02-03T03:16:40Z
[ "python", "urllib2" ]
How do i set the source IP/interface with Python and urllib2?
Here's a further refinement that makes use of [HTTPConnection's source\_address argument](http://docs.python.org/2/library/httplib.html#httplib.HTTPConnection) (introduced in Python 2.7): ``` import functools import httplib import urllib2 class BoundHTTPHandler(urllib2.HTTPHandler): def __init__(self, source_add...
Compile the Python interpreter statically?
1,150,373
34
2009-07-19T17:23:56Z
1,155,092
26
2009-07-20T18:21:42Z
[ "c++", "python", "c", "compilation" ]
I'm building a special-purpose embedded Python interpreter and want to avoid having dependencies on dynamic libraries so I want to compile the interpreter with static libraries instead (e.g. `libc.a` not `libc.so`). I would also like to statically link all dynamic libraries that are part of the Python standard library...
I found this (mainly concerning static compilation of Python modules): * <http://bytes.com/groups/python/23235-build-static-python-executable-linux> Which describes a file used for configuration located here: ``` <Python_Source>/Modules/Setup ``` If this file isn't present, it can be created by copying: ``` <Pytho...
How to escape a hash (#) char in python?
1,150,581
3
2009-07-19T18:52:16Z
1,150,586
7
2009-07-19T18:54:25Z
[ "python", "odbc", "escaping", "pyodbc" ]
I'm using pyodbc to query an AS400 (unfortunately), and some column names have hashes in them! Here is a small example: ``` self.cursor.execute('select LPPLNM, LPPDR# from BSYDTAD.LADWJLFU') for row in self.cursor: p = Patient() p.last = row.LPPLNM p.pcp = row.LPPDR# ``` I get errors like this obviously: ...
Use the `getattr` function ``` p.pcp = getattr(row, "LPPDR#") ``` This is, in general, the way that you deal with attributes which aren't legal Python identifiers. For example, you can say ``` setattr(p, "&)(@#$@!!~%&", "Hello World!") print getattr(p, "&)(@#$@!!~%&") # prints "Hello World!" ``` Also, as JG sugges...
A question regarding string instance uniqueness in python
1,150,765
3
2009-07-19T20:15:45Z
1,150,943
10
2009-07-19T21:24:36Z
[ "python", "string", "instance", "uniqueidentifier" ]
I was trying to figure out which integers python only instantiates once (-6 to 256 it seems), and in the process stumbled on some string behaviour I can't see the pattern in. Sometimes, equal strings created in different ways share the same id, sometimes not. This code: ``` A = "10000" B = "10000" C = "100" + "00" D =...
In terms of language specification, any compliant Python compiler and runtime is fully allowed, for any instance of an immutable type, to make a new instance OR find an existing instance of the same type that's equal to the required value and use a new reference to that same instance. This means it's always incorrect t...
Multiple regression in Python
1,151,088
4
2009-07-19T22:41:02Z
1,152,136
9
2009-07-20T07:33:51Z
[ "python", "math", "scipy", "regression" ]
I am currently using scipy's linregress function for single regression. I am unable to find if the same library, or another, is able to do multiple regression, that is, one dependent variable and more than one independent variable. I'd like to avoid R if possible. If you're wondering, I am doing FX market analysis with...
Use the OLS class [<http://www.scipy.org/Cookbook/OLS>] from the SciPy cookbook.
Equivalent of NotImplementedError for fields in Python
1,151,212
32
2009-07-19T23:48:42Z
1,151,260
34
2009-07-20T00:08:11Z
[ "python", "abstract-class" ]
In Python 2.x when you want to mark a method as abstract, you can define it like so: ``` class Base: def foo(self): raise NotImplementedError("Subclasses should implement this!") ``` Then if you forget to override it, you get a nice reminder exception. Is there an equivalent way to mark a field as abstrac...
Yes, you can. Use the `@property` decorator. For instance, if you have a field called "example" then can't you do something like this: ``` class Base(object): @property def example(self): raise NotImplementedError("Subclasses should implement this!") ``` Running the following produces a `NotImplement...
Equivalent of NotImplementedError for fields in Python
1,151,212
32
2009-07-19T23:48:42Z
1,151,275
23
2009-07-20T00:15:49Z
[ "python", "abstract-class" ]
In Python 2.x when you want to mark a method as abstract, you can define it like so: ``` class Base: def foo(self): raise NotImplementedError("Subclasses should implement this!") ``` Then if you forget to override it, you get a nice reminder exception. Is there an equivalent way to mark a field as abstrac...
Alternate answer: ``` @property def NotImplementedField(self): raise NotImplementedError class a(object): x = NotImplementedField class b(a): # x = 5 pass b().x a().x ``` This is like Evan's, but concise and cheap--you'll only get a single instance of NotImplementedField.
Error on connecting to Oracle from py2exe'd program: Unable to acquire Oracle environment handle
1,151,557
5
2009-07-20T02:57:13Z
1,151,577
8
2009-07-20T03:10:38Z
[ "python", "oracle", "py2exe", "cx-oracle" ]
My python program (Python 2.6) works fine when I run it using the Python interpreter, it connects to the Oracle database (10g XE) without error. However, when I compile it using py2exe, the executable version fails with "Unable to acquire Oracle environment handle" at the call to cx\_Oracle.connect(). I've tried the f...
Did you make sure to exclude the OCI.dll when you built with py2exe? If the version of the DLL on your machine is incompatible with the client version on another machine you test it on (I noticed you tried a 11g client but 10g on your machine), then this configuration will not work (I forget the actual error message th...
Python hashable dicts
1,151,658
47
2009-07-20T04:04:30Z
1,151,686
39
2009-07-20T04:18:04Z
[ "python" ]
As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different pa...
Hashables should be immutable -- not enforcing this but TRUSTING you not to mutate a dict after its first use as a key, the following approach would work: ``` class hashabledict(dict): def __key(self): return tuple((k,self[k]) for k in sorted(self)) def __hash__(self): return hash(self.__key()) def __eq_...
Python hashable dicts
1,151,658
47
2009-07-20T04:04:30Z
1,151,705
34
2009-07-20T04:30:24Z
[ "python" ]
As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different pa...
Here is the easy way to make a hashable dictionary. Just remember not to mutate them after embedding in another dictionary for obvious reasons. ``` class hashabledict(dict): def __hash__(self): return hash(tuple(sorted(self.items()))) ```
Python hashable dicts
1,151,658
47
2009-07-20T04:04:30Z
2,705,638
8
2010-04-24T18:24:55Z
[ "python" ]
As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different pa...
A reasonably clean, straightforward implementation is ``` import collections class FrozenDict(collections.Mapping): """Don't forget the docstrings!!""" def __init__(self, *args, **kwargs): self._d = dict(*args, **kwargs) def __iter__(self): return iter(self._d) def __len__(self): ...
Python hashable dicts
1,151,658
47
2009-07-20T04:04:30Z
6,014,481
18
2011-05-16T07:50:01Z
[ "python" ]
As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different pa...
The given answers are okay, but they could be improved by using `frozenset(...)` instead of `tuple(sorted(...))` to generate the hash: ``` >>> import timeit >>> timeit.timeit('hash(tuple(sorted(d.iteritems())))', "d = dict(a=3, b='4', c=2345, asdfsdkjfew=0.23424, x='sadfsadfadfsaf')") 4.7758948802947998 >>> timeit.tim...
Python hashable dicts
1,151,658
47
2009-07-20T04:04:30Z
16,162,138
16
2013-04-23T06:07:31Z
[ "python" ]
As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different pa...
All that is needed to make dictionaries usable for your purpose is to add a \_\_hash\_\_ method: ``` class Hashabledict(dict): def __hash__(self): return hash(frozenset(self)) ``` Note, the *frozenset* conversion will work for all dictionaries (i.e. it doesn't require the keys to be sortable). Likewise, t...
How can I perform a ping or traceroute using native python?
1,151,771
4
2009-07-20T05:01:59Z
7,018,928
7
2011-08-10T22:57:19Z
[ "python", "ping", "traceroute" ]
I would like to be able to perform a ping and traceroute from within Python without having to execute the corresponding shell commands so I'd prefer a native python solution.
If you don't mind using an external module and not using UDP or TCP, [scapy](http://www.secdev.org/projects/scapy/) is an easy solution: ``` from scapy.all import * target = ["192.168.1.254"] result, unans = traceroute(target,l4=UDP(sport=RandShort())/DNS(qd=DNSQR(qname="www.google.com"))) ``` Or you can use the tcp ...
Python iterators – how to dynamically assign self.next within a new style class?
1,152,238
11
2009-07-20T08:07:03Z
1,152,353
8
2009-07-20T08:33:45Z
[ "python", "iterator" ]
As part of some WSGI middleware I want to write a python class that wraps an iterator to implement a close method on the iterator. This works fine when I try it with an old-style class, but throws a TypeError when I try it with a new-style class. What do I need to do to get this working with a new-style class? Exampl...
What you're trying to do makes sense, but there's something evil going on inside Python here. ``` class foo(object): c = 0 def __init__(self): self.next = self.next2 def __iter__(self): return self def next(self): if self.c == 5: raise StopIteration self.c += 1 ...
Alternative to the `match = re.match(); if match: ...` idiom?
1,152,385
23
2009-07-20T08:40:43Z
1,152,490
11
2009-07-20T09:06:08Z
[ "python", "code-golf", "idioms" ]
If you want to check if something matches a regex, if so, print the first group, you do.. ``` import re match = re.match("(\d+)g", "123g") if match is not None: print match.group(1) ``` This is completely pedantic, but the intermediate `match` variable is a bit annoying.. Languages like Perl do this by creating ...
I don't think it's trivial. I don't want to have to sprinkle a redundant conditional around my code if I'm writing code like that often. This is slightly odd, but you can do this with an iterator: ``` import re def rematch(pattern, inp): matcher = re.compile(pattern) matches = matcher.match(inp) if match...
django documentation locally setting up
1,152,479
6
2009-07-20T09:03:42Z
1,152,499
8
2009-07-20T09:08:29Z
[ "python", "django", "python-sphinx" ]
I was trying to setup django . I do have Django-1.1-alpha-1. I was trying to make the documentation which is located at Django-1.1-alpha-1/doc using make utility. But I am getting some error saying ``` > C:\django\Django-1.1-alpha-1\docs>C:\cygwin\bin\make.exe html mkdir -p _build/html _build/doctrees sphinx-build...
Install [sphinx](http://sphinx.pocoo.org/). ``` $ easy_install -U Sphinx ```
Is it better to use an exception or a return code in Python?
1,152,541
34
2009-07-20T09:18:45Z
1,152,556
31
2009-07-20T09:21:54Z
[ "python", "performance", "exception" ]
You may know this recommendation from Microsoft about the use of exceptions in .NET: > Performance Considerations > > ... > > Throw exceptions only for > extraordinary conditions, ... > > In addition, do not throw an exception > when a return code is sufficient... (See the whole text at <http://msdn.microsoft.com/en-...
The pythonic thing to do is to raise and handle exceptions. The excellent book "Python in a nutshell" discusses this in 'Error-Checking Strategies' in Chapter 6. The book discusses EAFP ("it's easier to ask forgiveness than permission") vs. LBYL ("look before you leap"). So to answer your question: No, I would not r...
Is it better to use an exception or a return code in Python?
1,152,541
34
2009-07-20T09:18:45Z
1,152,562
7
2009-07-20T09:23:05Z
[ "python", "performance", "exception" ]
You may know this recommendation from Microsoft about the use of exceptions in .NET: > Performance Considerations > > ... > > Throw exceptions only for > extraordinary conditions, ... > > In addition, do not throw an exception > when a return code is sufficient... (See the whole text at <http://msdn.microsoft.com/en-...
In Python exceptions are not very expensive like they are in some other languages, so I wouldn't recommend trying to avoid exceptions. But if you do throw an exception you would usually want catch it somewhere in your code, the exception being if a fatal error occurs.
Is it better to use an exception or a return code in Python?
1,152,541
34
2009-07-20T09:18:45Z
1,153,109
7
2009-07-20T11:49:51Z
[ "python", "performance", "exception" ]
You may know this recommendation from Microsoft about the use of exceptions in .NET: > Performance Considerations > > ... > > Throw exceptions only for > extraordinary conditions, ... > > In addition, do not throw an exception > when a return code is sufficient... (See the whole text at <http://msdn.microsoft.com/en-...
Usually, Python is geared towards expressiveness. I would apply the same principle here: usually, you expect a function to return a **result** (in line with its name!) and not an error code. For this reason, it is usually better raising an exception than returning an error code. However, what is stated in the MSDN...
Is it better to use an exception or a return code in Python?
1,152,541
34
2009-07-20T09:18:45Z
1,153,149
8
2009-07-20T12:02:16Z
[ "python", "performance", "exception" ]
You may know this recommendation from Microsoft about the use of exceptions in .NET: > Performance Considerations > > ... > > Throw exceptions only for > extraordinary conditions, ... > > In addition, do not throw an exception > when a return code is sufficient... (See the whole text at <http://msdn.microsoft.com/en-...
The best way to understand exceptions is "[if your method can't do what its name says it does, throw](http://www.hanselman.com/blog/IfYourMethodCantDoWhatItsNamePromisesItCanThrow.aspx)." My personal opinion is that this advice should be applied equally to both .NET and Python. The key difference is where you have met...
Simple python / Beautiful Soup type question
1,153,167
3
2009-07-20T12:05:38Z
1,153,182
7
2009-07-20T12:08:10Z
[ "python", "string", "beautifulsoup" ]
I'm trying to do some simple string manipulation with the href attribute of a hyperlink extracted using [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/): ``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('<a href="http://www.some-site.com/">Some Hyperlink</a>') href = soup.find("a")["href...
Python strings do not have an `indexOf` method. Use `href.index('/')` `href.find('/')` is similar. But `find` returns `-1` if the string is not found, while `index` raises a `ValueError`. So the correct thing is to use `index` (since '...'[-1] will return the last character of the string).
Mercurial scripting with python
1,153,469
28
2009-07-20T13:08:01Z
1,153,698
8
2009-07-20T13:49:47Z
[ "python", "documentation", "mercurial", "revision" ]
I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python. The reason is that I want to add it to the css/js files on our website like so: ``` <link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" /> ``` So that whenever a change is made to t...
Do you mean [this documentation](http://mercurial.selenic.com/wiki/MercurialApi)? Note that, as stated in that page, there is no *official* API, because they still reserve the right to change it at any time. But you can see the list of changes in the last few versions, it is not very extensive.
Mercurial scripting with python
1,153,469
28
2009-07-20T13:08:01Z
1,154,440
14
2009-07-20T16:06:03Z
[ "python", "documentation", "mercurial", "revision" ]
I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python. The reason is that I want to add it to the css/js files on our website like so: ``` <link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" /> ``` So that whenever a change is made to t...
It's true there's no official API, but you can get an idea about best practices by reading other extensions, particularly those bundled with hg. For this particular problem, I would do something like this: ``` from mercurial import ui, hg from mercurial.node import hex repo = hg.repository('/path/to/repo/root', ui.ui...
Integrate Python And C++
1,153,577
29
2009-07-20T13:28:04Z
1,153,604
7
2009-07-20T13:31:37Z
[ "c++", "python", "integration" ]
I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution. Is it possible to integrate C++ and Python in the same project?
Yes, it is possible, encouraged and [documented](http://docs.python.org/extending/extending.html). I have done it myself and found it to be very easy.
Integrate Python And C++
1,153,577
29
2009-07-20T13:28:04Z
1,153,635
53
2009-07-20T13:35:54Z
[ "c++", "python", "integration" ]
I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution. Is it possible to integrate C++ and Python in the same project?
Interfacing Python with C/C++ is not an easy task. Here I copy/paste a [previous answer](http://stackoverflow.com/questions/456884/extending-python-to-swig-or-not-to-swig/456949#456949) on a previous question for the different methods to write a python extension. Featuring Boost.Python, SWIG, Pybindgen... * You can w...
How do I debug a py2exe 'application failed to initialize properly' error?
1,153,643
7
2009-07-20T13:37:08Z
1,154,736
9
2009-07-20T17:11:13Z
[ "python", "wxpython", "py2exe" ]
I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out py2exe. But I haven't been able to get it to work. It would always compile an e...
Note that there is a later version of the Visual C++ 2008 Redistributable package: [SP1](http://www.microsoft.com/downloads/info.aspx?na=47&p=2&SrcDisplayLang=en&SrcCategoryId=&SrcFamilyId=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&u=details.aspx%3ffamilyid%3dA5C84275-3B97-4AB7-A40D-3802B2AF5FC2%26displaylang%3den). However,...
PyQt: how to handle auto-resize of widgets when their content changes
1,153,714
9
2009-07-20T13:53:55Z
1,166,388
7
2009-07-22T16:08:31Z
[ "c++", "python", "qt", "qt4", "pyqt4" ]
I am having some issues with the size of qt4 widgets when their content changes. I will illustrate my problems with two simple scenarios: Scenario 1: I have a QLineEdit widget. Sometimes, when I'm changing its content using QLineEdit.setText(), the one-line string doesn't fit into the widget at its current size anym...
I'm answering in C++ here, since that's what I'm most familiar with, and your problem isn't specific to PyQt. Normally, you just need to call `QWidget::updateGeometry()` when the `sizeHint()` may have changed, just like you need to call `QWidget::update()` when the contents may have changed. Your problem, however, is...
SQLAlchemy and django, is it production ready?
1,154,331
21
2009-07-20T15:44:44Z
1,155,407
17
2009-07-20T19:21:06Z
[ "python", "database", "django", "sqlalchemy" ]
Has anyone used `SQLAlchemy` in addition to `Django`'s ORM? I'd like to use Django's ORM for object manipulation and SQLalchemy for complex queries (like those that require left outer joins). Is it possible? Note: I'm aware about `django-sqlalchemy` but the project doesn't seem to be production ready.
What I would do, 1. Define the schema in Django orm, let it write the db via syncdb. You get the admin interface. 2. In view1 you need a complex join ``` def view1(request): import sqlalchemy data = sqlalchemy.complex_join_magic(...) ... payload = {'data': data, ...} return rend...
How to run statistics Cumulative Distribution Function and Probablity Density Function using SciPy?
1,154,378
4
2009-07-20T15:55:52Z
1,154,859
8
2009-07-20T17:35:06Z
[ "python", "statistics", "scipy", "probability" ]
I am new to Python and new to SciPy libraries. I wanted to take some ques from the experts here on the list before dive into SciPy world. I was wondering if some one could provide a rough guide about how to run two stats functions: Cumulative Distribution Function (CDF) and Probability Distribution Function (PDF). My...
See this article: [Probability distributions in SciPy](http://www.johndcook.com/blog/2009/07/20/probability-distributions-scipy/).
Python: List initialization differences
1,154,494
3
2009-07-20T16:17:33Z
1,154,521
15
2009-07-20T16:24:26Z
[ "python", "list" ]
I want a list full of the same thing, where the thing will either be a string or a number. Is there a difference in the way these two list are created? Is there anything hidden that I should probably know about? ``` list_1 = [0] * 10 list_2 = [0 for i in range(10)] ``` Are there any better ways to do this same task?...
It depends on whether your list elements are mutable, if they are, there'll be a difference: ``` >>> l = [[]] * 10 >>> l [[], [], [], [], [], [], [], [], [], []] >>> l[0].append(1) >>> l [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] >>> l = [[] for i in range(10)] >>> l[0].append(1) >>> l [[1], [], [], [], [], []...
Count occurrence of a character in a string
1,155,617
433
2009-07-20T20:00:36Z
1,155,636
31
2009-07-20T20:03:19Z
[ "python", "string", "count" ]
What's the simplest way to count the number of occurrences of a character in a string? e.g. count the number of times `'a'` appears in `'Mary had a little lamb'`
Regular expressions maybe? ``` import re my_string = "Mary had a little lamb" len(re.findall("a", my_string)) ```
Count occurrence of a character in a string
1,155,617
433
2009-07-20T20:00:36Z
1,155,647
617
2009-07-20T20:04:26Z
[ "python", "string", "count" ]
What's the simplest way to count the number of occurrences of a character in a string? e.g. count the number of times `'a'` appears in `'Mary had a little lamb'`
> [str.count(sub[, start[, end]])](https://docs.python.org/2/library/stdtypes.html#str.count) > > Return the number of non-overlapping occurrences of substring `sub` in the range `[start, end]`. Optional arguments `start` and `end` are interpreted as in slice notation. ``` >>> sentence = 'Mary had a little lamb' >>> s...
Count occurrence of a character in a string
1,155,617
433
2009-07-20T20:00:36Z
1,155,648
76
2009-07-20T20:04:45Z
[ "python", "string", "count" ]
What's the simplest way to count the number of occurrences of a character in a string? e.g. count the number of times `'a'` appears in `'Mary had a little lamb'`
You can use [count()](https://docs.python.org/2/library/string.html#string.count) : ``` >>> 'Mary had a little lamb'.count('a') 4 ```
Count occurrence of a character in a string
1,155,617
433
2009-07-20T20:00:36Z
1,155,649
20
2009-07-20T20:04:47Z
[ "python", "string", "count" ]
What's the simplest way to count the number of occurrences of a character in a string? e.g. count the number of times `'a'` appears in `'Mary had a little lamb'`
``` myString.count('a'); ``` more info [here](http://docs.python.org/library/stdtypes.html)
Count occurrence of a character in a string
1,155,617
433
2009-07-20T20:00:36Z
1,155,652
13
2009-07-20T20:05:03Z
[ "python", "string", "count" ]
What's the simplest way to count the number of occurrences of a character in a string? e.g. count the number of times `'a'` appears in `'Mary had a little lamb'`
``` "aabc".count("a") ```
Count occurrence of a character in a string
1,155,617
433
2009-07-20T20:00:36Z
11,768,336
51
2012-08-01T22:12:08Z
[ "python", "string", "count" ]
What's the simplest way to count the number of occurrences of a character in a string? e.g. count the number of times `'a'` appears in `'Mary had a little lamb'`
As other answers said, using the string method count() is probably the simplest, but if you're doing this frequently, check out collections.Counter: ``` from collections import Counter str = "Mary had a little lamb" counter = Counter(str) print counter['a'] ```
Print current call stack from a method in Python code
1,156,023
141
2009-07-20T21:24:05Z
1,156,048
161
2009-07-20T21:27:43Z
[ "python", "debugging", "stack-trace" ]
In Python, how can I print the current call stack from within a method (for debugging purposes).
Here's an example of getting the stack via the [traceback](http://docs.python.org/library/traceback.html) module, and printing it: ``` import traceback def f(): g() def g(): for line in traceback.format_stack(): print(line.strip()) f() # Prints: # File "so-stack.py", line 10, in <module> # f() ...
Print current call stack from a method in Python code
1,156,023
141
2009-07-20T21:24:05Z
1,156,055
46
2009-07-20T21:28:14Z
[ "python", "debugging", "stack-trace" ]
In Python, how can I print the current call stack from within a method (for debugging purposes).
``` import traceback traceback.print_stack() ```
Print current call stack from a method in Python code
1,156,023
141
2009-07-20T21:24:05Z
16,200,714
11
2013-04-24T19:37:20Z
[ "python", "debugging", "stack-trace" ]
In Python, how can I print the current call stack from within a method (for debugging purposes).
`inspect.stack()` returns the current stack rather than the exception traceback: ``` import inspect print inspect.stack() ``` See <https://gist.github.com/FredLoney/5454553> for a log\_stack utility function.
Python search in lists of lists
1,156,087
28
2009-07-20T21:34:26Z
1,156,114
20
2009-07-20T21:39:56Z
[ "python", "list" ]
I have a list of two-item lists and need to search for things in it. If the list is: ``` list =[ ['a','b'], ['a','c'], ['b','d'] ] ``` I can search for a pair easily by doing ``` ['a','b'] in list ``` Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do thi...
You're always going to have a loop - someone might come along with a clever one-liner that hides the loop within a call to `map()` or similar, but it's always going to be there. My preference would always be to have clean and simple code, unless performance is a major factor. Here's perhaps a more Pythonic version of...
Python search in lists of lists
1,156,087
28
2009-07-20T21:34:26Z
1,156,128
7
2009-07-20T21:43:54Z
[ "python", "list" ]
I have a list of two-item lists and need to search for things in it. If the list is: ``` list =[ ['a','b'], ['a','c'], ['b','d'] ] ``` I can search for a pair easily by doing ``` ['a','b'] in list ``` Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do thi...
``` >>> my_list =[ ['a', 'b'], ['a', 'c'], ['b', 'd'] ] >>> 'd' in (x[1] for x in my_list) True ``` Editing to add: Both David's answer using **any** and mine using **in** will end when they find a match since we're using generator expressions. Here is a test using an infinite generator to show that: ``` def mygen()...
Python search in lists of lists
1,156,087
28
2009-07-20T21:34:26Z
1,156,143
34
2009-07-20T21:47:27Z
[ "python", "list" ]
I have a list of two-item lists and need to search for things in it. If the list is: ``` list =[ ['a','b'], ['a','c'], ['b','d'] ] ``` I can search for a pair easily by doing ``` ['a','b'] in list ``` Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do thi...
Nothing against RichieHindle's and Anon's answers, but here's how I'd write it: ``` data = [['a','b'], ['a','c'], ['b','d']] search = 'c' any(e[1] == search for e in data) ``` Like RichieHindle said, there is a hidden loop in the implementation of `any` (although I think it breaks out of the loop as soon as it finds ...
Python search in lists of lists
1,156,087
28
2009-07-20T21:34:26Z
1,156,145
13
2009-07-20T21:47:41Z
[ "python", "list" ]
I have a list of two-item lists and need to search for things in it. If the list is: ``` list =[ ['a','b'], ['a','c'], ['b','d'] ] ``` I can search for a pair easily by doing ``` ['a','b'] in list ``` Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do thi...
``` >>> the_list =[ ['a','b'], ['a','c'], ['b''d'] ] >>> any('c' == x[1] for x in the_list) True ```
Python search in lists of lists
1,156,087
28
2009-07-20T21:34:26Z
1,158,136
9
2009-07-21T09:25:00Z
[ "python", "list" ]
I have a list of two-item lists and need to search for things in it. If the list is: ``` list =[ ['a','b'], ['a','c'], ['b','d'] ] ``` I can search for a pair easily by doing ``` ['a','b'] in list ``` Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do thi...
the above all look good but do you want to keep the result? if so... you can use the following ``` result = [element for element in data if element[1] == search] ``` then a simple ``` len(result) ``` lets you know if anything was found (and now you can do stuff with the results) **of course** this does not hand...
Having Django serve downloadable files
1,156,246
155
2009-07-20T22:10:30Z
1,156,490
62
2009-07-20T23:20:15Z
[ "python", "django", "download" ]
I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded. For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt And on the server, I know that all downloadable files reside in a folder "/home/user/files/". Is...
A "download" is simply an HTTP header change. See <http://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment> for how to respond with a download. You only need one URL definition for `"/download"`. The request's `GET` or `POST` dictionary will have the ...
Having Django serve downloadable files
1,156,246
155
2009-07-20T22:10:30Z
1,158,750
126
2009-07-21T11:57:59Z
[ "python", "django", "download" ]
I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded. For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt And on the server, I know that all downloadable files reside in a folder "/home/user/files/". Is...
For the "best of both worlds" you could combine S.Lott's solution with the [xsendfile module](http://www.google.com.ng/search?q=mod_xsendfile&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a): django generates the path to the file (or the file itself), but the actual file serving is handled by Apa...
Having Django serve downloadable files
1,156,246
155
2009-07-20T22:10:30Z
4,565,501
24
2010-12-30T19:17:20Z
[ "python", "django", "download" ]
I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded. For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt And on the server, I know that all downloadable files reside in a folder "/home/user/files/". Is...
S.Lott has the "good"/simple solution, and elo80ka has the "best"/efficient solution. Here is a middle "better"/middle solution - no server setup, but more efficient for large files than the naive fix. <http://djangosnippets.org/snippets/365/> Basically django still handles serving the file, but does not load the who...
Having Django serve downloadable files
1,156,246
155
2009-07-20T22:10:30Z
5,301,921
11
2011-03-14T17:10:18Z
[ "python", "django", "download" ]
I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded. For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt And on the server, I know that all downloadable files reside in a folder "/home/user/files/". Is...
It was mentioned above that the mod\_xsendfile method does not allow for non-ASCII characters in filenames. For this reason, I have a patch available for mod\_xsendfile that will allow any file to be sent, as long as the name is url encoded, and the additional header: ``` X-SendFile-Encoding: url ``` Is sent as well...
Having Django serve downloadable files
1,156,246
155
2009-07-20T22:10:30Z
18,985,653
8
2013-09-24T15:22:06Z
[ "python", "django", "download" ]
I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded. For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt And on the server, I know that all downloadable files reside in a folder "/home/user/files/". Is...
Tried @Rocketmonkeys solution but downloaded files were being stored as \*.bin and given random names. That's not fine of course. Adding another line from @elo80ka solved the problem. Here is the code I'm using now: ``` filename = "/home/stackoverflow-addict/private-folder(not-porn)/image.jpg" wrapper = FileWrapper(...
Having Django serve downloadable files
1,156,246
155
2009-07-20T22:10:30Z
21,210,929
14
2014-01-18T22:54:28Z
[ "python", "django", "download" ]
I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded. For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt And on the server, I know that all downloadable files reside in a folder "/home/user/files/". Is...
For a very simple **but not efficient or scalable** solution, you can just use the built in django `serve` view. This is excellent for quick prototypes or one-off work, but as has been mentioned throughout this question, you should use something like apache or nginx in production. ``` from django.views.static import s...
Remove all occurrences of a value from a Python list
1,157,106
167
2009-07-21T03:12:10Z
1,157,132
114
2009-07-21T03:17:58Z
[ "python", "list" ]
In Python `remove()` will remove the first occurrence of value in a list. How to remove all occurrences of a value from a list, without sorting the list? This is what I have in mind. ``` >>> x = [1, 2, 3, 4, 2, 2, 3] >>> def remove_values_from_list(the_list, val): while val in the_list: the_list....
You can use a list comprehension: ``` def remove_values_from_list(the_list, val): return [value for value in the_list if value != val] x = [1, 2, 3, 4, 2, 2, 3] x = remove_values_from_list(x, 2) print x # [1, 3, 4, 3] ```
Remove all occurrences of a value from a Python list
1,157,106
167
2009-07-21T03:12:10Z
1,157,160
223
2009-07-21T03:28:39Z
[ "python", "list" ]
In Python `remove()` will remove the first occurrence of value in a list. How to remove all occurrences of a value from a list, without sorting the list? This is what I have in mind. ``` >>> x = [1, 2, 3, 4, 2, 2, 3] >>> def remove_values_from_list(the_list, val): while val in the_list: the_list....
Functional approach: **2.x** ``` >>> x = [1,2,3,2,2,2,3,4] >>> filter(lambda a: a != 2, x) [1, 3, 3, 4] ``` **3.x** ``` >>> list(filter((2).__ne__, x)) [1, 3, 3, 4] ```