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
How is it that json serialization is so much faster than yaml serialization in Python?
2,451,732
35
2010-03-16T02:23:12Z
9,331,885
19
2012-02-17T16:25:50Z
[ "python", "json", "serialization", "yaml" ]
I have code that relies heavily on yaml for cross-language serialization and while working on speeding some stuff up I noticed that yaml was insanely slow compared to other serialization methods (e.g., pickle, json). So what really blows my mind is that json is so much faster that yaml when the output is nearly identi...
In applications I've worked on, the type inference between strings to numbers (float/int) is where the largest overhead is for parsing yaml is because strings can be written without quotes. Because all strings in json are in quotes there is no backtracking when parsing strings. A great example where this would slow dow...
String formatting named parameters?
2,451,821
86
2010-03-16T02:50:31Z
2,451,826
160
2010-03-16T02:52:46Z
[ "python", "string", "syntax" ]
I know it's a really simple question, but I have no idea how to google it. how can I do ``` print '<a href="%s">%s</a>' % (my_url) ``` So that `my_url` is used twice? I assume I have to "name" the `%s` and then use a dict in the params, but I'm not sure of the proper syntax? --- just FYI, I'm aware I can just use ...
``` print '<a href="%(url)s">%(url)s</a>' % {'url': my_url} ```
String formatting named parameters?
2,451,821
86
2010-03-16T02:50:31Z
2,452,382
32
2010-03-16T05:56:07Z
[ "python", "string", "syntax" ]
I know it's a really simple question, but I have no idea how to google it. how can I do ``` print '<a href="%s">%s</a>' % (my_url) ``` So that `my_url` is used twice? I assume I have to "name" the `%s` and then use a dict in the params, but I'm not sure of the proper syntax? --- just FYI, I'm aware I can just use ...
In Python 3, you might choose to use the new string formatting method. ``` print('<a href="{0}">{0}</a>'.format(my_url)) ``` which saves you from repeating the argument, or ``` print('<a href="{url}">{url}</a>'.format(url=my_url)) ``` if you want named parameters.
Python: Create a duplicate of an array
2,452,321
4
2010-03-16T05:34:56Z
2,452,338
9
2010-03-16T05:40:54Z
[ "python", "list", "pointers", "arrays" ]
I have an double array ``` alist[1][1]=-1 alist2=[] for x in xrange(10): alist2.append(alist[x]) alist2[1][1]=15 print alist[1][1] ``` and I get 15. Clearly I'm passing a pointer rather than an actual variable... Is there an easy way to make a **seperate** double array (no shared pointers) **without having to do...
I think [copy.deepcopy()](http://docs.python.org/library/copy.html) is for just this case.
XOR swap algorithm in python?
2,452,336
3
2010-03-16T05:40:42Z
2,452,342
13
2010-03-16T05:43:11Z
[ "python", "algorithm", "tuples" ]
I tried to implement [XOR swap](http://en.wikipedia.org/wiki/XOR_swap_algorithm) in python. ``` x,y= 10,20 x,y,x = x^y,x^y,x^y print('%s , %s'%(x,y)) ``` OUTPUT: ``` 30 , 30 ``` I am not new to python but I am unable to explain this output. It should have been `20,10`. What is going on under the hood?
First, a tuple is created consisting of `x^y`, `x^y` and `x^y`. Then the tuple is unpacked into `x`, `y`, and `x`, causing both to be bound to the result of `x^y`. Save yourself the headache and do it the Pythonic way: ``` x, y = y, x ```
XOR swap algorithm in python?
2,452,336
3
2010-03-16T05:40:42Z
2,452,357
9
2010-03-16T05:47:02Z
[ "python", "algorithm", "tuples" ]
I tried to implement [XOR swap](http://en.wikipedia.org/wiki/XOR_swap_algorithm) in python. ``` x,y= 10,20 x,y,x = x^y,x^y,x^y print('%s , %s'%(x,y)) ``` OUTPUT: ``` 30 , 30 ``` I am not new to python but I am unable to explain this output. It should have been `20,10`. What is going on under the hood?
While it's definitely best, as other answers say, to just `x, y = y, x`, if you're allergic to creating and unpacking tuples you *can* do it with successive x-oring... it just has to be successive, not *simultaneous* as you're doing! ``` >>> x = 1234 >>> y = 3421 >>> x ^= y >>> y ^= x >>> x ^= y >>> print x 3421 >>> p...
Newbie python error in regards to import
2,452,567
4
2010-03-16T06:50:03Z
2,452,639
8
2010-03-16T07:12:29Z
[ "python", "google-app-engine" ]
I'm a python newbie and starting out with using the Bottle web framework on Google App Engine. I've been messing with the super small, super easy Hello World sample and have already ran into problems. Heh. I finally got the code to work with this... ``` import bottle from bottle import route from google.appengine.ext....
In your code you have two different ways of calling methods from bottle package. ``` route('/hello') ``` and ``` bottle.default_app() ``` First call requires `from bottle import route` or `from bottle import *` and second one requires `import bottle`. `from foo import bar` is letting you to use method or parameter...
Python library for converting plain text (ASCII) into GSM 7-bit character set?
2,452,861
5
2010-03-16T08:13:08Z
2,453,027
10
2010-03-16T08:51:40Z
[ "python", "encoding", "sms" ]
Is there a python library for encoding ascii data to 7-bit GSM character set (for sending SMS)?
There is now :) Thanks to [Chad](http://stackoverflow.com/users/37309/chad) for pointing out that this wasn't quite right ## Python2 version ``` # -*- coding: utf8 -*- gsm = (u"@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\x1bÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>" u"?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÃ...
find the colour name from a hexadecimal colour code
2,453,344
8
2010-03-16T09:57:33Z
2,453,492
7
2010-03-16T10:18:24Z
[ "python", "image-processing" ]
i want to find the name of a colour from the hexadecimal colour code. When i get a hex colour code i want to find the most matching colour name. for example for the code #c06040 , how to find out if it is a shade of brown, blue or yellow ?. so that i can find the colour of an object in the image without human intervent...
There is a program distributed with the Python source called *pynche* which can do this The functionality you need is in the method `ColorDB.nearest()` in `ColorDB.py` From Python/Tools/README > ``` > Introduction > > Pynche is a color editor based largely on a similar program that I > originally wrote back ...
Python list is not the same reference
2,453,672
6
2010-03-16T10:49:29Z
2,453,688
14
2010-03-16T10:51:45Z
[ "python" ]
This is the code: ``` L=[1,2] L is L[:] False ``` Why is this False?
`L[:]` (slice notation) means: Make a copy of the entire list, element by element. So you have two lists that have identical content, but are separate entities. Since `is` evaluates object identity, it returns `False`. `L == L[:]` returns `True`.
Django QuerySet ordering by number of reverse ForeignKey matches
2,453,821
2
2010-03-16T11:14:01Z
2,454,022
7
2010-03-16T11:50:25Z
[ "python", "django" ]
I have the following Django models: ``` class Foo(models.Model): title = models.CharField(_(u'Title'), max_length=600) class Bar(models.Model): foo = models.ForeignKey(Foo) eg_id = models.PositiveIntegerField(_(u'Example ID'), default=0) ``` I wish to return a list of `Foo` objects which have a reverse r...
Use Django's lovely [aggregation features](http://docs.djangoproject.com/en/1.1/topics/db/aggregation/). ``` from django.db.models import Count qs = Foo.objects.filter( bar__eg_id__in=id_list ).annotate( bar_count=Count('bar') ).order_by('bar_count') ```
Detect destination of shortened, or "tiny" url
2,454,149
16
2010-03-16T12:11:10Z
2,454,303
14
2010-03-16T12:37:17Z
[ "python", "url", "redirect", "tinyurl" ]
I have just scraped a bunch of Google Buzz data, and I want to know which Buzz posts reference the same news articles. The problem is that many of the links in these posts have been modified by URL shorteners, so it could be the case that many distinct shortened URLs actually all point to the same news article. Given ...
The easiest way to get the destination of a shortened URL is with `urllib`. Given that the short URL is valid (response code 200), the URL be returned to you. ``` >>> import urllib >>> resp = urllib.urlopen('http://bit.ly/bcFOko') >>> resp.getcode() 200 >>> resp.url 'http://mrdoob.com/lab/javascript/harmony/' ``` And...
Django '<object> matching query does not exist' when I can see it in the database
2,454,329
9
2010-03-16T12:40:14Z
2,454,448
9
2010-03-16T12:57:16Z
[ "python", "django" ]
My model looks like this: ``` class Staff(models.Model): StaffNumber = models.CharField(max_length=20,primary_key=True) NameFirst = models.CharField(max_length=30,blank=True,null=True) NameLast = models.CharField(max_length=30) SchoolID = models.CharField(max_length=10,blank=True,null=True) Autocom...
Try ``` a = Staff.objects.get(NameFirst=u'"ANDREA"') ``` The `u` tells Python/Django it's a Unicode string, not a plain old `str`, and in your `s[0].NameFirst` sample, it's showing the value as containing double quotes.
What is a Pythonic way to get a list of tuples of all the possible combinations of the elements of two lists?
2,454,626
3
2010-03-16T13:25:41Z
2,454,646
13
2010-03-16T13:28:20Z
[ "list", "python" ]
Suppose I have two differently-sized lists ``` a = [1, 2, 3] b = ['a', 'b'] ``` What is a Pythonic way to get a list of tuples `c` of all the possible combinations of one element from `a` and one element from `b`? ``` >>> print c [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')] ``` The order of elements...
Use a list comprehension: ``` >>> a = [1, 2, 3] >>> b = ['a', 'b'] >>> c = [(x,y) for x in a for y in b] >>> print c [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')] ```
What is a Pythonic way to get a list of tuples of all the possible combinations of the elements of two lists?
2,454,626
3
2010-03-16T13:25:41Z
2,454,649
9
2010-03-16T13:28:35Z
[ "list", "python" ]
Suppose I have two differently-sized lists ``` a = [1, 2, 3] b = ['a', 'b'] ``` What is a Pythonic way to get a list of tuples `c` of all the possible combinations of one element from `a` and one element from `b`? ``` >>> print c [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')] ``` The order of elements...
Try `itertools.product`.
How to spell check python docstring with emacs?
2,455,062
5
2010-03-16T14:20:02Z
2,455,436
12
2010-03-16T15:01:12Z
[ "python", "emacs", "spell-checking", "docstring" ]
I'd like to run a spell checker on the docstrings of my Python code, if possible from within emacs. I've found the ispell-check-comments setting which can be used to spell check only comments in code, but I was not able to target only the docstrings which are a fairly python-specific thing.
I recommend you to try flyspell-mode. You could use something like: (add-hook 'python-mode-hook 'flyspell-prog-mode) in your Emacs configuration.
How to get the width of a string in pixels?
2,455,255
7
2010-03-16T14:40:40Z
2,455,286
8
2010-03-16T14:44:41Z
[ "python", "wxpython" ]
I am using wxPython's HyperTreeList and I want to set the column width exactly equal to length of the largest string in it. To accomplish that, I'd like to to convert a python string size into pixels. For Example: If we have a string like ``` str = "python" len(str) = 6 ``` How could I convert the above string leng...
It depends on how you are printing the text. You may be interested by `PIL ImageDraw` which has a `textsize` method. See <http://effbot.org/imagingbook/imagedraw.htm> Update: This was answering the original question. It may looks a little off-topic after question updates.
How to get the width of a string in pixels?
2,455,255
7
2010-03-16T14:40:40Z
2,455,379
12
2010-03-16T14:55:19Z
[ "python", "wxpython" ]
I am using wxPython's HyperTreeList and I want to set the column width exactly equal to length of the largest string in it. To accomplish that, I'd like to to convert a python string size into pixels. For Example: If we have a string like ``` str = "python" len(str) = 6 ``` How could I convert the above string leng...
You'll have to do [something](http://bytes.com/topic/python/answers/693968-wxpython-status-bar-adjust-length-string) [like](http://www.wxpython.org/docs/api/wx.DC-class.html#GetTextExtent) (see the [documentation of wxWidgets](http://docs.wxwidgets.org/2.8/wx_wxdc.html#wxdcgettextextent) for more info) ``` f = window....
BasicHTTPServer, SimpleHTTPServer and concurrency
2,455,606
4
2010-03-16T15:21:26Z
2,455,756
7
2010-03-16T15:39:11Z
[ "python", "concurrency", "simplehttpserver" ]
I'm writing a small web server for testing purposes using python, BasicHTTPServer and SimpleHTTPServer. It looks like it's processing one request at a time. Is there any way to make it a little faster without messing around too deeply? Basicly my code looks as the following and I'd like to keep it this simple ;) ``` o...
You can make your own threading or forking class with a mixin inheritance from [SocketServer](http://docs.python.org/library/socketserver.html): ``` import SocketServer import BaseHTTPServer class ThreadingHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass ``` This has its limits as it does...
Reordering matrix elements to reflect column and row clustering in naiive python
2,455,761
20
2010-03-16T15:39:32Z
3,017,704
30
2010-06-10T19:21:41Z
[ "python", "statistics", "numpy", "cluster-analysis", "scipy" ]
I'm looking for a way to perform clustering separately on matrix rows and than on its columns, reorder the data in the matrix to reflect the clustering and putting it all together. The clustering problem is easily solvable, so is the dendrogram creation (for example in [this blog](http://www.janeriksolem.net/2009/04/hi...
See my [recent answer](http://stackoverflow.com/questions/2982929/plotting-results-of-hierarchical-clustering-ontop-of-a-matrix-of-data-in-python/3011894#3011894), copied in part below, to [this related question](http://stackoverflow.com/questions/2982929/). ``` import scipy import pylab import scipy.cluster.hierarchy...
how to build good python web application
2,455,996
2
2010-03-16T16:06:42Z
2,456,021
11
2010-03-16T16:10:29Z
[ "python", "web-applications" ]
hello i never worked with web programming and i've been asked lately to write a web-based software to manage assets and tasks. to be used by more than 900 persons what are the recommended modules , frameworks , libraries for this task. and it will be highly appreciated if you guyz recommend some books and article...
Check out [Django](http://www.djangoproject.com/). I would say it is the most comprehensive and easy to use python web framework. They have a [book](http://www.djangobook.com/en/2.0/) and [tutorial](http://docs.djangoproject.com/en/dev/intro/tutorial01/) as well. You might also like to visit [Python wiki](http://wiki...
python print end=' '
2,456,148
50
2010-03-16T16:26:54Z
2,456,162
27
2010-03-16T16:28:55Z
[ "python" ]
I have this python script where I need to run `gdal_retile.py` but I get an exception on this line: ``` if Verbose: print("Building internam Index for %d tile(s) ..." % len(inputTiles), end=' ') ``` The `end=''` is invalid syntax. I am curious as to why, and what the author probably meant to do. I'm new to pytho...
How about this: ``` #Only for use in Python 2.6.0a2 and later from __future__ import print_function ``` This allows you to use the Python 3.0 style `print` function without having to hand-edit all occurrences of `print` :)
python print end=' '
2,456,148
50
2010-03-16T16:26:54Z
2,456,292
67
2010-03-16T16:43:04Z
[ "python" ]
I have this python script where I need to run `gdal_retile.py` but I get an exception on this line: ``` if Verbose: print("Building internam Index for %d tile(s) ..." % len(inputTiles), end=' ') ``` The `end=''` is invalid syntax. I am curious as to why, and what the author probably meant to do. I'm new to pytho...
Are you sure you are using Python 3.x? The syntax isn't available in Python 2.x because `print` is still a statement. `print("foo" % bar, end=" ")` in Python 2.x is identical to `print ("foo" % bar, end=" ")` or `print "foo" % bar, end=" "` i.e. as a call to print with a tuple as argument. That's obviously bad s...
UTF-8 HTML and CSS files with BOM (and how to remove the BOM with Python)
2,456,380
9
2010-03-16T16:53:14Z
2,456,686
8
2010-03-16T17:33:19Z
[ "python", "file", "utf-8", "byte-order-mark" ]
First, some background: I'm developing a web application using Python. All of my (text) files are currently stored in UTF-8 with the BOM. This includes all my HTML templates and CSS files. These resources are stored as binary data (BOM and all) in my DB. When I retrieve the templates from the DB, I decode them using `...
Check the first character after decoding to see if it's the BOM: ``` if u.startswith(u'\ufeff'): u = u[1:] ```
UTF-8 HTML and CSS files with BOM (and how to remove the BOM with Python)
2,456,380
9
2010-03-16T16:53:14Z
2,459,793
19
2010-03-17T03:47:42Z
[ "python", "file", "utf-8", "byte-order-mark" ]
First, some background: I'm developing a web application using Python. All of my (text) files are currently stored in UTF-8 with the BOM. This includes all my HTML templates and CSS files. These resources are stored as binary data (BOM and all) in my DB. When I retrieve the templates from the DB, I decode them using `...
Since you state: > All of my (text) files are currently > stored in UTF-8 with the BOM then use the 'utf-8-sig' codec to decode them: ``` >>> s = u'Hello, world!'.encode('utf-8-sig') >>> s '\xef\xbb\xbfHello, world!' >>> s.decode('utf-8-sig') u'Hello, world!' ``` It automatically removes the expected BOM, and works...
Using IDLE to run Python PyUnit unit tests
2,457,068
8
2010-03-16T18:30:49Z
2,457,281
7
2010-03-16T19:04:32Z
[ "python", "unit-testing", "python-idle" ]
Is there a way, within IDLE, to run the PyUnit (unittest module) unit tests directly? I ask because I have a short test module and when I run it with python mymodule.py from the Cygwin shell I get all tests passed, but when I use Run->Run Module from IDLE the tests pass but then I get an exception (SystemExit: False)....
No one answered (I find that if there aren't any answers in the first few minutes, the likelihood of an answer goes down significantly :), so I kept researching this myself. Not sure if this is the most elegant solution or not, but changing: ``` if __name__ == '__main__': unittest.main() ``` to ``` if __name__ ...
Using IDLE to run Python PyUnit unit tests
2,457,068
8
2010-03-16T18:30:49Z
9,140,610
8
2012-02-04T11:46:06Z
[ "python", "unit-testing", "python-idle" ]
Is there a way, within IDLE, to run the PyUnit (unittest module) unit tests directly? I ask because I have a short test module and when I run it with python mymodule.py from the Cygwin shell I get all tests passed, but when I use Run->Run Module from IDLE the tests pass but then I get an exception (SystemExit: False)....
You can also do ``` if __name__ == '__main__': unittest.main(exit=False) ``` if you're using Python >= 2.7
Looping through columns in a .csv files in Python
2,457,193
3
2010-03-16T18:51:15Z
2,457,220
7
2010-03-16T18:55:25Z
[ "python", "csv", "sum" ]
I want to be able to use Python to open a `.csv` file like this: ``` 5,26,42,2,1,6,6 ``` and then perform some operation on them like addition. ``` total = 0 with open("file.csv") as csv_file: for row in csv.reader(csv_file, delimiter=','): for number in range(7): total += int(row...
You can just say ``` for col in row: total += int(col) ``` For example: ``` import csv from StringIO import StringIO total = 0 for row in csv.reader(StringIO("1,2,3,4")): for col in row: total += int(col) print total # prints 10 ``` The reason why you can do this is that csv.reader returns a si...
Absolute path of a file object
2,458,676
12
2010-03-16T22:41:23Z
2,458,866
11
2010-03-16T23:15:54Z
[ "python", "file", "filesystems" ]
This has been discussed on StackOverflow before - I am trying to find a good way to find the absolute path of a file object, but I need it to be robust to `os.chdir()`, so cannot use ``` f = file('test') os.path.abspath(f.name) ``` Instead, I was wondering whether the following is a good solution - basically extendin...
One significant risk is that, once the file is open, the process is dealing with that file by its file descriptor, *not* its path. On many operating systems, **the file's path can be changed by any other process** (by a `mv` operation in an unrelated process, say) and the file descriptor is still valid and refers to th...
Invertible STFT and ISTFT in Python
2,459,295
40
2010-03-17T01:12:29Z
6,891,772
54
2011-07-31T19:30:16Z
[ "python", "scipy", "fft", "signal-processing" ]
Is there any general-purpose form of [short-time Fourier transform](https://en.wikipedia.org/wiki/Short-time_Fourier_transform) with corresponding inverse transform built into SciPy or NumPy or whatever? There's the pyplot `specgram` function in matplotlib, which calls `ax.specgram()`, which calls `mlab.specgram()`, w...
Here is my Python code, simplified for this answer: ``` import scipy, pylab def stft(x, fs, framesz, hop): framesamp = int(framesz*fs) hopsamp = int(hop*fs) w = scipy.hanning(framesamp) X = scipy.array([scipy.fft(w*x[i:i+framesamp]) for i in range(0, len(x)-framesamp, hopsamp)]) ...
web2py or grok (zope) on a big portal,
2,459,549
3
2010-03-17T02:26:22Z
2,459,620
7
2010-03-17T02:48:39Z
[ "python", "zope", "web2py", "zodb", "grok" ]
I am planning to make some big project (1 000 000 users, approximately 500 request pre second - in hot time). For performance I'm going to use no relational dbms (each request could cost lot of instructions in relational dbms like mysql) - so i can't use DAL. My question is: 1. how web2py is working with a big traffi...
First, don't assume that a data abstraction layer will have unacceptable performance, until you actually see it in practice. It is pretty easy to switch to RAW sql if and when you run into a problem. Second, most users who worry about there server technology handling a million users never finish their applications. Pi...
Are Python properties broken?
2,459,715
3
2010-03-17T03:23:12Z
2,459,719
13
2010-03-17T03:25:21Z
[ "python", "properties", "message", "enhancement", "new-style-class" ]
How can it be that this test case ``` import unittest class PropTest(unittest.TestCase): def test(self): class C(): val = 'initial val' def get_p(self): return self.val def set_p(self, prop): if prop == 'legal val': ...
Your class `C` does not inherit from `object` or any other new-style class, so it is an old-style class (and therefore does not support properties). Descriptors are for new-style classes only. To fix, change `class C()` to `class C(object)`. <http://www.python.org/download/releases/2.2.3/descrintro/> provides some det...
how to import csv data into django models
2,459,979
33
2010-03-17T04:59:20Z
2,459,996
9
2010-03-17T05:04:15Z
[ "python", "django", "csv", "django-models", "export" ]
I have some CSV data and I want to import into django models using the example CSV data: ``` 1;"02-01-101101";"Worm Gear HRF 50";"Ratio 1 : 10";"input shaft, output shaft, direction A, color dark green"; 2;"02-01-101102";"Worm Gear HRF 50";"Ratio 1 : 20";"input shaft, output shaft, direction A, color dark green"; 3;"0...
The Python [csv library](http://docs.python.org/library/csv.html) can do your parsing and your code can translate them into `Products()`.
how to import csv data into django models
2,459,979
33
2010-03-17T04:59:20Z
15,961,736
37
2013-04-12T01:41:27Z
[ "python", "django", "csv", "django-models", "export" ]
I have some CSV data and I want to import into django models using the example CSV data: ``` 1;"02-01-101101";"Worm Gear HRF 50";"Ratio 1 : 10";"input shaft, output shaft, direction A, color dark green"; 2;"02-01-101102";"Worm Gear HRF 50";"Ratio 1 : 20";"input shaft, output shaft, direction A, color dark green"; 3;"0...
You want to use the csv module that is part of the python language and you should use Django's get\_or\_create method ``` with open(path) as f: reader = csv.reader(f) for row in reader: _, created = Teacher.objects.get_or_create( first_name=row[0], last_name...
how to import csv data into django models
2,459,979
33
2010-03-17T04:59:20Z
24,669,572
16
2014-07-10T06:12:01Z
[ "python", "django", "csv", "django-models", "export" ]
I have some CSV data and I want to import into django models using the example CSV data: ``` 1;"02-01-101101";"Worm Gear HRF 50";"Ratio 1 : 10";"input shaft, output shaft, direction A, color dark green"; 2;"02-01-101102";"Worm Gear HRF 50";"Ratio 1 : 20";"input shaft, output shaft, direction A, color dark green"; 3;"0...
I told you in a comment why you shouldn't be asking this. But you're new and I like new people who come to SO. First of all, look - there's [a way to ask for recommendations](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/#howtoask) - it generally revolves around *being specific* about **what you're ...
'int' object is not callable when using the sum function on a list
2,460,087
9
2010-03-17T05:32:37Z
2,460,094
34
2010-03-17T05:34:29Z
[ "python", "list" ]
``` coinCount = [2 for i in range(4)] total = sum(coinCount) ``` This gives me ``` TypeError: 'int' object is not callable ``` I don't understand why because ``` print type(coinCount) ``` Gives me ``` type <'list'> ```
You no doubt used the identifier `sum` previously in your code as a local variable name, and the last value you bound to it was an `int`. So, in that code snippet, you're trying to call the `int`. `print sum` just before you try calling it and you'll see, but code inspection will probably reveal it faster. This kind o...
Edit Distance in Python
2,460,177
14
2010-03-17T06:02:07Z
2,460,201
20
2010-03-17T06:11:19Z
[ "python", "algorithm", "edit", "distance" ]
I'm programming a spellcheck program in Python. I have a list of valid words (the dictionary) and I need to output a list of words from this dictionary that have an edit distance of 2 from a given invalid word. I know I need to start by generating a list with an edit distance of one from the invalid word(and then run ...
You are looking for Norvig's excellent post with source code: How To Write a Spelling Corrector <http://norvig.com/spell-correct.html> Includes Python source code, theory, and background.
Edit Distance in Python
2,460,177
14
2010-03-17T06:02:07Z
19,928,962
7
2013-11-12T12:16:49Z
[ "python", "algorithm", "edit", "distance" ]
I'm programming a spellcheck program in Python. I have a list of valid words (the dictionary) and I need to output a list of words from this dictionary that have an edit distance of 2 from a given invalid word. I know I need to start by generating a list with an edit distance of one from the invalid word(and then run ...
``` #this calculates edit distance not levenstein edit distance word1="rice" word2="ice" len_1=len(word1) len_2=len(word2) x =[[0]*(len_2+1) for _ in range(len_1+1)]#the matrix whose last element ->edit distance for i in range(0,len_1+1): #initialization of base case values x[i][0]=i for j in range(0,len_2+1)...
Edit Distance in Python
2,460,177
14
2010-03-17T06:02:07Z
32,558,749
8
2015-09-14T06:52:27Z
[ "python", "algorithm", "edit", "distance" ]
I'm programming a spellcheck program in Python. I have a list of valid words (the dictionary) and I need to output a list of words from this dictionary that have an edit distance of 2 from a given invalid word. I know I need to start by generating a list with an edit distance of one from the invalid word(and then run ...
The thing you are looking at is called an edit distance and here is a [nice explanation on wiki](https://en.wikipedia.org/wiki/Edit_distance). There are a lot of ways how to define a distance between the two words and the one that you want is called Levenshtein distance and here is a DP implementation in python. ``` d...
Get a unique computer ID in Python on windows and linux
2,461,141
11
2010-03-17T09:41:21Z
2,462,978
11
2010-03-17T14:23:18Z
[ "python", "hardware" ]
I'd like to get an id unique to a computer with Python on Windows and Linux. It could be the CPU ID, the motherboard serial, ... or anything else. I looked at several modules (pycpuid, psi, ...) without luck. Any idea on how to do that?
There seems to be no direct "python" way of doing this. On modern PC hardware, there usually is an UUID stored in the BIOS - on Linux there is a command line utility `dmidecode` that can read this; example from my desktop: ``` System Information Manufacturer: Dell Inc. Product Name: OptiPlex 755 ...
Get a unique computer ID in Python on windows and linux
2,461,141
11
2010-03-17T09:41:21Z
3,152,570
7
2010-06-30T19:13:04Z
[ "python", "hardware" ]
I'd like to get an id unique to a computer with Python on Windows and Linux. It could be the CPU ID, the motherboard serial, ... or anything else. I looked at several modules (pycpuid, psi, ...) without luck. Any idea on how to do that?
for Windows you need **DmiDecode for Windows** ([link](http://gnuwin32.sourceforge.net/packages/dmidecode.htm)) : ``` subprocess.Popen('dmidecode.exe -s system-uuid'.split()) ``` for Linux (non root): ``` subprocess.Popen('hal-get-property --udi /org/freedesktop/Hal/devices/computer --key system.hardware.uuid'.split...
Numpy image - rotate matrix 270 degrees
2,461,303
6
2010-03-17T10:07:03Z
2,461,347
7
2010-03-17T10:13:24Z
[ "python", "matrix", "image-manipulation", "numpy" ]
I've got a Numpy 2d array that represents a grey-scale image and I need to rotate it 270 degrees. Might be being a bit thick here but the two ways I can find to do this seem quite... circulous: ``` rotated = numpy.rot90(numpy.rot90(numpy.rot90(orignumpyarray))) rotated = numpy.fliplr(numpy.flipud(numpy.rot90(orignump...
You can tell `rot90` to [rotate several times](http://docs.scipy.org/doc/numpy/reference/generated/numpy.rot90.html#numpy.rot90), this should work: ``` rotated = numpy.rot90(orignumpyarray,3) ```
How to implement full text search in Django?
2,461,322
8
2010-03-17T10:09:44Z
2,461,501
15
2010-03-17T10:37:21Z
[ "python", "django", "django-queryset", "full-text-search" ]
I would like to implement a search function in a django blogging application. The status quo is that I have a list of strings supplied by the user and the queryset is narrowed down by each string to include only those objects that match the string. See: ``` if request.method == "POST": form = SearchForm(request.P...
I suggest you to adopt a search engine. We've used [Haystack search](http://haystacksearch.org/), a modular search application for django supporting many search engines (Solr, Xapian, Whoosh, etc...) Advantages: * Faster * perform search queries even without querying the database. * Highlight searched terms * "More ...
Why is IoC / DI not common in Python?
2,461,702
146
2010-03-17T11:10:33Z
2,462,042
8
2010-03-17T12:10:16Z
[ "python", "design-patterns", "dependency-injection", "inversion-of-control", "architecture" ]
In Java [IoC](http://en.wikipedia.org/wiki/Inversion_of_Control) / [DI](http://en.wikipedia.org/wiki/Dependency_Injection) is a very common practice which is extensively used in web applications, nearly all available frameworks and Java EE. On the other hand, there are also lots of big Python web applications, but besi...
Haven't used Python in several years, but I would say that it has more to do with it being a dynamically typed language than anything else. For a simple example, in Java, if I wanted to test that something wrote to standard out appropriately I could use DI and pass in any PrintStream to capture the text being written a...
Why is IoC / DI not common in Python?
2,461,702
146
2010-03-17T11:10:33Z
2,462,076
24
2010-03-17T12:16:25Z
[ "python", "design-patterns", "dependency-injection", "inversion-of-control", "architecture" ]
In Java [IoC](http://en.wikipedia.org/wiki/Inversion_of_Control) / [DI](http://en.wikipedia.org/wiki/Dependency_Injection) is a very common practice which is extensively used in web applications, nearly all available frameworks and Java EE. On the other hand, there are also lots of big Python web applications, but besi...
Part of it is the way the module system works in Python. You can get a sort of "singleton" for free, just by importing it from a module. Define an actual instance of an object in a module, and then any client code can import it and actually get a working, fully constructed / populated object. This is in contrast to Ja...
Why is IoC / DI not common in Python?
2,461,702
146
2010-03-17T11:10:33Z
2,465,052
113
2010-03-17T18:59:17Z
[ "python", "design-patterns", "dependency-injection", "inversion-of-control", "architecture" ]
In Java [IoC](http://en.wikipedia.org/wiki/Inversion_of_Control) / [DI](http://en.wikipedia.org/wiki/Dependency_Injection) is a very common practice which is extensively used in web applications, nearly all available frameworks and Java EE. On the other hand, there are also lots of big Python web applications, but besi...
I don't actually think that DI/IoC are *that* uncommon in Python. What *is* uncommon, however, are DI/IoC *frameworks/containers*. Think about it: what does a DI container do? It allows you to 1. wire together independent components into a complete application ... 2. ... at runtime. We have names for "wiring togethe...
Why is IoC / DI not common in Python?
2,461,702
146
2010-03-17T11:10:33Z
2,465,344
30
2010-03-17T19:46:56Z
[ "python", "design-patterns", "dependency-injection", "inversion-of-control", "architecture" ]
In Java [IoC](http://en.wikipedia.org/wiki/Inversion_of_Control) / [DI](http://en.wikipedia.org/wiki/Dependency_Injection) is a very common practice which is extensively used in web applications, nearly all available frameworks and Java EE. On the other hand, there are also lots of big Python web applications, but besi...
Django makes great use of inversion of control. For instance, the database server is selected by the configuration file, then the framework provides appropriate database wrapper instances to database clients. The difference is that Python has first-class types. Data types, including classes, are themselves objects. If...
Why is IoC / DI not common in Python?
2,461,702
146
2010-03-17T11:10:33Z
7,308,688
12
2011-09-05T13:19:24Z
[ "python", "design-patterns", "dependency-injection", "inversion-of-control", "architecture" ]
In Java [IoC](http://en.wikipedia.org/wiki/Inversion_of_Control) / [DI](http://en.wikipedia.org/wiki/Dependency_Injection) is a very common practice which is extensively used in web applications, nearly all available frameworks and Java EE. On the other hand, there are also lots of big Python web applications, but besi...
I back "Jörg W Mittag" answer: "The Python implementation of DI/IoC is so lightweight that it completely vanishes". To back up this statement, take a look at the famous Martin Fowler's example ported from Java to Python: [Python:Design\_Patterns:Inversion\_of\_Control](https://web.archive.org/web/20130703221553/http:...
Python: Class factory using user input as class names
2,461,751
10
2010-03-17T11:20:31Z
2,461,898
13
2010-03-17T11:49:08Z
[ "python", "metaprogramming", "factory", "metaclass" ]
I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasses should depend on user input. There is a superclass "Unit", to which I can add attributes at runtime. This already works. ``` def add_attr (...
To create a class from a name, use the `class` statement and assign the name. Observe: ``` def meta(name): class cls(Unit): pass cls.__name__ = name return cls ``` Now I suppose I should explain myself, and so on. When you create a class using the class statement, it is done dynamically-- it is e...
Python: 'break' outside loop
2,462,566
7
2010-03-17T13:32:45Z
2,462,583
26
2010-03-17T13:34:50Z
[ "python" ]
in the following python code: ``` narg=len(sys.argv) print "@length arg= ", narg if narg == 1: print "@Usage: input_filename nelements nintervals" break ``` I get: ``` SyntaxError: 'break' outside loop ``` Why?
Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave. What are you trying to do? Perhaps you should use `sys.exit()` or `return` instead?
how to set wxPython main frame bottom right on screen?
2,462,802
6
2010-03-17T14:03:47Z
2,463,774
10
2010-03-17T15:57:47Z
[ "python", "wxpython" ]
For better description, ``` +-----------------------+ | Desktop (screen) | | | | | | +----------+ | | | wxPython | | | | App. | | | | | | | | | | | +----------+ | +-----------------------+ ``` ...
You can use wx.DisplaySize to get display screen size, and from window.GetSize() you can get the size of your window which you want to position, these two informations are enough to pos it correctly. e.g. in this example I position a MinFrame it at bottom-right ``` import wx def alignToBottomRight(win): dw, dh = ...
Is it possible to change the model name in the django admin site?
2,462,905
25
2010-03-17T14:15:42Z
2,462,921
42
2010-03-17T14:17:32Z
[ "python", "django", "django-models", "django-admin" ]
I am translating a django app and I would like to translate also the homepage of the django admin site. On this page are listed the application names and the model class names. I would like to translate the model class name but I don't find how to give a user-friendly name for a model class. Does anybody know how to ...
Look at the [`Meta` options](https://docs.djangoproject.com/en/dev/ref/models/options/#verbose-name) `verbose_name` and `verbose_name_plural`, both of which are translatable.
Get the dictionary values for every key in a list
2,463,196
5
2010-03-17T14:49:52Z
2,463,297
8
2010-03-17T15:01:29Z
[ "python", "dictionary" ]
Let's say I have a list: ``` a = ['apple', 'carrot'] ``` and a dictionary: ``` d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]} ``` How can I use the list **a** as a key to lookup in the dictionary **d**? I want the result to be written to a comma-separated textfile like this ``` apple, carrot 2, ...
``` a = ['apple', 'orange'] d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]} print ',\t'.join(a) for row in zip(*(d[key] for key in a)): print ',\t'.join(map(str, row)) ``` Output: ``` apple, orange 2, 345 4, 667 ```
Is it possible to renice a subprocess?
2,463,533
7
2010-03-17T15:26:45Z
2,470,061
10
2010-03-18T13:22:10Z
[ "python", "subprocess", "nice", "renice" ]
I know about [`os.nice()`](https://docs.python.org/2/library/os.html#os.nice) it works perfect for parent process, but I need to do renice of my child subprocesses. I found way to do this, but it seems to be not very handy and too excessive: ``` os.system("renice -n %d %d" % ( new_nice, suprocess.pid ) ) ``` And it i...
Use the `preexec_fn` parameter of [`subprocess.Popen`](https://docs.python.org/2/library/subprocess.html#popen-constructor): > If `preexec_fn` is set to a callable object, this object will be called in the child process just before the child is executed. (Unix only) Example: ``` >>> Popen(["nice"]).communicate() 0 (...
Python in-memory zip library
2,463,770
24
2010-03-17T15:57:25Z
2,463,818
21
2010-03-17T16:02:30Z
[ "python", "memory", "zip", "archive" ]
Is there a Python library that allows manipulation of zip archives in memory, without having to use actual disk files? The ZipFile library does not allow you to update the archive. The only way seems to be to extract it to a directory, make your changes, and create a new zip from that directory. I want to modify zip a...
From the article [In-Memory Zip in Python](http://www.kompato.com/post/43805938842/in-memory-zip-in-python): > Below is a post of mine from May of 2008 on zipping in memory with Python, re-posted since Posterous is shutting down. > > I recently noticed that there is a for-pay component available to zip files in-memory...
Python in-memory zip library
2,463,770
24
2010-03-17T15:57:25Z
2,463,819
36
2010-03-17T16:02:39Z
[ "python", "memory", "zip", "archive" ]
Is there a Python library that allows manipulation of zip archives in memory, without having to use actual disk files? The ZipFile library does not allow you to update the archive. The only way seems to be to extract it to a directory, make your changes, and create a new zip from that directory. I want to modify zip a...
According to the [Python docs](http://docs.python.org/library/zipfile.html#zipfile-objects): ``` class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]]) Open a ZIP file, where file can be either a path to a file (a string) or a file-like object. ``` So, to open the file in memory, just create a file-like ...
Python in-memory zip library
2,463,770
24
2010-03-17T15:57:25Z
19,722,365
13
2013-11-01T07:13:59Z
[ "python", "memory", "zip", "archive" ]
Is there a Python library that allows manipulation of zip archives in memory, without having to use actual disk files? The ZipFile library does not allow you to update the archive. The only way seems to be to extract it to a directory, make your changes, and create a new zip from that directory. I want to modify zip a...
The example Ethier provided has several problems, some of them major: * doesn't work for real data on Windows. A ZIP file is binary and its data should always be written with a file opened 'wb' * the ZIP file is appended to for each file, this is inefficient. It can just be opened and kept as an `InMemoryZip` attribut...
Numpy histogram of large arrays
2,464,871
12
2010-03-17T18:31:09Z
2,465,323
8
2010-03-17T19:43:20Z
[ "python", "numpy", "scipy", "histogram" ]
I have a bunch of csv datasets, about 10Gb in size each. I'd like to generate histograms from their columns. But it seems like the only way to do this in numpy is to first load the entire column into a numpy array and then call `numpy.histogram` on that array. This consumes an unnecessary amount of memory. Does numpy ...
As you said, it's not that hard to roll your own. You'll need to set up the bins yourself and reuse them as you iterate over the file. The following ought to be a decent starting point: ``` import numpy as np datamin = -5 datamax = 5 numbins = 20 mybins = np.linspace(datamin, datamax, numbins) myhist = np.zeros(numbin...
What's the u prefix in a python string
2,464,959
92
2010-03-17T18:43:20Z
2,464,968
49
2010-03-17T18:45:05Z
[ "python", "syntax" ]
Like in: ``` u'Hello' ``` My guess is that it indicates "unicode", is it correct? If so, since when is it available?
You're right. <http://docs.python.org/2/tutorial/introduction.html#unicode-strings> It's been syntax since 2.0.
What's the u prefix in a python string
2,464,959
92
2010-03-17T18:43:20Z
2,464,974
24
2010-03-17T18:45:32Z
[ "python", "syntax" ]
Like in: ``` u'Hello' ``` My guess is that it indicates "unicode", is it correct? If so, since when is it available?
> My guess is that it indicates "unicode", is it correct? Yes. > If so, since when is it available? Python 2.x. (In Python 3.x the strings use Unicode by default and there's no need for the `u` prefix.)
What's the u prefix in a python string
2,464,959
92
2010-03-17T18:43:20Z
16,741,817
58
2013-05-24T18:55:03Z
[ "python", "syntax" ]
Like in: ``` u'Hello' ``` My guess is that it indicates "unicode", is it correct? If so, since when is it available?
The u in `u'Some String'` means that your string is a *unicode string*. *Q: I'm in a terrible, awful hurry and I landed here from google. I'm trying to write this data to a file and I'm getting an error and I need the dead simplest, probably flawed, solution this second.* A: You should really read Joel's [Absolute Mi...
python on usb stick
2,465,593
8
2010-03-17T20:24:21Z
2,465,611
10
2010-03-17T20:26:07Z
[ "python", "portable-applications" ]
Is there any free and open-source option to run python from an usb-stick on Windows system (i.e. python installed on an usb-stick ) and can run on any Windows system just by pluging-in the usb-stick?
Try [Portable Python](http://www.portablepython.com/).
Custom keys for Google App Engine models (Python)
2,465,675
12
2010-03-17T20:34:22Z
2,466,007
13
2010-03-17T21:20:54Z
[ "python", "google-app-engine", "gae-datastore", "primary-key" ]
First off, I'm relatively new to Google App Engine, so I'm probably doing something silly. Say I've got a model Foo: ``` class Foo(db.Model): name = db.StringProperty() ``` I want to use `name` as a unique key for every `Foo` object. How is this done? When I want to get a specific `Foo` object, I currently query...
I've used the code below in a project before. It will work as long as the field on which you're basing your key name on is required. ``` class NamedModel(db.Model): """A Model subclass for entities which automatically generate their own key names on creation. See documentation for _generate_key function for ...
Generating a list of values a regex COULD match in Python
2,465,719
2
2010-03-17T20:40:24Z
2,468,247
7
2010-03-18T08:01:25Z
[ "python", "regex" ]
I'm trying to use a regex as an input, and from there generate all the possible values that the regex would match. So, for example, if the regex is "three-letter words starting with a, and ending in c," then the code would generate a list with the values [aac, abc, acc, adc, a1c....]. Is there an easy way to do this?...
Here's a brute force solution that should work. It has a running time of O(L^max\_length) (where L is the size of the alphabet), so use it at your own risk. ``` def all_matching_strings(alphabet, max_length, regex): """Find the list of all strings over 'alphabet' of length up to 'max_length' that match 'regex'""" if ...
How to copy a dictionary and only edit the copy
2,465,921
190
2010-03-17T21:07:06Z
2,465,932
240
2010-03-17T21:09:08Z
[ "python", "python-3.x", "dictionary" ]
Can someone please explain this to me? This doesn't make any sense to me. I copy a dictionary into another and edit the second and both are changed. Why is this happening? ``` >>> dict1 = {"key1": "value1", "key2": "value2"} >>> dict2 = dict1 >>> dict2 {'key2': 'value2', 'key1': 'value1'} >>> dict2["key2"] = "WHY?!" ...
Python *never* implicitly copies objects. When you set `dict2 = dict1`, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state. If you want to copy the dict (which is rare), you have to do so explicitly with ``` dict2 = di...
How to copy a dictionary and only edit the copy
2,465,921
190
2010-03-17T21:07:06Z
2,465,951
145
2010-03-17T21:11:00Z
[ "python", "python-3.x", "dictionary" ]
Can someone please explain this to me? This doesn't make any sense to me. I copy a dictionary into another and edit the second and both are changed. Why is this happening? ``` >>> dict1 = {"key1": "value1", "key2": "value2"} >>> dict2 = dict1 >>> dict2 {'key2': 'value2', 'key1': 'value1'} >>> dict2["key2"] = "WHY?!" ...
When you assign `dict2 = dict1`, you are not making a copy of `dict1`, it results in `dict2` being just another name for `dict1`. To copy the mutable types like dictionaries, use `copy` / `deepcopy` of the [`copy`](http://docs.python.org/library/copy.html) module. ``` import copy dict2 = copy.deepcopy(dict1) ```
How to copy a dictionary and only edit the copy
2,465,921
190
2010-03-17T21:07:06Z
22,214,248
21
2014-03-06T03:28:22Z
[ "python", "python-3.x", "dictionary" ]
Can someone please explain this to me? This doesn't make any sense to me. I copy a dictionary into another and edit the second and both are changed. Why is this happening? ``` >>> dict1 = {"key1": "value1", "key2": "value2"} >>> dict2 = dict1 >>> dict2 {'key2': 'value2', 'key1': 'value1'} >>> dict2["key2"] = "WHY?!" ...
You can also just make a new dictionary with a dictionary comprehension. This avoids importing copy. ``` dout = dict((k,v) for k,v in mydict.items()) ``` Of course in python >= 2.7 you can do: ``` dout = {k:v for k,v in mydict.items()} ``` But for backwards compat., the top method is better.
How to copy a dictionary and only edit the copy
2,465,921
190
2010-03-17T21:07:06Z
22,341,377
40
2014-03-12T03:23:16Z
[ "python", "python-3.x", "dictionary" ]
Can someone please explain this to me? This doesn't make any sense to me. I copy a dictionary into another and edit the second and both are changed. Why is this happening? ``` >>> dict1 = {"key1": "value1", "key2": "value2"} >>> dict2 = dict1 >>> dict2 {'key2': 'value2', 'key1': 'value1'} >>> dict2["key2"] = "WHY?!" ...
``` >>> x={'a': 1, 'b': {'m': 4, 'n': 5, 'o': 6}, 'c': 3} >>> u=x.copy() >>> v=dict(x) >>> import copy >>> w=copy.deepcopy(x) >>> x['a']=10 >>> x {'a': 10, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}} >>> u {'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}} >>> v {'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}} >>> w {'a': 1, 'c...
Twisted: why is it that passing a deferred callback to a deferred thread makes the thread blocking all of a sudden?
2,466,000
6
2010-03-17T21:18:42Z
2,466,250
12
2010-03-17T22:06:48Z
[ "python", "multithreading", "twisted", "redis" ]
I unsuccessfully tried using txredis (the non blocking twisted api for redis) for a persisting message queue I'm trying to set up with a scrapy project I am working on. I found that although the client was not blocking, it became much slower than it could have been because what should have been one event in the reactor...
Well, as the [twisted docs](http://twistedmatrix.com/documents/current/core/howto/gendefer.html) say: > Deferreds do not make the code > magically not block Whenever you're using blocking code, such as `sleep`, you have to defer it to a new thread. ``` #!/usr/bin/env python from twisted.internet import reactor,defer...
Set attributes from dictionary in python
2,466,191
39
2010-03-17T21:54:59Z
2,466,207
73
2010-03-17T21:57:33Z
[ "python", "initialization" ]
Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object? Something like this: ``` dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 } e = Employee( dict ) print e.name # Oscar print e.age + 10 # 42 ``` I think it would be pretty much the ...
Sure, something like this: ``` class Employee(object): def __init__(self, initial_data): for key in initial_data: setattr(self, key, initial_data[key]) ``` *Update* As Brent Nash suggests, you can make this more flexible by allowing keyword arguments as well: ``` class Employee(object): ...
Set attributes from dictionary in python
2,466,191
39
2010-03-17T21:54:59Z
2,466,232
7
2010-03-17T22:02:00Z
[ "python", "initialization" ]
Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object? Something like this: ``` dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 } e = Employee( dict ) print e.name # Oscar print e.age + 10 # 42 ``` I think it would be pretty much the ...
You can access the attributes of an object with `__dict__`, and call the update method on it: ``` >>> class Employee(object): ... def __init__(self, _dict): ... self.__dict__.update(_dict) ... >>> dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 } >>> e = Employee(dict) >>> e.name 'Oscar' >>> ...
Set attributes from dictionary in python
2,466,191
39
2010-03-17T21:54:59Z
2,466,380
20
2010-03-17T22:31:43Z
[ "python", "initialization" ]
Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object? Something like this: ``` dict = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 } e = Employee( dict ) print e.name # Oscar print e.age + 10 # 42 ``` I think it would be pretty much the ...
Setting attributes in this way is almost certainly not the best way to solve a problem. Either: 1. You know what all the fields should be ahead of time. In that case, you can set all the attributes explicitly. This would look like ``` class Employee(object): def __init__(self, name, last_name, age): ...
How to generate SSH key pairs with Python
2,466,401
19
2010-03-17T22:35:40Z
22,449,476
18
2014-03-17T08:15:30Z
[ "python", "ssh", "m2crypto", "ssh-keys" ]
I'm attempting to write a script to generate SSH Identity key pairs for me. ``` from M2Crypto import RSA key = RSA.gen_key(1024, 65337) key.save_key("/tmp/my.key", cipher=None) ``` The file `/tmp/my.key` looks great now. By running `ssh-keygen -y -f /tmp/my.key > /tmp/my.key.pub` I can extract the public key. My qu...
Just in case there are any future travellers looking to do this. The RSA module support writing out the public key in OpenSSH format now (possibly didn't at the time of earlier posts). So I think you can do what you need with: ``` from os import chmod from Crypto.PublicKey import RSA key = RSA.generate(2048) with ope...
slicing behaviour question of a list of lists
2,466,941
3
2010-03-18T00:49:22Z
2,466,962
9
2010-03-18T00:54:45Z
[ "python", "function", "slice" ]
I got a function like ``` def f(): ... ... return [list1, list2] ``` this returns a list of lists ``` [[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]] ``` now when I do the following: ``` for i in range(0,2):print f()[i][0:10] ``` it works and print the lists sliced but if i do ``` prin...
The second slice slices the sequence returned from the first slice, so yes, you will have to loop somehow in order to slice within: ``` [x[0:10] for x in f()[0:2]] ```
Django and Reportlab Question
2,467,042
7
2010-03-18T01:19:10Z
2,700,286
9
2010-04-23T16:33:48Z
[ "python", "django", "pdf", "reportlab" ]
I have written this small Django view to return pdf. ``` @login_required def code_view(request,myid): try: deal = Deal.objects.get(id=myid) except: raise Http404 header = deal.header code = deal.code response = HttpResponse(mimetype='application/pdf') response['Content-Dispositi...
You should move to the next level and use DocTemplates. Images are quite easy, but using bullets is really hard - you have to define styles and more! I use a set of classes like the below: ``` # -*- coding: utf-8 -*- from django.utils.encoding import smart_str from reportlab.lib.colors import Color from reportlab.li...
Dynamically evaluating simple boolean logic in Python
2,467,590
10
2010-03-18T04:49:55Z
2,467,674
10
2010-03-18T05:16:41Z
[ "python", "tree", "logic", "boolean", "boolean-logic" ]
I've got some dynamically-generated boolean logic expressions, like: * (A or B) and (C or D) * A or (A and B) * A * *empty - evaluates to True* The placeholders get replaced with booleans. Should I, 1. Convert this information to a Python expression like `True or (True or False)` and `eval` it? 2. Create a binary tr...
It shouldn't be difficult at all to write a evaluator that can handle this, for example using [pyparsing](http://pyparsing.wikispaces.com/). You only have a few operations to handle (and, or, and grouping?), so you should be able to parse and evaluate it yourself. You shouldn't need to explicitly form the binary tree ...
Dynamically evaluating simple boolean logic in Python
2,467,590
10
2010-03-18T04:49:55Z
2,472,414
13
2010-03-18T18:33:23Z
[ "python", "tree", "logic", "boolean", "boolean-logic" ]
I've got some dynamically-generated boolean logic expressions, like: * (A or B) and (C or D) * A or (A and B) * A * *empty - evaluates to True* The placeholders get replaced with booleans. Should I, 1. Convert this information to a Python expression like `True or (True or False)` and `eval` it? 2. Create a binary tr...
**Here's a small (possibly, 74 lines including whitespace) module I built in about an hour and a half (plus almost an hour to refactoring):** ``` str_to_token = {'True':True, 'False':False, 'and':lambda left, right: left and right, 'or':lambda left, right: left or right,...
Python: UnicodeEncodeError when reading from stdin
2,467,928
6
2010-03-18T06:36:30Z
2,467,956
13
2010-03-18T06:41:02Z
[ "python", "unicode", "antlr", "stdin" ]
When running a Python program that reads from stdin, I get the following error: ``` UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 320: ordinal not in range(128) ``` How can I fix it? Note: The error occurs internal to antlr and the line looks like that: ``` self.strdata = unicode(data...
The problem is, that when reading from stdin, python decodes it using the system default encoding: ``` >>> import sys >>> sys.getdefaultencoding() 'ascii' ``` The input is very likely UTF-8 or Windows-CP-1252, so the program chokes on non-ASCII-characters. To convert sys.stdin to a stream with the proper decoder, I ...
Python | How to create dynamic and expandable dictionaries
2,468,334
4
2010-03-18T08:26:30Z
2,468,374
9
2010-03-18T08:36:08Z
[ "python" ]
I want to create a Python dictionary which holds values in a multidimensional accept and it should be able to expand, this is the structure that the values should be stored :- ``` userdata = {'data':[{'username':'Ronny Leech','age':'22','country':'Siberia'},{'username':'Cronulla James','age':'34','country':'USA'}]} ``...
``` userdata = { "data":[]} def fil_userdata(): for i in xrange(0,5): user = {} user["name"]=... user["age"]=... user["country"]=... add_user(user) def add_user(user): userdata["data"].append(user) ``` or shorter: ``` def gen_user(): return {"name":"foo", "age":22} userdata = {"data": [ge...
How to call function that takes an argument in a Django template?
2,468,804
30
2010-03-18T09:53:37Z
2,468,830
35
2010-03-18T09:58:02Z
[ "python", "django", "function", "variables", "django-templates" ]
I'm passing to Django's template a function, which returns some records. I want to call this function and iterate over its result. ``` {% for item in my_func(10) %} ``` That doesn't work. I've tried to set the function's return value to a variable and iterate over the variable, but there seems to be no way to set a v...
You cannot call a function that requires arguments in a template. [Write](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags) a template tag or filter instead.
How to call function that takes an argument in a Django template?
2,468,804
30
2010-03-18T09:53:37Z
2,519,636
7
2010-03-25T21:46:03Z
[ "python", "django", "function", "variables", "django-templates" ]
I'm passing to Django's template a function, which returns some records. I want to call this function and iterate over its result. ``` {% for item in my_func(10) %} ``` That doesn't work. I've tried to set the function's return value to a variable and iterate over the variable, but there seems to be no way to set a v...
> I'm passing to Django's template a function, which returns me some records Why don't you pass to Django template the variable storing function's return value, instead of the function? > I've tried to set fuction's return value to a variable and iterate over variable, but there seems to be no way to set variable in ...
How to call function that takes an argument in a Django template?
2,468,804
30
2010-03-18T09:53:37Z
21,530,804
12
2014-02-03T15:11:23Z
[ "python", "django", "function", "variables", "django-templates" ]
I'm passing to Django's template a function, which returns some records. I want to call this function and iterate over its result. ``` {% for item in my_func(10) %} ``` That doesn't work. I've tried to set the function's return value to a variable and iterate over the variable, but there seems to be no way to set a v...
if you have an object you can define it as `@property` so you can get results without a call, e.g. ``` class Item: @property def results(self): return something ``` then in the template: ``` <% for result in item.results %> ... <% endfor %> ```
Equivalent of python eval in Haskell
2,469,139
8
2010-03-18T10:49:34Z
2,469,183
11
2010-03-18T10:54:41Z
[ "python", "haskell", "metaprogramming", "eval" ]
There is function in python called `eval` that takes string input and evaluates it. ``` >>> x = 1 >>> print eval('x+1') 2 >>> print eval('12 + 32') 44 >>> ``` What is Haskell equivalent of `eval` function?
It doesn't have an inbuilt eval function. However are some packages on hackage [that can do the same sort of thing](http://hackage.haskell.org/package/plugins). ([docs](http://www.cse.unsw.edu.au/~dons/hs-plugins/html/System-Eval-Haskell.html)). Thanks to [@luqui](http://stackoverflow.com/users/33796/luqui) there is al...
Equivalent of python eval in Haskell
2,469,139
8
2010-03-18T10:49:34Z
2,470,408
25
2010-03-18T14:09:49Z
[ "python", "haskell", "metaprogramming", "eval" ]
There is function in python called `eval` that takes string input and evaluates it. ``` >>> x = 1 >>> print eval('x+1') 2 >>> print eval('12 + 32') 44 >>> ``` What is Haskell equivalent of `eval` function?
It is true that in Haskell, as in Java or C++ or similar languages, you *can* call out to the compiler, then dynamically load the code and execute it. However, this is generally heavy weight and almost never why people use `eval()` in other languages. People tend to use `eval()` in a language because given that langua...
Equivalent of python eval in Haskell
2,469,139
8
2010-03-18T10:49:34Z
2,471,983
10
2010-03-18T17:23:54Z
[ "python", "haskell", "metaprogramming", "eval" ]
There is function in python called `eval` that takes string input and evaluates it. ``` >>> x = 1 >>> print eval('x+1') 2 >>> print eval('12 + 32') 44 >>> ``` What is Haskell equivalent of `eval` function?
There is no 'eval' built into the language, though Template Haskell allows compile time evaluation. For runtime 'eval' -- i.e. runtime metaprogramming -- there are a number of packages on Hackage that essentially import GHC or GHCi, including the old hs-plugins package, and the hint package.
Set the current directory when running a SimpleHTTPServer
2,469,256
21
2010-03-18T11:04:22Z
2,469,278
29
2010-03-18T11:08:21Z
[ "python" ]
Is there any way to set the directory where you want to start a SimpleHTTPServer or BaseHTTPServer?
If you're using `SimpleHTTPServer` directly from command line, you can simply use shell features: ``` pushd /path/you/want/to/serve; python -m SimpleHTTPServer; popd ```
Configuring Pydev Interpreter in Eclipse to use Enthought Python Distribution
2,469,849
16
2010-03-18T12:45:02Z
2,470,989
10
2010-03-18T15:24:00Z
[ "python", "pydev", "enthought" ]
I downloaded Pydev plugin for Eclipse (3.5.2) today on Mac OSX 10.5.8. To be able to use Pydev, I need to configure the interpreter in Eclipse. I am not clear what exactly I need to do here, or what this step does. I want to make sure that when I run programs from Eclipse using Pydev, it uses the Enthought Python Distr...
At least on Windows, this seems to doable via: 1. [Navigate Eclipse menus] `"Window"`->`"Preferences"`->`"PyDev"`->`"Interpreter - Python"`-> `"New"` (which is next to `"Auto Config"` you tried to use, if I get it right) 2. [Type or paste into textboxes] `"Interpreter Name"`, `"Interpreter Executable"` 3. Click `"OK"`...
Configuring Pydev Interpreter in Eclipse to use Enthought Python Distribution
2,469,849
16
2010-03-18T12:45:02Z
4,060,609
12
2010-10-30T20:43:21Z
[ "python", "pydev", "enthought" ]
I downloaded Pydev plugin for Eclipse (3.5.2) today on Mac OSX 10.5.8. To be able to use Pydev, I need to configure the interpreter in Eclipse. I am not clear what exactly I need to do here, or what this step does. I want to make sure that when I run programs from Eclipse using Pydev, it uses the Enthought Python Distr...
Mac OS 10.6.4: Selecting the interpreter as `/Library/Frameworks/Python.framework/Versions/2.7/Python` did not work. I had to select `/Library/Frameworks/Python.framework/Versions/2.7/bin/python`
How to pass SOAP headers into python SUDS that are not defined in WSDL file
2,469,988
11
2010-03-18T13:08:28Z
2,546,113
19
2010-03-30T14:46:02Z
[ "python", "xml", "wsdl", "suds", "soapheader" ]
I have a camera on my network which I am trying to connect to with suds but suds doesn't send all the information needed. I need to put extra soap headers not defined in the WSDL file so the camera can understand the message. All the headers are contained in a SOAP envelope and then the suds command should be in the bo...
I have worked out how to enter in new headers and namespaces in suds. As stated above you create an Element and pass it in as a soapheader as so: ``` from suds.sax.element import Element client = client(url) ssnns = ('ssn', 'http://namespaces/sessionid') ssn = Element('SessionID', ns=ssnns).setText('123') client.s...
What does this sentence mean in 'The Zen of Python'?
2,470,761
8
2010-03-18T14:56:40Z
2,470,773
10
2010-03-18T14:58:10Z
[ "python" ]
Please tell me what the following sentence means in '[The Zen of Python](http://www.python.org/dev/peps/pep-0020/)'. > "Although that way may not be obvious > at first unless you’re Dutch." Thanks in advance.
It is a reference to the fact that Python's creator, [Guido van Rossum](http://www.python.org/~guido/), is Dutch.
What does this sentence mean in 'The Zen of Python'?
2,470,761
8
2010-03-18T14:56:40Z
2,471,037
11
2010-03-18T15:28:37Z
[ "python" ]
Please tell me what the following sentence means in '[The Zen of Python](http://www.python.org/dev/peps/pep-0020/)'. > "Although that way may not be obvious > at first unless you’re Dutch." Thanks in advance.
When Python was not so popular, and mostly used by scripters and IT people to avoid bash monsters, features and modules and stuff went into the language without pondering over them as much as today. A simple example: the `backtick` operator was syntactic sugar for repr(). The "one obvious way to do it" was opposed to...
Is there a functional way to do this?
2,471,413
5
2010-03-18T16:09:47Z
2,471,793
7
2010-03-18T16:55:49Z
[ "python", "sequences" ]
``` def flattenList(toFlatten): final=[] for el in toFlatten: if isinstance(el, list): final.extend(flattenList(el)) else: final.append(el) return final ``` When I don't know how deeply the lists will nest, this is the only way I can think to do this.
1. You should avoid typechecking in Python. In this case, this means avoiding arbitrarily-nested structures where you distinguish by type. You can build your own node type which you can traverse by methods *other* than typechecking, like looking at a specific attribute. 2. For flattening one level or exactly n levels, ...
Using sphinx with Markdown instead of RST
2,471,804
147
2010-03-18T16:57:05Z
2,487,862
79
2010-03-21T16:53:55Z
[ "python", "markdown", "python-sphinx" ]
I hate RST but love sphinx. Is there a way that sphinx reads markdown instead of reStructuredText?
The "proper" way to do that would be to write a [docutils parser](http://docutils.sourceforge.net/docs/dev/hacking.html#parsing-the-document) for markdown. (Plus a Sphinx option to choose the parser.) The beauty of this would be instant support for all docutils output formats (but you might not care about that, as simi...
Using sphinx with Markdown instead of RST
2,471,804
147
2010-03-18T16:57:05Z
17,228,308
20
2013-06-21T05:31:54Z
[ "python", "markdown", "python-sphinx" ]
I hate RST but love sphinx. Is there a way that sphinx reads markdown instead of reStructuredText?
Markdown and ReST do different things. RST provides an object model for working with documents. Markdown provides a way to engrave bits of text. It seems reasonable to want to reference your bits of Markdown content from your sphinx project, using RST to stub out the overall information architecture and flow of a la...
Using sphinx with Markdown instead of RST
2,471,804
147
2010-03-18T16:57:05Z
22,919,306
21
2014-04-07T17:36:12Z
[ "python", "markdown", "python-sphinx" ]
I hate RST but love sphinx. Is there a way that sphinx reads markdown instead of reStructuredText?
This doesn't use Sphinx, but [MkDocs](http://www.mkdocs.org) will build your documentation using Markdown. I also hate rst, and have really enjoyed MkDocs so far.
Using sphinx with Markdown instead of RST
2,471,804
147
2010-03-18T16:57:05Z
30,197,203
7
2015-05-12T17:00:29Z
[ "python", "markdown", "python-sphinx" ]
I hate RST but love sphinx. Is there a way that sphinx reads markdown instead of reStructuredText?
I went with Beni's suggestion of using pandoc for this task. Once installed the following script will convert all markdown files in the source directory to rst files, so that you can just write all your documentation in markdown. Hope this is useful for others. ``` #!/usr/bin/env python import os import subprocess DO...
Using sphinx with Markdown instead of RST
2,471,804
147
2010-03-18T16:57:05Z
33,797,841
31
2015-11-19T07:40:50Z
[ "python", "markdown", "python-sphinx" ]
I hate RST but love sphinx. Is there a way that sphinx reads markdown instead of reStructuredText?
You can use Markdown and reStructuredText in the same Sphinx project. How to do this is succinctly documented on [Read The Docs](http://docs.readthedocs.org/en/latest/getting_started.html#in-markdown). Install recommonmark (`pip install recommonmark`) and then edit `conf.py`: ``` from recommonmark.parser import Common...
Using sphinx with Markdown instead of RST
2,471,804
147
2010-03-18T16:57:05Z
36,103,903
12
2016-03-19T16:02:59Z
[ "python", "markdown", "python-sphinx" ]
I hate RST but love sphinx. Is there a way that sphinx reads markdown instead of reStructuredText?
It looks like a basic implementation has made it's way into Sphinx but word has not gotten round yet. [See github issue comment](https://github.com/sphinx-doc/sphinx/issues/825#issuecomment-180197293) install dependencies: ``` pip install commonmark recommonmark ``` adjust `conf.py`: ``` source_parsers = { '.md...
In Python what's the best way to emulate Perl's __END__?
2,471,942
19
2010-03-18T17:18:46Z
5,079,712
11
2011-02-22T14:55:43Z
[ "python", "perl" ]
Am I correct in thinking that that Python doesn't have a direct equivalent for Perl's `__END__`? ``` print "Perl...\n"; __END__ End of code. I can put anything I want here. ``` One thought that occurred to me was to use a triple-quoted string. Is there a better way to achieve this in Python? ``` print "Python..." ...
The ``` __END__ ``` block in perl dates from a time when programmers had to work with data from the outside world and liked to keep examples of it in the program itself. Hard to imagine I know. It was useful for example if you had a moving target like a hardware log file with mutating messages due to firmware updat...
How can I use python itertools.groupby() to group a list of strings by their first character?
2,472,001
4
2010-03-18T17:25:27Z
2,472,009
10
2010-03-18T17:26:41Z
[ "python", "string", "itertools" ]
I have a list of strings similar to this list: ``` tags = ('apples', 'apricots', 'oranges', 'pears', 'peaches') ``` How should I go about grouping this list by the first character in each string using itertools.groupby()? How should I supply the 'key' argument required by itertools.groupby()?
``` groupby(tags, key=operator.itemgetter(0)) ```