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
Can modules have properties the same way that objects can?
880,530
54
2009-05-19T01:03:31Z
880,550
43
2009-05-19T01:09:42Z
[ "python", "properties", "python-module" ]
With python properties, I can make it such that ``` obj.y ``` calls a function rather than just returning a value. Is there a way to do this with modules? I have a case where I want ``` module.y ``` to call a function, rather than just returning the value stored there.
Only instances of new-style classes can have properties. You can make Python believe such an instance is a module by stashing it in `sys.modules[thename] = theinstance`. So, for example, your m.py module file could be: ``` import sys class _M(object): def __init__(self): self.c = 0 def afunction(self): sel...
Can modules have properties the same way that objects can?
880,530
54
2009-05-19T01:03:31Z
880,751
34
2009-05-19T02:40:12Z
[ "python", "properties", "python-module" ]
With python properties, I can make it such that ``` obj.y ``` calls a function rather than just returning a value. Is there a way to do this with modules? I have a case where I want ``` module.y ``` to call a function, rather than just returning the value stored there.
I would do this in order to properly inherit all the attributes of a module, and be correctly identified by isinstance() ``` import types class MyModule(types.ModuleType): @property def y(self): return 5 >>> a=MyModule("test") >>> a <module 'test' (built-in)> >>> a.y 5 ``` And then you can insert t...
Applications of Python
880,917
2
2009-05-19T04:03:09Z
880,940
15
2009-05-19T04:11:47Z
[ "python" ]
What are some applications for Python that **relative amateur programmers** can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python? Thanks.
Google App Engine has excellent support for developing -- and especially for deploying -- web applications in Python (with several possible frameworks, of which Django may be the most suitable one for "relative amateurs"). Apart from web apps, Blender lets you use Python for 3D graphics, Poser for apps involving moving...
How to redirect the output of .exe to a file in python?
880,918
12
2009-05-19T04:03:32Z
880,929
7
2009-05-19T04:07:35Z
[ "python", "redirect", "io" ]
In a script , I want to run a .exe with some command line parameters as "-a",and then redirect the standard output of the program to a file? How can I implement that?
Easiest is `os.system("the.exe -a >thefile.txt")`, but there are many other ways, for example with the `subprocess` module in the standard library.
How to redirect the output of .exe to a file in python?
880,918
12
2009-05-19T04:03:32Z
881,686
21
2009-05-19T09:02:05Z
[ "python", "redirect", "io" ]
In a script , I want to run a .exe with some command line parameters as "-a",and then redirect the standard output of the program to a file? How can I implement that?
You can redirect directly to a file using subprocess. ``` import subprocess with open('output.txt', 'w') as output_f: p = subprocess.Popen('Text/to/execute with-arg', stdout=output_f, stderr=output_f) ```
how to send email in python
881,184
2
2009-05-19T06:08:51Z
881,200
12
2009-05-19T06:14:45Z
[ "python" ]
``` import smtplib SERVER = "localhost" FROM = "[email protected]" TO = ["[email protected]"] SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() ``` This is giving the error: ``` '**The debugged program raised the...
Rename your file to something other than email.py. Also get rid of any email.pyc file left over. Problem solved.
What is the reason for performing a double fork when creating a daemon?
881,388
109
2009-05-19T07:25:18Z
881,408
11
2009-05-19T07:32:26Z
[ "python", "unix" ]
I'm trying to create a daemon in python. I've found the [following question](http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python), which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found p...
Taken from [Bad CTK](http://blog.charcoalphile.com/2008/05/03/python-tips-for-writing-daemons/): "On some flavors of Unix, you are forced to do a double-fork on startup, in order to go into daemon mode. This is because single forking isn’t guaranteed to detach from the controlling terminal."
What is the reason for performing a double fork when creating a daemon?
881,388
109
2009-05-19T07:25:18Z
881,415
8
2009-05-19T07:33:54Z
[ "python", "unix" ]
I'm trying to create a daemon in python. I've found the [following question](http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python), which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found p...
According to "Advanced Programming in the Unix Environment", by Stephens and Rago, the second fork is more a recommendation, and it is done to guarantee that the daemon does not acquire a controlling terminal on System V-based systems.
What is the reason for performing a double fork when creating a daemon?
881,388
109
2009-05-19T07:25:18Z
881,434
75
2009-05-19T07:42:54Z
[ "python", "unix" ]
I'm trying to create a daemon in python. I've found the [following question](http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python), which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found p...
Looking at the code referenced in the question, the justification is: ``` # Fork a second child and exit immediately to prevent zombies. This # causes the second child process to be orphaned, making the init # process responsible for its cleanup. And, since the first child is # a session leader without a controlling...
What is the reason for performing a double fork when creating a daemon?
881,388
109
2009-05-19T07:25:18Z
5,386,753
111
2011-03-22T04:19:44Z
[ "python", "unix" ]
I'm trying to create a daemon in python. I've found the [following question](http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python), which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found p...
I was trying to understand the double fork and stumbled upon this question here. After a lot of research this is what I figured out. Hopefully it will help clarify things better for anyone who has the same question. In Unix every process belongs to a group which in turn belongs to a session. Here is the hierarchy… ...
What is the reason for performing a double fork when creating a daemon?
881,388
109
2009-05-19T07:25:18Z
16,317,668
65
2013-05-01T11:54:52Z
[ "python", "unix" ]
I'm trying to create a daemon in python. I've found the [following question](http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python), which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found p...
Strictly speaking, the double-fork has nothing to do with re-parenting the daemon as a child of `init`. All that is necessary to re-parent the child is that the parent must exit. This can be done with only a single fork. Also, doing a double-fork by itself doesn't re-parent the daemon process to `init`; the daemon's pa...
In print statements, what determines whether python shell prints null character or waits for input
881,564
2
2009-05-19T08:24:55Z
881,576
11
2009-05-19T08:26:58Z
[ "python" ]
Recently I was trying some practice programs in python and I came across this small problem. when I typed ``` print "" ``` in IDLE, the python shell printed a null character. If I typed ``` print """""" ``` in IDLE, the python shell printed a null character. but the python shell waits for input if I type ``` pr...
In python you can have strings enclosed with either 1 or 3 quotes. ``` print "a" print """a""" ``` In your case, the interpreter is waiting for the last triple quote.
Python imports: importing a module without .py extension?
881,639
3
2009-05-19T08:50:15Z
881,658
8
2009-05-19T08:55:32Z
[ "python", "debian" ]
In a Python system for which I develop, we usually have this module structure. ``` mymodule/ mymodule/mymodule/feature.py mymodule/test/feature.py ``` This allows our little testing framework to easily import test/feature.py and run unit tests. However, we now have the need for some shell scripts (which are written i...
The [imp module](http://docs.python.org/library/imp.html) is used for this: ``` daniel@purplehaze:/tmp/test$ cat mymodule print "woho!" daniel@purplehaze:/tmp/test$ cat test.py import imp imp.load_source("apanapansson", "mymodule") daniel@purplehaze:/tmp/test$ python test.py woho! daniel@purplehaze:/tmp/test$ ```
How to tell if a class is descended from another class
881,676
11
2009-05-19T09:00:23Z
881,689
27
2009-05-19T09:03:33Z
[ "python" ]
I have a function that accepts a class (not an instance) and, depending on whether or not it's a specific class *or a subclass of that*, I need to pass it in to one of two other (third-party) factory functions. (To forestall any objections, I'm aware this is not very Pythonic, but I'm dependent on what the third-party...
> issubclass only works for instances, not class objects themselves. It works fine for me: ``` >>> class test(object):pass ... >>> issubclass(test,object) True ```
How to use dynamic foreignkey in Django?
881,792
22
2009-05-19T09:27:30Z
881,874
33
2009-05-19T09:59:09Z
[ "python", "django", "foreign-keys" ]
I want to connect a single `ForeignKey` to two different models. For example: I have two models named `Casts` and `Articles`, and a third model, `Faves`, for favoriting either of the other models. How can I make the `ForeignKey` dynamic? ``` class Articles(models.Model): title = models.CharField(max_length=100) ...
Here is how I do it: ``` from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import fields class Photo(models.Model): picture = models.ImageField(null=True, upload_to='./images/') caption = models.CharField(_("Optional caption"),max_length=100,null=True, blank=True) ...
How to use dynamic foreignkey in Django?
881,792
22
2009-05-19T09:27:30Z
881,912
12
2009-05-19T10:11:44Z
[ "python", "django", "foreign-keys" ]
I want to connect a single `ForeignKey` to two different models. For example: I have two models named `Casts` and `Articles`, and a third model, `Faves`, for favoriting either of the other models. How can I make the `ForeignKey` dynamic? ``` class Articles(models.Model): title = models.CharField(max_length=100) ...
Here's an approach. (Note that the models are singular, Django automatically pluralizes for you.) ``` class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Cast(models.Model): title = models.CharField(max_length=100) body = models.TextField() FAVE_CHOIC...
Rendering JSON objects using a Django template after an Ajax call
882,215
58
2009-05-19T11:36:21Z
882,648
8
2009-05-19T13:06:40Z
[ "python", "ajax", "django", "json", "templates" ]
I've been trying to understand what's the optimal way to do [Ajax](http://en.wikipedia.org/wiki/Ajax%5F%28programming%29) in [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). By reading stuff here and there I gathered that the common process is: 1. formulate your Ajax call using some [JavaScript](...
There's no reason you can't return a rendered bit of HTML using Ajax, and insert that into the existing page at the point you want. Obviously you can use Django's templates to render this HTML, if you want.
Rendering JSON objects using a Django template after an Ajax call
882,215
58
2009-05-19T11:36:21Z
883,743
13
2009-05-19T16:19:13Z
[ "python", "ajax", "django", "json", "templates" ]
I've been trying to understand what's the optimal way to do [Ajax](http://en.wikipedia.org/wiki/Ajax%5F%28programming%29) in [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). By reading stuff here and there I gathered that the common process is: 1. formulate your Ajax call using some [JavaScript](...
Here is how I use the same template for traditional rendering and Ajax-response rendering. Template: ``` <div id="sortable"> {% include "admin/app/model/subtemplate.html" %} </div> ``` Included template (aka: subtemplate): ``` <div id="results_listing"> {% if results %} {% for c in results %} ..... ...
Rendering JSON objects using a Django template after an Ajax call
882,215
58
2009-05-19T11:36:21Z
884,339
24
2009-05-19T18:29:24Z
[ "python", "ajax", "django", "json", "templates" ]
I've been trying to understand what's the optimal way to do [Ajax](http://en.wikipedia.org/wiki/Ajax%5F%28programming%29) in [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). By reading stuff here and there I gathered that the common process is: 1. formulate your Ajax call using some [JavaScript](...
Hey thanks vikingosegundo! I like using decorators too :-). But in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead [the snippet n. 942](http://www.djangosnippets.org/snippets/942/) cause it's an improved version of the original one. Here's how it ...
How to hide "cgi-bin", ".py", etc from my URLs?
882,430
11
2009-05-19T12:24:38Z
882,664
12
2009-05-19T13:09:58Z
[ "python", "cgi" ]
Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py" But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never h...
The python way of writing web applications is not cgi-bin. It is by using [WSGI](http://wsgi.org). WSGI is a standard interface between web servers and Python web applications or frameworks. The [PEP 0333](http://www.python.org/dev/peps/pep-0333/) defines it. There are no disadvantages in using it instead of CGI. And...
Sending HTML email using Python
882,712
148
2009-05-19T13:20:18Z
882,770
225
2009-05-19T13:30:55Z
[ "python", "html-email" ]
How can I send the HTML content in an email using Python? I can send simple text.
From [Python v2.6.2 documentation - 19.1.11. email: Examples](http://docs.python.org/library/email-examples.html#id4): > Here’s an example of how to create an HTML message with an alternative plain text version: ``` #! /usr/bin/python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.t...
Sending HTML email using Python
882,712
148
2009-05-19T13:20:18Z
882,804
7
2009-05-19T13:37:02Z
[ "python", "html-email" ]
How can I send the HTML content in an email using Python? I can send simple text.
Here's sample code. This is inspired from code found on the [Python Cookbook](http://code.activestate.com/recipes/langs/python/) site (can't find the exact link) ``` def createhtmlmail (html, text, subject, fromEmail): """Create a mime-message that will render HTML in popular MUAs, text in better ones""" i...
Sending HTML email using Python
882,712
148
2009-05-19T13:20:18Z
883,269
46
2009-05-19T14:55:23Z
[ "python", "html-email" ]
How can I send the HTML content in an email using Python? I can send simple text.
You might try using my [mailer](http://pypi.python.org/pypi/mailer/) module. ``` from mailer import Mailer from mailer import Message message = Message(From="[email protected]", To="[email protected]") message.Subject = "An HTML Email" message.Html = """<p>Hi!<br> How are you?<br> Here is the <a hr...
Sending HTML email using Python
882,712
148
2009-05-19T13:20:18Z
26,369,282
21
2014-10-14T19:59:15Z
[ "python", "html-email" ]
How can I send the HTML content in an email using Python? I can send simple text.
Here is a [Gmail](http://en.wikipedia.org/wiki/Gmail) implementation of the accepted answer: ``` import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # me == my email address # you == recipient's email address me = "[email protected]" you = "[email protected]" # Create message ...
Sending HTML email using Python
882,712
148
2009-05-19T13:20:18Z
32,129,736
16
2015-08-20T22:52:22Z
[ "python", "html-email" ]
How can I send the HTML content in an email using Python? I can send simple text.
Here is a simple way to send an HTML email, just by specifying the Content-Type header as 'text/html': ``` import email.message import smtplib msg = email.message.Message() msg['Subject'] = 'foo' msg['From'] = '[email protected]' msg['To'] = '[email protected]' msg.add_header('Content-Type','text/html') msg.set_payloa...
Is there a way to poll a file handle returned from subprocess.Popen?
883,152
4
2009-05-19T14:33:15Z
883,166
9
2009-05-19T14:36:21Z
[ "python", "pipe", "subprocess" ]
Say I write this: ``` from subprocessing import Popen, STDOUT, PIPE p = Popen(["myproc"], stderr=STDOUT, stdout=PIPE) ``` Now if I do ``` line = p.stdout.readline() ``` my program waits until the subprocess outputs the next line. Is there any magic I can do to `p.stdout` so that I could read the output if it's the...
Use `p.stdout.read(1)` this will read character by character And here is a full example: ``` import subprocess import sys process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) while True: out = process.stdout.read(1) if out == '' and process.poll() != None: break ...
django excel xlwt
883,313
30
2009-05-19T15:04:14Z
883,351
50
2009-05-19T15:09:44Z
[ "python", "django", "excel", "xlwt" ]
On a django site, I want to generate an excel file based on some data in the database. I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library? I've also found this [snip...
neat package! i didn't know about this According to the doc, the `save(filename_or_stream)` method takes either a filename to save on, or a file-like stream to write on. And a Django response object happens to be a file-like stream! so just do `xls.save(response)`. Look the Django docs about [generating PDFs](http://...
Python unittest: how do I test the argument in an Exceptions?
883,357
5
2009-05-19T15:10:36Z
883,401
11
2009-05-19T15:19:27Z
[ "python", "unit-testing" ]
I am testing for Exceptions using unittest, for example: ``` self.assertRaises(UnrecognizedAirportError, func, arg1, arg2) ``` and my code raises: ``` raise UnrecognizedAirportError('From') ``` Which works well. How do I test that the argument in the exception is what I expect it to be? I wish to somehow assert t...
Like this. ``` >>> try: ... raise UnrecognizedAirportError("func","arg1","arg2") ... except UnrecognizedAirportError, e: ... print e.args ... ('func', 'arg1', 'arg2') >>> ``` Your arguments are in `args`, if you simply subclass `Exception`. See <http://docs.python.org/library/exceptions.html#module-exception...
Custom ordering in Django
883,575
20
2009-05-19T15:49:31Z
883,641
37
2009-05-19T16:03:55Z
[ "python", "django", "django-models" ]
How do you define a specific ordering in Django `QuerySet`s? Specifically, if I have a `QuerySet` like so: `['a10', 'a1', 'a2']`. Regular order (using `Whatever.objects.order_by('someField')`) will give me `['a1', 'a10', 'a2']`, while I am looking for: `['a1', 'a2', 'a10']`. What is the proper way to define my own o...
As far as I'm aware, there's no way to specify database-side ordering in this way as it would be too backend-specific. You may wish to resort to good old-fashioned Python sorting: ``` class Foo(models.Model): name = models.CharField(max_length=128) Foo.objects.create(name='a10') Foo.objects.create(name='a1') Foo....
Custom ordering in Django
883,575
20
2009-05-19T15:49:31Z
889,445
21
2009-05-20T18:20:33Z
[ "python", "django", "django-models" ]
How do you define a specific ordering in Django `QuerySet`s? Specifically, if I have a `QuerySet` like so: `['a10', 'a1', 'a2']`. Regular order (using `Whatever.objects.order_by('someField')`) will give me `['a1', 'a10', 'a2']`, while I am looking for: `['a1', 'a2', 'a10']`. What is the proper way to define my own o...
@Jarret's answer (do the sort in Python) works great for simple cases. As soon as you have a large table and want to, say, pull only the first page of results sorted in a certain way, this approach breaks (you have to pull every single row from the database before you can do the sort). At that point I would look into a...
How to spawn parallel child processes on a multi-processor system?
884,650
33
2009-05-19T19:39:42Z
884,846
44
2009-05-19T20:26:13Z
[ "python", "exec", "subprocess", "multiprocessing" ]
I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called: ``` $ python create_graphs.py --name=NAME ``` where NAME is something like XYZ, ABC, NYU etc. In ...
What you are looking for is the [process pool](http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool) class in multiprocessing. ``` import multiprocessing import subprocess def work(cmd): return subprocess.call(cmd, shell=False) if __name__ == '__main__': count = multiprocessing.cpu...
How to parse a RFC 2822 date/time into a Python datetime?
885,015
21
2009-05-19T21:03:05Z
885,048
8
2009-05-19T21:10:19Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
I have a date of the form specified by RFC 2822 -- say `Fri, 15 May 2009 17:58:28 +0000`, as a string. Is there a quick and/or standard way to get it as a `datetime` object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.
There is a parsedate function in [email.util](http://docs.python.org/library/email.util.html). It parses all valid RFC 2822 dates and some special cases.
How to parse a RFC 2822 date/time into a Python datetime?
885,015
21
2009-05-19T21:03:05Z
885,049
12
2009-05-19T21:11:14Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
I have a date of the form specified by RFC 2822 -- say `Fri, 15 May 2009 17:58:28 +0000`, as a string. Is there a quick and/or standard way to get it as a `datetime` object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.
``` from email.utils import parsedate print parsedate('Fri, 15 May 2009 17:58:28 +0000') ``` [Documentation](http://docs.python.org/library/email.util.html#email.utils.parsedate).
How to parse a RFC 2822 date/time into a Python datetime?
885,015
21
2009-05-19T21:03:05Z
1,258,623
26
2009-08-11T05:50:00Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
I have a date of the form specified by RFC 2822 -- say `Fri, 15 May 2009 17:58:28 +0000`, as a string. Is there a quick and/or standard way to get it as a `datetime` object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.
The problem is that parsedate will ignore the offset. Do this instead: ``` from email.utils import parsedate_tz print parsedate_tz('Fri, 15 May 2009 17:58:28 +0700') ```
How to parse a RFC 2822 date/time into a Python datetime?
885,015
21
2009-05-19T21:03:05Z
17,155,727
7
2013-06-17T19:58:42Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
I have a date of the form specified by RFC 2822 -- say `Fri, 15 May 2009 17:58:28 +0000`, as a string. Is there a quick and/or standard way to get it as a `datetime` object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.
I'd like to elaborate on previous answers. `email.utils.parsedate` and `email.utils.parsedate_tz` both return tuples, since the OP needs a `datetime.datetime` object, I'm adding these examples for completeness: ``` from email.utils import parsedate from datetime import datetime import time t = parsedate('Sun, 14 Jul ...
Django Admin & Model Deletion
885,103
2
2009-05-19T21:26:03Z
885,222
9
2009-05-19T21:54:56Z
[ "python", "django", "django-admin" ]
I've got a bunch of classes that inherit from a common base class. This common base class does some cleaning up in its `delete` method. ``` class Base(models.Model): def delete(self): print "foo" class Child(Base): def delete(self): print "bar" super(Child, self).delete() ``` When I c...
According to [this](http://code.djangoproject.com/ticket/11022) documentation bug report ([Document that the admin bulk delete doesn't call Model.delete()](http://code.djangoproject.com/ticket/11022)), the admin's *bulk* delete does NOT call the model's delete function. If you're using bulk delete from the admin, this ...
How do you calculate the greatest number of repetitions in a list?
885,546
10
2009-05-19T23:27:17Z
885,584
42
2009-05-19T23:43:39Z
[ "python", "list" ]
If I have a list in Python like ``` [1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] ``` How do I calculate the greatest number of repeats for any element? In this case `2` is repeated a maximum of 4 times and `1` is repeated a maximum of 3 times. Is there a way to do this but also record the index at which the longest run bega...
Use [groupby](http://docs.python.org/library/itertools.html#itertools.groupby), it group elements by value: ``` from itertools import groupby group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]) print max(group, key=lambda k: len(list(k[1]))) ``` And here is the code in action: ``` >>> group = groupby([1, 2, 2, 2, ...
Beautiful Soup and uTidy
886,381
3
2009-05-20T06:05:38Z
886,400
9
2009-05-20T06:11:05Z
[ "python", "screen-scraping", "beautifulsoup", "tidy" ]
I want to pass the results of [utidy](http://utidylib.berlios.de/) to Beautiful Soup, ala: ``` page = urllib2.urlopen(url) options = dict(output_xhtml=1,add_xml_decl=0,indent=1,tidy_mark=0) cleaned_html = tidy.parseString(page.read(), **options) soup = BeautifulSoup(cleaned_html) ``` When run, the following error res...
Just wrap [`str()`](http://docs.python.org/library/functions.html#str) around `cleaned_html` when passing it to BeautifulSoup.
Get the 1-norm of a vector in Python
886,633
10
2009-05-20T07:37:49Z
886,762
15
2009-05-20T08:15:52Z
[ "python", "vector", "norm" ]
How can I calculate the 1-norm of the difference of two vectors, `||a - b||_1 = sum(|a_i - b_i|)` in Python? ``` a = [1,2,3,4] b = [2,3,4,5] ||a - b||_1 = 4 ```
Python has powerful built-in types, but **Python lists are not mathematical vectors or matrices**. You *could* do this with lists, but it will likely be cumbersome for anything more than trivial operations. If you find yourself needing vector or matrix arithmetic often, the **standard in the field is [NumPy](http://sc...
Get the 1-norm of a vector in Python
886,633
10
2009-05-20T07:37:49Z
886,791
8
2009-05-20T08:20:33Z
[ "python", "vector", "norm" ]
How can I calculate the 1-norm of the difference of two vectors, `||a - b||_1 = sum(|a_i - b_i|)` in Python? ``` a = [1,2,3,4] b = [2,3,4,5] ||a - b||_1 = 4 ```
In NumPy, for two vectors `a` and `b`, this is just ``` numpy.linalg.norm(a - b, ord=1) ```
Controling bars width in matplotlib with per-month data
886,716
6
2009-05-20T08:03:25Z
888,141
12
2009-05-20T14:10:31Z
[ "python", "matplotlib" ]
When I plot data sampled per month with bars, their width is very thin. If I set X axis minor locator to DayLocator(), I can see the bars width is adjusted to 1 day, but I would like them to fill a whole month. I tried to set the minor ticks locator to MonthLocator() without effect. **[edit]** Maybe an example will ...
Just use the `width` keyword argument: ``` bar(x, y, width=30) ``` Or, since different months have different numbers of days, to make it look good you can use a sequence: ``` bar(x, y, width=[(x[j+1]-x[j]).days for j in range(len(x)-1)] + [30]) ```
Machine vision in Python
887,252
19
2009-05-20T10:45:29Z
930,299
7
2009-05-30T18:34:25Z
[ "python", "matlab", "computer-vision" ]
I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started. As far as I know, the only free library for Python that does machine vision is [PyCV](http://pycv.sharkdolphin.com/) (which is a wrapper for [OpenCV](http://opencv.willowgarag...
documentation: A few years ago I used OpenCV wrapped for Python quite a lot. OpenCV is extensively documented, ships with many examples, and there's even a [book](http://oreilly.com/catalog/9780596516130/). The Python wrappers I was using were thin enough so that very little wrapper specific documentation was required ...
Machine vision in Python
887,252
19
2009-05-20T10:45:29Z
930,318
13
2009-05-30T18:48:31Z
[ "python", "matlab", "computer-vision" ]
I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started. As far as I know, the only free library for Python that does machine vision is [PyCV](http://pycv.sharkdolphin.com/) (which is a wrapper for [OpenCV](http://opencv.willowgarag...
OpenCV is probably your best bet for a library; you have your choice of wrappers for them. I looked at the SWIG wrapper that comes with the standard OpenCV install, but ended up using [ctypes-opencv](http://code.google.com/p/ctypes-opencv/) because the memory management seemed cleaner. They are both very thin wrappers...
Is there support for the IN-operator in the "SQL Expression Language" used in SQLAlchemy?
887,388
11
2009-05-20T11:27:26Z
887,402
14
2009-05-20T11:32:30Z
[ "python", "sqlalchemy" ]
Is it possible to express a query like the one below in the "SQL Expression Language" used in SQLAlchemy? ``` SELECT * FROM foo WHERE foo.bar IN (1,2,3) ``` I want to avoid writing the WHERE-clause in plain text. Is there a way to express this similar to my examples below or in any way that doesn't use plain text? `...
``` select([foo], foo.c.bar.in_([1, 2, 3])) ``` You can use the [`.in_()`](http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.ColumnElement.in_) method with Columns or with Instrumented attributes. Both work. [It is mentioned here](http://www.sqlalchemy.org/docs/05/ormtutorial.html#co...
Change file creation date
887,557
10
2009-05-20T12:12:13Z
887,564
13
2009-05-20T12:15:28Z
[ "python", "linux", "file", "date" ]
Can I change creation date of some file using Python in Linux?
You can use [os.utime](http://docs.python.org/library/os.html#os.utime) to change access and modify time but not the creation date.
Change file creation date
887,557
10
2009-05-20T12:12:13Z
887,688
13
2009-05-20T12:44:51Z
[ "python", "linux", "file", "date" ]
Can I change creation date of some file using Python in Linux?
Linux and Unix file system stores : > File access, change and modification time (remember UNIX or Linux never stores file creation time, this is favorite question asked in UNIX/Linux sys admin job interview) [Understanding UNIX / Linux file systems](http://www.cyberciti.biz/tips/understanding-unixlinux-filesystem-ino...
Why python compile the source to bytecode before interpreting?
888,100
8
2009-05-20T14:04:26Z
888,116
7
2009-05-20T14:07:17Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting? Why not interpret from the source directly?
Because interpretting from bytecode directly is faster. It avoids the need to do lexing, for one thing.
Why python compile the source to bytecode before interpreting?
888,100
8
2009-05-20T14:04:26Z
888,117
8
2009-05-20T14:07:35Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting? Why not interpret from the source directly?
Because you can compile to a `.pyc` once and interpret from it many times. So if you're running a script many times you only have the overhead of parsing the source code once.
Why python compile the source to bytecode before interpreting?
888,100
8
2009-05-20T14:04:26Z
888,119
31
2009-05-20T14:07:45Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting? Why not interpret from the source directly?
Nearly no interpreter really interprets code *directly*, line by line – it's simply too inefficient. Almost all interpreters use some intermediate representation which can be executed easily. Also, small optimizations can be performed on this intermediate code. Python furthermore stores this code which has a huge ad...
Make Emacs use UTF-8 with Python Interactive Mode
888,406
7
2009-05-20T14:50:56Z
888,464
7
2009-05-20T15:00:14Z
[ "python", "emacs", "encoding", "utf-8", "terminal" ]
When I start Python from Mac OS' Terminal.app, python recognises the encoding as UTF-8: ``` $ python3.0 Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.encoding 'UTF-8' `...
check your environment variables: ``` $ LANG="en_US.UTF8" python -c "import sys; print sys.stdout.encoding" UTF-8 $ LANG="en_US" python -c "import sys; print sys.stdout.encoding" ANSI_X3.4-1968 ``` in your python hook, try: ``` (setenv "LANG" "en_US.UTF8") ```
ManyToOneField in Django
888,550
5
2009-05-20T15:15:54Z
888,591
8
2009-05-20T15:21:28Z
[ "python", "django" ]
I'm trying to define a many-to-one field in the class that is the "Many". For example, imagine a situation where a user can only be a member of one group but a group can have many users: ``` class User(models.Model): name = models.CharField() class Group(models.Model): name = models.CharField() # This is ...
A `ManyToOne` field, as you've guessed, is called `ForeignKey` in Django. You will have to define it on your `User` class for the logic to work properly, but Django will make a reverse property available on the `Groups` model automatically: ``` class Group(models.Model): name = models.CharField(max_length=64) cla...
Daemonizing python's BaseHTTPServer
888,834
8
2009-05-20T16:04:22Z
890,300
7
2009-05-20T21:17:13Z
[ "python", "daemon", "basehttpserver" ]
I am working on a daemon where I need to embed a HTTP server. I am attempting to do it with BaseHTTPServer, which when I run it in the foreground, it works fine, but when I try and fork the daemon into the background, it stops working. My main application continues to work, but BaseHTTPServer does not. I believe this ...
After a bit of googling I [finally stumbled over this BaseHTTPServer documentation](http://pymotw.com/2/BaseHTTPServer/index.html#module-BaseHTTPServer) and after that I ended up with: ``` from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from SocketServer import ThreadingMixIn class ThreadedHTTPServer(Th...
Function Decorators
889,088
5
2009-05-20T16:57:13Z
889,145
8
2009-05-20T17:12:34Z
[ "python", "decorator", "argument-passing" ]
I like being able to measure performance of the python functions I code, so very often I do something similar to this... ``` import time def some_function(arg1, arg2, ..., argN, verbose = True) : t = time.clock() # works best in Windows # t = time.time() # apparently works better in Linux # Function code...
Though [inspect](http://docs.python.org/3.0/library/inspect.html) may get you a bit on the way, what you want is in general *not* possible: ``` def f(*args): pass ``` Now how many arguments does `f` take? Since `*args` and `**kwargs` allow for an arbitrary number of arguments, there is no way to determine the num...
Function Decorators
889,088
5
2009-05-20T16:57:13Z
889,235
7
2009-05-20T17:34:31Z
[ "python", "decorator", "argument-passing" ]
I like being able to measure performance of the python functions I code, so very often I do something similar to this... ``` import time def some_function(arg1, arg2, ..., argN, verbose = True) : t = time.clock() # works best in Windows # t = time.time() # apparently works better in Linux # Function code...
+1 on Stephan202's answer, however (putting this in a separate answer since comments don't format code well!), the following bit of code in that answer: ``` verbose = False if 'verbose' in kwargs: verbose = True del kwargs['verbose'] ``` can be expressed much more clearly and concisely as: ``` verbose = kw...
Python regular expression to match # followed by 0-7 followed by ##
889,143
2
2009-05-20T17:12:09Z
889,188
7
2009-05-20T17:22:34Z
[ "python", "regex" ]
I would like to intercept string starting with `\*#\*` followed by a number between 0 and 7 and ending with: `##` so something like `\*#\*0##` but I could not find a regex for this
Assuming you want to allow **only** one # before and two after, I'd do it like this: ``` r'^(\#{1}([0-7])\#{2})' ``` It's important to note that [Alex's](http://stackoverflow.com/questions/889143/python-regular-expression/889154#889154) regex will also match things like ``` ###7###### ########1### ``` which may or ...
How to check if a file is a valid image file?
889,333
40
2009-05-20T17:55:16Z
889,349
8
2009-05-20T17:58:26Z
[ "python", "image" ]
I am currently using PIL. ``` import Image try: im=Image.open(filename) # do stuff except IOError: # filename not an image file ``` However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowError exception. Is there som...
A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking above.
How to check if a file is a valid image file?
889,333
40
2009-05-20T17:55:16Z
889,639
20
2009-05-20T19:02:45Z
[ "python", "image" ]
I am currently using PIL. ``` import Image try: im=Image.open(filename) # do stuff except IOError: # filename not an image file ``` However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowError exception. Is there som...
In addition to what Brian is suggesting you could use PIL's [verify](http://effbot.org/imagingbook/image.htm#tag-Image.Image.verify) method to check if the file is broken. > im.verify() > > Attempts to determine if the file is > broken, without actually decoding the > image data. If this method finds any > problems, i...
How to check if a file is a valid image file?
889,333
40
2009-05-20T17:55:16Z
902,779
88
2009-05-24T00:29:03Z
[ "python", "image" ]
I am currently using PIL. ``` import Image try: im=Image.open(filename) # do stuff except IOError: # filename not an image file ``` However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowError exception. Is there som...
I have just found the builtin [imghdr](http://docs.python.org/library/imghdr.html) module. From python documentation: > The imghdr module determines the type > of image contained in a file or byte > stream. This is how it works: ``` >>> import imghdr >>> imghdr.what('/tmp/bass') 'gif' ``` Using a module is much bet...
Accurate timing of functions in python
889,900
46
2009-05-20T19:52:35Z
889,916
29
2009-05-20T19:55:39Z
[ "python", "testing", "time", "profiling" ]
I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time\_it" that takes another function, runs it, and returns the time it took to run. ``` def time_it(f, *args): start = time.clock() f(*args) return (time.clock() - ...
Instead of writing your own profiling code, I suggest you check out the built-in Python profilers (`profile` or `cProfile`, depending on your needs): <http://docs.python.org/library/profile.html>
Accurate timing of functions in python
889,900
46
2009-05-20T19:52:35Z
889,919
58
2009-05-20T19:55:45Z
[ "python", "testing", "time", "profiling" ]
I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time\_it" that takes another function, runs it, and returns the time it took to run. ``` def time_it(f, *args): start = time.clock() f(*args) return (time.clock() - ...
Use the [`timeit` module](http://docs.python.org/library/timeit.html) from the Python standard library. Basic usage: ``` from timeit import Timer # first argument is the code to be run, the second "setup" argument is only run once, # and it not included in the execution time. t = Timer("""x.index(123)""", setup="""x...
Accurate timing of functions in python
889,900
46
2009-05-20T19:52:35Z
890,030
19
2009-05-20T20:21:00Z
[ "python", "testing", "time", "profiling" ]
I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time\_it" that takes another function, runs it, and returns the time it took to run. ``` def time_it(f, *args): start = time.clock() f(*args) return (time.clock() - ...
This code is very inaccurate ``` total= 0 for i in range(1000): start= time.clock() function() end= time.clock() total += end-start time= total/1000 ``` This code is less inaccurate ``` start= time.clock() for i in range(1000): function() end= time.clock() time= (end-start)/1000 ``` The very ina...
Accurate timing of functions in python
889,900
46
2009-05-20T19:52:35Z
18,527,364
9
2013-08-30T07:33:17Z
[ "python", "testing", "time", "profiling" ]
I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time\_it" that takes another function, runs it, and returns the time it took to run. ``` def time_it(f, *args): start = time.clock() f(*args) return (time.clock() - ...
If you want to time a python method even if block you measure may throw, one good approach is to use `with` statement. Define some `Timer` class as ``` import time class Timer: def __enter__(self): self.start = time.clock() return self def __exit__(self, *args): self.end = time.cl...
Accurate timing of functions in python
889,900
46
2009-05-20T19:52:35Z
18,528,044
16
2013-08-30T08:12:23Z
[ "python", "testing", "time", "profiling" ]
I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time\_it" that takes another function, runs it, and returns the time it took to run. ``` def time_it(f, *args): start = time.clock() f(*args) return (time.clock() - ...
You can create a "timeme" decorator like so ``` import time def timeme(method): def wrapper(*args, **kw): startTime = int(round(time.time() * 1000)) result = method(*args, **kw) endTime = int(round(time.time() * 1000)) print(endTime ...
How do I generate circular thumbnails with PIL?
890,051
23
2009-05-20T20:26:27Z
890,114
52
2009-05-20T20:37:16Z
[ "python", "thumbnails", "python-imaging-library", "circle" ]
How do I generate circular image thumbnails using PIL? The space outside the circle should be transparent. Snippets would be highly appreciated, thank you in advance.
The easiest way to do it is by using masks. Create a black and white mask with any shape you want. And put that shape as an alpha layer ``` from PIL import Image, ImageOps mask = Image.open('mask.png').convert('L') im = Image.open('image.png') output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.putalpha...
How do I generate circular thumbnails with PIL?
890,051
23
2009-05-20T20:26:27Z
22,336,005
11
2014-03-11T20:31:44Z
[ "python", "thumbnails", "python-imaging-library", "circle" ]
How do I generate circular image thumbnails using PIL? The space outside the circle should be transparent. Snippets would be highly appreciated, thank you in advance.
I would like to add to the already accepted answer a solution to antialias the resulting circle, the trick is to produce a bigger mask and then scale it down using an ANTIALIAS filter: here is the code ``` from PIL import Image, ImageOps, ImageDraw im = Image.open('image.jpg') bigsize = (im.size[0] * 3, im.size[1] * ...
Algorithm to Divide a list of numbers into 2 equal sum lists
890,171
23
2009-05-20T20:49:50Z
890,243
29
2009-05-20T21:03:29Z
[ "python", "algorithm", "dynamic-programming", "np-complete", "knapsack-problem" ]
There is a list of numbers. The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed. ``` #Example: >>>que = [2,3,10,5,8,9,7,3,5,2] >>>make_teams(que) 27 27 ``` Is there an error in the following code algorithm for some case? How do I optimize and/or pythoniz...
[Dynamic programming](http://en.wikipedia.org/wiki/Dynamic%5Fprogramming) is the solution you're looking for. Example with {3,4,10,3,2,5} ``` X-Axis: Reachable sum of group. max = sum(all numbers) / 2 (rounded up) Y-Axis: Count elements in group. max = count numbers / 2 (rounded up) 1 2 ...
Explain to me what the big deal with tail call optimization is and why Python needs it
890,461
20
2009-05-20T21:55:07Z
890,548
13
2009-05-20T22:19:21Z
[ "python", "tail-recursion", "tail-call-optimization" ]
So apparently, there's been a big brouhaha over whether or not Python needs tail call optimization. This came to a head when someone [shipped Guido a copy of SICP](http://drj11.wordpress.com/2009/04/30/python-tail-call-optimisation/) because he didn't "get it." I'm in the same boat as Guido. I understand the concept of...
Personally, i put great value on tail call optimization; but mainly because it makes recursion as efficient as iteration (or makes iteration a subset of recursion). On minimalistic languages you get huge expressive power without sacrificing performance. On a 'practical' language (like Python), OTOH, you usually have a...
Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later?
890,485
24
2009-05-20T22:02:21Z
890,502
51
2009-05-20T22:07:34Z
[ "python", "pickle" ]
More specific dupe of [875228—Simple data storing in Python](http://stackoverflow.com/questions/875228/simple-data-storing-in-python). I have a rather large dict (6 GB) and I need to do some processing on it. I'm trying out several document clustering methods, so I need to have the whole thing in memory at once. I h...
Why not use [python pickle](http://docs.python.org/library/pickle.html)? Python has a great serializing module called pickle it is very easy to use. ``` import cPickle cPickle.dump(obj, open('save.p', 'wb')) obj = cPickle.load(open('save.p', 'rb')) ``` There are two disadvantages with pickle: * It's not secure agai...
Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later?
890,485
24
2009-05-20T22:02:21Z
890,694
11
2009-05-20T23:12:21Z
[ "python", "pickle" ]
More specific dupe of [875228—Simple data storing in Python](http://stackoverflow.com/questions/875228/simple-data-storing-in-python). I have a rather large dict (6 GB) and I need to do some processing on it. I'm trying out several document clustering methods, so I need to have the whole thing in memory at once. I h...
I'd use [`shelve`](http://docs.python.org/library/shelve.html), `json`, `yaml`, or whatever, as suggested by other answers. `shelve` is specially cool because you can have the `dict` on disk and still use it. Values will be loaded on-demand. But if you really want to parse the text of the `dict`, and it contains only...
How do you reload a Django model module using the interactive interpreter via "manage.py shell"?
890,924
49
2009-05-21T00:38:16Z
903,943
38
2009-05-24T14:59:27Z
[ "python", "django" ]
I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well: [How do I unload (reload) a Python module?](http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module) For some reason, I am having trouble doing that wi...
Well, I think I have to answer to this. The problem is that Django caches its models in a singleton (singleton like structure) called AppCache. Basically, to reload Django models you need to first reload and re-import all the model modules stored in the AppCache. Then you need to wipe out the AppCache. Here's the code ...
Detect & Record Audio in Python
892,199
49
2009-05-21T10:05:32Z
892,293
36
2009-05-21T10:39:35Z
[ "python", "wav", "audio-recording" ]
I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module. I'm thinking it should be possible with the wave mo...
I believe the WAVE module does not support recording, just processing existing files. You might want to look at [PyAudio](http://people.csail.mit.edu/hubert/pyaudio/) for actually recording. WAV is about the world's simplest file format. In paInt16 you just get a signed integer representing a level, and closer to 0 is ...
Detect & Record Audio in Python
892,199
49
2009-05-21T10:05:32Z
6,743,593
64
2011-07-19T07:24:04Z
[ "python", "wav", "audio-recording" ]
I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module. I'm thinking it should be possible with the wave mo...
As a follow up to Nick Fortescue's answer, here's a more complete example of how to record from the microphone and process the resulting data: ``` from sys import byteorder from array import array from struct import pack import pyaudio import wave THRESHOLD = 500 CHUNK_SIZE = 1024 FORMAT = pyaudio.paInt16 RATE = 441...
Detect & Record Audio in Python
892,199
49
2009-05-21T10:05:32Z
16,385,946
11
2013-05-05T15:14:56Z
[ "python", "wav", "audio-recording" ]
I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module. I'm thinking it should be possible with the wave mo...
Thanks to cryo for improved version that I based my tested code below: ``` #Instead of adding silence at start and end of recording (values=0) I add the original audio . This makes audio sound more natural as volume is >0. See trim() #I also fixed issue with the previous code - accumulated silence counter needs to be ...
Overriding a static method in python
893,015
27
2009-05-21T13:47:09Z
893,060
37
2009-05-21T13:56:59Z
[ "python", "static", "override" ]
Referring to the [first answer](http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static/114267#114267) about python's bound and unbound methods here, I have a question: ``` class Test: def method_one(self): print "Called method_one" @staticmethod def me...
In the form that you are using there, you are explicitly specifying what class's static `method_two` to call. If `method_three` was a classmethod, and you called `cls.method_two`, you would get the results that you wanted: ``` class Test: def method_one(self): print "Called method_one" @staticmethod ...
Seeing escape characters when pressing the arrow keys in python shell
893,053
47
2009-05-21T13:55:32Z
893,200
15
2009-05-21T14:27:22Z
[ "python", "shell", "ssh", "arrow-keys" ]
In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc. But after I ssh into another machine and start `python` there, I get sessions like: ``` >>> import os >>> ^[[A ``` where the last character comes from arro...
Looks like readline is not enabled. Check if **PYTHONSTARTUP** variable is defined, for me it points to **/etc/pythonstart** and that file is executed by the python process before going interactive, which setups readline/history handling. Thanks to @chown here is the docs on this: <http://docs.python.org/2/tutorial/in...
Seeing escape characters when pressing the arrow keys in python shell
893,053
47
2009-05-21T13:55:32Z
2,806,049
13
2010-05-10T20:04:31Z
[ "python", "shell", "ssh", "arrow-keys" ]
In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc. But after I ssh into another machine and start `python` there, I get sessions like: ``` >>> import os >>> ^[[A ``` where the last character comes from arro...
1. install readline-devel package. 2. recompile python with readline module 3. Bingo!
Seeing escape characters when pressing the arrow keys in python shell
893,053
47
2009-05-21T13:55:32Z
26,356,378
33
2014-10-14T08:46:59Z
[ "python", "shell", "ssh", "arrow-keys" ]
In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc. But after I ssh into another machine and start `python` there, I get sessions like: ``` >>> import os >>> ^[[A ``` where the last character comes from arro...
I've solved this issue by installing `readline` package: ``` pip install readline ```
Multiple variables in Python 'with' statement
893,333
146
2009-05-21T14:51:27Z
893,356
17
2009-05-21T14:55:22Z
[ "python", "with-statement" ]
Is it possible to declare more than one variable using a `with` statement in Python? Something like: ``` from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) ``` ... or is cleaning up two resources at the same tim...
I think you want to do this instead: ``` from __future__ import with_statement with open("out.txt","wt") as file_out: with open("in.txt") as file_in: for line in file_in: file_out.write(line) ```
Multiple variables in Python 'with' statement
893,333
146
2009-05-21T14:51:27Z
893,360
52
2009-05-21T14:55:42Z
[ "python", "with-statement" ]
Is it possible to declare more than one variable using a `with` statement in Python? Something like: ``` from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) ``` ... or is cleaning up two resources at the same tim...
[`contextlib.nested`](http://docs.python.org/2/library/contextlib.html#contextlib.nested) supports this: ``` import contextlib with contextlib.nested(open("out.txt","wt"), open("in.txt")) as (file_out, file_in): ... ``` **Update:** To quote the documentation, regarding [`contextlib.nested`](http://docs.python....
Multiple variables in Python 'with' statement
893,333
146
2009-05-21T14:51:27Z
1,073,814
296
2009-07-02T11:25:50Z
[ "python", "with-statement" ]
Is it possible to declare more than one variable using a `with` statement in Python? Something like: ``` from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) ``` ... or is cleaning up two resources at the same tim...
It is possible in [Python 3 since v3.1](http://docs.python.org/3.1/reference/compound_stmts.html#with) and [Python 2.7](http://docs.python.org/dev/whatsnew/2.7.html#other-language-changes). The new `with` syntax supports multiple context managers: ``` with A() as a, B() as b, C() as c: doSomething(a,b,c) ``` Unli...
Python doctest fails on 0.0 != -0.0--what gives?
893,398
2
2009-05-21T15:01:39Z
893,413
9
2009-05-21T15:04:23Z
[ "python" ]
Given the following code: ``` def slope(x1, y1, x2, y2): """ >>> slope(5, 3, 4, 2) 1.0 >>> slope(1, 2, 3, 2) 0.0 >>> slope(1, 2, 3, 3) 0.5 >>> slope(2, 4, 1, 2) 2.0 """ xa = float (x1) xb = float (x2) ya = float (y1) yb = float (y2) return (ya...
It fails because [doctest](http://docs.python.org/3.0/library/doctest.html) does *string comparison*. It merely checks whether the output is identical to what would have been outputted if the code had been executed at the Python interactive interpreter: ``` >>> 0 / -2 -0.0 ``` **Edit:**: The link [referenced](http://...
item frequency count in python
893,417
40
2009-05-21T15:04:36Z
893,459
73
2009-05-21T15:10:59Z
[ "python", "count", "frequency", "counting" ]
I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is: ``` words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for ite...
[defaultdict](http://docs.python.org/library/collections.html#defaultdict-objects) to the rescue! ``` from collections import defaultdict words = "apple banana apple strawberry banana lemon" d = defaultdict(int) for word in words.split(): d[word] += 1 ``` This runs in O(n).
item frequency count in python
893,417
40
2009-05-21T15:04:36Z
893,463
10
2009-05-21T15:11:47Z
[ "python", "count", "frequency", "counting" ]
I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is: ``` words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for ite...
Standard approach: ``` from collections import defaultdict words = "apple banana apple strawberry banana lemon" words = words.split() result = collections.defaultdict(int) for word in words: result[word] += 1 print result ``` Groupby oneliner: ``` from itertools import groupby words = "apple banana apple stra...
item frequency count in python
893,417
40
2009-05-21T15:04:36Z
893,499
96
2009-05-21T15:16:59Z
[ "python", "count", "frequency", "counting" ]
I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is: ``` words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for ite...
If you are using python 2.7+/3.1+, there is a [Counter Class](http://docs.python.org/dev/py3k/library/collections.html#collections.Counter) in the collections module which is purpose built to solve this type of problem: ``` >>> from collections import Counter >>> words = "apple banana apple strawberry banana lemon" >>...
How do I calculate r-squared using Python and Numpy?
893,657
38
2009-05-21T15:55:54Z
895,063
25
2009-05-21T20:48:35Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.). This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I a...
From the [numpy.polyfit](http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html) documentation, it is fitting linear regression. Specifically, numpy.polyfit with degree 'd' fits a linear regression with the mean function E(y|x) = p\_d \* x\*\*d + p\_{d-1} \* x \*\*(d-1) + ... + p\_1 \* x + p\_0 So you...
How do I calculate r-squared using Python and Numpy?
893,657
38
2009-05-21T15:55:54Z
1,517,401
54
2009-10-04T21:15:51Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.). This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I a...
A very late reply, but just in case someone needs a ready function for this: [scipy.stats.stats.linregress](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html) i.e. ``` slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y) ``` as in @Adam Marples's answer.
How do I calculate r-squared using Python and Numpy?
893,657
38
2009-05-21T15:55:54Z
13,918,150
9
2012-12-17T16:37:46Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.). This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I a...
I have been using this successfully, where x and y are array-like. ``` def rsquared(x, y): """ Return R^2 where x and y are array-like.""" slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y) return r_value**2 ```
How do I calculate r-squared using Python and Numpy?
893,657
38
2009-05-21T15:55:54Z
30,804,603
7
2015-06-12T13:41:03Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.). This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I a...
From yanl (yet-another-library) `sklearn.metrics` has an [`r2_square`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.html) function; ``` from sklearn.metrics import r2_score coefficient_of_dermination = r2_score(y, p(x)) ```
PyQt: Show menu in a system tray application
893,984
20
2009-05-21T17:05:35Z
895,721
24
2009-05-21T23:08:33Z
[ "python", "menu", "pyqt", "system-tray" ]
First of all, I'm an experienced C programmer but new to python. I want to create a simple application in python using pyqt. Let's imagine this application it is as simple as when it is run it has to put an icon in the system tray and it has offer an option in its menu to exit the application. This code works, it show...
Well, after some debugging I found the problem. The QMenu object it is destroyed after finish `__init__` function because it doesn't have a parent. While the parent of a QSystemTrayIcon can be an object for the QMenu it has to be a Qwidget. This code works (see how QMenu gets the same parent as the QSystemTrayIcon whic...
How do I get the current file, current class, and current method with Python?
894,088
28
2009-05-21T17:23:59Z
894,137
30
2009-05-21T17:34:00Z
[ "python", "filenames" ]
* Name of the file from where code is running * Name of the class from where code is running * Name of the method (attribute of the class) where code is running
Here is an example of each: ``` from inspect import stack class Foo: def __init__(self): print __file__ print self.__class__.__name__ print stack()[0][3] f = Foo() ```
How do I get the current file, current class, and current method with Python?
894,088
28
2009-05-21T17:23:59Z
894,138
9
2009-05-21T17:34:10Z
[ "python", "filenames" ]
* Name of the file from where code is running * Name of the class from where code is running * Name of the method (attribute of the class) where code is running
``` import sys class A: def __init__(self): print __file__ print self.__class__.__name__ print sys._getframe().f_code.co_name a = A() ```
Has Python changed to more object oriented?
894,502
9
2009-05-21T18:56:03Z
894,541
12
2009-05-21T19:03:43Z
[ "python", "ruby", "oop" ]
I remember that at one point, [it was said that Python is less object oriented than Ruby](http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html), since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?
I'm not sure that I buy the argument that Ruby is more object-oriented than Python. There's more to being object-oriented than just using objects and dot syntax. A common argument that I see is that in Python to get the length of a list, you do something like this: ``` len(some_list) ``` I see this as a [bikeshed arg...
Has Python changed to more object oriented?
894,502
9
2009-05-21T18:56:03Z
894,692
39
2009-05-21T19:32:01Z
[ "python", "ruby", "oop" ]
I remember that at one point, [it was said that Python is less object oriented than Ruby](http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html), since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?
Jian Lin — the answer is "Yes", Python is more object-oriented than when Matz decided he wanted to create Ruby, and both languages now feature "everything is an object". Back when Python was younger, "types" like strings and numbers lacked methods, whereas "objects" were built with the "class" statement (or by delibe...
Has Python changed to more object oriented?
894,502
9
2009-05-21T18:56:03Z
894,716
7
2009-05-21T19:36:28Z
[ "python", "ruby", "oop" ]
I remember that at one point, [it was said that Python is less object oriented than Ruby](http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html), since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?
Although this is not properly an answer... Why do you care about Python being more or less OO? The cool thing about Python is that it's *pythonic*, not object oriented or funcitonal or whichever paradigm that is fashionable at the moment! :-) I learnt to program with Java and Object Orientation, but now I don't give a...
Circular dependency in Python
894,864
40
2009-05-21T20:08:08Z
894,885
67
2009-05-21T20:11:55Z
[ "python", "circular-dependency" ]
I have two files, `node.py` and `path.py`, which define two classes, `Node` and `Path`, respectively. Up to today, the definition for `Path` referenced the `Node` object, and therefore I had done ``` from node.py import * ``` in the `path.py` file. However, as of today I created a new method for `Node` that referen...
*[Importing Python Modules](http://effbot.org/zone/import-confusion.htm)* is a great article that explains circular imports in Python. The easiest way to fix this is to move the path import to the end of the node module.
Bubble Sort Homework
895,371
113
2009-05-21T21:47:24Z
895,405
9
2009-05-21T21:54:22Z
[ "python", "algorithm", "sorting", "bubble-sort" ]
In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them. This is my attempt in Python: ``` mylist = [12, 5, 13, 8, 9, 65] def bubble(badList): length = len(badList) - 1 unsorted = True ...
This is what happens when you use variable name of negative meaning, you need to invert their values. The following would be easier to understand: ``` sorted = False while not sorted: ... ``` On the other hand, the logic of the algorithm is a little bit off. You need to check whether two elements swapped during t...
Bubble Sort Homework
895,371
113
2009-05-21T21:47:24Z
895,410
8
2009-05-21T21:55:33Z
[ "python", "algorithm", "sorting", "bubble-sort" ]
In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them. This is my attempt in Python: ``` mylist = [12, 5, 13, 8, 9, 65] def bubble(badList): length = len(badList) - 1 unsorted = True ...
Your use of the Unsorted variable is wrong; you want to have a variable that tells you if you have swapped two elements; if you have done that, you can exit your loop, otherwise, you need to loop again. To fix what you've got here, just put the "unsorted = false" in the body of your if case; remove your else case; and ...
Bubble Sort Homework
895,371
113
2009-05-21T21:47:24Z
895,755
11
2009-05-21T23:18:39Z
[ "python", "algorithm", "sorting", "bubble-sort" ]
In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them. This is my attempt in Python: ``` mylist = [12, 5, 13, 8, 9, 65] def bubble(badList): length = len(badList) - 1 unsorted = True ...
The goal of bubble sort is to move the *heavier* items at the bottom in each round, while moving the *lighter* items up. In the inner loop, where you compare the elements, **you don't have to iterate the whole list in each turn**. The *heaviest* is already placed last. The *swapped* variable is an extra check so we can...
Bubble Sort Homework
895,371
113
2009-05-21T21:47:24Z
902,736
106
2009-05-23T23:49:07Z
[ "python", "algorithm", "sorting", "bubble-sort" ]
In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them. This is my attempt in Python: ``` mylist = [12, 5, 13, 8, 9, 65] def bubble(badList): length = len(badList) - 1 unsorted = True ...
To explain why your script isn't working right now, I'll rename the variable `unsorted` to `sorted`. At first, your list isn't yet sorted. Of course, we set `sorted` to `False`. As soon as we start the `while` loop, we assume that the list is already sorted. The idea is this: as soon as we find two elements that are ...
What if I want to store a None value in the memcache?
895,386
10
2009-05-21T21:50:03Z
895,579
7
2009-05-21T22:29:26Z
[ "python", "google-app-engine", "memcached" ]
This is specifically related to the Google App Engine Memcache API, but I'm sure it also applies to other Memcache tools. The dictionary .get() method allows you to specify a default value, such as dict.get('key', 'defaultval') This can be useful if it's possible you might want to store None as a value in a dictionar...
A possible way to do this is to create new class that defines `None` for this purpose, and assign instances of this to the cache (unfortunately you cannot extend `None`). Alternatively, you could use the empty string "", or avoid storing None/null values altogether (absence of the key implies None). Then check for ins...