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
Creating connection between two computers in python
936,625
9
2009-06-01T20:32:24Z
936,685
7
2009-06-01T20:42:17Z
[ "python", "networking" ]
The question: How do I create a python application that can connect and send packets over the internet to another computer running the same application? Is there any existing code/library I could use? The background: I am pretty new to programming (HS senior). I've created a lot of simple things in python but I've rec...
The standard library includes SocketServer (documented [here](http://docs.python.org/library/socketserver.html)), which might do what you want. However I wonder if a better solution might be to use a message queue. Lots of good implementations already exist, including Python interfaces. I've used [RabbitMQ](http://www...
Why does "**" bind more tightly than negation?
936,904
9
2009-06-01T21:33:07Z
936,926
22
2009-06-01T21:37:53Z
[ "python", "order-of-operations" ]
I was just bitten by the following scenario: ``` >>> -1 ** 2 -1 ``` Now, digging through the Python docs, [it's clear that this is intended behavior](http://docs.python.org/reference/expressions.html#the-power-operator), but *why?* I don't work with any other languages with power as a builtin operator, but not having...
That behaviour is the same as in math formulas, so I am not sure what the problem is, or why it is counter-intuitive. Can you explain where have you seen something different? "\*\*" always bind more than "-": -x^2 is not the same as (-x)^2 Just use (-1) \*\* 2, exactly as you'd do in math.
Python recursion and return statements
937,000
15
2009-06-01T21:55:29Z
937,011
23
2009-06-01T21:58:31Z
[ "python", "recursion" ]
I'm fairly new to Python and recursive functions as a whole, so pardon my ignorance. I am trying to implement a binary search tree in Python and have the following insert method (taken out of a class): ``` def insert(self, key, root=None): '''Inserts a node in the tree''' if root == None: root = self....
On your recursive lines, you do not return anything. If you want it to return 0, you should replace them with lines like: ``` return self.insert(key, root=tmp.left) ``` instead of just ``` self.insert(key, root=tmp.left) ```
Python recursion and return statements
937,000
15
2009-06-01T21:55:29Z
937,057
18
2009-06-01T22:09:20Z
[ "python", "recursion" ]
I'm fairly new to Python and recursive functions as a whole, so pardon my ignorance. I am trying to implement a binary search tree in Python and have the following insert method (taken out of a class): ``` def insert(self, key, root=None): '''Inserts a node in the tree''' if root == None: root = self....
You are inside a function and want to return a value, what do you do? You write ``` def function(): return value ``` In your case you want to return the value returned by a function call, so you have to do. ``` def function(): return another_function() ``` However you do ``` def function(): another_fun...
Can you pass a dictionary when replacing strings in Python?
937,697
6
2009-06-02T02:37:59Z
937,739
10
2009-06-02T02:56:43Z
[ "php", "python", "regex", "string" ]
In PHP, you have `preg_replace($patterns, $replacements, $string)`, where you can make all your substitutions at once by passing in an array of patterns and replacements. What is the equivalent in Python? I noticed that the string and re functions `replace()` and `sub()` don't take dictionaries... Edited to clarify ...
closest is probably: ``` somere.sub(lambda m: replacements[m.group()], text) ``` for example: ``` >>> za = re.compile('z\w') >>> za.sub(lambda m: dict(za='BLU', zo='BLA')[m.group()], 'fa za zo bu') 'fa BLU BLA bu' ``` with a `.get` instead of `[]`-indexing if you want to supply a default for matches that are missin...
How do you specify a default for a Django ForeignKey Model or AdminModel field?
937,954
14
2009-06-02T04:56:29Z
13,562,197
23
2012-11-26T09:46:25Z
[ "python", "django-models", "django-admin" ]
How can I set a default value on a ForeignKey field in a django Model or AdminModel? Something like this (but of course this doesn't work)... ``` created_by = models.ForeignKey(User, default=request.user) ``` I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.
``` class Foo(models.Model): a = models.CharField(max_length=42) class Bar(models.Model): b = models.CharField(max_length=42) a = models.ForeignKey(Foo, default=lambda: Foo.objects.get(id=1) ) ```
Recursive Relationship with Google App Engine and BigTable
938,035
5
2009-06-02T05:38:04Z
938,106
10
2009-06-02T06:12:46Z
[ "python", "database-design", "google-app-engine", "bigtable" ]
In a classic relational database, I have the following table: ``` CREATE TABLE Person( Id int IDENTITY(1,1) NOT NULL PRIMARY KEY, MotherId int NOT NULL REFERENCES Person(Id), FatherId int NOT NULL REFERENCES Person(Id), FirstName nvarchar(255)) ``` I am trying to convert this table into a Google App E...
I think that you want SelfReferenceProperty here ``` class Person(db.Model): mother = db.SelfReferenceProperty(collection_name='mother_set') father = db.SelfReferenceProperty(collection_name='father_set') firstName = db.StringProperty() ``` Alternatively, you can put the Mother and Father relations in sep...
How to match a string of a certain length with a regex
938,065
4
2009-06-02T05:55:06Z
938,161
8
2009-06-02T06:27:52Z
[ "python", "regex" ]
For a project of mine, I'm trying to implement a small part of the BitTorrent protocol, which can be found [here](http://www.bittorrent.org/beps/bep%5F0003.html). Specifically, I want to use the "Bencoding" part of it, which is a way to safely encode data for transfer over a socket. The format is as follows: ``` 8:a s...
Any parser you use for this is going to need to be stateful (i.e. remember stuff), and regexes are, by and large, not stateful. They're the wrong tool for this job. If those are the only data types you have to worry about, I think I'd just write custom parsers for each data type, passing control to the appropriate par...
Bad Practice to run code in constructor thats likely to fail?
938,426
12
2009-06-02T08:05:55Z
938,453
20
2009-06-02T08:13:14Z
[ "python", "oop", "exception-handling", "constructor" ]
my question is rather a design question. In Python, if code in your "constructor" fails, the object ends up not being defined. Thus: ``` someInstance = MyClass("test123") #lets say that constructor throws an exception someInstance.doSomething() # will fail, name someInstance not defined. ``` I do have a situation tho...
In C++ at least, there is nothing wrong with putting failure-prone code in the constructor - you simply throw an exception if an error occurs. If the code is needed to properly construct the object, there reallyb is no alternative (although you can abstract the code into subfunctions, or better into the constructors of...
Bad Practice to run code in constructor thats likely to fail?
938,426
12
2009-06-02T08:05:55Z
938,677
26
2009-06-02T09:35:25Z
[ "python", "oop", "exception-handling", "constructor" ]
my question is rather a design question. In Python, if code in your "constructor" fails, the object ends up not being defined. Thus: ``` someInstance = MyClass("test123") #lets say that constructor throws an exception someInstance.doSomething() # will fail, name someInstance not defined. ``` I do have a situation tho...
There is a difference between a constructor in C++ and an `__init__` method in Python. In C++, the task of a constructor is to construct an object. If it fails, no destructor is called. Therefore if any resources were acquired before an exception was thrown, the cleanup should be done before exiting the constructor. Th...
Scope of python lambda functions and their parameters
938,429
54
2009-06-02T08:07:04Z
938,457
49
2009-06-02T08:14:33Z
[ "python", "lexical-closures" ]
I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions. So I have the following simplified code below: `...
The problem here is the `m` variable (a reference) being taken from the surrounding scope. Only parameters are held in the lambda scope. To solve this you have to create another scope for lambda: ``` def callback(msg): print msg def callback_factory(m): return lambda: callback(m) funcList=[] for m in ('do',...
Scope of python lambda functions and their parameters
938,429
54
2009-06-02T08:07:04Z
938,493
92
2009-06-02T08:27:06Z
[ "python", "lexical-closures" ]
I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions. So I have the following simplified code below: `...
When a lambda is created, it doesn't make a copy of the variables in the enclosing scope that it uses. It maintains a reference to the environment so that it can look up the value of the variable later. There is just one `m`. It gets assigned to every time through the loop. After the loop, the variable `m` has value `'...
Total memory used by Python process?
938,733
99
2009-06-02T09:50:40Z
938,754
14
2009-06-02T09:59:10Z
[ "python", "memory-management" ]
Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.
On unix, you can use the `ps` tool to monitor it: ``` $ ps u -p 1347 | awk '{sum=sum+$6}; END {print sum/1024}' ``` where 1347 is some process id. Also, the result is in MB.
Total memory used by Python process?
938,733
99
2009-06-02T09:50:40Z
938,800
45
2009-06-02T10:13:40Z
[ "python", "memory-management" ]
Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.
On Windows, you can use WMI ([home page](http://timgolden.me.uk/python/wmi.html), [cheeseshop](http://pypi.python.org/pypi/WMI/1.3.2)): ``` def memory(): import os from wmi import WMI w = WMI('.') result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpi...
Total memory used by Python process?
938,733
99
2009-06-02T09:50:40Z
7,669,482
105
2011-10-06T01:23:56Z
[ "python", "memory-management" ]
Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.
For Unixes (Linux, Mac OS X, Solaris) you could also use the `getrusage()` function from the standard library module `resource`. The resulting object has the attribute `ru_maxrss`, which gives *peak* memory usage for the calling process: ``` >>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss 2656 # peak memory usa...
Total memory used by Python process?
938,733
99
2009-06-02T09:50:40Z
21,632,554
53
2014-02-07T16:11:44Z
[ "python", "memory-management" ]
Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.
[Here](http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/) is a useful solution that works for various operating systems, including Windows 7 x64: ``` import os import psutil process = psutil.Process(os.getpid()) print(process.memory_info().rss) ```
Purpose of @ symbols in Python?
939,426
9
2009-06-02T13:13:22Z
939,447
9
2009-06-02T13:16:22Z
[ "python" ]
I've noticed in several examples i see things such as this: ``` # Comments explaining code i think @innerclass ``` or: ``` def foo(): """ Basic Doc String """ @classmethod ``` Googling doesn't get me very far, for just a general definition of what this is. Also i cant find anything really in the python documentati...
They're decorators. `<shameless plug>` I have a [blog post](http://jasonmbaker.wordpress.com/2009/04/25/the-magic-of-python-decorators/) on the subject. `</shameless plug>`
Purpose of @ symbols in Python?
939,426
9
2009-06-02T13:13:22Z
939,459
18
2009-06-02T13:17:30Z
[ "python" ]
I've noticed in several examples i see things such as this: ``` # Comments explaining code i think @innerclass ``` or: ``` def foo(): """ Basic Doc String """ @classmethod ``` Googling doesn't get me very far, for just a general definition of what this is. Also i cant find anything really in the python documentati...
They are called decorators. They are functions applied to other functions. Here is a copy of my answer to a similar question. Python decorators add extra functionality to another function. An italics decorator could be like ``` def makeitalic(fn): def newFunc(): return "<i>" + fn() + "</i>" return new...
Threading In Python
939,754
6
2009-06-02T14:03:16Z
939,827
18
2009-06-02T14:15:42Z
[ "python", "multithreading" ]
I'm new to threading and was wondering if it's bad to spawn a lot of threads for various tasks (in a server environment). Do threads take up a lot more memory/cpu compared to more linear programming?
You have to consider multiple things if you want to use multiple threads: 1. You can only run #processors threads simultaneously. (Obvious) 2. In Python each thread is a 'kernel thread' which normally takes a non-trivial amount of resources (8 mb stack by default on linux) 3. Python has a global interpreter lock, whic...
print vs stderr
939,866
23
2009-06-02T14:25:54Z
939,887
30
2009-06-02T14:29:35Z
[ "python", "printing", "stderr" ]
Are there any specific advantages or disadvantages to either `print` or `stderr`?
They're just two different things. `print` generally goes to `sys.stdout`. It's worth knowing the difference between [`stdin`, `stdout`, and `stderr`](http://en.wikipedia.org/wiki/Standard_streams) - they all have their uses. In particular, `stdout` should be used for normal program output, whereas `stderr` should be ...
print vs stderr
939,866
23
2009-06-02T14:25:54Z
939,902
74
2009-06-02T14:31:45Z
[ "python", "printing", "stderr" ]
Are there any specific advantages or disadvantages to either `print` or `stderr`?
`print` can print on any file-like object, including `sys.stderr`. ``` print >> sys.stderr, 'Text' ``` The advantages of using `sys.stderr` for errors instead of `sys.stdout` are: * If the user redirected stdout to a file, she still sees errors on the screen. * It's not buffered, so if `sys.stderr` is redirected to ...
print vs stderr
939,866
23
2009-06-02T14:25:54Z
2,411,107
28
2010-03-09T17:33:44Z
[ "python", "printing", "stderr" ]
Are there any specific advantages or disadvantages to either `print` or `stderr`?
Be careful: there are some subtleties here, including whether or not the streams are going to interactive devices. The biggest surprise is that in Python 3 stderr is line buffered (at least in Unix). For example, in a terminal window, the following prints a number every two seconds in Python 2: ``` for n in range(5): ...
How do I update an object's members using a dict?
940,089
9
2009-06-02T15:07:29Z
940,101
17
2009-06-02T15:09:14Z
[ "python", "django" ]
I'm writing a Django app that performs various functions, including inserting, or updating new records into the database via the URL. So some internal application sends off a request to `/import/?a=1&b=2&c=3`, for example. In the view, I want to create a new object, `foo = Foo()` and have the members of `foo` set to t...
You can use the setattr function to dynamically set attributes: ``` for key,value in request.GET.items(): setattr(foo, key, value) ```
Distributing Ruby/Python desktop apps
940,149
10
2009-06-02T15:15:46Z
940,241
11
2009-06-02T15:31:46Z
[ "python", "ruby", "user-interface", "desktop", "software-distribution" ]
Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby? I come to believe that general bugginess of \_why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain. RubyGTK, wxRuby, etc s...
I don't know about ruby2exe, but py2exe works perfeclty fine. Even with librairies like wxWidgets. **Edit**: you don't even have to ask the user to install wxWidgets, it's bundled with the app (same goes for py2app) I use it for my very small project [here](http://github.com/loicwolff/notagapp/). For the Mac crowd, p...
Distributing Ruby/Python desktop apps
940,149
10
2009-06-02T15:15:46Z
941,539
8
2009-06-02T19:48:28Z
[ "python", "ruby", "user-interface", "desktop", "software-distribution" ]
Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby? I come to believe that general bugginess of \_why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain. RubyGTK, wxRuby, etc s...
For Ruby, the [One-Click Ruby Application Builder](http://rubyforge.org/projects/ocra/) (OCRA) is emerging as the successor to [RubyScript2Exe](http://www.erikveen.dds.nl/rubyscript2exe/). Ocra works with both Ruby 1.8.6 and 1.9.1, and with wxRuby. Supports LZMA compression for relatively compact executables.
PyQt sending parameter to slot when connecting to a signal
940,555
21
2009-06-02T16:38:00Z
940,655
33
2009-06-02T16:52:11Z
[ "python", "qt4", "pyqt" ]
I have a taskbar menu that when clicked is connected to a slot that gets the trigger event. Now the problem is that I want to know which menu item was clicked, but I don't know how to send that information to the function connected to. Here is the used to connect the action to the function: ``` QtCore.QObject.connect(...
Use a `lambda` Here's an example from the [PyQt book](http://www.qtrac.eu/pyqtbook.html): ``` self.connect(button3, SIGNAL("clicked()"), lambda who="Three": self.anyButton(who)) ``` By the way, you can also use `functools.partial`, but I find the `lambda` method simpler and clearer.
How does Spring for Python compare with Spring for Java
940,564
6
2009-06-02T16:39:13Z
940,804
20
2009-06-02T17:26:25Z
[ "java", "python", "spring" ]
I am an avid fan of the Spring framework for Java (by Rod Johnson). I am learning Python and was excited to find about Spring for Python. I would be interested in hearing the community's views on the comparison of these two flavours of Spring. How well does it fit Python's paradigms etc.
Dependency injection frameworks are not nearly as useful in a dynamically typed language. See for example the presentation [Dependency Injection: Vitally important or totally irrelevant?](http://onestepback.org/articles/depinj/index.html) In Java the flexibility provided by a dependency injection framework is vital, wh...
How does Spring for Python compare with Spring for Java
940,564
6
2009-06-02T16:39:13Z
945,831
11
2009-06-03T16:54:44Z
[ "java", "python", "spring" ]
I am an avid fan of the Spring framework for Java (by Rod Johnson). I am learning Python and was excited to find about Spring for Python. I would be interested in hearing the community's views on the comparison of these two flavours of Spring. How well does it fit Python's paradigms etc.
DISCLOSURE: I am the project lead for Spring Python, so you can consider my opinion biased. I find that several of the options provided by Spring Python are useful including: [aspect oriented programming](http://blog.springpython.webfactional.com/2009/03/23/the-case-for-aop-in-python/), [dependency injection, remoting...
Using list comprehensions and exceptions?
940,783
3
2009-06-02T17:22:34Z
940,834
13
2009-06-02T17:33:13Z
[ "python", "list", "list-comprehension" ]
Okay lets say I have a list, and I want to check if that list exists within another list. I can do that doing this: ``` all(value in some_map for value in required_values) ``` Which works fine, but lets say I want to the raise an exception when a required value is missing, with the value that it is missing. How can I...
> lets say i want to the raise an exception when a required value is missing, with the value that it is missing. How can i do that using list comprehension? List comprehensions are a syntactically concise way to create a list based on some existing list—they're *not* a general-purpose way of writing any `for`-loop i...
Regular expression syntax for "match nothing"?
940,822
42
2009-06-02T17:30:50Z
940,840
59
2009-06-02T17:34:15Z
[ "python", "regex" ]
I have a python template engine that heavily uses regexp. It uses concatenation like: ``` re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) ``` I can modify individual substrings (regexp1, regexp2 etc). Is there any small and light expression that matches nothing, which I can use inside a template where I...
This shouldn't match anything: ``` re.compile('$^') ``` So if you replace regexp1, regexp2 and regexp3 with '$^' it will be impossible to find a match. Unless you are using the multi line mode. --- After some tests I found a better solution ``` re.compile('a^') ``` It is impossible to match and will fail earlier ...
Regular expression syntax for "match nothing"?
940,822
42
2009-06-02T17:30:50Z
940,934
14
2009-06-02T17:45:58Z
[ "python", "regex" ]
I have a python template engine that heavily uses regexp. It uses concatenation like: ``` re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) ``` I can modify individual substrings (regexp1, regexp2 etc). Is there any small and light expression that matches nothing, which I can use inside a template where I...
To match an empty string - even in multiline mode - you can use `\A\Z`, so: ``` re.compile('\A\Z|\A\Z*|\A\Z+') ``` The difference is that `\A` and `\Z` are start and end of *string*, whilst `^` and `$` these can match start/end of *lines*, so `$^|$^*|$^+` could potentially match a string containing newlines (if the f...
Regular expression syntax for "match nothing"?
940,822
42
2009-06-02T17:30:50Z
942,122
18
2009-06-02T22:02:15Z
[ "python", "regex" ]
I have a python template engine that heavily uses regexp. It uses concatenation like: ``` re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) ``` I can modify individual substrings (regexp1, regexp2 etc). Is there any small and light expression that matches nothing, which I can use inside a template where I...
`(?!)` should always fail to match. It is the zero-width negative look-ahead. If what is in the parentheses matches then the whole match fails. Given that it has nothing in it, it will fail the match for anything (including nothing).
Is it reasonable to integrate python with c for performance?
940,982
2
2009-06-02T17:54:54Z
940,997
8
2009-06-02T17:57:11Z
[ "python", "c", "performance" ]
I like to use python for almost everything and always had clear in my mind that if for some reason I was to find a bottleneck in my python code(due to python's limitations), I could always use a C script integrated to my code. But, as I started to read a [guide](http://www.suttoncourtenay.org.uk/duncan/accu/integratin...
> \* Optimising inner loops in code Isn't that about performance ?
Is it reasonable to integrate python with c for performance?
940,982
2
2009-06-02T17:54:54Z
941,036
9
2009-06-02T18:06:23Z
[ "python", "c", "performance" ]
I like to use python for almost everything and always had clear in my mind that if for some reason I was to find a bottleneck in my python code(due to python's limitations), I could always use a C script integrated to my code. But, as I started to read a [guide](http://www.suttoncourtenay.org.uk/duncan/accu/integratin...
In my experience it is rarely necessary to optimize using C. I prefer to identify bottlenecks and improve algorithms in those areas completely in Python. Using hash tables, caching, and generally re-organizing your data structures to suit future needs has amazing potential for speeding up your program. As your program ...
Validating a slug in Django
941,270
6
2009-06-02T18:54:25Z
941,297
10
2009-06-02T18:59:15Z
[ "python", "django", "validation", "slug" ]
I'm guessing this is going to involve regexp or something, but I'll give it a shot. At the minute, a user can break a website by typing something similar to `£$(*£$(£@$&£($` in the title field, which is converted into a slug using Django `slugify`. Because none of these characters can be converted, Django returns ...
This question is half a decade old so in updating my question I should explain that I'm at least nodding to the past where some features might not have existed. The easiest way to handle slugs in forms these days is to just use `django.models.SlugField`. It will validate itself for you and imply that this field is an ...
Validating a slug in Django
941,270
6
2009-06-02T18:54:25Z
6,466,286
12
2011-06-24T10:03:14Z
[ "python", "django", "validation", "slug" ]
I'm guessing this is going to involve regexp or something, but I'll give it a shot. At the minute, a user can break a website by typing something similar to `£$(*£$(£@$&£($` in the title field, which is converted into a slug using Django `slugify`. Because none of these characters can be converted, Django returns ...
SLUG\_REGEX = re.compile('^[-\w]+$')
Any python OpenID server available?
941,296
12
2009-06-02T18:59:07Z
941,311
14
2009-06-02T19:01:47Z
[ "python", "openid" ]
I'd like to host my own OpenID provider. Is there anything available in Python?
[You are weak with the Google.](http://openidenabled.com/python-openid/) (Edit: That's a link to [OpenID-Enabled.com](http://openidenabled.com/). There are also PHP and Ruby versions available there.)
Any python OpenID server available?
941,296
12
2009-06-02T18:59:07Z
1,513,138
7
2009-10-03T07:57:29Z
[ "python", "openid" ]
I'd like to host my own OpenID provider. Is there anything available in Python?
[poit](http://yangman.ca/poit/) is a standalone, single-user OpenID server implemented in Python, using python-openid. (It's a project I started)
How to construct a web file browser?
941,638
2
2009-06-02T20:11:52Z
941,652
10
2009-06-02T20:14:50Z
[ "javascript", "python", "html", "web-applications" ]
Goal: simple browser app, for navigating files on a web server, in a tree view. Background: Building a web site as a learning experience, w/ Apache, mod\_python, Python code. (No mod\_wsgi yet.) What tools should I learn to write the browser tree? I see JavaScript, Ajax, neither of which I know. Learn them? Grab a JS...
First, switch to mod\_wsgi. Second, write a hello world in Python using mod\_wsgi. Third, change your hello world to show the results of `os.listdir()`. I think you're approximately done. As you mess with this, you'll realize that transforming the content you have (information from `os.listdir`) into presentation i...
Operation on every pair of element in a list
942,543
25
2009-06-03T00:21:23Z
942,551
89
2009-06-03T00:24:43Z
[ "python" ]
Using Python, I'd like to compare every possible pair in a list. Suppose I have ``` my_list = [1,2,3,4] ``` I'd like to do an operation (let's call it foo) on every combination of 2 elements from the list. The final result should be the same as ``` foo(1,1) foo(1,2) ... foo(4,3) foo(4,4) ``` My first thought was ...
Check out [`product()`](http://docs.python.org/library/itertools.html#itertools.product) in the `itertools` module. It does exactly what you describe. ``` import itertools my_list = [1,2,3,4] for pair in itertools.product(my_list, repeat=2): foo(*pair) ``` This is equivalent to: ``` my_list = [1,2,3,4] for x in...
Missing 'Median' Aggregate Function in Django?
942,620
8
2009-06-03T00:51:25Z
942,633
7
2009-06-03T00:57:17Z
[ "python", "django", "aggregate-functions" ]
The Development version of Django has aggregate functions like Avg, Count, Max, Min, StdDev, Sum, and Variance ([link text](http://docs.djangoproject.com/en/dev/ref/models/querysets/#id8)). Is there a reason Median is missing from the list? Implementing one seems like it would be easy. Am I missing something? How much...
Well, the *reason* is probably that you need to track all the numbers to calculate median. Avg, Count, Max, Min, StDev, Sum, and Variance can all be calculated with constant storage needs. That is, once you "record" a number you'll never need it again. FWIW, the variables you need to track are: min, max, count, `<n>` ...
Missing 'Median' Aggregate Function in Django?
942,620
8
2009-06-03T00:51:25Z
942,940
12
2009-06-03T03:27:26Z
[ "python", "django", "aggregate-functions" ]
The Development version of Django has aggregate functions like Avg, Count, Max, Min, StdDev, Sum, and Variance ([link text](http://docs.djangoproject.com/en/dev/ref/models/querysets/#id8)). Is there a reason Median is missing from the list? Implementing one seems like it would be easy. Am I missing something? How much...
Because median isn't a SQL aggregate. See, for example, the [list of PostgreSQL aggregate functions](http://www.postgresql.org/docs/8.3/static/functions-aggregate.html) and [the list of MySQL aggregate functions](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html).
Missing 'Median' Aggregate Function in Django?
942,620
8
2009-06-03T00:51:25Z
9,503,282
12
2012-02-29T16:56:05Z
[ "python", "django", "aggregate-functions" ]
The Development version of Django has aggregate functions like Avg, Count, Max, Min, StdDev, Sum, and Variance ([link text](http://docs.djangoproject.com/en/dev/ref/models/querysets/#id8)). Is there a reason Median is missing from the list? Implementing one seems like it would be easy. Am I missing something? How much...
Here's your missing function. Pass it a queryset and the name of the column that you want to find the median for: ``` def median_value(queryset, term): count = queryset.count() return queryset.values_list(term, flat=True).order_by(term)[int(round(count/2))] ``` That wasn't as hard as some of the other respons...
Benefit of installing Django from .deb versus .tar.gz?
943,242
4
2009-06-03T05:50:43Z
943,265
8
2009-06-03T05:59:05Z
[ "python", "django", "ubuntu", "apt-get" ]
I'm starting Django development, and I can either install it from the .deb using ``` $ apt-get install python-django ``` on my Ubuntu machine, or I can download the .tar.gz from [djangoproject.com](http://djangoproject.com), and start with that. What are the benefits and drawbacks of each approach?
Using `apt-get` lets your system keep track of the install (e.g. if you want to disinstall, upgrade, or the like, late). Installing from source (`.tar.gz` or otherwise) puts you in charge of what's what and where -- you can have multiple versions installed at various locations, etc, but there's no easy "uninstall" and ...
String manipulation in Cython
943,809
19
2009-06-03T09:19:23Z
944,512
9
2009-06-03T12:41:38Z
[ "python", "string", "cython" ]
I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance. (EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff like that.)...
I voted up the 'profile it' answer, but wanted to add this: where possible the best optimisation you can make is to use Python standard libraries or built-in functions to perform the tasks you want. These are typically implemented in C and will provide performance broadly equivalent to any extension, including extensio...
String manipulation in Cython
943,809
19
2009-06-03T09:19:23Z
1,806,183
7
2009-11-26T23:57:05Z
[ "python", "string", "cython" ]
I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance. (EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff like that.)...
"Ridiculously easy" is a very relative term. "Getting started" is just that. Writing robust extensions in C requires very careful attention to things like reference counting, memory allocation/freeing, and error handling. Cython does much of that for you. A non-unicode string in Cython is either a Python str object, o...
Method that gets called on module deletion in Python
944,336
4
2009-06-03T12:00:03Z
944,359
16
2009-06-03T12:05:17Z
[ "python", "destructor", "shutdown" ]
Is there a method that I can add to my module, which will get called when destructing the class? We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module. Was hoping there would be a `__del__` method either for modules or classes that don't ...
When destructing which class? I though you said module? Your module lives until the interpreter stops. you can add something to run at that time using the "atexit" module: ``` import atexit atexit.register(myfunction) ``` --- EDIT: Based on your comments. Since you don't want it as a destructor, my answer above is...
Efficient way of creating recursive paths Python
944,536
13
2009-06-03T12:46:07Z
944,561
42
2009-06-03T12:50:37Z
[ "python", "path", "operating-system" ]
Hi I need a simple function to create a path in Python where the parent may or may not exist. From python documentation os.makedirs will fail if one of the parents exists. I have written the below method as which works by makes as many sub directories as necessary. Does this look efficient? ``` def create_path(path...
> "From python documentation `os.makedirs` will fail if one of the parents exists." No, [`os.makedirs`](http://docs.python.org/library/os.html#os.makedirs) will fail if the directory itself already exists. It won't fail if just any of the parent directories already exists.
Efficient way of creating recursive paths Python
944,536
13
2009-06-03T12:46:07Z
21,349,806
12
2014-01-25T11:15:18Z
[ "python", "path", "operating-system" ]
Hi I need a simple function to create a path in Python where the parent may or may not exist. From python documentation os.makedirs will fail if one of the parents exists. I have written the below method as which works by makes as many sub directories as necessary. Does this look efficient? ``` def create_path(path...
Here's my take, which lets the system libraries do all the path-wrangling. Any errors other than the directory already existing are propagated. ``` import os, errno def ensure_dir(dirname): """ Ensure that a named directory exists; if it does not, attempt to create it. """ try: os.makedirs(dir...
Best practice for Python Assert
944,592
291
2009-06-03T12:57:16Z
944,660
102
2009-06-03T13:12:18Z
[ "python", "assert", "raise" ]
1. Is there a performance or code maintenance issue with using `assert` as part of the standard code instead of using it just for debugging purposes? Is ``` assert x >= 0, 'x is less than zero' ``` better or worse than ``` if x < 0: raise Exception, 'x is less than zero' ``` 2. Also, ...
To be able to automatically throw an error when x become less than zero throughout the function. You can use [class descriptors](http://docs.python.org/reference/datamodel.html#implementing-descriptors). Here is an example: ``` class LessThanZeroException(Exception): pass class variable(object): def __init__(...
Best practice for Python Assert
944,592
291
2009-06-03T12:57:16Z
944,661
13
2009-06-03T13:12:25Z
[ "python", "assert", "raise" ]
1. Is there a performance or code maintenance issue with using `assert` as part of the standard code instead of using it just for debugging purposes? Is ``` assert x >= 0, 'x is less than zero' ``` better or worse than ``` if x < 0: raise Exception, 'x is less than zero' ``` 2. Also, ...
The only thing that's really wrong with this approach is that it's hard to make a very descriptive exception using assert statements. If you're looking for the simpler syntax, remember you *can* also do something like this: ``` class XLessThanZeroException(Exception): pass def CheckX(x): if x < 0: rai...
Best practice for Python Assert
944,592
291
2009-06-03T12:57:16Z
945,135
509
2009-06-03T14:34:29Z
[ "python", "assert", "raise" ]
1. Is there a performance or code maintenance issue with using `assert` as part of the standard code instead of using it just for debugging purposes? Is ``` assert x >= 0, 'x is less than zero' ``` better or worse than ``` if x < 0: raise Exception, 'x is less than zero' ``` 2. Also, ...
Asserts should be used to test conditions that *should never happen*. The purpose is to crash early in the case of a corrupt program state. Exceptions should be used for errors that can conceivably happen, and you should almost always create your own Exception classes. --- For example, if you're writing a function t...
Best practice for Python Assert
944,592
291
2009-06-03T12:57:16Z
1,838,411
242
2009-12-03T08:15:24Z
[ "python", "assert", "raise" ]
1. Is there a performance or code maintenance issue with using `assert` as part of the standard code instead of using it just for debugging purposes? Is ``` assert x >= 0, 'x is less than zero' ``` better or worse than ``` if x < 0: raise Exception, 'x is less than zero' ``` 2. Also, ...
**"assert" statements are removed when the compilation is optimized**. So, yes, there are both performance and functional differences. > The current code generator emits no code for an assert statement when optimization is requested at compile time. - [Python 2.6.4 Docs](http://docs.python.org/reference/simple_stmts.h...
Best practice for Python Assert
944,592
291
2009-06-03T12:57:16Z
1,839,402
14
2009-12-03T11:37:29Z
[ "python", "assert", "raise" ]
1. Is there a performance or code maintenance issue with using `assert` as part of the standard code instead of using it just for debugging purposes? Is ``` assert x >= 0, 'x is less than zero' ``` better or worse than ``` if x < 0: raise Exception, 'x is less than zero' ``` 2. Also, ...
In addition to the other answers, asserts themselves throw exceptions, but only AssertionErrors. From a utilitarian standpoint, assertions aren't suitable for when you need fine grain control over which exceptions you catch.
Best practice for Python Assert
944,592
291
2009-06-03T12:57:16Z
18,980,471
76
2013-09-24T11:33:18Z
[ "python", "assert", "raise" ]
1. Is there a performance or code maintenance issue with using `assert` as part of the standard code instead of using it just for debugging purposes? Is ``` assert x >= 0, 'x is less than zero' ``` better or worse than ``` if x < 0: raise Exception, 'x is less than zero' ``` 2. Also, ...
Assume you work on 200,000 lines of code with four colleagues Alice, Bernd, Carl, and Daphne. They call your code, you call their code. Then `assert` has **four roles**: 1. **Inform Alice, Bernd, Carl, and Daphne what your code expects.** Assume you have a method that processes a list of tuples and the program l...
How to check for NaN in python?
944,700
300
2009-06-03T13:19:54Z
944,712
106
2009-06-03T13:22:05Z
[ "python", "math" ]
`float('nan')` results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.
The usual way to test for a NaN is to see if it's equal to itself: ``` def isNaN(num): return num != num ```
How to check for NaN in python?
944,700
300
2009-06-03T13:19:54Z
944,733
407
2009-06-03T13:24:37Z
[ "python", "math" ]
`float('nan')` results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.
[math.isnan()](http://docs.python.org/library/math.html#math.isnan) > Checks if the float x is a NaN (not a number). NaNs are part of the IEEE 754 standards. Operation like but not limited to inf \* 0, inf / inf or any operation involving a NaN, e.g. nan \* 1, return a NaN. > > *New in version 2.6.* ``` >>> import ma...
How to check for NaN in python?
944,700
300
2009-06-03T13:19:54Z
944,734
12
2009-06-03T13:24:51Z
[ "python", "math" ]
`float('nan')` results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.
[math.isnan()](http://docs.python.org/library/math.html#math.isnan) or compare the number to itself. NaN is always != NaN, otherwise (e.g. if it *is* a number) the comparison should succeed.
How to check for NaN in python?
944,700
300
2009-06-03T13:19:54Z
944,756
42
2009-06-03T13:28:31Z
[ "python", "math" ]
`float('nan')` results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.
`numpy.isnan(float)` tells you if it's `NaN` or not in Python 2.5.
How to check for NaN in python?
944,700
300
2009-06-03T13:19:54Z
2,138,383
9
2010-01-26T09:10:53Z
[ "python", "math" ]
`float('nan')` results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.
Another method if you're stuck on <2.6, you don't have numpy, and you don't have IEEE 754 support: ``` def isNaN(x): return str(x) == str(1e400*0) ```
How to check for NaN in python?
944,700
300
2009-06-03T13:19:54Z
3,060,088
9
2010-06-17T08:35:39Z
[ "python", "math" ]
`float('nan')` results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.
With python < 2.6 I ended up with ``` def isNaN(x): return str(float(x)).lower() == 'nan' ``` This works for me with python 2.5.1 on a Solaris 5.9 box and with python 2.6.5 on Ubuntu 10
How to check for NaN in python?
944,700
300
2009-06-03T13:19:54Z
12,588,878
19
2012-09-25T18:22:03Z
[ "python", "math" ]
`float('nan')` results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.
I actually just ran into this, but for me it was checking for nan, -inf, or inf. I just used ``` if float('-inf') < float(num) < float('inf'): ``` This is true for numbers, false for nan and both inf, and will raise an exception for things like strings or other types (which is probably a good thing). Also this does n...
Numpy: Should I use newaxis or None?
944,863
57
2009-06-03T13:48:45Z
945,313
65
2009-06-03T15:05:52Z
[ "python", "numpy" ]
In numpy one can use the 'newaxis' object in the slicing syntax to create an axis of length one, e.g.: ``` import numpy as np print np.zeros((3,5))[:,np.newaxis,:].shape # shape will be (3,1,5) ``` The [documentation states](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis) that one can al...
`None` is allowed because `numpy.newaxis` is merely an alias for `None`. ``` In [1]: import numpy In [2]: numpy.newaxis is None Out[2]: True ``` The authors probably chose it because they needed a convenient constant, and `None` was available. As for why you should prefer `newaxis` over `None`: mainly it's because ...
How can I script the creation of a movie from a set of images?
945,250
8
2009-06-03T14:54:29Z
945,570
8
2009-06-03T16:00:47Z
[ "python", "osx", "video" ]
I managed to get a set of images loaded using Python. I'd like my script to take this series of images (in whatever format I need them), and create a video from them. The big limit in all this is that I am looking for something easy and simple to install. Ideally, using the standard OS X installation procedure: * dow...
You may use OpenCV. And it can be installed on Mac. Also, it has a [python interface](http://opencv.willowgarage.com/wiki/PythonInterface). I have slightly modified a program taken from [here](http://morphm.ensmp.fr/wiki/morphee-admin/How%5Fto%5Fuse%5FMorph-M%5Fwith%5FOpenCV%5F), but don't know if it compiles, and can...
How can I script the creation of a movie from a set of images?
945,250
8
2009-06-03T14:54:29Z
945,829
19
2009-06-03T16:53:53Z
[ "python", "osx", "video" ]
I managed to get a set of images loaded using Python. I'd like my script to take this series of images (in whatever format I need them), and create a video from them. The big limit in all this is that I am looking for something easy and simple to install. Ideally, using the standard OS X installation procedure: * dow...
If you're not averse to using the command-line, there's the `convert` command from the ImageMagick package. It's available for Mac, Linux, Windows. See <http://www.imagemagick.org/script/index.php>. It supports a huge number of image formats and you can output your movie as an mpeg file: ``` convert -quality 100 *.pn...
Why doesn't anyone care about this MySQLdb bug? is it a bug?
945,482
10
2009-06-03T15:41:34Z
945,519
7
2009-06-03T15:48:58Z
[ "python", "deadlock", "mysql" ]
TL;DR: I've supplied a patch for a bug I found and I've got 0 feedback on it. I'm wondering if it's a bug at all. This is not a rant. Please read this and if you may be affected by it check the fix. I have found and reported this MySQLdb bug some weeks ago (edit: 6 weeks ago), sent a patch, posted it on a couple of OR...
> Why doesn’t anyone care about this > MySQLdb bug? bugs can take a while to prioritize, research, verify the problem, find a fix, test the fix, make sure the fix fix does not break anything else. I would suggest you deploy a work around, since it could take some time for this fix to arrive for you.
is there a multiple format specifier in Python?
945,972
7
2009-06-03T17:18:53Z
945,994
20
2009-06-03T17:21:59Z
[ "python" ]
I have a data table 44 columns wide that I need to write to file. I don't want to write: ``` outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...)) ``` In Fortran you can specify multiple format specifiers easily: ``` write (*,"(3f8.3)") a,b,c ``` Is there a similar capability in Python?
``` >>> "%d " * 3 '%d %d %d ' >>> "%d " * 3 % (1,2,3) '1 2 3 ' ```
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote()
946,170
22
2009-06-03T17:51:28Z
6,618,858
44
2011-07-08T00:58:30Z
[ "javascript", "python", "url", "encoding" ]
Are there any equivalent Javascript functions for Python's [`urllib.quote()`](http://docs.python.org/library/urllib.html#urllib.quote) and [`urllib.unquote()`](http://docs.python.org/library/urllib.html#urllib.unquote)? The closest I've come across are [`escape()`](http://www.w3schools.com/jsref/jsref%5Fescape.asp), [...
For the record: ``` JavaScript | Python ----------------------------------- encodeURI(str) | urllib.quote(str, safe='~@#$&()*!+=:;,.?/\''); ----------------------------------- encodeURIComponent(str) | urllib.quote(str, safe='~()*!.\'') ```
Using Python's list index() method on a list of tuples or objects?
946,860
34
2009-06-03T20:01:51Z
946,906
47
2009-06-03T20:07:23Z
[ "python", "list", "tuples", "reverse-lookup" ]
Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance: ``` >>> some_list = ["apple", "pear", "banana", "grape"] >>> some_list.index("pear") 1 >>> some_list.index("grape") 3 ``` Is there a graceful (idiomatic) way to e...
How about this? ``` >>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)] >>> [x for x, y in enumerate(tuple_list) if y[1] == 7] [1] >>> [x for x, y in enumerate(tuple_list) if y[0] == 'kumquat'] [2] ``` As pointed out in the comments, this would get all matches. To just get the first one, ...
Using Python's list index() method on a list of tuples or objects?
946,860
34
2009-06-03T20:01:51Z
946,940
8
2009-06-03T20:12:28Z
[ "python", "list", "tuples", "reverse-lookup" ]
Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance: ``` >>> some_list = ["apple", "pear", "banana", "grape"] >>> some_list.index("pear") 1 >>> some_list.index("grape") 3 ``` Is there a graceful (idiomatic) way to e...
One possibility is to use the [itemgetter](http://docs.python.org/library/operator.html#operator.itemgetter) function from the `operator` module: ``` import operator f = operator.itemgetter(0) print map(f, tuple_list).index("cherry") # yields 1 ``` The call to `itemgetter` returns a function that will do the equival...
Using Python's list index() method on a list of tuples or objects?
946,860
34
2009-06-03T20:01:51Z
947,184
24
2009-06-03T20:54:10Z
[ "python", "list", "tuples", "reverse-lookup" ]
Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance: ``` >>> some_list = ["apple", "pear", "banana", "grape"] >>> some_list.index("pear") 1 >>> some_list.index("grape") 3 ``` Is there a graceful (idiomatic) way to e...
Those list comprehensions are messy after a while. ### I like this Pythonic approach: ``` from operator import itemgetter def collect(l, index): return map(itemgetter(index), l) # And now you can write this: collect(tuple_list,0).index("cherry") # = 1 collect(tuple_list,1).index("3") # = 2 ``` ### If y...
How to execute a process remotely using python
946,946
19
2009-06-03T20:12:56Z
946,962
16
2009-06-03T20:15:42Z
[ "python", "ssh" ]
I want to connect too and execute a process on a remote server using python. I want to be able to get the return code and stderr(if any) of the process. Has anyone ever done anything like this before. I have done it with ssh, but I want to do it from python script. Cheers.
Well, you can call ssh from python... ``` import subprocess ret = subprocess.call(["ssh", "user@host", "program"]); # or, with stderr: prog = subprocess.Popen(["ssh", "user@host", "program"], stderr=subprocess.PIPE) errdata = prog.communicate()[1] ```
How to execute a process remotely using python
946,946
19
2009-06-03T20:12:56Z
8,798,354
29
2012-01-10T03:55:15Z
[ "python", "ssh" ]
I want to connect too and execute a process on a remote server using python. I want to be able to get the return code and stderr(if any) of the process. Has anyone ever done anything like this before. I have done it with ssh, but I want to do it from python script. Cheers.
Use the [ssh module called paramiko](http://pypi.python.org/pypi/paramiko/) which was created for this purpose instead of using `subprocess`. Here's an example below: ``` from paramiko import SSHClient client = SSHClient() client.load_system_host_keys() client.connect("hostname", username="user") stdin, stdout, stderr...
Get file creation time with Python on Mac
946,967
7
2009-06-03T20:16:51Z
947,239
14
2009-06-03T21:02:52Z
[ "python", "osx" ]
Python's os.path.getctime on the Mac (and under Unix in general) does not give the date when a file was created but "the time of the last change" (according to the docs at least). On the other hand in the Finder I can see the real file creation time so this information is kept by HFS+. Do you have any suggestions on h...
Use the [**`st_birthtime`**](https://docs.python.org/3/library/os.html#os.stat_result.st_birthtime) property on the result of a call to [`os.stat()`](https://docs.python.org/3/library/os.html#os.stat) (or `fstat`/`lstat`). ``` def get_creation_time(path): return os.stat(path).st_birthtime ``` You can convert the ...
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field
947,077
21
2009-06-03T20:35:24Z
964,825
20
2009-06-08T13:06:21Z
[ "python", "sql-server", "unicode", "utf-8", "pyodbc" ]
I am using **Ubuntu 9.04** I have installed the following package versions: ``` unixodbc and unixodbc-dev: 2.2.11-16build3 tdsodbc: 0.82-4 libsybdb5: 0.82-4 freetds-common and freetds-dev: 0.82-4 ``` I have configured `/etc/unixodbc.ini` like this: ``` [FreeTDS] Description = TDS driver (Sybase/MS SQL) ...
I can remember having this kind of stupid problems using odbc drivers, even if that time it was a java+oracle combination. The core thing is that odbc driver apparently encodes the query string when sending it to the DB. Even if the field is Unicode, and if you provide Unicode, in some cases it does not seem to matter...
Custom simple Python HTTP server not serving css files
947,372
4
2009-06-03T21:31:32Z
947,442
9
2009-06-03T21:44:24Z
[ "python", "css", "http" ]
I had found written in python, a very simple http server, it's do\_get method looks like this: ``` def do_GET(self): try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers(); filepath = self.path print filepath, US...
You're explicitly serving all files as `Content-type: text/html`, where you need to serve CSS files as `Content-type: text/css`. See [this page on the CSS-Discuss Wiki](http://css-discuss.incutio.com/?page=MozillaCssMimeType) for details. Web servers usually have a lookup table to map from file extension to Content-Typ...
Strip all non-numeric characters (except for ".") from a string in Python
947,776
37
2009-06-03T23:12:00Z
947,789
80
2009-06-03T23:14:46Z
[ "python" ]
I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this: ``` val = ''.join([c for c in val if c in '1234567890.']) ``` What would you do?
``` >>> import re >>> non_decimal = re.compile(r'[^\d.]+') >>> non_decimal.sub('', '12.34fe4e') '12.344' ```
Strip all non-numeric characters (except for ".") from a string in Python
947,776
37
2009-06-03T23:12:00Z
947,868
13
2009-06-03T23:44:12Z
[ "python" ]
I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this: ``` val = ''.join([c for c in val if c in '1234567890.']) ``` What would you do?
Here's some sample code: ``` $ cat a.py a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw' for i in xrange(1000000): ''.join([c for c in a if c in '1234567890.']) ``` --- ``` $ cat b.py import re non_decimal = re.compile(r'[^\d.]+') a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw' for i in xrange(1...
Strip all non-numeric characters (except for ".") from a string in Python
947,776
37
2009-06-03T23:12:00Z
948,855
10
2009-06-04T06:24:02Z
[ "python" ]
I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this: ``` val = ''.join([c for c in val if c in '1234567890.']) ``` What would you do?
Another 'pythonic' approach `filter( lambda x: x in '0123456789.', s )` but regex is faster.
How to save a Python interactive session?
947,810
240
2009-06-03T23:21:02Z
947,820
68
2009-06-03T23:23:20Z
[ "python", "shell", "read-eval-print-loop", "interactive-session" ]
I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, littl...
There is a [way](http://docs.python.org/tutorial/interactive.html?highlight=atexit) to do it. Store the file in `~/.pystartup`... ``` # Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (...
How to save a Python interactive session?
947,810
240
2009-06-03T23:21:02Z
947,846
225
2009-06-03T23:34:21Z
[ "python", "shell", "read-eval-print-loop", "interactive-session" ]
I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, littl...
[IPython](http://ipython.scipy.org/moin/) is extremely useful if you like using interactive sessions. For example for your usecase there is the *%save* magic command, you just input *%save my\_useful\_session 10-20 23* to save input lines 10 to 20 and 23 to my\_useful\_session.py. (to help with this, every line is pref...
How to save a Python interactive session?
947,810
240
2009-06-03T23:21:02Z
948,006
11
2009-06-04T00:28:21Z
[ "python", "shell", "read-eval-print-loop", "interactive-session" ]
I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, littl...
Also, [reinteract](http://blog.fishsoup.net/2007/11/10/reinteract-better-interactive-python/) gives you a notebook-like interface to a Python session.
How to save a Python interactive session?
947,810
240
2009-06-03T23:21:02Z
948,082
11
2009-06-04T01:03:36Z
[ "python", "shell", "read-eval-print-loop", "interactive-session" ]
I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, littl...
In addition to IPython, a similar utility [bpython](http://bpython-interpreter.org/) has a "save the code you've entered to a file" feature
How to save a Python interactive session?
947,810
240
2009-06-03T23:21:02Z
9,720,341
83
2012-03-15T13:06:35Z
[ "python", "shell", "read-eval-print-loop", "interactive-session" ]
I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, littl...
<http://www.andrewhjon.es/save-interactive-python-session-history> ``` import readline readline.write_history_file('/home/ahj/history') ```
How to save a Python interactive session?
947,810
240
2009-06-03T23:21:02Z
29,974,624
18
2015-04-30T17:56:37Z
[ "python", "shell", "read-eval-print-loop", "interactive-session" ]
I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, littl...
If you are using [IPython](http://ipython.org/) you can save to a file all your previous commands using the magic function *[%history](http://ipython.org/ipython-doc/2/api/generated/IPython.core.magics.history.html#IPython.core.magics.history.HistoryMagics)* with the *-f* parameter, p.e: ``` %history -f /tmp/history.p...
If slicing does not create a copy of a list nor does list() how can I get a real copy of my list?
948,032
9
2009-06-04T00:40:53Z
948,049
22
2009-06-04T00:48:32Z
[ "python", "list", "copy" ]
I am trying to modify a list and since my modifications were getting a bit tricky and my list large I took a slice of my list using the following code ``` tempList=origList[0:10] for item in tempList: item[-1].insert(0 , item[1]) del item[1] ``` I did this thinking that all of the modifications to the list wo...
Slicing creates a shallow copy. In your example, I see that you are calling insert() on item[-1], which means that item is a list of lists. That means that your shallow copies still reference the original objects. You can think of it as making copies of the pointers, not the actual objects. Your solution lies in using...
Sqlalchemy complex in_ clause
948,212
6
2009-06-04T01:40:38Z
6,724,961
16
2011-07-17T15:48:17Z
[ "python", "sql", "sqlalchemy" ]
I'm trying to find a way to cause sqlalchemy to generate sql of the following form: ``` select * from t where (a,b) in ((a1,b1),(a2,b2)); ``` Is this possible? If not, any suggestions on a way to emulate it? Thanks kindly!
Use tuple\_ ``` keys = [(a1, b1), (a2, b2)] session.query(T).filter(tuple_(T.a, T.b).in_(keys)).all() ``` <http://www.sqlalchemy.org/docs/core/expression_api.html> => Look for tuple\_
Python: split a list based on a condition?
949,098
132
2009-06-04T07:37:18Z
949,110
13
2009-06-04T07:41:20Z
[ "python" ]
What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of: ``` good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals] ``` is there a more elegant way to do this? Update: here'...
**First go** (pre-OP-edit): Use sets: ``` mylist = [1,2,3,4,5,6,7] goodvals = [1,3,7,8,9] myset = set(mylist) goodset = set(goodvals) print list(myset.intersection(goodset)) # [1, 3, 7] print list(myset.difference(goodset)) # [2, 4, 5, 6] ``` That's good for both readability (IMHO) and performance. **Second go...
Python: split a list based on a condition?
949,098
132
2009-06-04T07:37:18Z
949,191
20
2009-06-04T08:10:50Z
[ "python" ]
What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of: ``` good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals] ``` is there a more elegant way to do this? Update: here'...
Problem with all proposed solutions is that it will scan and apply the filtering function twice. I'd make a simple small function like this: ``` def SplitIntoTwoLists(l, f): a = [] b = [] for i in l: if f(i): a.append(i) else: b.append(i) return (a,b) ``` That way you are not processing any...
Python: split a list based on a condition?
949,098
132
2009-06-04T07:37:18Z
949,490
72
2009-06-04T09:32:23Z
[ "python" ]
What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of: ``` good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals] ``` is there a more elegant way to do this? Update: here'...
Here's the lazy iterator approach: ``` from itertools import tee def split_on_condition(seq, condition): l1, l2 = tee((condition(item), item) for item in seq) return (i for p, i in l1 if p), (i for p, i in l2 if not p) ``` It evaluates the condition once per item and returns two generators, first yielding va...
Python: split a list based on a condition?
949,098
132
2009-06-04T07:37:18Z
950,591
63
2009-06-04T13:28:23Z
[ "python" ]
What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of: ``` good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals] ``` is there a more elegant way to do this? Update: here'...
> ``` > good = [x for x in mylist if x in goodvals] > bad = [x for x in mylist if x not in goodvals] > ``` > > is there a more elegant way to do this? That code is perfectly readable, and extremely clear! ``` # files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ] IMAGE_TYPES = ('.jpg','...
Python: split a list based on a condition?
949,098
132
2009-06-04T07:37:18Z
3,281,886
9
2010-07-19T14:20:02Z
[ "python" ]
What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of: ``` good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals] ``` is there a more elegant way to do this? Update: here'...
I basically like Anders' approach as it is very general. Here's a version that puts the categorizer first (to match filter syntax) and uses a defaultdict (assumed imported). ``` def categorize(func, seq): """Return mapping from categories to lists of categorized items. """ d = defaultdict(list) for...
Python: split a list based on a condition?
949,098
132
2009-06-04T07:37:18Z
7,881,048
13
2011-10-24T19:42:33Z
[ "python" ]
What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of: ``` good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals] ``` is there a more elegant way to do this? Update: here'...
My take on it. I propose a lazy, single-pass, `partition` function, which preserves relative order in the output subsequences. ## 1. Requirements I assume that the requirements are: * maintain elements' relative order (hence, no sets and dictionaries) * evaluate condition only once for every element (hence not usi...
Python: split a list based on a condition?
949,098
132
2009-06-04T07:37:18Z
12,135,169
100
2012-08-27T00:51:47Z
[ "python" ]
What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of: ``` good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals] ``` is there a more elegant way to do this? Update: here'...
``` good, bad = [], [] for x in mylist: (bad, good)[x in goodvals].append(x) ```
ODFPy documentation
949,171
13
2009-06-04T08:03:41Z
2,183,603
7
2010-02-02T11:26:47Z
[ "python", "openoffice.org", "odf" ]
I need to manipulate the ODF file format (open document format, the open office's internal format), and I need to do it in Python. It seem's ODFPy is a wonderful library for this purpose. Unfortunately the official documentation is very poor, almost unuseful. I can't find almost anything online - maybe it is not so po...
The documentation is unfortunately horrible, and the generated Python wrapper is lousily documented in code, providing lots of functions whose argument lists look like func(\*args). The reference manual *is* actually useful, but not when you're starting out - it doesn't provide any context of how to use these function...
Terminating a Python Program
949,504
4
2009-06-04T09:35:06Z
949,519
8
2009-06-04T09:37:34Z
[ "python" ]
What command do you use in python to terminate a program? i.e. the equivalent of "end" in basic, or "quit" in BASH. I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet. i tried ``` import sys sys.exit() ``` but it will display following error : ``` ...
sys.exit(error\_code) Error\_code will be 0 for a normal exit, 1 or some other positive number for an exit due to an error of some kind, e.g. the user has entered the wrong parameters. sys.exit() "is undefined on some architectures", (although it worked when I tried it on my Linux box!) The [official python docs](ht...
Terminating a Python Program
949,504
4
2009-06-04T09:35:06Z
949,923
9
2009-06-04T11:19:34Z
[ "python" ]
What command do you use in python to terminate a program? i.e. the equivalent of "end" in basic, or "quit" in BASH. I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet. i tried ``` import sys sys.exit() ``` but it will display following error : ``` ...
`sys.exit()` raises the `SystemExit` exception. If you don't catch that exception the program ends. Since you're getting that output, I'm not sure what is happening, but I guess that you're catching all exceptions and printing them yourself: ``` try: ... except: print exception somehow raise ``` If that...
Dynamic loading of python modules
951,124
32
2009-06-04T14:59:25Z
951,256
38
2009-06-04T15:25:02Z
[ "python", "dynamic", "python-import" ]
In python how do you dynamically add modules to a package while your programming is running. I want to be able to add modules to the package directory from an outside process, and be able to use those new modules in my program: ``` import package def doSomething(name): pkg = __import__("package." + name) mod...
Your code is almost correct. See [`__import__`](http://docs.python.org/library/functions.html#__import__) function. ``` def doSomething(name): name = "package." + name mod = __import__(name, fromlist=['']) mod.doSomething() ```
Dynamic loading of python modules
951,124
32
2009-06-04T14:59:25Z
951,678
16
2009-06-04T16:33:38Z
[ "python", "dynamic", "python-import" ]
In python how do you dynamically add modules to a package while your programming is running. I want to be able to add modules to the package directory from an outside process, and be able to use those new modules in my program: ``` import package def doSomething(name): pkg = __import__("package." + name) mod...
Bastien already answered the question, anyway you may find useful this function I use to load all the modules from a subfolder in a dictionary: ``` def loadModules(): res = {} import os # check subfolders lst = os.listdir("services") dir = [] for d in lst: s = os.path.abspath("services"...
Dynamic loading of python modules
951,124
32
2009-06-04T14:59:25Z
951,846
8
2009-06-04T17:02:57Z
[ "python", "dynamic", "python-import" ]
In python how do you dynamically add modules to a package while your programming is running. I want to be able to add modules to the package directory from an outside process, and be able to use those new modules in my program: ``` import package def doSomething(name): pkg = __import__("package." + name) mod...
One trick with Bastien's answer... The `__import__()` function returns the package object, not the module object. If you use the following function, it will dynamically load the module from the package and return you the module, not the package. ``` def my_import(name): mod = __import__(name) components = name...