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
Difference between raise Exception, "foo" and raise Exception("foo")?
6,448,229
16
2011-06-23T00:56:14Z
6,448,248
24
2011-06-23T01:00:41Z
[ "python" ]
The title is pretty self explanatory -- what's the difference between: ``` raise Exception, "foo" ``` and ``` raise Exception("foo") ``` Does it do exactly the same thing, just different syntax? I'm using Python 2.x, but I'd like to hear of any differences in Python 3.x
both amount to the same thing in Python2. in Python3, the `raise Exception, "foo"` syntax is no longer supported.
What does urllib2.Request(<url>) do and how do i print/view it
6,448,430
6
2011-06-23T01:35:56Z
6,450,639
7
2011-06-23T07:20:33Z
[ "python" ]
I'm trying to learn how urllib2 works and how it encapsulates its various components before sending out an actual request or response. So far I have: ``` theurl = "www.example.com" ``` That obviously specifies the URL to look at. ``` req = urllib2.Request(theurl) ``` Don't know what this does, hence the question. ...
The class "Request" you're asking about: <http://docs.python.org/library/urllib2.html#urllib2.Request> > class urllib2.Request(url[, data][, > headers][, origin\_req\_host][, > unverifiable]) > > This class is an abstraction of a URL > request. The function you actually want to make a request (which can accept a `Req...
Does garbage collection make python slower?
6,448,742
7
2011-06-23T02:35:59Z
6,448,754
18
2011-06-23T02:38:07Z
[ "python", "memory-management", "memory-leaks", "garbage-collection", "cython" ]
OK, so we are developing an network related application where the user can upload their own python scripts to decide for an algorithm. Our code contains c and cython and python modules. Since avoiding latency, memory footprint and minimal processing is critical for us, we were wondering if it's a wise and effective (p...
Just let the language do what it wants to do, and if you find you have an actual problem, come on back and post about it. Otherwise it's premature optimization.
Does garbage collection make python slower?
6,448,742
7
2011-06-23T02:35:59Z
6,448,994
11
2011-06-23T03:27:49Z
[ "python", "memory-management", "memory-leaks", "garbage-collection", "cython" ]
OK, so we are developing an network related application where the user can upload their own python scripts to decide for an algorithm. Our code contains c and cython and python modules. Since avoiding latency, memory footprint and minimal processing is critical for us, we were wondering if it's a wise and effective (p...
`gc.disable` only turns off the *cyclic* garbage collector. Objects will still be collected when the refcount drops to zero anyway. So unless you have a lot of cyclic references, it will make no difference. Are you are talking about doing a customised Python build and disabling the ref counting GC?
WxPython changing the shape of bitmap button
6,449,709
4
2011-06-23T05:27:20Z
6,469,338
15
2011-06-24T14:35:04Z
[ "python", "wxpython" ]
Hi I'm sort new to wxPython and still in the process of learning. I'm trying to make a bitmap button using a particular image like this for example: <http://i.min.us/idk3Uy.png> The catch is I want to retain the original shape of the image in the button, like a circular button for example instead of a rectangular one ...
You're probably going to have to implement a custom control for this. I've done my fair share of custom wxPython controls, so I went ahead and wrote a `ShapedButton` class for you. =) To run this demo, you just need three images: * button-normal.png * button-pressed.png * button-disabled.png The three images are use...
Can I import as only for a function, and have the rest imported as they are?
6,450,228
2
2011-06-23T06:39:18Z
6,450,308
7
2011-06-23T06:47:36Z
[ "python", "import" ]
Let's say I have a function named "hello" in a module named a, and various other functions. Is it possible to import hello as goodbye, along with the other symbols? I am thinking of something like this, however it's not valid: ``` from a import hello as goodbye,* ```
You can import from a, then bind the new name that you want and delete the previous. Something like ``` from a import * goodbye = hello del hello ``` Star imports are usually not so good exactly because of namespace pollution.
mod_wsgi and multiple installations of python
6,450,459
13
2011-06-23T07:03:56Z
6,450,764
8
2011-06-23T07:33:54Z
[ "python", "apache", "mod-wsgi" ]
This is kind of a continuation of [this](http://stackoverflow.com/questions/6449400/no-module-named-os-found-django-mod-wsgi-apache-2-2) question, but it has deviated so I started a new one. I'd like to use Python 2.5 instead of OS X's default 2.6. I've set this up for my terminal and whatnot, but whenever apache runs ...
You should use the following directives depending on which version of mod\_wsgi you use For mod\_wsgi 1.x: ``` WSGIPythonExecutable /path/to/python/2.5/exe ``` For mod\_wsgi 2.x: ``` WSGIPythonHome /path/to/python/2.5/exe/directory ``` The `WSGIPythonPath` is just intended to add your own libraries to the Python P...
Detect alternating signs
6,451,514
4
2011-06-23T08:49:38Z
6,451,605
7
2011-06-23T08:59:21Z
[ "python", "numpy" ]
Is there a nice and short way to tell whether a python list (or numpy array) contains numbers with alternating signs? In other words: ``` is_alternating_signs([1, -1, 1, -1, 1]) == True is_alternating_signs([-1, 1, -1, 1, -1]) == True is_alternating_signs([1, -1, 1, -1, -1]) == False ```
OK, thanks to SO "related" feature. I found [this question](http://stackoverflow.com/questions/2652368/how-to-detect-a-sign-change-for-elements-in-a-numpy-array) and adopted the answer by [ianalis](http://stackoverflow.com/users/100217/ianalis) and the comment by [lazyr](http://stackoverflow.com/users/566644/lazyr) ``...
python how to convert datetime dates to decimal years
6,451,655
4
2011-06-23T09:03:34Z
6,451,892
14
2011-06-23T09:23:15Z
[ "python", "date" ]
I am looking for a way to convert datetime objects to decimal year. Below is an example ``` >>> obj = SomeObjet() >>> obj.DATE_OBS datetime.datetime(2007, 4, 14, 11, 42, 50) ``` How do i convert datetime.datetime(2007, 4, 14, 11, 42, 50) to decimal years? From this format dd/mm/yyyy to this kind of format yyyy.yyyy
``` from datetime import datetime as dt import time def toYearFraction(date): def sinceEpoch(date): # returns seconds since epoch return time.mktime(date.timetuple()) s = sinceEpoch year = date.year startOfThisYear = dt(year=year, month=1, day=1) startOfNextYear = dt(year=year+1, month=1, ...
DeadlineExceededError: ApplicationError: 5 in using urllib2.urlopen() function
6,453,003
4
2011-06-23T11:02:25Z
6,453,671
12
2011-06-23T12:03:42Z
[ "python", "google-app-engine", "try-catch", "urllib2", "urlopen" ]
In my application I am using the urllib2.urlopen() function to call an api and get the result from that api.But this is not working fine.Sometimes it shows the result but sometimes it gives the following error: ``` Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/e...
The default timeout for URL Fetch requests is just 5 seconds so you might want to increase it by using the `urlfetch` directly: ``` from google.appengine.api import urlfetch try: resp = urlfetch.fetch('http://whoapi.com/api-v1/?domain=%s&rtype=serverip&apikey=xyzxyz'% domain, method=urlfetch.GET, deadline=10) ...
How to add the current query string to an URL in a Django template?
6,453,652
30
2011-06-23T12:01:38Z
6,454,045
74
2011-06-23T12:32:54Z
[ "python", "django" ]
When I load a page, there is a link *"sameLink"* that I want to append to it the ***query string*** of its containing page. I have following URL: ``` somedomain/reporting/article-by-month?variable1=2008 ``` How can I do that?
To capture the QUERY\_PARAMS that were part of the request, you reference the dict that contains those parameters (`request.GET`) and urlencode them so they are acceptable as part of an href. `request.GET.urlencode` returns a string that looks like `ds=&date_published__year=2008` which you can put into a link on the pa...
Target WSGI script cannot be loaded as Python module
6,454,564
24
2011-06-23T13:11:40Z
19,724,641
8
2013-11-01T10:10:06Z
[ "python", "django", "apache", "mod-wsgi", "wsgi" ]
I am trying to deploy mod\_wsgi with apache to run a django application but I am getting an error 500 internal server error The apache logs shows: ``` [Thu Jun 23 14:01:47 2011] [error] [client 152.78.95.64] mod_wsgi (pid=16142): Exception occurred processing WSGI script '/home/user/bms/apache/django.wsgi'. [Thu Jun 2...
For me the issue was that the WSGI script wasn't executable. ``` sudo chmod a+x django.wsgi ``` or just ``` sudo chmod u+x django.wsgi ``` so long as you have the correct owner
Target WSGI script cannot be loaded as Python module
6,454,564
24
2011-06-23T13:11:40Z
28,118,284
18
2015-01-23T20:34:31Z
[ "python", "django", "apache", "mod-wsgi", "wsgi" ]
I am trying to deploy mod\_wsgi with apache to run a django application but I am getting an error 500 internal server error The apache logs shows: ``` [Thu Jun 23 14:01:47 2011] [error] [client 152.78.95.64] mod_wsgi (pid=16142): Exception occurred processing WSGI script '/home/user/bms/apache/django.wsgi'. [Thu Jun 2...
For me the problem was wsgi python version mismatch. I was using python 3, so: ``` $ sudo apt-get remove libapache2-mod-python libapache2-mod-wsgi $ sudo apt-get install libapache2-mod-wsgi-py3 ```
Reference an Element in a List of Tuples
6,454,894
14
2011-06-23T13:32:32Z
6,454,922
26
2011-06-23T13:34:28Z
[ "python", "list", "reference", "element", "tuples" ]
Sorry in advance, but I'm new to Python. I have a list of `tuples`, and I was wondering how I can reference, say, the first element of each `tuple` within the list. I would think it's something like ``` for i in number_of_tuples : first_element = myList[i[0]] ``` you know, `[list_element[tuple_element]]`? However, ...
You can get a list of the first element in each tuple using a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` >>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty'] >>> first_elts = [x[0] for x in my_tuples] >>> first_elts [1, 'a', True, 'q'] ...
Reference an Element in a List of Tuples
6,454,894
14
2011-06-23T13:32:32Z
6,456,580
25
2011-06-23T15:25:47Z
[ "python", "list", "reference", "element", "tuples" ]
Sorry in advance, but I'm new to Python. I have a list of `tuples`, and I was wondering how I can reference, say, the first element of each `tuple` within the list. I would think it's something like ``` for i in number_of_tuples : first_element = myList[i[0]] ``` you know, `[list_element[tuple_element]]`? However, ...
All of the other answers here are correct but do not explain why what you were trying was wrong. When you do `myList[i[0]]` you are telling Python that `i` is a tuple and you want the value or the first element of tuple `i` as the index for myList. In the majority of programming languages when you need to access a nes...
Python Regex that adds space after dot
6,455,557
2
2011-06-23T14:19:10Z
6,455,641
10
2011-06-23T14:24:08Z
[ "python", "regex" ]
How can I use `re` to write a regex in Python that finds the pattern: > dot "." followed directly by any char [a-zA-Z] (not space or digit) and then add a space between the dot and the char? i.e. ``` str="Thanks.Bob" newsttr="Thanks. Bob" ``` Thanks in advance, Zvi
`re.sub(r'\.([a-zA-Z])', r'. \1', oldstr)`
How to get column names from SQLAlchemy result (declarative syntax)
6,455,560
16
2011-06-23T14:19:14Z
6,456,360
16
2011-06-23T15:12:35Z
[ "python", "sqlalchemy", "pylons", "pyramid" ]
I am working in a pyramid project and I've the table in SQLAlchemy in declarative syntax ``` """models.py""" class Projects(Base): __tablename__ = 'projects' __table_args__ = {'autoload': True} ``` I get the results by using ``` """"views.py""" session = DBSession() row_data = session.query(Projects).filter_...
The difference is between ORM and non-ORM, not declarative, which is just a helper for the ORM. Query has a method `column_descriptions()` that was added for this purpose:: <http://www.sqlalchemy.org/docs/orm/query.html#sqlalchemy.orm.query.Query.column_descriptions> the example there seems like it has a typo, says ...
How to get column names from SQLAlchemy result (declarative syntax)
6,455,560
16
2011-06-23T14:19:14Z
31,734,636
10
2015-07-30T21:45:51Z
[ "python", "sqlalchemy", "pylons", "pyramid" ]
I am working in a pyramid project and I've the table in SQLAlchemy in declarative syntax ``` """models.py""" class Projects(Base): __tablename__ = 'projects' __table_args__ = {'autoload': True} ``` I get the results by using ``` """"views.py""" session = DBSession() row_data = session.query(Projects).filter_...
You can do something similar to Foo Stack's answer without resorting to private fields by doing: ``` conn.execute(query).keys() ```
Python/Django - *args as list
6,456,119
4
2011-06-23T14:54:52Z
6,456,134
8
2011-06-23T14:56:36Z
[ "python", "django", "django-models" ]
I'm using the .order\_by() method/function; however, I want to construct the order\_by fields dynamically. The problem is .order\_by() expects to receive a string or buffer. So, I can't build a list or tuple or object to send to the function. How can I achieve this goal? I wanted to do something like: ``` field_list ...
You can use `model.objects.all().order_by(*field_list)`; this is due to the fact that `order_by` accepts multiple string arguments, not lists of multiple strings. See [This chapter in djangobook, search for `order_by`](http://www.djangobook.com/en/1.0/chapter05/), and [this](http://docs.python.org/tutorial/controlflow...
find items in list1 that are also in list2 and delete items not in list1
6,456,300
2
2011-06-23T15:08:26Z
6,456,422
9
2011-06-23T15:16:05Z
[ "python", "list" ]
i want to find items that are in `list1`: ``` list1 = ['peach', 'plum', 'apple', 'kiwi', 'grape'] ``` that are also in `list2`: ``` list2 = ['peach,0,1,1,0,1,0,1', 'carrot,1,0,1,1,0,1,1', 'lime,0,1,1,0,1,1,0', 'apple,0,1,1,0,1,1,1'] ``` the problem is that the items in `list2` have numbers after the needed item. ho...
``` # using a set makes the later `x in keep` test faster keep = set(['peach', 'plum', 'apple', 'kiwi', 'grape']) list2= ['peach,0,1,1,0,1,0,1', 'carrot,1,0,1,1,0,1,1', 'lime,0,1,1,0,1,1,0', 'apple,0,1,1,0,1,1,1'] # x.split(',',1)[0] = the part before the first `,` new = [x for x in list2 if x.split(',',1)[...
Scrapy Unit Testing
6,456,304
30
2011-06-23T15:08:46Z
12,741,030
30
2012-10-05T06:51:32Z
[ "python", "unit-testing", "scrapy", "nose" ]
I'd like to implement some unit tests in a Scrapy (screen scraper/web crawler). Since a project is run through the "scrapy crawl" command I can run it through something like nose. Since scrapy is built on top of twisted can I use its unit testing framework Trial? If so, how? Otherwise I'd like to get *nose* working. *...
The way I've done it is create fake responses, this way you can test the parse function offline. But you get the real situation by using real HTML. A problem with this approach is that your local HTML file may not reflect the latest state online. So if the HTML changes online you may have a big bug, but your test case...
Scrapy Unit Testing
6,456,304
30
2011-06-23T15:08:46Z
12,751,649
10
2012-10-05T18:01:30Z
[ "python", "unit-testing", "scrapy", "nose" ]
I'd like to implement some unit tests in a Scrapy (screen scraper/web crawler). Since a project is run through the "scrapy crawl" command I can run it through something like nose. Since scrapy is built on top of twisted can I use its unit testing framework Trial? If so, how? Otherwise I'd like to get *nose* working. *...
The newly added [Spider Contracts](http://doc.scrapy.org/en/latest/topics/contracts.html) are worth trying. It gives you a simple way to add tests without requiring a lot of code.
inserting into python dictionary
6,456,718
14
2011-06-23T15:35:09Z
6,456,784
13
2011-06-23T15:38:39Z
[ "python", "dictionary" ]
The default behavior for python dictionary is to create a new key in the dictionary if that key does not already exist. For example: ``` d = {} d['did not exist before'] = 'now it does' ``` this is all well and good for most purposes, but what if I'd like python to do nothing if the key isn't already in the dictionar...
You could use [`.update`](http://docs.python.org/library/stdtypes.html#dict.update): ``` masterlist.update((x, False) for x in exceptions if masterlist.has_key(x)) ```
inserting into python dictionary
6,456,718
14
2011-06-23T15:35:09Z
6,456,826
9
2011-06-23T15:41:39Z
[ "python", "dictionary" ]
The default behavior for python dictionary is to create a new key in the dictionary if that key does not already exist. For example: ``` d = {} d['did not exist before'] = 'now it does' ``` this is all well and good for most purposes, but what if I'd like python to do nothing if the key isn't already in the dictionar...
You can inherit a `dict` class, override it's `__setitem__` to check for existance of key (or do the same with monkey-patching only one instance). Sample class: ``` class a(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) dict.__setitem__(self, 'a', 'b') def __...
Pip Install -r continue past installs that fail
6,457,794
14
2011-06-23T16:56:00Z
6,458,729
9
2011-06-23T18:15:10Z
[ "python", "installer", "pip" ]
I am installing a list of packages with pip-python using the command ``` pip install -r requirements.txt ``` sometimes it fails installing packages for whatever reason. Is it possible to have it continue the the next package even with these failures?
You could write a little wrapper script to call pip iteratively, something like: ``` #!/usr/bin/env python """ pipreqs.py: run ``pip install`` iteratively over a requirements file. """ def main(argv): try: filename = argv.pop(0) except IndexError: print("usage: pipreqs.py REQ_FILE [PIP_ARGS]") ...
Pip Install -r continue past installs that fail
6,457,794
14
2011-06-23T16:56:00Z
21,311,174
18
2014-01-23T14:36:42Z
[ "python", "installer", "pip" ]
I am installing a list of packages with pip-python using the command ``` pip install -r requirements.txt ``` sometimes it fails installing packages for whatever reason. Is it possible to have it continue the the next package even with these failures?
I have the same problem. continuing on the line of @Greg Haskins, maybe this bash one-liner is more succinct: ``` cat requirements.txt | while read PACKAGE; do pip install "$PACKAGE"; done # TODO: extend to make the script print a list of failed installs, # so we can retry them. ``` (for the non-shellscripters: it c...
Create a python class that is treated as a list, but with more features?
6,458,461
3
2011-06-23T17:53:05Z
6,458,526
8
2011-06-23T17:57:23Z
[ "python", "list", "inheritance", "numpy" ]
I have a class called dataList. It is basically a list with some metadata---myDataList.data contains the (numpy) list itself, myDataList.tag contains a description, etc. I would like to be able to make myDataList[42] return the corresponding element of myDataList.data, and I would like for Numpy, etc. to recognize it a...
You can subclass list and provide additional methods: ``` class CustomList(list): def __init__(self, *args, **kwargs): list.__init__(self, args[0]) def foobar(self): return 'foobar' ``` CustomList inherits the methods of Python's ordinary lists and you can easily let it implement further meth...
Python - escaping double quotes using string.replace
6,459,755
5
2011-06-23T19:47:56Z
6,459,810
8
2011-06-23T19:52:25Z
[ "python", "regex", "string" ]
How do I replace " with \" in a python string? I have a string with double quotes: ``` s = 'a string with "double" quotes' ``` I want to escape the double quotes with one backslash. Doing the following doesn't quite work, it escapes with two backslashes: ``` s.replace('"', '\\"') 'a string with \\"double\\" quotes...
The string *is* correct. But `repr` will use backslash-escapes itself to show unprintable characters, and for consistency (it's supposed to form a Python string literal that, when evaluated, gives back the same string that was the input to `repr`) also escapes each backslash that occurs in the string. Note that this i...
Translate Exif DMS to DD Geolocation with Python
6,460,381
5
2011-06-23T20:42:22Z
6,464,697
8
2011-06-24T07:27:21Z
[ "python", "python-imaging-library", "exif", "geo" ]
I am using the following code to extract the geolocation of an image taken with an iPhone: ``` from PIL import Image from PIL.ExifTags import TAGS def get_exif(fn): ret = {} i = Image.open(fn) info = i._getexif() for tag, value in info.items(): decoded = TAGS.get(tag, tag) ret[decoded]...
Here's a way to do it, adapted for a script I wrote some months ago using pyexiv2: ``` a = get_exif('photo2.jpg') lat = [float(x)/float(y) for x, y in a['GPSInfo'][2]] latref = a['GPSInfo'][1] lon = [float(x)/float(y) for x, y in a['GPSInfo'][4]] lonref = a['GPSInfo'][3] lat = lat[0] + lat[1]/60 + lat[2]/3600 lon = l...
Can you migrate backwards to before the first migration in South?
6,460,598
42
2011-06-23T21:06:08Z
6,460,788
60
2011-06-23T21:24:12Z
[ "python", "django", "django-south" ]
Can you migrate an app backwards to before its first migration in Django South? If not, are there plans to add such functionality, perhaps using an option passed to `migrate`?
``` ./manage.py migrate myapp zero ``` See: <https://docs.djangoproject.com/en/1.9/ref/django-admin/#migrate>
Populating django field with pre_save()?
6,461,989
22
2011-06-23T23:52:53Z
6,462,188
34
2011-06-24T00:43:58Z
[ "python", "database", "django", "model", "triggers" ]
``` class TodoList(models.Model): title = models.CharField(maxlength=100) slug = models.SlugField(maxlength=100) def save(self): self.slug = title super(TodoList, self).save() ``` I'm assuming the above is how to create and store a slug when a title is inserted into the table TodoList, if n...
Most likely you are referring to [django's `pre_save` signal](https://docs.djangoproject.com/en/dev/ref/signals/#pre-save). You could setup something like this: ``` from django.db.models.signals import pre_save from django.dispatch import receiver from django.template.defaultfilters import slugify @receiver(pre_save)...
Populating django field with pre_save()?
6,461,989
22
2011-06-23T23:52:53Z
19,394,170
9
2013-10-16T02:13:10Z
[ "python", "database", "django", "model", "triggers" ]
``` class TodoList(models.Model): title = models.CharField(maxlength=100) slug = models.SlugField(maxlength=100) def save(self): self.slug = title super(TodoList, self).save() ``` I'm assuming the above is how to create and store a slug when a title is inserted into the table TodoList, if n...
``` @receiver(pre_save, sender=TodoList) def my_callback(sender, instance, *args, **kwargs): instance.slug = slugify(instance.title) ```
Populating django field with pre_save()?
6,461,989
22
2011-06-23T23:52:53Z
27,601,427
8
2014-12-22T11:05:15Z
[ "python", "database", "django", "model", "triggers" ]
``` class TodoList(models.Model): title = models.CharField(maxlength=100) slug = models.SlugField(maxlength=100) def save(self): self.slug = title super(TodoList, self).save() ``` I'm assuming the above is how to create and store a slug when a title is inserted into the table TodoList, if n...
you can use django signals.pre\_save: ``` from django.db.models.signals import post_save, post_delete, pre_save class TodoList(models.Model): @staticmethod def pre_save(sender, instance, **kwargs): #do anything you want pre_save.connect(TodoList.pre_save, TodoList, dispatch_uid="sightera.yourpackage....
Subtract Overlaps Between Two Ranges Without Sets
6,462,272
7
2011-06-24T01:02:36Z
6,462,739
9
2011-06-24T02:35:01Z
[ "python", "range", "overlap" ]
**NO SETS!** I can't use Sets because: * The ranges will be too long. * They will take up too much memory * The creation of the sets themselves will take too long. --- Using only the endpoints of the of the ranges, is there an optimal way to subtract two lists of ranges? ### Example: ``` r1 = (1, 1000), (1100, 12...
The [interval](http://pypi.python.org/pypi/interval/1.0.0) package may provide all that you need. ``` from interval import Interval, IntervalSet r1 = IntervalSet([Interval(1, 1000), Interval(1100, 1200)]) r2 = IntervalSet([Interval(30, 50), Interval(60, 200), Interval(1150, 1300)]) print(r1 - r2) >>> [1..30),(50..60)...
nltk language model (ngram) calculate the prob of a word from context
6,462,709
11
2011-06-24T02:28:48Z
14,967,785
10
2013-02-19T21:29:31Z
[ "python", "nlp", "nltk" ]
I am using Python and NLTK to build a language model as follows: ``` from nltk.corpus import brown from nltk.probability import LidstoneProbDist, WittenBellProbDist estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2) lm = NgramModel(3, brown.words(categories='news'), estimator) # Thanks to miku, I fixed this ...
I know this question is old but it pops up every time I google nltk's NgramModel class. NgramModel's prob implementation is a little unintuitive. The asker is confused. As far as I can tell, the answers aren't great. Since I don't use NgramModel often, this means I get confused. No more. The source code lives here: <h...
Assigning random value to a parameter in a python program
6,462,784
3
2011-06-24T02:44:28Z
6,462,809
10
2011-06-24T02:49:20Z
[ "python", "random", "parameters", "init" ]
I need to assign a default random value in `__init__()`. For example: ``` import math import random class Test: def __init__(self, r = random.randrange(0, math.pow(2,128)-1)): self.r = r print self.r ``` If I create 10 instances of Test, they all get the exact same random value. I don't understand...
The value of the default parameter is being set at the time the function is created, not when it is called - that's why it's the same every time. The typical way to deal with this is to set the default parameter to `None` and test it with an `if` statement. ``` import math import random class Test: def __init__(...
WTForms getting the errors
6,463,035
10
2011-06-24T03:31:27Z
6,471,207
17
2011-06-24T17:01:32Z
[ "python", "flask", "wtforms" ]
Currently in WTForms to access errors you have to loop through field errors like so: ``` for error in form.username.errors: print error ``` Since I'm building a rest application which uses no form views, I'm forced to check through all form fields in order to find where the error lies. Is there a way I could...
The actual `form` object has an [`errors`](http://wtforms.readthedocs.org/en/latest/forms.html#wtforms.form.Form.errors) attribute that contains the field names and their errors in a dictionary. So you could do: ``` for fieldName, errorMessages in form.errors.iteritems(): for err in errorMessages: # do som...
WTForms getting the errors
6,463,035
10
2011-06-24T03:31:27Z
14,989,572
8
2013-02-20T20:44:42Z
[ "python", "flask", "wtforms" ]
Currently in WTForms to access errors you have to loop through field errors like so: ``` for error in form.username.errors: print error ``` Since I'm building a rest application which uses no form views, I'm forced to check through all form fields in order to find where the error lies. Is there a way I could...
For anyone looking to do this in Flask templates: ``` {% for field in form.errors %} {% for error in form.errors[field] %} <div class="alert alert-error"> <strong>Error!</strong> {{error}} </div> {% endfor %} {% endfor %} ```
WTForms getting the errors
6,463,035
10
2011-06-24T03:31:27Z
20,644,520
7
2013-12-17T20:58:08Z
[ "python", "flask", "wtforms" ]
Currently in WTForms to access errors you have to loop through field errors like so: ``` for error in form.username.errors: print error ``` Since I'm building a rest application which uses no form views, I'm forced to check through all form fields in order to find where the error lies. Is there a way I could...
A cleaner solution for Flask templates: Python 3: ``` {% for field, errors in form.errors.items() %} <div class="alert alert-error"> {{ form[field].label }}: {{ ', '.join(errors) }} </div> {% endfor %} ``` Python 2: ``` {% for field, errors in form.errors.iteritems() %} <div class="alert alert-error"> {{ fo...
How can I get a list of all the Python standard library modules
6,463,918
18
2011-06-24T05:47:47Z
6,464,112
9
2011-06-24T06:11:38Z
[ "python", "virtualenv", "std" ]
I want something like `sys.builtin_module_names` except for the standard library. Other things that didn't work: * `sys.modules` - only shows modules that have already been loaded * `sys.prefix` - a path that would include non-standard library modules EDIT: and doesn't seem to work inside a virtualenv. The reason I w...
Why not work out what's part of the standard library yourself? ``` import distutils.sysconfig as sysconfig import os std_lib = sysconfig.get_python_lib(standard_lib=True) for top, dirs, files in os.walk(std_lib): for nm in files: if nm != '__init__.py' and nm[-3:] == '.py': print os.path.join(t...
How can I get a list of all the Python standard library modules
6,463,918
18
2011-06-24T05:47:47Z
28,873,415
10
2015-03-05T08:43:11Z
[ "python", "virtualenv", "std" ]
I want something like `sys.builtin_module_names` except for the standard library. Other things that didn't work: * `sys.modules` - only shows modules that have already been loaded * `sys.prefix` - a path that would include non-standard library modules EDIT: and doesn't seem to work inside a virtualenv. The reason I w...
If anyone's still reading this in 2015, I came across the same issue, and didn't like any of the existing solutions. So, I brute forced it by writing some code to scrape the TOC of the Standard Library page in the official Python docs. I also built a simple API for getting a list of standard libraries (for Python versi...
What's the standard way of doing this sort in Python?
6,464,524
5
2011-06-24T07:04:29Z
6,464,582
8
2011-06-24T07:12:21Z
[ "python", "sorting" ]
Imagine I have a list of tuples in this format: ``` (1, 2, 3) (1, 0, 2) (3, 9 , 11) (0, 2, 8) (2, 3, 4) (2, 4, 5) (2, 7, 8) .... ``` How could I sort the list by the first element of the tuples, and then by the second? I'd like to get to this list: ``` (0, 2, 8) (1, 0, 2) (1, 2, 3) (2, 3, 4) (2, 4, 5) (2, 7, 8) (3, ...
Why not simply let python sort the list for you ? ``` my_list = [ (1, 2, 3), (1, 0, 2), (3, 9 , 11), (0, 2, 8), (2, 3, 4), (2, 4, 5), (2, 7, 8), ] print sorted(my_list) >>>[(0, 2, 8), (1, 0, 2), (1, 2, 3), (2, 3, 4), (2, 4, 5), (2, 7, 8), (3, 9, 11)] ```
How can i convert an xml file into JSON using python?
6,465,256
4
2011-06-24T08:30:46Z
10,201,397
8
2012-04-18T01:04:48Z
[ "python", "xml", "json", "xml-serialization" ]
I have an XML file which I want to convert into JSON file using python, but its nt working out for me. ``` <?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> ``` The above XML file I am parsing using ElementTree a...
Another option is [xmltodict](https://github.com/martinblech/xmltodict) (full disclosure: I wrote it). It can help you convert your XML to a dict+list+string structure, following this ["standard"](http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html). It is [Expat](http://docs.python.org/library/pye...
Import paths - the right way?
6,465,549
12
2011-06-24T08:54:58Z
6,466,248
14
2011-06-24T10:00:34Z
[ "python", "path", "python-import" ]
I know there are A LOT of similar or the same questions, but i still cannot understand / find the right way for me to work with modules. Python is my favorite language, and i like everything in it except working with imports: recursive imports (when you try to reference a name that is not yet there), import paths, etc....
What is the entry point for your program? Usually the entry point for a program will be at the root of the project. Since it is at the root, all the modules within the root will be importable, provided there is an `__init__.py` file in them. So, using your example: ``` my_project/ main.py package1/ __...
What is the return value of os.system() in Python?
6,466,711
21
2011-06-24T10:46:52Z
6,466,732
9
2011-06-24T10:49:10Z
[ "python", "operating-system" ]
I came across this: ``` >>> import os >>> os.system('ls') file.txt README 0 ``` What is return value of [`os.system()`](https://docs.python.org/2/library/os.html#os.system)? Why I get 0?
> "On Unix, the return value is the exit > status of the process encoded in the > format specified for wait(). Note that > POSIX does not specify the meaning of > the return value of the C system() > function, so the return value of the > Python function is system-dependent." <http://docs.python.org/library/os.html#os...
What is the return value of os.system() in Python?
6,466,711
21
2011-06-24T10:46:52Z
6,466,753
23
2011-06-24T10:50:53Z
[ "python", "operating-system" ]
I came across this: ``` >>> import os >>> os.system('ls') file.txt README 0 ``` What is return value of [`os.system()`](https://docs.python.org/2/library/os.html#os.system)? Why I get 0?
That is the return code. When a process finishes it returns a code. 0 means that there weren't errors. For others error codes: * [on Linux](http://tldp.org/LDP/abs/html/exitcodes.html) * [on Windows](http://msdn.microsoft.com/en-us/library/ms681381%28v=vs.85%29.aspx)
extracting element and insert a space
6,467,043
7
2011-06-24T11:22:27Z
6,467,095
16
2011-06-24T11:27:13Z
[ "python", "html-parsing", "beautifulsoup" ]
im parsing html using BeautifulSoup in python i dont know how to insert a space when extracting text element this is the code: ``` import BeautifulSoup soup=BeautifulSoup.BeautifulSoup('<html>this<b>is</b>example</html>') print soup.text ``` then output is > thisisexample but i want to insert a space to this like...
Use `getText` instead: ``` import BeautifulSoup soup=BeautifulSoup.BeautifulSoup('<html>this<b>is</b>example</html>') print soup.getText(separator=u' ') # u'this is example' ```
Generic methods in python
6,467,461
8
2011-06-24T11:58:40Z
6,467,555
13
2011-06-24T12:07:11Z
[ "python" ]
Is it possible to implement generic method handlers in python which allow for calling of non-existent functions? Something like this: ``` class FooBar: def __generic__method__handler__(.., methodName, ..): print methodName fb = FooBar() fb.helloThere() -- output -- helloThere ```
The first thing to remember is that methods are attributes which happen to be [callable](http://docs.python.org/library/functions.html#callable). ``` >>> s = " hello " >>> s.strip() 'hello' >>> s.strip <built-in method strip of str object at 0x000000000223B9E0> ``` So you can handle non-existent methods in the same w...
how to return a dictionary in python django and view it in javascript?
6,467,812
5
2011-06-24T12:29:55Z
6,468,119
8
2011-06-24T12:58:45Z
[ "javascript", "python", "django" ]
I'm returning this in my view: ``` data = {'val1' : 'this is x', 'val2' : True} return HttpResponse(data) ``` I want to use this information in the dictionary within my javascript. Kind of like this: ``` function(data) { if (data["val2"]) { //success ...
Very simply: ``` import json data = {'val1' : 'this is x', 'val2' : True} return HttpResponse( json.dumps( data ) ) ```
How to get the correlation between two timeseries using Pandas
6,467,832
8
2011-06-24T12:31:45Z
6,468,875
10
2011-06-24T14:01:15Z
[ "python", "statistics", "correlation", "pandas" ]
I have two sets of temperature date, which have readings at regular (but different) time intervals. I'm trying to get the correlation between these two sets of data. I've been playing with [Pandas](http://pandas.pydata.org/ "Pandas") to try to do this. I've created two timeseries, and am using `TimeSeriesA.corr(TimeSe...
You have a number of options using pandas, but you have to make a decision about how it makes sense to align the data given that they don't occur at the same instants. **Use the values "as of" the times in one of the time series**, here's an example: ``` In [15]: ts Out[15]: 2000-01-03 00:00:00 -0.722...
How can I disable the automatic checking for updates when Google App Engine Launcher is started?
6,468,191
11
2011-06-24T13:04:30Z
9,944,512
15
2012-03-30T14:03:54Z
[ "python", "windows", "google-app-engine" ]
I've been tinkering with the GAE and I enjoy the ease of use of the GAE Launcher that is available with the Windows SDK. My problem is that when I start the application, it takes it a long time for it to become responsive. This is because the program first checks for updates before starting the app. This causes it to ...
Google App Engine (GAE) use the python [urllib2](http://docs.python.org/library/urllib2.html) library to check for updates. This library gets the proxy settings from `*_proxy` environment variables, instead of the windows registry. > By default, ProxyHandler uses the environment variables named <scheme>\_proxy, where ...
How to check Django version
6,468,397
234
2011-06-24T13:22:45Z
6,468,505
315
2011-06-24T13:30:56Z
[ "python", "django" ]
I have to use [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) and [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. ...
Django 1.5 supports Python 2.6.5 and later. If you're under Linux and want to check the Python version you're using, run `python -V` from the command line. If you want to check the Django version, open a Python console and type ``` import django django.VERSION ```
How to check Django version
6,468,397
234
2011-06-24T13:22:45Z
16,805,125
200
2013-05-29T03:42:07Z
[ "python", "django" ]
I have to use [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) and [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. ...
Basically the same as bcoughlan's answer, but here it is as an executable command: ``` python -c "import django; print(django.get_version())" ```
How to check Django version
6,468,397
234
2011-06-24T13:22:45Z
18,493,645
18
2013-08-28T16:40:59Z
[ "python", "django" ]
I have to use [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) and [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. ...
If you have [pip](http://pip.openplans.org/), you can also do a ``` pip freeze ``` and it will show your Django version. You can pipe it through grep to get just the Django version. That is, ``` josh@villaroyale:~/code/djangosite$ pip freeze | grep Django Django==1.4.3 ```
How to check Django version
6,468,397
234
2011-06-24T13:22:45Z
19,157,430
78
2013-10-03T10:58:37Z
[ "python", "django" ]
I have to use [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) and [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. ...
If you have installed the application: ``` django-admin.py version ```
How to check Django version
6,468,397
234
2011-06-24T13:22:45Z
21,295,822
25
2014-01-22T22:56:40Z
[ "python", "django" ]
I have to use [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) and [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. ...
``` >>> import django >>> print(django.get_version()) 1.6.1 ``` I am using the [IDLE](http://en.wikipedia.org/wiki/IDLE_%28Python%29) (Python GUI).
How to check Django version
6,468,397
234
2011-06-24T13:22:45Z
21,445,277
29
2014-01-29T23:57:07Z
[ "python", "django" ]
I have to use [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) and [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. ...
Go to your [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) project home directory and do: ``` ./manage.py --version ```
How to check Django version
6,468,397
234
2011-06-24T13:22:45Z
26,386,738
26
2014-10-15T15:47:37Z
[ "python", "django" ]
I have to use [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) and [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. ...
For [Python](http://stackoverflow.com/q/1093322/1551116): ``` import sys sys.version ``` For Django (as mentioned by others here): ``` import django django.get_version() ``` The potential problem with simply checking the version, is that versions get upgraded and so the code can go out of date. You want to make sur...
How to check Django version
6,468,397
234
2011-06-24T13:22:45Z
28,702,103
27
2015-02-24T17:15:52Z
[ "python", "django" ]
I have to use [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) and [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. ...
Type the following at the command prompt: ``` django-admin.py version ``` If django is installed it will print its current version (eg. `1.6.5`), otherwise the shell will print an error message.
How to check Django version
6,468,397
234
2011-06-24T13:22:45Z
38,470,436
8
2016-07-20T00:11:15Z
[ "python", "django" ]
I have to use [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) and [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. ...
As you say you have two versions of python, I assume they are in different [virtual environments](http://docs.python-guide.org/en/latest/dev/virtualenvs/) (e.g. venv) or perhaps [conda environments](http://conda.pydata.org/docs/using/envs.html). When you installed django, it was likely in only one environment. It is p...
How to determine if one date is before another
6,469,495
4
2011-06-24T14:48:17Z
6,469,531
10
2011-06-24T14:50:35Z
[ "python" ]
I have a date in the format "2011-06-24", and a list of other date strings in the same format. For each string in the list, I want to determine if that date is in the past, compared to "2011-06-24". Is there a way to do this easily in python?
What is the problem here? Since the dates are obviously in ISO notation you can perform a standard comparison of the dates as strings here...
How to determine if one date is before another
6,469,495
4
2011-06-24T14:48:17Z
6,469,624
14
2011-06-24T14:57:46Z
[ "python" ]
I have a date in the format "2011-06-24", and a list of other date strings in the same format. For each string in the list, I want to determine if that date is in the past, compared to "2011-06-24". Is there a way to do this easily in python?
``` >>> "2011-06-24" > "2010-06-23" True >>> "2011-06-24" > "2012-06-25" False ```
Is it possible to express a platform-specific dependency in setup.py without building platform-specific versions of my egg?
6,469,508
8
2011-06-24T14:49:01Z
6,469,851
8
2011-06-24T15:15:00Z
[ "python", "setuptools", "distutils" ]
We have a placeholder egg that contains no code and only exists for the sake of pulling down a list of dependent packages from our PyPi repository. Most of these dependent packages are platform-agnostic, however some are only used on Win32 platforms. Is it possible to somehow make the dependency platform-conditional,...
In `setup.py`: ``` from setuptools import setup import sys setup( name="...", install_requires=["This", "That"] + ( ["WinOnly", "AnotherWinOnly"] if "win" in sys.platform else [] ) ) ``` `distutils.util.get_platform` has more information than `sys.platform` if you need it: ``` >>> sys.platfo...
How can I spawn new shells to run python scripts from a base python script?
6,469,655
18
2011-06-24T14:59:24Z
6,469,735
7
2011-06-24T15:06:24Z
[ "python", "subprocess" ]
I have succesfully run several python scripts calling them from a base script using the subprocess module: ``` subprocess.popen([sys.executable, 'script.py'], shell=True) ``` However, each of these scripts executes some simulations (.exe files from a C++ app) that generate some output to the shell. All these outputs ...
Popen already generates a sub process to handle things. You just need to redirect the output pipes. Look at the [subprocess](http://docs.python.org/library/subprocess.html#subprocess.Popen) docs, specifically the section on popen stdin, stdout and stderr redirection. If you don't redirect these pipes, it inherits them...
How can I spawn new shells to run python scripts from a base python script?
6,469,655
18
2011-06-24T14:59:24Z
20,613,015
17
2013-12-16T14:15:19Z
[ "python", "subprocess" ]
I have succesfully run several python scripts calling them from a base script using the subprocess module: ``` subprocess.popen([sys.executable, 'script.py'], shell=True) ``` However, each of these scripts executes some simulations (.exe files from a C++ app) that generate some output to the shell. All these outputs ...
To open in a different console, do (tested on Win7 / Python 3): ``` from sys import executable from subprocess import Popen, CREATE_NEW_CONSOLE Popen([executable, 'script.py'], creationflags=CREATE_NEW_CONSOLE) input('Enter to exit from this launcher script...') ```
Accessing function arguments from decorator
6,470,049
5
2011-06-24T15:26:21Z
6,470,447
8
2011-06-24T15:56:14Z
[ "python", "google-app-engine", "decorator" ]
I have a Request handler and a decorator, I would like to work with the self object inside the decorator ``` class MyHandler(webapp.RequestHandler): @myDecorator def get(self): #code ``` **Update: Please notice the difference between the first and second self** ``` class myDecorator(object):...
I'm not entirely clear what it is you want, but if you just want to use the decorated function's arguments, then that is exactly what a basic decorator does. So to access say, `self.request` from a decorator you could do: ``` def log_request(fn): def decorated_get(self): logging.debug("request object:", se...
Catch multiple exceptions in one line (except block)
6,470,428
1,219
2011-06-24T15:55:08Z
6,470,452
1,771
2011-06-24T15:56:34Z
[ "python", "exception", "exception-handling" ]
I know that I can do: ``` try: # do something that may fail except: # do this if ANYTHING goes wrong ``` I can also do this: ``` try: # do something that may fail except IDontLikeYourFaceException: # put on makeup or smile except YouAreTooShortException: # stand on a ladder ``` But if I want to ...
From <https://docs.python.org/2/tutorial/errors.html#handling-exceptions>: "An except clause may name multiple exceptions as a parenthesized tuple, for example": ``` except (IDontLikeYouException, YouAreBeingMeanException) as e: pass ``` Separating the exception from the variable with a comma will still work in P...
Catch multiple exceptions in one line (except block)
6,470,428
1,219
2011-06-24T15:55:08Z
23,631,486
34
2014-05-13T12:37:28Z
[ "python", "exception", "exception-handling" ]
I know that I can do: ``` try: # do something that may fail except: # do this if ANYTHING goes wrong ``` I can also do this: ``` try: # do something that may fail except IDontLikeYourFaceException: # put on makeup or smile except YouAreTooShortException: # stand on a ladder ``` But if I want to ...
For python 2.5 and earlier versions, the correct syntax is: ``` except (IDontLikeYouException, YouAreBeingMeanException), e: print e ``` Where `e` is the Exception instance.
Catch multiple exceptions in one line (except block)
6,470,428
1,219
2011-06-24T15:55:08Z
24,338,247
45
2014-06-21T04:20:29Z
[ "python", "exception", "exception-handling" ]
I know that I can do: ``` try: # do something that may fail except: # do this if ANYTHING goes wrong ``` I can also do this: ``` try: # do something that may fail except IDontLikeYourFaceException: # put on makeup or smile except YouAreTooShortException: # stand on a ladder ``` But if I want to ...
> **How do I catch multiple exceptions in one line (except block)** # Best Practice To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variabl...
Catch multiple exceptions in one line (except block)
6,470,428
1,219
2011-06-24T15:55:08Z
26,650,022
17
2014-10-30T10:01:18Z
[ "python", "exception", "exception-handling" ]
I know that I can do: ``` try: # do something that may fail except: # do this if ANYTHING goes wrong ``` I can also do this: ``` try: # do something that may fail except IDontLikeYourFaceException: # put on makeup or smile except YouAreTooShortException: # stand on a ladder ``` But if I want to ...
From [Python documentation -> 8.3 Handling Exceptions](https://docs.python.org/2/tutorial/errors.html#handling-exceptions): > A `try` statement may have more than one except clause, to specify > handlers for different exceptions. At most one handler will be > executed. Handlers only handle exceptions that occur in the...
Python script to see if a web page exists without downloading the whole page?
6,471,275
11
2011-06-24T17:07:56Z
6,471,552
15
2011-06-24T17:34:22Z
[ "python", "httplib", "urlparse" ]
I'm trying to write a script to test for the existence of a web page, would be nice if it would check without downloading the whole page. This is my jumping off point, I've seen multiple examples use httplib in the same way, however, every site I check simply returns false. ``` import httplib from httplib import HTTP...
how about this: ``` import httplib from urlparse import urlparse def checkUrl(url): p = urlparse(url) conn = httplib.HTTPConnection(p.netloc) conn.request('HEAD', p.path) resp = conn.getresponse() return resp.status < 400 if __name__ == '__main__': print checkUrl('http://www.stackoverflow.com...
Avoiding "MySQL server has gone away" on infrequently used Python / Flask server with SQLAlchemy
6,471,549
28
2011-06-24T17:34:12Z
6,473,271
27
2011-06-24T20:13:05Z
[ "python", "mysql", "sqlalchemy", "flask", "database-connection" ]
How can Flask / SQLAlchemy be configured to create a new database connection if one is not present? I have an infrequently visited Python / Flask server which uses SQLAlchemy. It gets visited every couple of days, and on the first visit it often throws a "MySQL server has gone away" error. Subsequent page views are fi...
I've had trouble with this before, and found that the way to handle it is by not keeping sessions around. The trouble is you are trying to keep a connection open for way too long. Instead, use a thread local scoped session like so either in `__init__.py` or in a utility package that you import everywhere: ``` from sql...
Link To Foreignkey in Admin Causes AttributeError When Debug Is False
6,473,340
4
2011-06-24T20:21:20Z
7,192,721
11
2011-08-25T15:04:22Z
[ "python", "django", "django-admin", "foreign-keys" ]
I have used the following code in my models.py file: Create hyperlink to foreignkey ``` class ModelAdminWithForeignKeyLinksMetaclass(MediaDefiningClass): def __getattr__(cls, name): def foreign_key_link(instance, field): target = getattr(instance, field) return u'<a href="../../...
I stumbled on exactly the same problem, luckily, I've fixed it. The original solution (the one you used) comes from [this question](http://stackoverflow.com/questions/2470285/foreign-keys-in-django-admin-list-display), my solution is based on it: ``` class ForeignKeyLinksMetaclass(MediaDefiningClass): def __new_...
Python list of lists transpose without zip(*m) thing
6,473,679
65
2011-06-24T20:54:44Z
6,473,724
91
2011-06-24T20:59:37Z
[ "python", "list", "transpose" ]
Let's take: ``` l = [[1,2,3],[4,5,6],[7,8,9]] ``` The result I'm looking for is ``` r = [[1,4,7],[2,5,8],[3,6,9]] ``` and not ``` r = [(1,4,7),(2,5,8),(3,6,9)] ``` Much appreciated
How about ``` map(list, zip(*l)) --> [[1, 4, 7], [2, 5, 8], [3, 6, 9]] ``` For python 3.X users do ``` list(map(list, zip(*l))) ```
Python list of lists transpose without zip(*m) thing
6,473,679
65
2011-06-24T20:54:44Z
6,473,727
27
2011-06-24T20:59:43Z
[ "python", "list", "transpose" ]
Let's take: ``` l = [[1,2,3],[4,5,6],[7,8,9]] ``` The result I'm looking for is ``` r = [[1,4,7],[2,5,8],[3,6,9]] ``` and not ``` r = [(1,4,7),(2,5,8),(3,6,9)] ``` Much appreciated
One way to do it is with the NumPy transpose. ``` >>> numpy.asarray(l).T.tolist() [[1, 4, 7], [2, 5, 8], [3, 6, 9]] ``` Or another one without zip: ``` >>> map(list,map(None,*l)) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] ```
Python list of lists transpose without zip(*m) thing
6,473,679
65
2011-06-24T20:54:44Z
6,473,742
18
2011-06-24T21:02:00Z
[ "python", "list", "transpose" ]
Let's take: ``` l = [[1,2,3],[4,5,6],[7,8,9]] ``` The result I'm looking for is ``` r = [[1,4,7],[2,5,8],[3,6,9]] ``` and not ``` r = [(1,4,7),(2,5,8),(3,6,9)] ``` Much appreciated
Equivalently to Jena's solution: ``` >>> l=[[1,2,3],[4,5,6],[7,8,9]] >>> [list(i) for i in zip(*l)] ... [[1, 4, 7], [2, 5, 8], [3, 6, 9]] ```
Python list of lists transpose without zip(*m) thing
6,473,679
65
2011-06-24T20:54:44Z
6,473,782
14
2011-06-24T21:06:27Z
[ "python", "list", "transpose" ]
Let's take: ``` l = [[1,2,3],[4,5,6],[7,8,9]] ``` The result I'm looking for is ``` r = [[1,4,7],[2,5,8],[3,6,9]] ``` and not ``` r = [(1,4,7),(2,5,8),(3,6,9)] ``` Much appreciated
just for fun ``` >>> [[j[i] for j in l] for i in range(len(l))] [[1, 4, 7], [2, 5, 8], [3, 6, 9]] ```
SQL Alchemy - Getting a list of tables
6,473,925
37
2011-06-24T21:25:31Z
6,474,046
37
2011-06-24T21:40:08Z
[ "python", "mysql", "sqlalchemy", "pyramid" ]
I couldn't find any information about this in the documentation, but how can I get a list of tables created in SQLAlchemy? I used the class method to create the tables.
All of the tables are collected in the `tables` attribute of the sqlalchemy MetaData object. to just get a list of the names of those tables: ``` >>> metadata.tables.keys() ['posts', 'comments', 'users'] ``` If you're using the declarative extension, then you probably aren't managing the metadata yourself. Fortunatel...
SQL Alchemy - Getting a list of tables
6,473,925
37
2011-06-24T21:25:31Z
30,554,677
15
2015-05-31T06:51:20Z
[ "python", "mysql", "sqlalchemy", "pyramid" ]
I couldn't find any information about this in the documentation, but how can I get a list of tables created in SQLAlchemy? I used the class method to create the tables.
There is a method in `engine` object to fetch the list of tables name. `engine.table_names()`
list is a subset of another list
6,474,352
4
2011-06-24T22:20:13Z
6,474,376
11
2011-06-24T22:24:29Z
[ "python", "list", "subset" ]
in Python, given two lists of pairs: ``` listA = [ [1,20], [3,19], [37,11], [21,17] ] listB = [ [1,20], [21,17] ] ``` how do you efficiently write a python function which return True if listB is a subset of listA? oh and [1,20] pair is equivalent to [20,1]
Use `frozenset`. ``` >>> listA = [ [1,20], [3,19], [37,11], [21,17] ] >>> listB = [ [1,20], [21,17] ] >>> setA = frozenset([frozenset(element) for element in listA]) >>> setB = frozenset([frozenset(element) for element in listB]) >>> setA frozenset([frozenset([17, 21]), frozenset([1, 20]), frozenset([11, 37]), froze...
list is a subset of another list
6,474,352
4
2011-06-24T22:20:13Z
6,485,817
8
2011-06-26T18:16:03Z
[ "python", "list", "subset" ]
in Python, given two lists of pairs: ``` listA = [ [1,20], [3,19], [37,11], [21,17] ] listB = [ [1,20], [21,17] ] ``` how do you efficiently write a python function which return True if listB is a subset of listA? oh and [1,20] pair is equivalent to [20,1]
Just in order to offer an alternative, perhaps using tuple and set is more efficient: ``` >>> set(map(tuple,listB)) <= set(map(tuple,listA)) True ```
How to make Python 2.x Unicode strings not print as u'string'?
6,474,365
10
2011-06-24T22:22:50Z
6,475,047
12
2011-06-25T00:37:36Z
[ "python", "unicode" ]
I'm currently testing a webservice that returns large amounts of JSON data in the form of dictionaries. The keys and values for those dictionaries are all unicode strings, and thus they print like ``` {u'key1':u'value', u'key2':u'value2'} ``` when printed to the screen in the interactive interpreter. Now imagine tha...
if it's json you want, just print [json](https://docs.python.org/2/library/json.html): ``` >>> import json >>> print json.dumps({u'key1':u'value', u'key2':u'value2'}, indent=4) { "key2": "value2", "key1": "value" } ```
thread module question
6,474,509
2
2011-06-24T22:47:41Z
6,474,552
12
2011-06-24T22:56:47Z
[ "python" ]
so i have the code: ``` def Listen(filepath): def play(filepath): def play_music(music_file): """ stream music with mixer.music module in blocking manner this will stream the sound from disk while playing """ clock = p...
Read the TypeError message: "2nd arg must be a tuple." You have `(filepath)`. This is not a tuple. A tuple of one element should be written: `(filepath,)` to disambiguate.
SQLAlchemy: filter by membership in at least one many-to-many related table
6,474,989
14
2011-06-25T00:25:28Z
6,512,603
21
2011-06-28T20:19:16Z
[ "python", "mysql", "many-to-many", "sqlalchemy" ]
Using SQLAlchemy 0.7.1 and a MySQL 5.1 database, I've got a many-to-many relationship set up as follows: ``` user_groups = Table('user_groups', Base.metadata, Column('user_id', String(128), ForeignKey('users.username')), Column('group_id', Integer, ForeignKey('groups.id')) ) class ZKUser(Base, ZKTableAudit): ...
OK, after a lot of research, I realized that it was my own ignorance of SQL terminology that was holding me back. My search for a solution to find users belonging to "at least one of" the list of groups should have been to find users belonging to "any" of the list of groups. The `any` ORM function from SQLAlchemy does ...
creating a color coded time chart using colorbar and colormaps in python
6,475,082
4
2011-06-25T00:43:44Z
6,502,742
7
2011-06-28T06:57:09Z
[ "python", "matplotlib", "colorbar", "color-mapping" ]
I'm trying to make a time tracking chart based on a daily time tracking file that I used. I wrote code that crawls through my files and generates a few lists. endTimes is a list of times that a particular activity ends in minutes going from 0 at midnight the first day of the month to however many minutes are in a mont...
It sounds like you want something like a stacked bar chart with the color values mapped to a given range? In that case, here's a rough example: ``` import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np # Generate data.... intervals, weights = [], [] max_weight = 5 for _ in range(30): numti...
python-ldap OS X 10.6 and Python 2.6
6,475,118
7
2011-06-25T01:01:38Z
7,125,143
7
2011-08-19T17:22:52Z
[ "python", "django", "python-ldap" ]
Trying to install python-ldap for my Django project -- so far tried easy\_install, pip, as well as building myself, but still getting the same errors: ``` dlopen(/Library/Python/2.6/site-packages/_ldap.so, 2): Symbol not found: _ldap_create_assertion_control_value Referenced from: /Library/Python/2.6/site-packages/_ld...
The problem and solution are documented [here](http://projects.skurfer.com/posts/2011/python_ldap_lion/). Summary: The 10.7.{0,1} system tools and headers are all from OpenLDAP 2.4.x while the libraries are from OpenLDAP 2.2.0. The solution is to build the OpenLDAP libs to match the system headers and link python-ldap...
Python for-in loop preceded by a variable
6,475,314
28
2011-06-25T01:58:58Z
6,475,331
22
2011-06-25T02:05:09Z
[ "python", "for-loop", "for-in-loop" ]
``` foo = [x for x in bar if x.occupants > 1] ``` After googling and searching on here, couldn't figure out what this does. Maybe I wasn't searching the right stuff but here it is. Any input in debunking this shorthand is greatly appreciated.
It's a [list comprehension](http://docs.python.org/tutorial/datastructures.html?highlight=comprehension#list-comprehensions) `foo` will be a filtered list of `bar` containing the objects with the attribute occupants > 1 `bar` can be a `list`, `set`, `dict` or any other iterable Here is an example to clarify ``` >>>...
Global variable Python classes
6,475,321
14
2011-06-25T02:00:59Z
6,475,332
40
2011-06-25T02:05:51Z
[ "python", "global-variables" ]
What is the proper way to define a global variable that has class scope in python? Coming from a C/C++/Java background I assume that this is correct: ``` class Shape: lolwut = None def __init__(self, default=0): self.lolwut = default; def a(self): print self.lolwut def b(self): ...
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g `Shape.lolwut` or via an instance e.g. `shape.lolwut` but be careful while setting it as it will set an instance level attribute not class attribute ``` class Shape(object): lolwut = 1 shape = S...
Read large text files in Python, line by line without loading it in to memory
6,475,328
76
2011-06-25T02:04:14Z
6,475,340
21
2011-06-25T02:07:39Z
[ "python" ]
I need to read a large file, line by line. Lets say that file has more than 5GB and I need to read each line, but obviously I do not want to use `readlines()` because it will create a very large list in the memory. How will the code below work for this case? Is `xreadlines` itself reading one by one into memory? Is th...
All you need to do is use the file object as an iterator. ``` for line in open("log.txt"): do_something_with(line) ``` Even better is using context manager in recent Python versions. ``` with open("log.txt") as fileobject: for line in fileobject: do_something_with(line) ``` This will automatically c...
Read large text files in Python, line by line without loading it in to memory
6,475,328
76
2011-06-25T02:04:14Z
6,475,407
102
2011-06-25T02:26:20Z
[ "python" ]
I need to read a large file, line by line. Lets say that file has more than 5GB and I need to read each line, but obviously I do not want to use `readlines()` because it will create a very large list in the memory. How will the code below work for this case? Is `xreadlines` itself reading one by one into memory? Is th...
I provided this answer because Keith's, while succinct, doesn't close the file *explicitly* ``` with open("log.txt") as infile: for line in infile: do_something_with(line) ```
Read large text files in Python, line by line without loading it in to memory
6,475,328
76
2011-06-25T02:04:14Z
6,475,425
7
2011-06-25T02:31:27Z
[ "python" ]
I need to read a large file, line by line. Lets say that file has more than 5GB and I need to read each line, but obviously I do not want to use `readlines()` because it will create a very large list in the memory. How will the code below work for this case? Is `xreadlines` itself reading one by one into memory? Is th...
An old school approach: ``` fh = open(file_name, 'rt') line = fh.readline() while line: # do stuff with line line = fh.readline() fh.close() ```
stripping inline tags with python's lxml
6,476,548
4
2011-06-25T07:37:46Z
6,476,913
9
2011-06-25T09:15:37Z
[ "python", "xml", "tags", "lxml" ]
I have to deal with two types of inline tags in xml documents. The first type of tags enclose text that I want to keep in-between. I can deal with this with lxml's ``` etree.tostring(element, method="text", encoding='utf-8') ``` The second type of tags include text that I don't want to keep. How can I get rid of thes...
I think that `strip_tags` and `strip_elements` are what you want in each case. For example, this script: ``` from lxml import etree text = "<x>hello, <z>keep me</z> and <y>ignore me</y>, and here's some <y>more</y> text</x>" tree = etree.fromstring(text) print etree.tostring(tree, pretty_print=True) # Remove the <...
What do double parentheses mean in a function call? e.g. func(stuff)(stuff)?
6,476,825
8
2011-06-25T08:53:27Z
6,476,838
17
2011-06-25T08:55:32Z
[ "python", "unicode", "stdout", "codec" ]
> Original title: > > "**Help me understand this weird Python idiom? `sys.stdout = codecs.getwriter('utf-8')(sys.stdout)`**" I use this idiom all the time to print a bunch of content to standard out in utf-8 in Python 2.\*: ``` sys.stdout = codecs.getwriter('utf-8')(sys.stdout) ``` But to be honest, I have no idea w...
`.getwriter` returns a functioncallable object; you are merely calling it in the same line. Example: ``` def returnFunction(): def myFunction(): print('hello!') return myFunction ``` Demo: ``` >>> returnFunction()() hello! ``` You could have alternatively done: ``` >>> result = returnFunction() >>...
Python: Display special characters when using print statement
6,477,823
43
2011-06-25T12:50:36Z
6,477,836
74
2011-06-25T12:52:53Z
[ "python", "printing", "escaping", "character" ]
I would like to display the escape characters when using print statement. E.g. ``` a = "Hello\tWorld\nHello World" print a Hello World Hello World ``` I would like it to display: "Hello\tWorld\nHello\sWorld" Thanks in advance
Use [repr](http://docs.python.org/library/functions.html#repr): ``` a = "Hello\tWorld\nHello World" print repr(a) # 'Hello\tWorld\nHello World' ``` Note you do not get `\s` for a space. I hope that was a typo...? But if you really do want `\s` for spaces, you could do this: ``` print repr(a).replace(' ',r'\s') ```
Python: Display special characters when using print statement
6,477,823
43
2011-06-25T12:50:36Z
6,478,018
10
2011-06-25T13:28:26Z
[ "python", "printing", "escaping", "character" ]
I would like to display the escape characters when using print statement. E.g. ``` a = "Hello\tWorld\nHello World" print a Hello World Hello World ``` I would like it to display: "Hello\tWorld\nHello\sWorld" Thanks in advance
Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a [raw string](http://docs.python.org/reference/lexical_analysis.html#string-literals) by prefixing it with `r`: `r"Hello\tWorld\nHello World"`. ``` >>> a = r"Hello\tWorld\n...
Assigning a function to an object attribute
6,478,371
19
2011-06-25T14:28:07Z
6,478,550
13
2011-06-25T15:01:21Z
[ "python", "methods" ]
Based on my understanding of [Python's data model](http://docs.python.org/py3k/reference/datamodel.html#the-standard-type-hierarchy), and specifically the subsection "Instance Methods", whenever you read an attribute whose value is of type "user-defined function", some magic kicks in and you get a bound instance method...
Here is how you do it: ``` import types class Scriptable: def __init__(self, script = None): if script is not None: self.script = types.MethodType(script, self) # replace the method def script(self): print("greetings from the default script") ``` As ba\_\_friend noted in the comm...
Assigning a function to an object attribute
6,478,371
19
2011-06-25T14:28:07Z
6,479,888
8
2011-06-25T19:03:14Z
[ "python", "methods" ]
Based on my understanding of [Python's data model](http://docs.python.org/py3k/reference/datamodel.html#the-standard-type-hierarchy), and specifically the subsection "Instance Methods", whenever you read an attribute whose value is of type "user-defined function", some magic kicks in and you get a bound instance method...
Thanks to Alex Martelli's [answer](http://stackoverflow.com/questions/1015307/python-bind-an-unbound-method/1015405#1015405) here is another version: ``` class Scriptable: def script(self): print(self) print("greetings from the default script") def another_script(self): print(self) print("...
Python split consecutive delimiters
6,478,845
5
2011-06-25T15:56:54Z
6,478,877
7
2011-06-25T16:01:44Z
[ "python", "string", "split" ]
The default `split` method in Python treats consecutive spaces as a single delimiter. But if you specify a delimiter string, consecutive delimiters are *not* collapsed: ``` >>> 'aaa'.split('a') ['', '', '', ''] ``` What is the most straightforward way to collapse consecutive delimiters? I know I could just remove emp...
You can use a regular expression as the delimiter, as in : ``` re.split(pattern, string[, maxsplit=0, flags=0]) ``` From [the docs](http://docs.python.org/library/re.html).
Python split consecutive delimiters
6,478,845
5
2011-06-25T15:56:54Z
6,478,890
8
2011-06-25T16:04:13Z
[ "python", "string", "split" ]
The default `split` method in Python treats consecutive spaces as a single delimiter. But if you specify a delimiter string, consecutive delimiters are *not* collapsed: ``` >>> 'aaa'.split('a') ['', '', '', ''] ``` What is the most straightforward way to collapse consecutive delimiters? I know I could just remove emp...
This is about as concise as you can get: ``` string = 'aaa' result = [s for s in string.split('a') if s] ``` Or you could switch to regular expressions: ``` string = 'aaa' result = re.split('a+', string) ```
Python StringIO replacement that works with bytes instead of strings?
6,479,100
32
2011-06-25T16:40:18Z
6,479,113
46
2011-06-25T16:42:39Z
[ "python", "unicode", "python-2.7", "stringio" ]
Is there any replacement for python `StringIO` class, one that will work with `bytes` instead of strings? It may not be obvious but if you used StringIO for processing binary data you are out of luck with Python 2.7 or newer.
Try [`io.BytesIO`](http://docs.python.org/library/io.html?highlight=bytesio#io.BytesIO). As [others](http://stackoverflow.com/a/6480012/577088) [have](http://stackoverflow.com/a/6481034/577088) pointed out, you can indeed use `StringIO` in 2.7, but `BytesIO` is a good choice for forward-compatibility.