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
Combining two JSON objects in to one
1,096,554
6
2009-07-08T07:13:13Z
1,096,575
13
2009-07-08T07:19:26Z
[ "python", "json" ]
I have two JSON objects. One is python array which is converted using json,dumps() and other contains records from database and is serialized using json serializer. I want to combine them into a single JSON object. For eg: ``` obj1 = ["a1", "a2", "a3"] obj2 = [ { "pk": "e1", "model": "AB.abc", ...
You can't do it once they're in JSON format - JSON is just text. You need to combine them in Python first: ``` data = { 'obj1' : obj1, 'obj2' : obj2 } json.dumps(data) ```
How do I sort unicode strings alphabetically in Python?
1,097,908
78
2009-07-08T12:59:09Z
1,097,961
9
2009-07-08T13:08:24Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python? Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Sw...
Try James Tauber's [Python Unicode Collation Algorithm](http://jtauber.com/blog/2006/01/27/python%5Funicode%5Fcollation%5Falgorithm/). It may not do exactly as you want, but seems well worth a look. For a bit more information about the issues, see [this post](http://www.cmlenz.net/archives/2008/07/the-truth-about-unico...
How do I sort unicode strings alphabetically in Python?
1,097,908
78
2009-07-08T12:59:09Z
1,098,160
57
2009-07-08T13:42:40Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python? Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Sw...
IBM's [ICU](http://site.icu-project.org/) library does that (and a lot more). It has Python bindings: [PyICU](http://pypi.python.org/pypi/PyICU). **Update**: The core difference in sorting between ICU and `locale.strcoll` is that ICU uses the full [Unicode Collation Algorithm](http://unicode.org/reports/tr10/) while `...
How do I sort unicode strings alphabetically in Python?
1,097,908
78
2009-07-08T12:59:09Z
1,318,709
41
2009-08-23T14:32:43Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python? Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Sw...
I don't see this in the answers. My Application sorts according to the locale using python's standard library. It is pretty easy. ``` # python2.5 code below # corpus is our unicode() strings collection as a list corpus = [u"Art", u"Älg", u"Ved", u"Wasa"] import locale # this reads the environment and inits the right...
How do I sort unicode strings alphabetically in Python?
1,097,908
78
2009-07-08T12:59:09Z
5,013,415
7
2011-02-16T07:00:15Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python? Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Sw...
A summary and extended answer: `locale.strcoll` under Python 2, and `locale.strxfrm` will in fact solve the problem, and does a good job, assuming that you have the locale in question installed. I tested it under Windows too, where the locale names confusingly are different, but on the other hand it seems to have all ...
How to make Python check if ftp directory exists?
1,098,218
8
2009-07-08T13:51:56Z
1,098,253
8
2009-07-08T13:56:38Z
[ "python", "ftp" ]
I'm using this script to connect to sample ftp server and list available directories: ``` from ftplib import FTP ftp = FTP('ftp.cwi.nl') # connect to host, default port (some example server, i'll use other one) ftp.login() # user anonymous, passwd anonymous@ ftp.retrlines('LIST') # list directory c...
you can use a list. example ``` import ftplib server="localhost" user="user" password="[email protected]" try: ftp = ftplib.FTP(server) ftp.login(user,password) except Exception,e: print e else: filelist = [] #to store all files ftp.retrlines('LIST',filelist.append) # append to list f...
How to make Python check if ftp directory exists?
1,098,218
8
2009-07-08T13:51:56Z
14,331,184
10
2013-01-15T04:28:30Z
[ "python", "ftp" ]
I'm using this script to connect to sample ftp server and list available directories: ``` from ftplib import FTP ftp = FTP('ftp.cwi.nl') # connect to host, default port (some example server, i'll use other one) ftp.login() # user anonymous, passwd anonymous@ ftp.retrlines('LIST') # list directory c...
Nslt will list an array for all files in ftp server. Just check if your folder name is there. ``` from ftplib import FTP ftp = FTP('yourserver') ftp.login('username', 'password') folderName = 'yourFolderName' if folderName in ftp.nlst(): #do needed task ```
Proper way to use **kwargs in Python
1,098,549
247
2009-07-08T14:45:53Z
1,098,556
245
2009-07-08T14:47:38Z
[ "python", "kwargs" ]
What is the proper way to use `**kwargs` in Python when it comes to default values? `kwargs` returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? ``` class ExampleClass: def __init__(self, **kwargs): self.val = kw...
You can pass a default value to `get()` for keys that are not in the dictionary: ``` self.val2 = kwargs.get('val2',"default value") ``` However, if you plan on using a particular argument with a particular default value, why not use named arguments in the first place? ``` def __init__(self, val2="default value", **k...
Proper way to use **kwargs in Python
1,098,549
247
2009-07-08T14:45:53Z
1,098,577
42
2009-07-08T14:49:58Z
[ "python", "kwargs" ]
What is the proper way to use `**kwargs` in Python when it comes to default values? `kwargs` returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? ``` class ExampleClass: def __init__(self, **kwargs): self.val = kw...
You'd do ``` self.attribute = kwargs.pop('name', default_value) ``` or ``` self.attribute = kwargs.get('name', default_value) ``` If you use `pop`, then you can check if there are any spurious values sent, and take the appropriate action (if any).
Proper way to use **kwargs in Python
1,098,549
247
2009-07-08T14:45:53Z
1,098,588
8
2009-07-08T14:51:57Z
[ "python", "kwargs" ]
What is the proper way to use `**kwargs` in Python when it comes to default values? `kwargs` returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? ``` class ExampleClass: def __init__(self, **kwargs): self.val = kw...
You could do something like this ``` class ExampleClass: def __init__(self, **kwargs): arguments = {'val':1, 'val2':2} arguments.update(kwargs) self.val = arguments['val'] self.val2 = arguments['val2'] ```
Proper way to use **kwargs in Python
1,098,549
247
2009-07-08T14:45:53Z
1,098,605
30
2009-07-08T14:55:22Z
[ "python", "kwargs" ]
What is the proper way to use `**kwargs` in Python when it comes to default values? `kwargs` returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? ``` class ExampleClass: def __init__(self, **kwargs): self.val = kw...
Using \*\*kwargs and default values is easy. Sometimes, however, you shouldn't be using \*\*kwargs in the first place. In this case, we're not really making best use of \*\*kwargs. ``` class ExampleClass( object ): def __init__(self, **kwargs): self.val = kwargs.get('val',"default1") self.val2 = k...
Proper way to use **kwargs in Python
1,098,549
247
2009-07-08T14:45:53Z
1,098,639
36
2009-07-08T15:03:14Z
[ "python", "kwargs" ]
What is the proper way to use `**kwargs` in Python when it comes to default values? `kwargs` returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? ``` class ExampleClass: def __init__(self, **kwargs): self.val = kw...
I suggest something like this ``` def testFunc( **kwargs ): options = { 'option1' : 'default_value1', 'option2' : 'default_value2', 'option3' : 'default_value3', } options.update(kwargs) print options testFunc( option1='new_value1', option3='new_value3' ) # {'option2':...
Proper way to use **kwargs in Python
1,098,549
247
2009-07-08T14:45:53Z
1,098,834
156
2009-07-08T15:29:29Z
[ "python", "kwargs" ]
What is the proper way to use `**kwargs` in Python when it comes to default values? `kwargs` returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? ``` class ExampleClass: def __init__(self, **kwargs): self.val = kw...
While most answers are saying that, e.g., ``` def f(**kwargs): foo = kwargs.pop('foo') bar = kwargs.pop('bar') ...etc... ``` is "the same as" ``` def f(foo=None, bar=None, **kwargs): ...etc... ``` this is not true. In the latter case, `f` can be called as `f(23, 42)`, while the former case accepts n...
Proper way to use **kwargs in Python
1,098,549
247
2009-07-08T14:45:53Z
2,053,613
11
2010-01-13T00:44:27Z
[ "python", "kwargs" ]
What is the proper way to use `**kwargs` in Python when it comes to default values? `kwargs` returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? ``` class ExampleClass: def __init__(self, **kwargs): self.val = kw...
Here's another approach: ``` def my_func(arg1, arg2, arg3): ... so something ... kwargs = {'arg1': 'Value One', 'arg2': 'Value Two', 'arg3': 'Value Three'} # Now you can call the function with kwargs like this: my_func(**kwargs) ```
Proper way to use **kwargs in Python
1,098,549
247
2009-07-08T14:45:53Z
13,629,607
19
2012-11-29T15:55:28Z
[ "python", "kwargs" ]
What is the proper way to use `**kwargs` in Python when it comes to default values? `kwargs` returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? ``` class ExampleClass: def __init__(self, **kwargs): self.val = kw...
Since `**kwargs` is used when the number of arguments is unknown, why not doing this? ``` class Exampleclass(object): def __init__(self, **kwargs): for k in kwargs.keys(): if k in [acceptable_keys_list]: self.__setattr__(k, kwargs[k]) ```
IndexError: list index out of range and python
1,098,643
8
2009-07-08T15:03:55Z
1,098,660
16
2009-07-08T15:07:15Z
[ "python", "indexoutofboundsexception" ]
I'm telling my program to print out line 53 of an output. Is this error telling me that there aren't that many lines and therefore can not print it out?
If you have a list with 53 items, the last one is `thelist[52]` because indexing start at 0.
IndexError: list index out of range and python
1,098,643
8
2009-07-08T15:03:55Z
1,098,675
10
2009-07-08T15:08:32Z
[ "python", "indexoutofboundsexception" ]
I'm telling my program to print out line 53 of an output. Is this error telling me that there aren't that many lines and therefore can not print it out?
Yes, You are trying to access an element of the list that does not exist. ``` MyList = ["item1", "item2"] print MyList[0] # Will work print MyList[1] # Will Work print MyList[2] # Will crash. ``` Have you got an off-by-one error?
Help me lambda-nize this
1,098,841
3
2009-07-08T15:31:04Z
1,098,882
8
2009-07-08T15:37:39Z
[ "python", "lambda" ]
To help me better understand lambda I wrote this short snippet that rotates and transforms a quad (I hope I got the math right). Now, I want to replace the three steps below with one liner lambdas, possibly in conjunction with map(). Im using a [vector class](http://www.pygame.org/wiki/2DVectorClass?parent=CookBook) b...
You could use `map`, `reduce`, et al, but nowadays list comprehensions are the preferred way to do things in Python: ``` rot_points = (i.rotated(self.orientation.get_angle()) for i in points) real_points = [self.pos+i*self.scale for i in rot_points] ``` Notice how I used `(parentheses)` instead of `[brackets]` in th...
Matching Nested Structures With Regular Expressions in Python
1,099,178
14
2009-07-08T16:30:38Z
1,101,030
20
2009-07-08T23:10:34Z
[ "python", "regex", "recursive-regex" ]
I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "`( (a ( ( c ) b ) ) ( d ) e )`". What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it...
Regular expressions *cannot* parse nested structures. Nested structures are not regular, by definition. They cannot be constructed by a regular grammar, and they cannot be parsed by a finite state automaton (a regular expression can be seen as a shorthand notation for an FSA). Today's "regex" engines sometimes support...
Matching Nested Structures With Regular Expressions in Python
1,099,178
14
2009-07-08T16:30:38Z
1,101,046
15
2009-07-08T23:14:09Z
[ "python", "regex", "recursive-regex" ]
I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "`( (a ( ( c ) b ) ) ( d ) e )`". What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it...
You can't do this generally using Python regular expressions. (.NET regular expressions have been extended with "balancing groups" which is what allows nested matches.) However, PyParsing is a very nice package for this type of thing: ``` from pyparsing import nestedExpr data = "( (a ( ( c ) b ) ) ( d ) e )" print n...
Matching Nested Structures With Regular Expressions in Python
1,099,178
14
2009-07-08T16:30:38Z
14,715,850
13
2013-02-05T19:56:12Z
[ "python", "regex", "recursive-regex" ]
I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "`( (a ( ( c ) b ) ) ( d ) e )`". What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it...
**Edit:** [falsetru's nested parser](http://stackoverflow.com/a/17141899/190597), which I've slightly modified to accept arbitrary regex patterns to specify delimiters and item separators, is faster and simpler than my original `re.Scanner` solution: ``` import re def parse_nested(text, left=r'[(]', right=r'[)]', sep...
Why can't Python find shared objects that are in directories in sys.path?
1,099,981
72
2009-07-08T19:06:17Z
1,100,016
97
2009-07-08T19:12:33Z
[ "python", "shared-libraries", "libcurl", "pycurl" ]
I'm trying to import pycurl: ``` $ python -c "import pycurl" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: libcurl.so.4: cannot open shared object file: No such file or directory ``` Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path: ``` $ python -c "i...
`sys.path` is only searched for Python modules. For dynamic linked libraries, the paths searched must be in `LD_LIBRARY_PATH`. Check if your `LD_LIBRARY_PATH` includes `/usr/local/lib`, and if it doesn't, add it and try again. Some more information ([source](http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries...
Why can't Python find shared objects that are in directories in sys.path?
1,099,981
72
2009-07-08T19:06:17Z
1,100,297
41
2009-07-08T20:13:10Z
[ "python", "shared-libraries", "libcurl", "pycurl" ]
I'm trying to import pycurl: ``` $ python -c "import pycurl" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: libcurl.so.4: cannot open shared object file: No such file or directory ``` Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path: ``` $ python -c "i...
Ensure your libcurl.so module is in the system library path, which is distinct and separate from the python library path. A "quick fix" is to add this path to a LD\_LIBRARY\_PATH variable. However, setting that system wide (or even account wide) is a BAD IDEA, as it is possible to set it in such a way that some progra...
Why can't Python find shared objects that are in directories in sys.path?
1,099,981
72
2009-07-08T19:06:17Z
1,109,196
19
2009-07-10T12:17:02Z
[ "python", "shared-libraries", "libcurl", "pycurl" ]
I'm trying to import pycurl: ``` $ python -c "import pycurl" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: libcurl.so.4: cannot open shared object file: No such file or directory ``` Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path: ``` $ python -c "i...
You can also set LD\_RUN\_PATH to /usr/local/lib in your user environment when you compile pycurl in the first place. This will embed /usr/local/lib in the RPATH attribute of the C extension module .so so that it automatically knows where to find the library at run time without having to have LD\_LIBRARY\_PATH set at r...
Why can't Python find shared objects that are in directories in sys.path?
1,099,981
72
2009-07-08T19:06:17Z
2,384,146
8
2010-03-05T02:18:08Z
[ "python", "shared-libraries", "libcurl", "pycurl" ]
I'm trying to import pycurl: ``` $ python -c "import pycurl" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: libcurl.so.4: cannot open shared object file: No such file or directory ``` Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path: ``` $ python -c "i...
Had the exact same issue. I installed curl 7.19 to /opt/curl/ to make sure that I would not affect current curl on our production servers. Once I linked libcurl.so.4 to /usr/lib: sudo ln -s /opt/curl/lib/libcurl.so /usr/lib/libcurl.so.4 I still got the same error! Durf. But running ldconfig make the linkage for me a...
FFT-based 2D convolution and correlation in Python
1,100,100
19
2009-07-08T19:32:19Z
1,768,140
15
2009-11-20T03:22:54Z
[ "python", "image", "numpy", "signal-processing", "fft" ]
Is there a FFT-based 2D cross-correlation or convolution function built into scipy (or another popular library)? There are functions like these: * `scipy.signal.correlate2d` - "the direct method implemented by `convolveND` will be slow for large data" * `scipy.ndimage.correlate` - "The array is correlated with the ...
I found `scipy.signal.fftconvolve`, [as also pointed out by magnus](http://stackoverflow.com/a/1477259/125507), but didn't realize at the time that it's *n*-dimensional. Since it's built-in and produces the right values, it seems like the ideal solution. From [Example of 2D Convolution](http://www.songho.ca/dsp/convol...
Create PyQt menu from a list of strings
1,100,775
10
2009-07-08T22:01:56Z
1,102,089
23
2009-07-09T06:10:54Z
[ "python", "qt", "pyqt", "signals-slots" ]
I have a list of strings and want to create a menu entry for each of those strings. When the user clicks on one of the entries, always the same function shall be called with the string as an argument. After some trying and research I came up with something like this: ``` import sys from PyQt4 import QtGui, QtCore cla...
You're meeting what's been often referred to (maybe not entirely pedantically-correctly;-) as the "scoping problem" in Python -- the binding is late (lexical lookup at call-time) while you'd like it early (at def-time). So where you now have: ``` for item in menuitems: entry = menu.addAction(item) ...
Library to read ELF file DWARF debug information
1,101,272
19
2009-07-09T00:37:14Z
1,101,352
9
2009-07-09T01:11:00Z
[ "python", "debugging", "elf", "dwarf" ]
Any recommendations for a good cross-platform library for reading ELF file debug information in DWARF format? I'd like to read the DWARF debug info in a Python program.
The concept of "ELF debug info" doesn't really exist: the ELF specification leaves the content of the .debug section deliberately unspecified. Common debug formats are STAB and [DWARF](http://dwarfstd.org/). A library to read DWARF is [libdwarf](http://www.prevanders.net/dwarf.html).
Library to read ELF file DWARF debug information
1,101,272
19
2009-07-09T00:37:14Z
3,647,042
7
2010-09-05T17:40:47Z
[ "python", "debugging", "elf", "dwarf" ]
Any recommendations for a good cross-platform library for reading ELF file debug information in DWARF format? I'd like to read the DWARF debug info in a Python program.
You might be interested in the DWARF library from [pydevtools](http://code.google.com/p/pydevtools/): ``` >>> from devtools.dwarf import DWARF >>> dwarf = DWARF('test/test') >>> dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) >>> print dwarf .debug_info COMPILE_UNIT<header overall ...
Library to read ELF file DWARF debug information
1,101,272
19
2009-07-09T00:37:14Z
8,754,544
19
2012-01-06T07:09:00Z
[ "python", "debugging", "elf", "dwarf" ]
Any recommendations for a good cross-platform library for reading ELF file debug information in DWARF format? I'd like to read the DWARF debug info in a Python program.
There's a new kid on the block - [pyelftools](https://github.com/eliben/pyelftools) - a pure Python library for parsing the ELF and DWARF formats. Give it a try. It aims to be feature-complete and is currently in active development, so any problems should be handled quickly and enthusiastically :-)
How to parse dates with -0400 timezone string in python?
1,101,508
47
2009-07-09T02:19:03Z
1,101,597
72
2009-07-09T02:47:14Z
[ "python", "datetime", "timezone" ]
I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that. What's the right way to parse this string into a datetime object?
You can use the parse function from dateutil: ``` >>> from dateutil.parser import parse >>> d = parse('2009/05/13 19:19:30 -0400') >>> d datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400)) ``` This way you obtain a datetime object you can then use. **UPDATE:** As [answered](http://stackoverflow...
How to parse dates with -0400 timezone string in python?
1,101,508
47
2009-07-09T02:19:03Z
15,516,170
7
2013-03-20T05:41:41Z
[ "python", "datetime", "timezone" ]
I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that. What's the right way to parse this string into a datetime object?
The problem with using dateutil is that you can't have the same format string for both serialization and deserialization, as dateutil has limited formatting options (only `dayfirst` and `yearfirst`). In my application, I store the format string in .INI file, and each deployment can have its own format. Thus, I really ...
How to parse dates with -0400 timezone string in python?
1,101,508
47
2009-07-09T02:19:03Z
23,122,493
25
2014-04-17T00:21:33Z
[ "python", "datetime", "timezone" ]
I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that. What's the right way to parse this string into a datetime object?
`%z` is supported in Python 3.2+: ``` >>> from datetime import datetime >>> datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z') datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000))) ``` On earlier versions: ``` from datetime import da...
python calendar.HTMLCalendar
1,101,524
3
2009-07-09T02:23:48Z
1,102,014
16
2009-07-09T05:42:33Z
[ "python", "html", "calendar" ]
I think I want to use pythons built in calendar module to create an HTML calendar with data. I say I think because I'll probably think of a better way, but right now it's a little personal. I don't know if this was intended to be used this way but it seems like it is a little pointless if you can't at least making the ...
The calendar module has usually been pretty useless, but in 2.5 it introduced the Calendar object. This won't render an HTML calendar for you, but it has loads of methods that will help you render a calendar. For example, monthdatescalendar(year, month) will give you a list of all weeks in the month given, where each ...
python calendar.HTMLCalendar
1,101,524
3
2009-07-09T02:23:48Z
1,458,077
33
2009-09-22T04:17:47Z
[ "python", "html", "calendar" ]
I think I want to use pythons built in calendar module to create an HTML calendar with data. I say I think because I'll probably think of a better way, but right now it's a little personal. I don't know if this was intended to be used this way but it seems like it is a little pointless if you can't at least making the ...
Create a new class inheriting from HTMLCalendar. Override the formatday method. Whoever makes comments like "this library is useless" obviously doesn't understand Python. ``` class EmployeeScheduleCalendar(HTMLCalendar): def formatday(self, day, weekday): """ Return a day as a table cell. ...
Help needed improving Python code using List Comprehensions
1,101,611
3
2009-07-09T02:51:36Z
1,101,656
9
2009-07-09T03:07:40Z
[ "python", "list-comprehension" ]
I've been writing little Python programs at home to learn more about the language. The most recent feature I've tried to understand are List Comprehensions. I created a little script that estimates when my car needs its next oil change based on how frequently I've gotten the oil changed in the past. In the code snippet...
Try this: ``` assert len(oil_changes) >= 2 sum_of_diffs = oil_changes[-1] - oil_changes[0] number_of_diffs = len(oil_changes) - 1 average_diff = sum_of_diffs / float(number_of_diffs) ```
Help needed improving Python code using List Comprehensions
1,101,611
3
2009-07-09T02:51:36Z
1,101,939
9
2009-07-09T05:15:57Z
[ "python", "list-comprehension" ]
I've been writing little Python programs at home to learn more about the language. The most recent feature I've tried to understand are List Comprehensions. I created a little script that estimates when my car needs its next oil change based on how frequently I've gotten the oil changed in the past. In the code snippet...
As other answers pointed out, you don't really need to worry unless your `oil_changes` list is extremely long. However, as a fan of "stream-based" computing, I think it's interesting to point out that `itertools` offers all the tools you need to compute your `next_oil` value in O(1) space (and O(N) time of course!-) no...
Tkinter: AttributeError: NoneType object has no attribute get
1,101,750
14
2009-07-09T03:48:56Z
1,101,765
39
2009-07-09T03:53:34Z
[ "python", "user-interface", "tkinter" ]
I have seen a couple of other posts on similar error message but couldn't find a solution which would fix it in my case. I dabbled a bit with TkInter and created a very simple UI. The code follows- ``` from string import * from Tkinter import * import tkMessageBox root=Tk() vid = IntVar() def grabText(event): i...
The `grid` (and `pack`, and `place`) function of the `Entry` object (and of all other widgets) returns `None`. In python when you do `a().b()`, the result of the expression is whatever `b()` returns, therefore `Entry(...).grid(...)` will return `None`. You should split that onto two lines, like this: ``` entryBox = E...
Should I use Celery or Carrot for a Django project?
1,102,254
19
2009-07-09T07:05:44Z
1,102,290
69
2009-07-09T07:15:14Z
[ "python", "django", "message-queue", "rabbitmq", "amqp" ]
I'm a little confused as to which one I should use. I think either will work, but is one better or more appropriate than the other? <http://github.com/ask/carrot/tree/master> <http://github.com/ask/celery/tree/master>
If you need to send/receive messages to/from AMQP message queues, use `carrot`. If you want to run scheduled tasks on a number of machines, use `celery`. If you're making soup, use both ;-)
python - Problem storing Unicode character to MySQL with Django
1,102,465
6
2009-07-09T08:04:19Z
1,106,383
11
2009-07-09T20:52:28Z
[ "python", "mysql", "django", "unicode", "django-models" ]
I have the string ``` u"Played Mirror's Edge\u2122" ``` Which should be shown as ``` Played Mirror's Edge™ ``` But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA: ``` a = models.Achievement(name=u"Played Mirror's Edge\u2122") a.save() `...
Thank you to everyone who was posting here. It really helps my unicode knowledge (and hoepfully other people learned something). We seemed to be all barking up the wrong tree since I tried to simplify my problem and didn't give ALL information. It seems that I wasn't using "REAL" unicode strings, but rather BeautifulS...
Moving files under python
1,102,825
8
2009-07-09T09:36:13Z
1,102,860
8
2009-07-09T09:43:43Z
[ "python", "windows", "move" ]
I'm confused with file moving under python. Under windows commandline, if i have directory c:\a and a directory c:\b, i can do ``` move c:\a c:\b ``` which moves a to b result is directory structure c:\b\a If I try this with os.rename or shutil.move: ``` os.rename("c:/a", "c:/b") ``` I get ``` WindowsError: [Erro...
You can try using the [Shutil](http://docs.python.org/library/shutil.html#module-shutil) module.
Moving files under python
1,102,825
8
2009-07-09T09:36:13Z
1,102,872
16
2009-07-09T09:46:37Z
[ "python", "windows", "move" ]
I'm confused with file moving under python. Under windows commandline, if i have directory c:\a and a directory c:\b, i can do ``` move c:\a c:\b ``` which moves a to b result is directory structure c:\b\a If I try this with os.rename or shutil.move: ``` os.rename("c:/a", "c:/b") ``` I get ``` WindowsError: [Erro...
``` os.rename("c:/a", "c:/b/a") ``` is equivalent to ``` move c:\a c:\b ``` under windows commandline
Can I detect if my code is running on cPython or Jython?
1,103,487
8
2009-07-09T12:19:34Z
1,103,497
13
2009-07-09T12:22:41Z
[ "python", "django", "jython" ]
I'm working on a small django project that will be deployed in a servlet container later. But development is much faster if I work with cPython instead of Jython. So what I want to do is test if my code is running on cPython or Jython in my settiings.py so I can tell it to use the appropriate db driver (postgresql\_psy...
if you're running Jython ``` import platform platform.system() ``` return 'Java' [here has some discussion](http://stackoverflow.com/questions/1086000/), hope this helps.
Can I detect if my code is running on cPython or Jython?
1,103,487
8
2009-07-09T12:19:34Z
1,147,610
19
2009-07-18T14:01:38Z
[ "python", "django", "jython" ]
I'm working on a small django project that will be deployed in a servlet container later. But development is much faster if I work with cPython instead of Jython. So what I want to do is test if my code is running on cPython or Jython in my settiings.py so I can tell it to use the appropriate db driver (postgresql\_psy...
As sunqiang pointed out ``` import platform platform.system() ``` works for Jython 2.5, but this doesn't work on Jython 2.2 (the previous Jython release). Also, there has been some discussion about returning more operating system specific details for calls like these in Jython 3.x. Nothing has been decided there, but...
Can I detect if my code is running on cPython or Jython?
1,103,487
8
2009-07-09T12:19:34Z
13,682,964
12
2012-12-03T12:10:53Z
[ "python", "django", "jython" ]
I'm working on a small django project that will be deployed in a servlet container later. But development is much faster if I work with cPython instead of Jython. So what I want to do is test if my code is running on cPython or Jython in my settiings.py so I can tell it to use the appropriate db driver (postgresql\_psy...
The most clear-cut way is: > > > import platform > > > > > > platform.python\_implementation() 'CPython' By default, most of the time the underlying interpreter is CPython only which is also arguably the most efficient one :)
Combining module files in Python
1,104,066
6
2009-07-09T13:59:06Z
1,104,080
7
2009-07-09T14:00:31Z
[ "python", "packaging" ]
Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file.
Take a look at Python Eggs: <http://peak.telecommunity.com/DevCenter/PythonEggs> Or, you can use regular zips: <http://docs.python.org/library/zipimport.html>
Combining module files in Python
1,104,066
6
2009-07-09T13:59:06Z
6,611,335
8
2011-07-07T13:27:07Z
[ "python", "packaging" ]
Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file.
After looking for a solution to the same problem, I ended up writing a simple tool which combines multiple .py files into one: [PyBreeder](http://pagekite.net/wiki/Floss/PyBreeder/) It will only work with pure-Python modules and may require some trial-and-error to get the order of modules right, but it is quite handy ...
storing uploaded photos and documents - filesystem vs database blob
1,105,429
10
2009-07-09T17:39:58Z
1,105,444
9
2009-07-09T17:42:19Z
[ "python", "postgresql", "storage", "photos", "photo-management" ]
**My specific situation** Property management web site where users can upload photos and lease documents. For every apartment unit, there might be 4 photos, so there won't be an overwhelming number of photo in the system. For photos, there will be thumbnails of each. **My question** My #1 priority is performance. F...
File system. No contest. The data has to go through a lot more layers when you store it in the db. Edit on caching: If you want to cache the file while the user uploads it to ensure the operation finishes as soon as possible, dumping it straight to disk (i.e. file system) is about as quick as it gets. As long as the f...
storing uploaded photos and documents - filesystem vs database blob
1,105,429
10
2009-07-09T17:39:58Z
1,105,453
10
2009-07-09T17:43:25Z
[ "python", "postgresql", "storage", "photos", "photo-management" ]
**My specific situation** Property management web site where users can upload photos and lease documents. For every apartment unit, there might be 4 photos, so there won't be an overwhelming number of photo in the system. For photos, there will be thumbnails of each. **My question** My #1 priority is performance. F...
While there are exceptions to everything, the general case is that storing images in the file system is your best bet. You can easily provide caching services to the images, you don't need to worry about additional code to handle image processing, and you can easily do maintenance on the images if needed through standa...
Parse annotations from a pdf
1,106,098
16
2009-07-09T19:52:08Z
12,502,560
10
2012-09-19T20:40:13Z
[ "python", "pdf" ]
I want a python function that takes a pdf and returns a list of the text of the note annotations in the document. I have looked at python-poppler (<https://code.launchpad.net/~poppler-python/poppler-python/trunk>) but I can not figure out how to get it to give me anything useful. I found the `get_annot_mapping` method...
Just in case somebody is looking for some working code. Here is a script I use. ``` import poppler import sys import urllib import os def main(): input_filename = sys.argv[1] # http://blog.hartwork.org/?p=612 document = poppler.document_new_from_file('file://%s' % \ urllib.pathname2url(os.path.abspath(inp...
How are these type of python decorators written?
1,106,223
6
2009-07-09T20:16:56Z
1,106,289
12
2009-07-09T20:32:25Z
[ "python", "language-features", "decorator" ]
I'd like to write a decorator that would limit the number of times a function can be executed, something along the following syntax : ``` @max_execs(5) def my_method(*a,**k): # do something here pass ``` I think it's possible to write this type of decorator, but I don't know how. I think a function won't be thi...
This is what I whipped up. It doesn't use a class, but it does use function attributes: ``` def max_execs(n=5): def decorator(fn): fn.max = n fn.called = 0 def wrapped(*args, **kwargs): fn.called += 1 if fn.called <= fn.max: return fn(*args, **kwargs)...
Do I have any obligations if I upload an egg to the CheeseShop?
1,106,759
14
2009-07-09T22:24:51Z
1,108,038
9
2009-07-10T06:43:17Z
[ "python", "egg", "pypi" ]
Suppose I'd like to upload some eggs on the Cheese Shop. Do I have any obligation? Am I required to provide a license? Am I required to provide tests? Will I have any obligations to the users of this egg ( if any ) ? I haven't really released anything as open source 'till now, and I'd like to know the process.
1. You have an obligation to register the package with a useful description. Nothing is more frustrating than finding a Package that *may* be good, but you don't know, because there is no description. Typical example of Lazy developer: <http://pypi.python.org/pypi/gevent/0.9.1> Better: <http://pypi.python.org/p...
Find functions explicitly defined in a module (python)
1,106,840
18
2009-07-09T22:49:03Z
1,107,150
21
2009-07-10T00:36:47Z
[ "python", "introspection" ]
Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this: ``` from datetime import date, datetime def test(): return "This is a real method" ``` Even if i use inspect() to f...
Are you looking for something like this? ``` import sys, inspect def is_mod_function(mod, func): return inspect.isfunction(func) and inspect.getmodule(func) == mod def list_functions(mod): return [func.__name__ for func in mod.__dict__.itervalues() if is_mod_function(mod, func)] print 'functio...
Python: StopIteration exception and list comprehensions
1,106,903
8
2009-07-09T23:09:56Z
1,106,921
10
2009-07-09T23:15:50Z
[ "python", "iterator", "list-comprehension", "stopiteration" ]
I'd like to read at most 20 lines from a csv file: ``` rows = [csvreader.next() for i in range(20)] ``` Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise. Is there an elegant way to deal with an iterator that could throw a StopIteration exception in a list comprehension or sh...
You can use [`itertools.islice`](http://docs.python.org/library/itertools.html#itertools.islice). It is the iterator version of list slicing. If the iterator has less than 20 elements, it will return all elements. ``` import itertools rows = list(itertools.islice(csvreader, 20)) ```
Python Lambda Problems
1,107,210
12
2009-07-10T01:01:25Z
1,107,243
15
2009-07-10T01:13:24Z
[ "python", "lambda" ]
What's going on here? I'm trying to create a list of functions: ``` def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) ``` This isn't doing what I expect. I would expect the list to act like this: ``` funcs[3](3) = 9 funcs[0](5) = 0 ``` But all the functions in the list ...
lambdas in python are closures.... the arguments you give it aren't going to be evaluated until the lambda is evaluated. At that time, i=9 regardless, because your iteration is finished. The behavior you're looking for can be achieved with functools.partial ``` import functools def f(a,b): return a*b funcs = []...
Python Lambda Problems
1,107,210
12
2009-07-10T01:01:25Z
1,107,260
8
2009-07-10T01:18:54Z
[ "python", "lambda" ]
What's going on here? I'm trying to create a list of functions: ``` def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) ``` This isn't doing what I expect. I would expect the list to act like this: ``` funcs[3](3) = 9 funcs[0](5) = 0 ``` But all the functions in the list ...
There's only one `i` which is bound to each lambda, contrary to what you think. This is a common mistake. One way to get what you want is: ``` for i in range(0,10): funcs.append(lambda x, i=i: f(i, x)) ``` Now you're creating a default parameter `i` in each lambda closure and binding to it the current *value* of...
Python Lambda Problems
1,107,210
12
2009-07-10T01:01:25Z
1,107,333
11
2009-07-10T01:56:49Z
[ "python", "lambda" ]
What's going on here? I'm trying to create a list of functions: ``` def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) ``` This isn't doing what I expect. I would expect the list to act like this: ``` funcs[3](3) = 9 funcs[0](5) = 0 ``` But all the functions in the list ...
Yep, the usual "scoping problem" (actually a binding-later-than-you want problem, but it's often called by that name). You've already gotten the two best (because simplest) answers -- the "fake default" `i=i` solution, and `functools.partial`, so I'm only giving the third one of the classic three, the "factory lambda":...
looking for a more pythonic way to access the database
1,107,297
4
2009-07-10T01:37:14Z
1,107,303
8
2009-07-10T01:42:16Z
[ "python", "mysql" ]
I have a bunch of python methods that follow this pattern: ``` def delete_session(guid): conn = get_conn() cur = conn.cursor() cur.execute("delete from sessions where guid=%s", guid) conn.commit() conn.close() ``` Is there a more pythonic way to execute raw sql. The 2 lines at the beginning and ...
You could write a context manager and use the with statement. For example, see this blog post: <http://jessenoller.com/2009/02/03/get-with-the-program-as-contextmanager-completely-different/> Also the python documentation has a sample that pretty much matches your needs. See section 8.1 on this page, in particular th...
How can I extract the call graph of a function from Python source files?
1,108,119
10
2009-07-10T07:09:58Z
1,108,142
9
2009-07-10T07:16:55Z
[ "python", "windows", "call-graph" ]
Do you know an integrated tool that will generate the call graph of a function from Python sources? I need one that is consistent and can run on Windows OS.
You could try with [PyCallGraph](http://pycallgraph.slowchop.com/) From its documentation: > Python Call Graph works with Linux, > Windows and Mac OS X. Otherwise, you can directly do it on your own, using the traceback module: ``` import traceback traceback.print_stack() ```
How can I extract the call graph of a function from Python source files?
1,108,119
10
2009-07-10T07:09:58Z
10,366,447
9
2012-04-28T18:40:30Z
[ "python", "windows", "call-graph" ]
Do you know an integrated tool that will generate the call graph of a function from Python sources? I need one that is consistent and can run on Windows OS.
PyCallGraph produces the dynamic graph resulting from the specific execution of a Python program and not the static graph extracted from the source code. Does anybody know of a tool which produces the static graph?
How to include a python .egg library that is in a subdirectory (relative location)?
1,108,384
12
2009-07-10T08:29:05Z
1,108,400
18
2009-07-10T08:32:35Z
[ "python", "egg" ]
How do you import python .egg files that are stored in a relative location to the .py code? For example, ``` My Application/ My Application/library1.egg My Application/libs/library2.egg My Application/test.py ``` How do you import and use library1 and library2 from within test.py, while leaving the .egg libraries in...
An .egg is just a .zip file that acts like a directory from which you can import stuff. You can use the `PYTHONPATH` variable to add the `.egg` to your path, or append a directory to `sys.path`. Another option is to use a `.pth` file pointing to the eggs. For more info see [A Small Introduction to Python eggs](http:/...
How do I read a date in Excel format in Python?
1,108,428
32
2009-07-10T08:41:45Z
1,108,474
50
2009-07-10T08:53:44Z
[ "python", "excel", "datetime" ]
How can I convert an Excel date (in a number format) to a proper date in Python?
You can use [xlrd](http://pypi.python.org/pypi/xlrd). From its [documentation](http://www.lexicon.net/sjmachin/xlrd.html), you can read that dates are always stored as numbers; however, you can use [`xldate_as_tuple`](http://www.lexicon.net/sjmachin/xlrd.html#xlrd.xldate%5Fas%5Ftuple-function) to convert it to a pytho...
How do I read a date in Excel format in Python?
1,108,428
32
2009-07-10T08:41:45Z
1,109,523
20
2009-07-10T13:29:51Z
[ "python", "excel", "datetime" ]
How can I convert an Excel date (in a number format) to a proper date in Python?
After testing and a few days wait for feedback, I'll svn-commit the following whole new function in xlrd's xldate module ... note that it won't be available to the diehards still running Python 2.1 or 2.2. ``` ## # Convert an Excel number (presumed to represent a date, a datetime or a time) into # a Python datetime.da...
How do I read a date in Excel format in Python?
1,108,428
32
2009-07-10T08:41:45Z
1,112,664
17
2009-07-11T01:25:02Z
[ "python", "excel", "datetime" ]
How can I convert an Excel date (in a number format) to a proper date in Python?
Here's the bare-knuckle no-seat-belts use-at-own-risk version: ``` import datetime def minimalist_xldate_as_datetime(xldate, datemode): # datemode: 0 for 1900-based, 1 for 1904-based return ( datetime.datetime(1899, 12, 30) + datetime.timedelta(days=xldate + 1462 * datemode) ) ```
How do I read a date in Excel format in Python?
1,108,428
32
2009-07-10T08:41:45Z
28,220,798
12
2015-01-29T17:21:59Z
[ "python", "excel", "datetime" ]
How can I convert an Excel date (in a number format) to a proper date in Python?
`xlrd.xldate_as_tuple` is nice, but there's `xlrd.xldate.xldate_as_datetime` that converts to datetime as well. ``` import xlrd wb = xlrd.open_workbook(filename) xlrd.xldate.xldate_as_datetime(41889, wb.datemode) => datetime.datetime(2014, 9, 7, 0, 0) ```
Returning MatPotLib image as string
1,108,881
6
2009-07-10T10:46:42Z
1,109,442
14
2009-07-10T13:13:05Z
[ "python", "django", "matplotlib" ]
I am using matplotlib in a django app and would like to directly return the rendered image. So far I can go `plt.savefig(...)`, then return the location of the image What I want to do is: ``` return HttpResponse(plt.renderfig(...), mimetype="image/png") ``` Any ideas?
Django's `HttpResponse` object supports file-like API and you can pass a file-object to savefig. ``` response = HttpResponse(mimetype="image/png") # create your image as usual, e.g. pylab.plot(...) pylab.savefig(response, format="png") return response ``` Hence, you can return the image directly in the `HttpResponse`...
How to store an IP in mySQL
1,108,918
19
2009-07-10T10:58:42Z
1,108,942
12
2009-07-10T11:03:11Z
[ "python", "mysql", "perl", "ip-address" ]
We've got a healthy debate going on in the office this week. We're creating a Db to store proxy information, for the most part we have the schema worked out except for how we should store IPs. One camp wants to use 4 smallints, one for each octet and the other wants to use a 1 big int,INET\_ATON. These tables are goin...
A `BIGINT` is `8` bytes in `MySQL`. To store `IPv4` addresses, an `UNSINGED INT` is enough, which I think is what you shoud use. I can't imagine a scenario where `4` octets would gain more performance than a single `INT`, and the latter is much more convenient. Also note that if you are going to issue queries like t...
How to store an IP in mySQL
1,108,918
19
2009-07-10T10:58:42Z
1,109,046
19
2009-07-10T11:34:58Z
[ "python", "mysql", "perl", "ip-address" ]
We've got a healthy debate going on in the office this week. We're creating a Db to store proxy information, for the most part we have the schema worked out except for how we should store IPs. One camp wants to use 4 smallints, one for each octet and the other wants to use a 1 big int,INET\_ATON. These tables are goin...
I would suggest looking at what type of queries you will be running to decide which format you adopt. Only if you need to pull out or compare individual octets would you have to consider splitting them up into separate fields. Otherwise, store it as an 4 byte integer. That also has the bonus of allowing you to use th...
switch versions of python
1,108,974
14
2009-07-10T11:12:53Z
1,108,999
30
2009-07-10T11:19:31Z
[ "python", "development-environment", "ubuntu-9.04" ]
Story: One of the app that i have works on python 2.4 and other on 2.6. I tried to do a sym link of python2.4 to python and things started to break loose on ubuntu jaunty. Now i am downloading every dependency of 2.4 and installing it using python2.4 setup.py install. The dependencies seem to be endless. Question1: Ho...
Use [Virtualenv](http://pypi.python.org/pypi/virtualenv). There is more information here: [Working with virtualenv](http://web.archive.org/web/20120303203403/http://www.arthurkoziel.com/2008/10/22/working-virtualenv/). Using virtualenv you can create a new virtual python environment with whatever version of Python yo...
Getting list of pixel values from PIL
1,109,422
12
2009-07-10T13:08:07Z
1,109,747
29
2009-07-10T14:04:23Z
[ "python", "image", "python-imaging-library" ]
Guys, I'm looking for a bit of assistance. I'm a newbie programmer and one of the problems I'm having at the minute is trying to convert a black & white `.jpg` image into a list which I can then modulate into an audio signal. This is part of a lager project to create a python SSTV program. I have imported the PIL modu...
Python shouldn't crash when you call getdata(). The image might be corrupted or there is something wrong with your PIL installation. Try it with another image or post the image you are using. This should break down the image the way you want: ``` from PIL import Image im = Image.open('um_000000.png') pixels = list(i...
Getting list of pixel values from PIL
1,109,422
12
2009-07-10T13:08:07Z
1,110,124
13
2009-07-10T15:12:52Z
[ "python", "image", "python-imaging-library" ]
Guys, I'm looking for a bit of assistance. I'm a newbie programmer and one of the problems I'm having at the minute is trying to convert a black & white `.jpg` image into a list which I can then modulate into an audio signal. This is part of a lager project to create a python SSTV program. I have imported the PIL modu...
If you have [numpy](http://numpy.scipy.org/) installed you can try: ``` data = numpy.asarray(im) ``` (I say "try" here, because it's unclear why `getdata()` isn't working for you, and I don't know whether `asarray` uses getdata, but it's worth a test.)
Getting list of pixel values from PIL
1,109,422
12
2009-07-10T13:08:07Z
1,111,950
10
2009-07-10T20:55:24Z
[ "python", "image", "python-imaging-library" ]
Guys, I'm looking for a bit of assistance. I'm a newbie programmer and one of the problems I'm having at the minute is trying to convert a black & white `.jpg` image into a list which I can then modulate into an audio signal. This is part of a lager project to create a python SSTV program. I have imported the PIL modu...
I assume you are getting an error like.. `TypeError: 'PixelAccess' object is not iterable`...? See the [Image.load](http://effbot.org/imagingbook/image.htm#tag-Image.Image.load) documentation for how to access pixels.. Basically, to get the list of pixels in an image, using `PIL`: ``` from PIL import Image i = Image...
Does python have a sorted list?
1,109,804
78
2009-07-10T14:18:00Z
1,109,866
35
2009-07-10T14:26:45Z
[ "python", "list", "sorting" ]
By which I mean a structure with: * O(log n) complexity for `x.push()` operations * O(log n) complexity to find an element * O(n) complexity to compute `list(x)` which will be sorted I also had a related question about performance of `list(...).insert(...)` which is now [here](http://stackoverflow.com/questions/11103...
The standard Python list is not sorted in any form. The standard heapq module can be used to append in O(log n) and remove the smallest one in O(log n), but isn't a sorted list in your definition. There are various implementations of balanced trees for Python that meet your requirements, e.g. [rbtree](http://pypi.pyth...
Does python have a sorted list?
1,109,804
78
2009-07-10T14:18:00Z
6,130,146
21
2011-05-25T19:59:28Z
[ "python", "list", "sorting" ]
By which I mean a structure with: * O(log n) complexity for `x.push()` operations * O(log n) complexity to find an element * O(n) complexity to compute `list(x)` which will be sorted I also had a related question about performance of `list(...).insert(...)` which is now [here](http://stackoverflow.com/questions/11103...
Though I have still never checked the "big O" speeds of basic Python list operations, the `bisect` standard module is probably also worth mentioning in this context: ``` import bisect L = [0, 100] bisect.insort(L, 50) bisect.insort(L, 20) bisect.insort(L, 21) print L ## [0, 20, 21, 50, 100] i = bisect.bisect(L, 20)...
Does python have a sorted list?
1,109,804
78
2009-07-10T14:18:00Z
22,616,929
21
2014-03-24T17:52:26Z
[ "python", "list", "sorting" ]
By which I mean a structure with: * O(log n) complexity for `x.push()` operations * O(log n) complexity to find an element * O(n) complexity to compute `list(x)` which will be sorted I also had a related question about performance of `list(...).insert(...)` which is now [here](http://stackoverflow.com/questions/11103...
Is there a particular reason for your big-O requirements? Or do you just want it to be fast? The [sortedcontainers](http://www.grantjenks.com/docs/sortedcontainers/) module is pure-Python and fast (as in fast-as-C implementations like blist and rbtree). The [performance comparison](http://www.grantjenks.com/docs/sorte...
What is the most efficent way to store a list in the Django models?
1,110,153
68
2009-07-10T15:16:19Z
1,110,207
37
2009-07-10T15:23:18Z
[ "python", "django", "django-models" ]
Currently I have a lot of python objects in my code similar to the following: ``` class MyClass(): def __init__(self, name, friends): self.myName = name self.myFriends = [str(x) for x in friends] ``` Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is ...
Would not this relationship be better expressed as a one-to-many foreign key relationship to a `Friends` table? I understand that `myFriends` are just strings but I would think that a better design would be to create a `Friend` model and have `MyClass` contain a foreign key realtionship to the resulting table.
What is the most efficent way to store a list in the Django models?
1,110,153
68
2009-07-10T15:16:19Z
1,111,475
8
2009-07-10T19:21:37Z
[ "python", "django", "django-models" ]
Currently I have a lot of python objects in my code similar to the following: ``` class MyClass(): def __init__(self, name, friends): self.myName = name self.myFriends = [str(x) for x in friends] ``` Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is ...
``` class Course(models.Model): name = models.CharField(max_length=256) students = models.ManyToManyField(Student) class Student(models.Model): first_name = models.CharField(max_length=256) student_number = models.CharField(max_length=128) # other fields, etc... friends = models.ManyToManyField('sel...
What is the most efficent way to store a list in the Django models?
1,110,153
68
2009-07-10T15:16:19Z
1,113,039
74
2009-07-11T05:43:45Z
[ "python", "django", "django-models" ]
Currently I have a lot of python objects in my code similar to the following: ``` class MyClass(): def __init__(self, name, friends): self.myName = name self.myFriends = [str(x) for x in friends] ``` Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is ...
## **"Premature optimization is the root of all evil."** With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping. To return a `list` of friend names we'll n...
What is the most efficent way to store a list in the Django models?
1,110,153
68
2009-07-10T15:16:19Z
7,151,813
21
2011-08-22T18:24:31Z
[ "python", "django", "django-models" ]
Currently I have a lot of python objects in my code similar to the following: ``` class MyClass(): def __init__(self, name, friends): self.myName = name self.myFriends = [str(x) for x in friends] ``` Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is ...
A simple way to store a list in Django is to just convert it into a JSON string, and then save that as Text in the model. You can then retrieve the list by converting the (JSON) string back into a python list. Here's how: The "list" would be stored in your Django model like so: ``` class MyModel(models.Model): my...
What is the most efficent way to store a list in the Django models?
1,110,153
68
2009-07-10T15:16:19Z
14,715,454
12
2013-02-05T19:35:21Z
[ "python", "django", "django-models" ]
Currently I have a lot of python objects in my code similar to the following: ``` class MyClass(): def __init__(self, name, friends): self.myName = name self.myFriends = [str(x) for x in friends] ``` Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is ...
As this is an old question, and Django techniques must have changed significantly since, this answer reflects Django version 1.4, and is most likely applicable for v 1.5. Django by default uses relational databases; you should make use of 'em. Map friendships to database relations (foreign key constraints) with the us...
How can I tell if my script is being run from a cronjob or from the command line?
1,110,203
2
2009-07-10T15:22:22Z
1,110,218
8
2009-07-10T15:24:39Z
[ "python", "cron" ]
I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines: ``` *** E0710091001.DAT *** [0.67%] *** E0710091001.DAT *** [1.33%] *** E0710091001.DAT *** [2.00%] *** E07100910...
you could create a flag. Possibly undocumented that your cron job would pass to the utility to structure the output.
How can I tell if my script is being run from a cronjob or from the command line?
1,110,203
2
2009-07-10T15:22:22Z
1,110,230
9
2009-07-10T15:26:48Z
[ "python", "cron" ]
I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines: ``` *** E0710091001.DAT *** [0.67%] *** E0710091001.DAT *** [1.33%] *** E0710091001.DAT *** [2.00%] *** E07100910...
I'd check `sys.stderr.isatty()` -- this way you avoid useless "decoration" output to stderr whenever it wouldn't be immediately perceptible by the user anyway.
Performance of list(...).insert(...)
1,110,332
10
2009-07-10T15:42:33Z
1,110,446
12
2009-07-10T15:58:34Z
[ "python", "architecture", "memory", "list", "memcpy" ]
I thought about the following question about computer's architecture. Suppose I do in Python ``` from bisect import bisect index = bisect(x, a) # O(log n) (also, shouldn't it be a standard list function?) x.insert(index, a) # O(1) + memcpy() ``` which takes `log n`, plus, if I correctly understand it, a ...
Python is a language. [Multiple implementations exist](http://www.python.org/dev/implementations/), and they *may* have different implementations for lists. So, without looking at the code of an actual implementation, you cannot know for sure how lists are implemented and how they behave under certain circumstances. M...
Performance of list(...).insert(...)
1,110,332
10
2009-07-10T15:42:33Z
1,111,886
8
2009-07-10T20:44:12Z
[ "python", "architecture", "memory", "list", "memcpy" ]
I thought about the following question about computer's architecture. Suppose I do in Python ``` from bisect import bisect index = bisect(x, a) # O(log n) (also, shouldn't it be a standard list function?) x.insert(index, a) # O(1) + memcpy() ``` which takes `log n`, plus, if I correctly understand it, a ...
Use the [blist module](http://www.python.org/pypi/blist/) if you need a list with better insert performance.
Python ftplib - uploading multiple files?
1,110,374
3
2009-07-10T15:47:30Z
1,110,380
9
2009-07-10T15:48:55Z
[ "python", "ftplib" ]
I've googled but I could only find how to upload one file... and I'm trying to upload all files from local directory to remote ftp directory. Any ideas how to achieve this?
with the loop? **edit**: in universal case uploading only files would look like this: ``` import os for root, dirs, files in os.walk('path/to/local/dir'): for fname in files: full_fname = os.path.join(root, fname) ftp.storbinary('STOR remote/dir' + fname, open(full_fname, 'rb')) ``` Obviously, yo...
Why does Django's signal handling use weak references for callbacks by default?
1,110,668
15
2009-07-10T16:47:10Z
1,110,874
8
2009-07-10T17:26:14Z
[ "python", "django", "garbage-collection", "weak-references", "django-signals" ]
The [Django docs](http://docs.djangoproject.com/en/dev/ref/signals/) say this on the subject: > Note also that Django stores signal > handlers as weak references by > default, so if your handler is a local > function, it may be garbage collected. > To prevent this, pass weak=False when > you call the signal’s connec...
Signals handlers are stored as weak references to avoid the object they reference from not being garbage collected (for example after explicit deletion of the signal handler), just because a signal is still flying around.
Get time zone information of the system in Python?
1,111,056
26
2009-07-10T17:59:28Z
1,111,110
43
2009-07-10T18:09:09Z
[ "python", "datetime" ]
I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.
That should work: ``` import time time.tzname ``` it returns a tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local DST timezone.
Get time zone information of the system in Python?
1,111,056
26
2009-07-10T17:59:28Z
10,854,983
19
2012-06-01T17:44:34Z
[ "python", "datetime" ]
I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.
Gives a UTC offset like in ThomasH's answer, but takes daylight savings into account. ``` >>> import time >>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone >>> offset / 60 / 60 * -1 -9 ``` The value of `time.timezone` or `time.altzone` is in seconds West of UTC (with areas East of UTC g...
Get time zone information of the system in Python?
1,111,056
26
2009-07-10T17:59:28Z
13,406,277
10
2012-11-15T21:11:00Z
[ "python", "datetime" ]
I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.
The code snippets for calculating offset are incorrect, see <http://bugs.python.org/issue7229>. The correct way to handle this is: ``` def local_time_offset(t=None): """Return offset of local zone from GMT, either at present or at time t.""" # python2.3 localtime() can't take None if t is None: t ...
How do I print a Python datetime in the local timezone?
1,111,317
10
2009-07-10T18:50:59Z
1,111,345
12
2009-07-10T18:54:42Z
[ "python", "timezone" ]
Let's say I have a variable t that's set to this: ``` datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>) ``` If I say `str(t)`, i get: ``` '2009-07-10 18:44:59.193982+00:00' ``` How can I get a similar string, except printed in the local timezone rather than UTC?
Think your should look around: datetime.astimezone() **<http://docs.python.org/library/datetime.html#datetime.datetime.astimezone>** Also see pytz module - it's quite easy to use -- as example: ``` eastern = timezone('US/Eastern') ``` **<http://pytz.sourceforge.net/>** Example: ``` from datetime import datetime i...
How do I print a Python datetime in the local timezone?
1,111,317
10
2009-07-10T18:50:59Z
2,071,364
8
2010-01-15T12:23:54Z
[ "python", "timezone" ]
Let's say I have a variable t that's set to this: ``` datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>) ``` If I say `str(t)`, i get: ``` '2009-07-10 18:44:59.193982+00:00' ``` How can I get a similar string, except printed in the local timezone rather than UTC?
I believe the best way to do this is to use the `LocalTimezone` class defined in the `datetime.tzinfo` documentation (goto <http://docs.python.org/library/datetime.html#tzinfo-objects> and scroll down to the "Example tzinfo classes" section): Assuming `Local` is an instance of `LocalTimezone` ``` t = datetime.datetim...
Is it really OK to do object closeing/disposing in __del__?
1,111,505
7
2009-07-10T19:26:49Z
1,111,564
8
2009-07-10T19:37:47Z
[ "python" ]
I have been thinking about how I write classes in Python. More specifically how the constructor is implemented and how the object should be destroyed. I don't want to rely on CPython's reference counting to do object cleanup. This basically tells me I should use with statements to manage my object life times and that I...
Not necessarily. You'll encounter problems when you have cyclic references. Eli Bendersky does a good job of explaining this in his blog post: * [Safely using destructors in Python](http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/)
Is it really OK to do object closeing/disposing in __del__?
1,111,505
7
2009-07-10T19:26:49Z
1,113,173
10
2009-07-11T07:38:25Z
[ "python" ]
I have been thinking about how I write classes in Python. More specifically how the constructor is implemented and how the object should be destroyed. I don't want to rely on CPython's reference counting to do object cleanup. This basically tells me I should use with statements to manage my object life times and that I...
Short answer : No. Long answer: Using `__del__` is tricky, mainly because it's not guaranteed to be called. That means you can't do things there that absolutely has to be done. This in turn means that `__del__` basically only can be used for cleanups that would happen sooner or later anyway, like cleaning up resources...
How do I capture SIGINT in Python?
1,112,343
286
2009-07-10T22:49:21Z
1,112,350
405
2009-07-10T22:52:48Z
[ "python", "control", "signals" ]
I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a `Ctrl`+`C` signal, and I'd like to do some cleanup. In Perl I'd do this: ``` $SIG{'INT'} = 'exit_gracefully'; sub exit_gracefully { print "Caught ^C \n"; exit (0); } ``` ...
Register your handler with `signal.signal` like this: ``` #!/usr/bin/env python import signal import sys def signal_handler(signal, frame): print('You pressed Ctrl+C!') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print('Press Ctrl+C') signal.pause() ``` Code adapted from [here](http://www...
How do I capture SIGINT in Python?
1,112,343
286
2009-07-10T22:49:21Z
1,112,352
18
2009-07-10T22:52:51Z
[ "python", "control", "signals" ]
I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a `Ctrl`+`C` signal, and I'd like to do some cleanup. In Perl I'd do this: ``` $SIG{'INT'} = 'exit_gracefully'; sub exit_gracefully { print "Caught ^C \n"; exit (0); } ``` ...
You can handle Ctrl-C by catching the `KeyboardInterrupt` exception. You can implement any clean-up code in the exception handler.
How do I capture SIGINT in Python?
1,112,343
286
2009-07-10T22:49:21Z
1,112,357
110
2009-07-10T22:54:24Z
[ "python", "control", "signals" ]
I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a `Ctrl`+`C` signal, and I'd like to do some cleanup. In Perl I'd do this: ``` $SIG{'INT'} = 'exit_gracefully'; sub exit_gracefully { print "Caught ^C \n"; exit (0); } ``` ...
You can treat it like an exception (KeyboardInterrupt), like any other. Make a new file and run it from your shell with the following contents to see what I mean: ``` import time, sys x = 1 while True: try: print x time.sleep(.3) x += 1 except KeyboardInterrupt: print "Bye" ...
How do I capture SIGINT in Python?
1,112,343
286
2009-07-10T22:49:21Z
1,112,363
14
2009-07-10T22:56:19Z
[ "python", "control", "signals" ]
I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a `Ctrl`+`C` signal, and I'd like to do some cleanup. In Perl I'd do this: ``` $SIG{'INT'} = 'exit_gracefully'; sub exit_gracefully { print "Caught ^C \n"; exit (0); } ``` ...
From Python's [documentation](http://docs.python.org/library/signal.html): ``` import signal import time def handler(signum, frame): print 'Here you go' signal.signal(signal.SIGINT, handler) time.sleep(10) # Press Ctrl+c here ```
How do I capture SIGINT in Python?
1,112,343
286
2009-07-10T22:49:21Z
10,972,804
34
2012-06-10T22:23:26Z
[ "python", "control", "signals" ]
I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a `Ctrl`+`C` signal, and I'd like to do some cleanup. In Perl I'd do this: ``` $SIG{'INT'} = 'exit_gracefully'; sub exit_gracefully { print "Caught ^C \n"; exit (0); } ``` ...
And as a context manager: ``` import signal class GracefulInterruptHandler(object): def __init__(self, sig=signal.SIGINT): self.sig = sig def __enter__(self): self.interrupted = False self.released = False self.original_handler = signal.getsignal(self.sig) def hand...
Perl equivalent of (Python-) list comprehension
1,112,444
13
2009-07-10T23:39:07Z
1,112,455
13
2009-07-10T23:42:52Z
[ "python", "perl", "list-comprehension" ]
I'm looking for ways to express this Python snippet in Perl: ``` data = {"A": None, "B": "yes", "C": None} key_list = [k for k in data if data[k]] # in this case the same as filter(lambda k: data[k], data) but let's ignore that ``` So looking at it one way, I just want the keys where the values are *None* or *undef...
Use [grep](http://perldoc.perl.org/functions/grep.html): ``` #!/usr/bin/perl use strict; use warnings; my %data = ("A" => 0, "B" => "yes", "C" => 0 ); my @keys = grep { $data{$_} } keys %data; ``` Grep returns the values from the list on the right-hand side for which the expression in braces evaluates to a true val...
Perl equivalent of (Python-) list comprehension
1,112,444
13
2009-07-10T23:39:07Z
1,112,462
21
2009-07-10T23:46:05Z
[ "python", "perl", "list-comprehension" ]
I'm looking for ways to express this Python snippet in Perl: ``` data = {"A": None, "B": "yes", "C": None} key_list = [k for k in data if data[k]] # in this case the same as filter(lambda k: data[k], data) but let's ignore that ``` So looking at it one way, I just want the keys where the values are *None* or *undef...
I think you want [`grep`](http://perldoc.perl.org/functions/grep.html): ``` #!/usr/bin/env perl use strict; use warnings; my %data = ( A => undef, B => 'yes', C => undef ); my @keys = grep { defined $data{$_} } keys %data; print "Key: $_\n" for @keys; ``` I also think that I type too slowly, and that I should relo...