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 to add to the pythonpath in windows 7?
3,701,646
153
2010-09-13T15:04:26Z
32,609,129
7
2015-09-16T12:51:09Z
[ "python", "windows", "environment-variables", "pythonpath" ]
I have a directory which hosts all of my Django apps (`C:\My_Projects`). I want to add this directory to my `pythonpath` so I can call the apps directly. I have tried adding `C:\My_Projects\;` to my `Path` variable from the Windows GUI (`My Computer > Properties > Advanced System Settings > Environment Variables`). Bu...
Adding *Python* and *PythonPath* to the Windows environment: 1. Open Explorer. 2. Right-click *'Computer'* in the Navigation Tree Panel on the left. 3. Select *'Properties'* at the bottom of the Context Menu. 4. Select *'Advanced system settings'* 5. Click *'Environment Variables...'* in the Advanced Tab 6. Under *'Sy...
Python test for a url and image type
3,702,331
4
2010-09-13T16:23:35Z
3,702,713
13
2010-09-13T17:08:00Z
[ "python", "syntax" ]
In the following code how to test for if the type is url or if the type is an image ``` for dictionaries in d_dict: type = dictionaries.get('type') if (type starts with http or https): logging.debug("type is url") else if type ends with .jpg or .png or .gif logging.debug("type is image") else: lo...
You cannot tell what type a resource is purely from its URL. It is perfectly valid to have an GIF file at a URL without a `.gif` file extension, or with a misleading file extension like `.txt`. In fact it is quite likely, now that URL-rewriting is popular, that you'll get image URLs with no file extension at all. It i...
How do I add basic authentication to a Python REST request?
3,702,370
5
2010-09-13T16:26:50Z
3,702,417
7
2010-09-13T16:32:06Z
[ "python", "web-services", "authentication", "rest", "http-post" ]
I have the following simple Python code that makes a simple post request to a REST service - ``` params= { "param1" : param1, "param2" : param2, "param3" : param3 } xmlResults = urllib.urlopen(MY_APP_PATH, urllib.urlencode(params)).read() results = MyResponseParser.parse(xmlResults) ``` The proble...
If basic authentication = HTTP authentication, use this: ``` import urllib import urllib2 username = 'foo' password = 'bar' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, MY_APP_PATH, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener...
How to copy InMemoryUploadedFile object to disk
3,702,465
24
2010-09-13T16:37:24Z
3,705,098
30
2010-09-13T23:16:28Z
[ "python", "django", "file-upload", "file-storage" ]
I am trying to catch a file sent with form and perform some operations on it before it will be saved. So I need to create a copy of this file in temp directory, but I don't know how to reach it. Shutil's functions fail to copy this file, since there is no path to it. So is there a way to do this operation in some other...
[This](http://stackoverflow.com/questions/2806586/reading-file-data-during-forms-clean-method/2806655#2806655) is similar question, it might help. ``` import os from django.core.files.storage import default_storage from django.core.files.base import ContentFile from django.conf import settings data = request.FILES['i...
How to print the full traceback without halting the program?
3,702,675
284
2010-09-13T17:03:30Z
3,702,847
371
2010-09-13T17:27:26Z
[ "python", "exception-handling" ]
I'm writing a program that parses 10 websites, locates data files, saves the files, and then parses them to make data that can be readily used in the NumPy library. There are **tons** of errors this file encounters through bad links, poorly formed XML, missing entries, and other things I've yet to categorize. I initial...
[`traceback.format_exc()`](http://docs.python.org/3/library/traceback.html#traceback.format_exc) or [`sys.exc_info()`](http://docs.python.org/3/library/sys.html#sys.exc_info) will yield more info if that's what you want. ``` import traceback import sys try: do_stuff() except Exception: print(traceback.format_...
How to print the full traceback without halting the program?
3,702,675
284
2010-09-13T17:03:30Z
16,946,886
122
2013-06-05T18:05:51Z
[ "python", "exception-handling" ]
I'm writing a program that parses 10 websites, locates data files, saves the files, and then parses them to make data that can be readily used in the NumPy library. There are **tons** of errors this file encounters through bad links, poorly formed XML, missing entries, and other things I've yet to categorize. I initial...
Some other answer have already pointed out the [traceback](http://docs.python.org/3/library/traceback.html) module. Please notice that with `print_exc`, in some corner cases, you will not obtain what you would expect. In Python 2.x: ``` import traceback try: raise TypeError("Oups!") except Exception, err: tr...
How to print the full traceback without halting the program?
3,702,675
284
2010-09-13T17:03:30Z
29,930,431
66
2015-04-28T21:40:32Z
[ "python", "exception-handling" ]
I'm writing a program that parses 10 websites, locates data files, saves the files, and then parses them to make data that can be readily used in the NumPy library. There are **tons** of errors this file encounters through bad links, poorly formed XML, missing entries, and other things I've yet to categorize. I initial...
If you're debugging and just want to see the current stack trace, you can simply call: [`traceback.print_stack()`](https://docs.python.org/3/library/traceback.html#traceback.print_stack) There's no need to manually raise an exception just to catch it again.
How to print the full traceback without halting the program?
3,702,675
284
2010-09-13T17:03:30Z
31,444,861
27
2015-07-16T03:23:54Z
[ "python", "exception-handling" ]
I'm writing a program that parses 10 websites, locates data files, saves the files, and then parses them to make data that can be readily used in the NumPy library. There are **tons** of errors this file encounters through bad links, poorly formed XML, missing entries, and other things I've yet to categorize. I initial...
> # How to print the full traceback without halting the program? When you don't want to halt your program on an error, you need to handle that error with a try/except: ``` try: do_something_that_might_error() except Exception as error: handle_the_error(error) ``` To extract the full traceback, we'll use the ...
How to tell if a file is gzip compressed?
3,703,276
17
2010-09-13T18:27:06Z
3,703,300
29
2010-09-13T18:30:11Z
[ "python", "compression", "gzip" ]
I have a Python program which is going to take text files as input. However, some of these files may be gzip compressed. Is there a cross-platform, usable from Python way to determine if a file is gzip compressed or not? Is the following reliable or could an ordinary text file 'accidentally' look gzip-like enough for m...
The [magic number](http://catb.org/jargon/html/M/magic-number.html) for gzip compressed files is `1f 8b`. Although testing for this is not 100% reliable, it is highly unlikely that "ordinary text files" start with those two bytes—in UTF-8 it's not even legal. Usually gzip compressed files sport the suffix `.gz` thou...
Tkinter button command activates upon running program?
3,704,568
10
2010-09-13T21:29:10Z
5,278,951
11
2011-03-11T22:13:42Z
[ "python", "user-interface", "tkinter" ]
I'm trying to make a build retrieval form, and seem to have issues with the buttons... I'm a novice at Python/tkinter GUI programming (and GUI programming in general) and borrowed the skeleton of a Hello World app, and sorta built off that. In the code below, I've set the "command" option of my Browse button to call m...
Make your event handler a lambda function which calls your get\_dir() with whatever arguments you want: xbBrowse = Button(frameN,text="Browse...",font=fontReg, command=lambda : self.get\_dir(xbPath)
In Python small floats tending to zero
3,704,570
16
2010-09-13T21:29:22Z
3,704,637
16
2010-09-13T21:43:01Z
[ "python", "floating-point", "numerical-stability" ]
I have a Bayesian Classifier programmed in Python, the problem is that when I multiply the features probabilities I get VERY small float values like 2.5e-320 or something like that, and suddenly it turns into 0.0. The 0.0 is obviously of no use to me since I must find the "best" class based on which class returns the M...
Would it be possible to do your work in a logarithmic space? (For example, instead of storing `1e-320`, just store `-320`, and use addition instead of multiplication)
In Python small floats tending to zero
3,704,570
16
2010-09-13T21:29:22Z
3,704,694
16
2010-09-13T21:50:57Z
[ "python", "floating-point", "numerical-stability" ]
I have a Bayesian Classifier programmed in Python, the problem is that when I multiply the features probabilities I get VERY small float values like 2.5e-320 or something like that, and suddenly it turns into 0.0. The 0.0 is obviously of no use to me since I must find the "best" class based on which class returns the M...
What you describe is a standard problem with the naive Bayes classifier. You can search for underflow with that to find the answer. or see [here](http://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html). The short answer is it is standard to express all that in terms of **logarithms**. ...
Replace non-ascii chars from a unicode string in Python
3,704,731
10
2010-09-13T21:57:01Z
3,704,793
19
2010-09-13T22:07:46Z
[ "python", "ascii" ]
How can I replace non-ascii chars from a unicode string in Python? This are the output I spect for the given inputs: música -> musica cartón -> carton caño -> cano Myaybe with a dict where 'á' is a key and 'a' a value?
If all you want to do is degrade accented characters to their non-accented equivalent: ``` >>> import unicodedata >>> unicodedata.normalize('NFKD', u"m\u00fasica").encode('ascii', 'ignore') 'musica' ```
How does django one-to-one relationships map the name to the child object?
3,705,124
3
2010-09-13T23:25:36Z
3,705,153
9
2010-09-13T23:32:20Z
[ "python", "django", "one-to-one" ]
Apart from one example in the docs, I can't find any documentation on how exactly django chooses the name with which one can access the child object from the parent object. In their example, they do the following: ``` class Place(models.Model): name = models.CharField(max_length=50) address = model...
If you define a custom [`related_name`](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name) then it will use that, otherwise it will lowercase the entire model name (in your example `.fancyrestaurant`). See the else block in [django.db.models.related code](http://code.djang...
Create console in python
3,705,421
3
2010-09-14T00:48:10Z
3,705,441
9
2010-09-14T00:53:11Z
[ "python", "console", "interactive" ]
I'm looking to have the same functionality (history, ...) as when you simply type python in your terminal. The script I have goes through a bunch of setup code, and when ready, the user should have a command prompt. What would be the best way to achieve this?
Either use [`readline`](http://pypi.python.org/pypi/readline/) and code the shell behaviour yourself, or simply prepare the environment and drop into [`IPython`](http://ipython.scipy.org/doc/manual/html/interactive/reference.html#embedding-ipython).
Best way to create a "reversed" list in Python?
3,705,670
43
2010-09-14T02:06:20Z
3,705,676
120
2010-09-14T02:07:54Z
[ "python", "reverse", "html-lists" ]
In Python, what is the best way to create a new list whose items are the same as those of some other list, but in reverse order? (I don't want to modify the existing list in place.) Here is one solution that has occurred to me: ``` new_list = list(reversed(old_list)) ``` It's also possible to duplicate `old_list` th...
``` newlist = oldlist[::-1] ``` The `[::-1]` slicing (which my wife Anna likes to call "the Martian smiley";-) means: slice the whole sequence, with a step of -1, i.e., in reverse. It works for all sequences. Note that this (*and* the alternatives you mentioned) is equivalent to a "shallow copy", i.e.: if the items a...
Best way to create a "reversed" list in Python?
3,705,670
43
2010-09-14T02:06:20Z
3,705,705
35
2010-09-14T02:18:45Z
[ "python", "reverse", "html-lists" ]
In Python, what is the best way to create a new list whose items are the same as those of some other list, but in reverse order? (I don't want to modify the existing list in place.) Here is one solution that has occurred to me: ``` new_list = list(reversed(old_list)) ``` It's also possible to duplicate `old_list` th...
Now let's [`timeit`](http://docs.python.org/library/timeit.html). *Hint:* Alex's `[::-1]` is fastest :) ``` $ p -m timeit "ol = [1, 2, 3]; nl = list(reversed(ol))" 100000 loops, best of 3: 2.34 usec per loop $ p -m timeit "ol = [1, 2, 3]; nl = list(ol); nl.reverse();" 1000000 loops, best of 3: 0.686 usec per loop $ ...
Creating a list with >255 elements
3,706,199
11
2010-09-14T04:49:25Z
3,706,212
20
2010-09-14T04:56:25Z
[ "python", "list", "parameters", "syntax-error", "literals" ]
Ok, so I'm writing some python code (I don't write python much, I'm more used to java and C). Anyway, so I have collection of integer literals I need to store. (Ideally >10,000 of them, currently I've only got 1000 of them) I would have liked to be accessing the literals by file IO, or by accessing there source API, b...
If you use `[]` instead of `list()`, you won't run into the limit because `[]` is not a function. ``` src = [0,1,2,2,2,0,1,2,... ,2,1,2,1,1,0,2,1] ```
Can Python xml ElementTree parse a very large xml file?
3,707,155
8
2010-09-14T08:17:24Z
3,719,654
9
2010-09-15T16:18:43Z
[ "python", "xml" ]
I'm trying to parse a large file (> 2GB) of structured markup data and the memory is not enough for this.Which is the optimal way of XML parsing class for this condition.More details please.
Check out the `iterparse()` function. A description of how you can use it to parse very large documents can be found [here](http://effbot.org/zone/element-iterparse.htm#incremental-parsing).
I need MSVCR90.dll version 9.0.21022.8
3,707,178
7
2010-09-14T08:21:42Z
3,707,219
7
2010-09-14T08:29:23Z
[ "python", "visual-c++", "py2exe" ]
According to a py2exe tutorial I found I need MSVCR90.dll version 9.0.21022.8 to run it for python 2.6. Where do I find MSVCR90.dll version 9.0.21022.8?
Install the [VS 2008 redistrbutable package](http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en).
What does this python syntax mean?
3,707,383
5
2010-09-14T08:57:52Z
3,707,561
8
2010-09-14T09:21:14Z
[ "python", "generator", "yield" ]
I am not a python guy and I am trying to understand some python code. I wonder what the last line of below code does? Is that kind of multiple objects returned? or list of 3 objects returned? ``` req = SomeRequestBean() req.setXXX(xxx) req.YYY = int(yyy) device,resp,fault = yield req #<----- What does this m...
There are two things going on in that line. The easier one to explain is that the `yield` statement is returning a value which is a sequence, so the commas take values of the sequence and put them in the variables, much like this: ``` >>> def func(): ... return (1,2,3) ... >>> a,b,c = func() >>> a 1 >>> b 2 >>> c ...
How to Escape Single Quotes in Python on Server to be used in Javascript on Client
3,708,152
18
2010-09-14T10:50:18Z
3,708,167
19
2010-09-14T10:52:28Z
[ "javascript", "python", "string", "escaping" ]
``` >>> sample = "hello'world" >>> print sample hello'world >>> print sample.replace("'","\'") hello'world ``` In my web app I need to store my python string with all single quotes escaped for manipulation later in the client browsers javascript. Trouble is python uses the same backslash escape notation so the replace...
Use: ``` sample.replace("'", r"\'") ``` or ``` sample.replace("'", "\\'") ```
How to Escape Single Quotes in Python on Server to be used in Javascript on Client
3,708,152
18
2010-09-14T10:50:18Z
3,708,606
38
2010-09-14T11:56:01Z
[ "javascript", "python", "string", "escaping" ]
``` >>> sample = "hello'world" >>> print sample hello'world >>> print sample.replace("'","\'") hello'world ``` In my web app I need to store my python string with all single quotes escaped for manipulation later in the client browsers javascript. Trouble is python uses the same backslash escape notation so the replace...
As a general solution for passing data from Python to Javascript, consider serializing it with the `json` library (part of the standard library in Python 2.6+). ``` >>> sample = "hello'world" >>> import json >>> print json.dumps(sample) "hello\'world" ```
Creating a Hierarchical Build with SCons
3,709,321
6
2010-09-14T13:30:50Z
3,709,371
8
2010-09-14T13:37:00Z
[ "python", "scons" ]
I have a library project that contains some samples in a subfolder. The library itself has a `SConstruct` file and each sample has its own folder and its own `SConstruct` file. I'd like to add a target to the main (root) `SConstruct` file which would allow me to compile the library as usual, and all the samples, at o...
<http://www.scons.org/doc/production/HTML/scons-man.html> > Creating a Hierarchical Build > > Notice that the file names specified > in a subdirectory's SConscript file > are relative to that subdirectory. > > SConstruct: > > ``` > env = Environment() > env.Program(target = 'foo', source = 'foo.c') > > SConscript('sub...
How to know the location of the library that I load in Python?
3,709,405
3
2010-09-14T13:41:30Z
3,709,418
12
2010-09-14T13:42:21Z
[ "python", "path" ]
import ABC loads ABC from somewhere. How can I know the 'somewhere'? I may be able to check the paths in `sys.path` one by one, but I wonder if I can find it in Python. ## More Questions 1. When I load library with 'from ABC import \*', how can I know where ABC is located? 2. Can 'class xyz' know where it is located...
``` >>> import abc >>> abc.__file__ 'C:\\Program Files\\Python31\\lib\\abc.py' ``` See [docs](http://docs.python.org/reference/datamodel.html#index-855). for more thorough inspection you could use [`inspect`](http://docs.python.org/library/inspect.html) module: ``` >>> import inspect >>> from abc import * >>> inspec...
How do libraries in different programming languages handle Date & Time, Timestamps & Durations, Leapseconds & -years, DSTs & Timezones, ...?
3,709,870
22
2010-09-14T14:32:43Z
3,710,304
17
2010-09-14T15:20:12Z
[ "c#", "python", "language-agnostic", "date", "time" ]
Is there a standard body or a specific normative way how time-related things should be *implemented in practice* (like ICU for Unicode-related tasks) or is this currently a "best-effort", depending on how much effort, time and money language and library implementers want to spend? Is there a specific and complete impl...
*I'll try to give an answer to the second and third question using the Java library which might become part of Java 7.* # javax.time.\* (JSR 310) These classes are a complete rewrite of JodaTime trying to fix the design flaws of `util.Date`/`util.Time` as well as JodaTime. JSR 310 tries to provide a comprehensive mo...
How do libraries in different programming languages handle Date & Time, Timestamps & Durations, Leapseconds & -years, DSTs & Timezones, ...?
3,709,870
22
2010-09-14T14:32:43Z
3,713,332
10
2010-09-14T22:17:54Z
[ "c#", "python", "language-agnostic", "date", "time" ]
Is there a standard body or a specific normative way how time-related things should be *implemented in practice* (like ICU for Unicode-related tasks) or is this currently a "best-effort", depending on how much effort, time and money language and library implementers want to spend? Is there a specific and complete impl...
I don't think there's a single standard to such things at the moment, however there are multiple standards which such things may conform to: ISO 8601 for example. [ICU](http://icu-project.org)'s own date/time handling is a cross-language (C/C++ and Java) and multi-platform library. It handles dates and times internal...
How do libraries in different programming languages handle Date & Time, Timestamps & Durations, Leapseconds & -years, DSTs & Timezones, ...?
3,709,870
22
2010-09-14T14:32:43Z
3,894,542
7
2010-10-08T21:46:19Z
[ "c#", "python", "language-agnostic", "date", "time" ]
Is there a standard body or a specific normative way how time-related things should be *implemented in practice* (like ICU for Unicode-related tasks) or is this currently a "best-effort", depending on how much effort, time and money language and library implementers want to spend? Is there a specific and complete impl...
I haven't used it in a while, but from past experience I'd say that [Boost.Date\_Time](http://www.boost.org/doc/libs/release/doc/html/date_time.html) is a pretty good example. While probably not the first choice for many fast paced projects today, the expressive power of C++ still seems to be a very good match for a c...
How do libraries in different programming languages handle Date & Time, Timestamps & Durations, Leapseconds & -years, DSTs & Timezones, ...?
3,709,870
22
2010-09-14T14:32:43Z
3,897,598
11
2010-10-09T19:46:33Z
[ "c#", "python", "language-agnostic", "date", "time" ]
Is there a standard body or a specific normative way how time-related things should be *implemented in practice* (like ICU for Unicode-related tasks) or is this currently a "best-effort", depending on how much effort, time and money language and library implementers want to spend? Is there a specific and complete impl...
**There are time(s) and there are dates (calendars)** The first problem is that dates are not linked to time but to astronomical position of Earh, Moon, etc. + regularity/periodicity of human activity. The time is also subjective and relative or even relativistic and measured either astronomically or or atomically. ...
How do I create a CSV file from database in Python?
3,710,263
17
2010-09-14T15:15:12Z
3,710,392
7
2010-09-14T15:30:04Z
[ "python", "mysql", "sqlite", "file-io", "csv" ]
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table heade...
Using the [csv module](http://docs.python.org/library/csv.html) is very straight forward and made for this task. ``` import csv writer = csv.writer(open("out.csv", 'w')) writer.writerow(['name', 'address', 'phone', 'etc']) writer.writerow(['bob', '2 main st', '703', 'yada']) writer.writerow(['mary', '3 main st', '704'...
How do I create a CSV file from database in Python?
3,710,263
17
2010-09-14T15:15:12Z
3,765,652
33
2010-09-22T01:13:33Z
[ "python", "mysql", "sqlite", "file-io", "csv" ]
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table heade...
``` import csv import sqlite3 from glob import glob; from os.path import expanduser conn = sqlite3.connect( # open "places.sqlite" from one of the Firefox profiles glob(expanduser('~/.mozilla/firefox/*/places.sqlite'))[0] ) cursor = conn.cursor() cursor.execute("select * from moz_places;") with open("out.csv", "w...
How to print what I think is an object?
3,710,823
8
2010-09-14T16:21:18Z
3,710,926
13
2010-09-14T16:34:14Z
[ "python", "generator" ]
``` test = ["a","b","c","d","e"] def xuniqueCombinations(items, n): if n==0: yield [] else: for i in xrange(len(items)-n+1): for cc in xuniqueCombinations(items[i+1:],n-1): yield [items[i]]+cc x = xuniqueCombinations(test, 3) print x ``` outputs ``` "generator object xuni...
leoluk is right, you need to iterate over it. But here's the correct syntax: ``` combos = xuniqueCombinations(test, 3) for x in combos: print x ``` Alternatively, you can convert it to a list first: ``` combos = list(xuniqueCombinations(test, 3)) print combos ```
How to use inspect to get the caller's info from callee in Python?
3,711,184
48
2010-09-14T17:04:20Z
3,711,243
48
2010-09-14T17:12:23Z
[ "python", "inspect" ]
I need to get the caller info (what file/what line) from callee. I learned that I can use inpect module for that for purposes, but not exactly how. How to get those info with inspect? Or is there any other way to get the info? ``` import inspect print __file__ c=inspect.currentframe() print c.f_lineno def hello(): ...
The caller's frame is one frame higher than the current frame. You can use [inspect.getouterframes](http://docs.python.org/library/inspect.html#inspect.getouterframes) to get the caller's frame, plus the filename and line number. ``` import inspect def hello(): (frame, filename, line_number, function_name, l...
How to use inspect to get the caller's info from callee in Python?
3,711,184
48
2010-09-14T17:04:20Z
22,378,386
21
2014-03-13T12:16:42Z
[ "python", "inspect" ]
I need to get the caller info (what file/what line) from callee. I learned that I can use inpect module for that for purposes, but not exactly how. How to get those info with inspect? Or is there any other way to get the info? ``` import inspect print __file__ c=inspect.currentframe() print c.f_lineno def hello(): ...
I would suggest to use `inspect.stack` instead: ``` import inspect def hello(): frame,filename,line_number,function_name,lines,index = inspect.stack()[1] print(frame,filename,line_number,function_name,lines,index) hello() ```
How do I assign a numerical value to each uppercase Letter?
3,711,303
4
2010-09-14T17:20:40Z
3,711,397
11
2010-09-14T17:32:30Z
[ "python", "string" ]
How do i assign a numerical value to each uppercase letter, and then use it later via string and then add up the values. EG. ``` A = 1, B = 2, C = 3 (etc..) string = 'ABC' ``` Then return the answer 6 (in this case).
``` base = ord('A') - 1 mystring = 'ABC' print sum(ord(char) - base for char in mystring) ```
Can I prevent modifying an object in Python?
3,711,657
8
2010-09-14T18:08:31Z
3,712,574
11
2010-09-14T20:18:31Z
[ "python", "global-variables" ]
I want to control global variables (or globally scoped variables) in a way that they are set only once in program initialization code, and lock them after that. I use UPPER\_CASE\_VARIABLES for global variables, but I want to have a sure way not to change the variable anyway. * Does python provide that (or similar) f...
Activestate has a recipe titled [*Constants in Python*](http://code.activestate.com/recipes/65207-constants-in-python) by the venerable [Alex Martelli](http://en.wikipedia.org/wiki/Alex_Martelli) for creating a`const` module with attributes which cannot be rebound after creation. That sounds like what you're looking fo...
Remove empty lines
3,711,856
24
2010-09-14T18:35:12Z
3,711,884
28
2010-09-14T18:38:22Z
[ "python", "string" ]
I have large string which I split by newlines. How can I remove all lines that are empty, (whitespace only)? pseudo code: ``` for stuff in largestring: remove stuff that is blank ```
Using regex: ``` if re.match(r'^\s*$', line): # line is empty (has only the following: \t\n\r and whitespace) ``` Using regex + [`filter()`](http://docs.python.org/dev/library/functions.html#filter): ``` filtered = filter(lambda x: not re.match(r'^\s*$', x), original) ``` As seen on [codepad](http://codepad.org...
Remove empty lines
3,711,856
24
2010-09-14T18:35:12Z
3,711,923
30
2010-09-14T18:45:05Z
[ "python", "string" ]
I have large string which I split by newlines. How can I remove all lines that are empty, (whitespace only)? pseudo code: ``` for stuff in largestring: remove stuff that is blank ```
Try list comprehension and [`string.strip()`](http://docs.python.org/library/stdtypes.html#str.strip): ``` >>> mystr = "L1\nL2\n\nL3\nL4\n \n\nL5" >>> mystr.split('\n') ['L1', 'L2', '', 'L3', 'L4', ' ', '', 'L5'] >>> [line for line in mystr.split('\n') if line.strip() != ''] ['L1', 'L2', 'L3', 'L4', 'L5'] ```
Python distutils error: "[directory]... doesn't exist or not a regular file"
3,712,033
19
2010-09-14T18:59:51Z
3,712,682
15
2010-09-14T20:34:59Z
[ "python", "distutils" ]
Let's take the following project layout: ``` $ ls -R . .: package setup.py ./package: __init__.py dir file.dat module.py ./package/dir: tool1.dat tool2.dat ``` And the following content for `setup.py`: ``` $ cat setup.py from distutils.core import setup setup(name='pyproj', version='0.1', pack...
In your `package_data`, your `'*'` glob will match `package/dir` itself, and try to copy that dir as a file, resulting in a failure. Find a glob that won't match the directory `package/dir`, rewriting your `setup.py` along these lines: ``` from distutils.core import setup setup(name='pyproj', version='0.1', ...
How does Boost.Python work?
3,712,125
7
2010-09-14T19:16:18Z
3,712,253
7
2010-09-14T19:34:29Z
[ "c++", "python", "boost-python" ]
How is Python able to call C++ objects when the interpreter is C and has been built w/ a C compiler?
Boost.Python has special macros that declare functions with `extern "C"` so the Python interpreter will be able to call them. It's kind of complicated, but you can look at the [Boost documentation](http://www.boost.org/doc/libs/1_44_0/libs/python/doc/v2/module.html#BOOST_PYTHON_MODULE-spec) for more info.
Is there a limitation on the number of tables a PostgreSQL database can have?
3,715,456
6
2010-09-15T07:15:49Z
3,715,655
9
2010-09-15T07:52:47Z
[ "python", "mysql", "database", "database-design", "postgresql" ]
I have created a database in PostgreSQL, let's call it **testdb**. I have a generic set of tables inside this database, **xxx\_table\_one**, **xxx\_table\_two** and **xxx\_table\_three**. Now, I have Python code where I want to dynamically create and remove "sets" of these 3 tables to my database with a unique identi...
PostgreSQL doesn't have many limits, your hardware is much more limited, that's where you encounter most problems. <http://www.postgresql.org/about/> You can have 2^32 tables in a single database, just over 4 billion.
Encoding an image file with base64
3,715,493
59
2010-09-15T07:24:48Z
3,715,530
101
2010-09-15T07:31:25Z
[ "python", "base64" ]
I want to encode an image into a string using the base64 module. I've ran into a problem though. How do I specify the image I want to be encoded? I tried using the directory to the image, but that simply leads to the directory being encoded. I want the actual image file to be encoded. **EDIT** I tired this snippet: ...
I'm not sure I understand your question. I assume you are doing something along the lines of: ``` import base64 with open("yourfile.ext", "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) ``` You have to open the file first of course, and read its contents - you cannot simply pass the pat...
Encoding an image file with base64
3,715,493
59
2010-09-15T07:24:48Z
3,715,592
40
2010-09-15T07:41:53Z
[ "python", "base64" ]
I want to encode an image into a string using the base64 module. I've ran into a problem though. How do I specify the image I want to be encoded? I tried using the directory to the image, but that simply leads to the directory being encoded. I want the actual image file to be encoded. **EDIT** I tired this snippet: ...
With python 2.x, you can trivially encode using .encode: ``` with open("path/to/file.png", "rb") as f: data = f.read() print data.encode("base64") ```
Is python's shutil.move() atomic on linux?
3,716,325
12
2010-09-15T09:27:25Z
3,716,361
15
2010-09-15T09:33:00Z
[ "python", "file", "unix", "atomic" ]
I am wondering whether python's shutil.move is atomic on linux ? Is the behavior different if the source and destination files are on two different partitions or is it same as when they are present on the same partition ? I am more concerned to know whether the shutil.move is atomic if the source and destination files...
It is not atomic if the files are on different filsystems. In that case, python opens the source and destination file, loops on reading from the source and writing to the desination and finally unlinks the source file. If the source and destination file are on the same file system, python uses the rename() C call, whi...
Multi-panel time series of lines and filled contours using matplotlib?
3,716,528
4
2010-09-15T09:54:14Z
3,718,712
9
2010-09-15T14:40:55Z
[ "python", "matplotlib", "scipy" ]
If I wanted to make a combined image like the one shown below ([original source here](http://wavemetrics.com/products/igorpro/gallery/user_lui.htm)), could you point me to the matplotlib objects do I need to assemble? I've been trying to work with AxesImage objects and I've also downloaded [SciKits Timeseries](http://p...
You shouldn't need any custom axes. The Timeseries Scikit is great, but you don't need it at all to work with dates in matplotlib... You'll probably want to use the various functions in [`matplotlib.dates`](http://matplotlib.sourceforge.net/api/dates_api.html), [`plot_date`](http://matplotlib.sourceforge.net/api/pyplo...
Django. You don't have permission to edit anything
3,718,077
63
2010-09-15T13:31:48Z
3,718,260
128
2010-09-15T13:48:23Z
[ "python", "django", "django-admin" ]
I created a little app a while ago. I created **admin.py** and used `admin.site.register(MenuEntry)` to add the class to admin console. It showed the items of that class just fine. Then I began working on another app and created everything as before. But now it says: **You don't have permission to edit anything.** I co...
I checked files one more time and found the difference. I forgot to add `admin.autodiscover()` in `urls.py` of the project. Thanks.
psycopg2.InternalError: how can I get more useful information?
3,718,251
6
2010-09-15T13:47:20Z
3,718,490
8
2010-09-15T14:17:12Z
[ "python", "postgresql" ]
I'm running this command in a Python script: ``` try: print sql_string cursor.execute(sql_string) except: print sys.exc_info() ``` and getting: ``` (<class 'psycopg2.InternalError'>, InternalError('current transaction is aborted, commands ignored until end of transaction block\n',), <traceback object at...
Try this: ``` try: print sql_string cursor.execute(sql_string) except Exception, e: print e.pgerror ``` If you are still getting "current transaction is aborted, commands ignored until end of transaction block" then your error is further back in your transaction and this query is only failing due to a pre...
Python "is" statement: what is happening?
3,718,513
24
2010-09-15T14:18:56Z
3,718,538
7
2010-09-15T14:22:09Z
[ "python" ]
I was quite surprised when ``` [] is not [] ``` evaluated to `True`. What is happening in this code? What really `not` and `is` statements are doing?
`is` means *is same instance*. It evaluates to true if the variables on either side of the operator point to the same object and false otherwise. [Reference](http://docs.python.org/release/2.5.2/ref/comparisons.html), near the bottom.
Python "is" statement: what is happening?
3,718,513
24
2010-09-15T14:18:56Z
3,718,541
45
2010-09-15T14:22:21Z
[ "python" ]
I was quite surprised when ``` [] is not [] ``` evaluated to `True`. What is happening in this code? What really `not` and `is` statements are doing?
`a is not b` is a special operator which is equivalent to `not a is b`. The operator `a is b` returns True if a and b are bound to the same object, otherwise False. When you create two empty lists you get two different objects, so `is` returns False (and therefore `is not` returns True).
Python "is" statement: what is happening?
3,718,513
24
2010-09-15T14:18:56Z
3,718,576
23
2010-09-15T14:26:24Z
[ "python" ]
I was quite surprised when ``` [] is not [] ``` evaluated to `True`. What is happening in this code? What really `not` and `is` statements are doing?
`is` is the identity comparison. `==` is the equality comparison. Your statement is making two different lists and checking if they are the same instance, which they are not. If you use `==` it will return true and because they are both empty lists.
Python "is" statement: what is happening?
3,718,513
24
2010-09-15T14:18:56Z
3,718,736
17
2010-09-15T14:42:39Z
[ "python" ]
I was quite surprised when ``` [] is not [] ``` evaluated to `True`. What is happening in this code? What really `not` and `is` statements are doing?
The best way to describe WHY that happens is this: Here is your example ``` >>> x = [] >>> y = [] >>> print(x is y) ... False ``` `x` and `y` are actually two different lists, so if you add something to `x`, it does not appear in `y` ``` >>> x.append(1) >>> print(x) ... [1] >>> print(y) ... [] ``` So how do we mak...
How to properly determine current script directory in Python?
3,718,657
81
2010-09-15T14:34:57Z
3,718,923
82
2010-09-15T15:01:21Z
[ "python", "pythonpath", "dirname" ]
I would like to see what is best way to determine current script directory in python? I discovered that two to the many ways of calling python code, it is hard to find a good solution. Here are some problems: * `__file__` is not defined if the script is executed with `exec`, `execfile` * `__module__` is defined only...
``` os.path.dirname(os.path.abspath(__file__)) ``` is indeed the best you're going to get. It's unusual to be executing a script with `exec`/`execfile`; normally you should be using the module infrastructure to load scripts. If you must use these methods, I suggest setting `__file__` in the `globals` you pass to the ...
How to properly determine current script directory in Python?
3,718,657
81
2010-09-15T14:34:57Z
6,209,894
57
2011-06-02T02:49:46Z
[ "python", "pythonpath", "dirname" ]
I would like to see what is best way to determine current script directory in python? I discovered that two to the many ways of calling python code, it is hard to find a good solution. Here are some problems: * `__file__` is not defined if the script is executed with `exec`, `execfile` * `__module__` is defined only...
If you really want to cover the case that a script is called via `execfile(...)`, you can use the `inspect` module to deduce the filename (including the path). As far as I am aware, this will work for all cases you listed: ``` filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.p...
How to properly determine current script directory in Python?
3,718,657
81
2010-09-15T14:34:57Z
22,881,871
24
2014-04-05T14:01:08Z
[ "python", "pythonpath", "dirname" ]
I would like to see what is best way to determine current script directory in python? I discovered that two to the many ways of calling python code, it is hard to find a good solution. Here are some problems: * `__file__` is not defined if the script is executed with `exec`, `execfile` * `__module__` is defined only...
``` #!/usr/bin/env python import inspect import os import sys def get_script_dir(follow_symlinks=True): if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze path = os.path.abspath(sys.executable) else: path = inspect.getabsfile(get_script_dir) if follow_symlinks: path ...
Using cscope to browse Python code with VIM?
3,718,868
13
2010-09-15T14:55:04Z
3,753,503
12
2010-09-20T16:37:32Z
[ "python", "vim", "editor", "cscope" ]
Has anyone managed successfully using `cscope` with Python code? I have VIM 7.2 and the latest version of `cscope` installed, however it doesn't get my code's tags correctly (always off by a couple of lines). I tried the `pycscope` script but its output isn't supported by the modern version of `cscope`. Any ideas? Or ...
EDIT: I'm going to run through the process step by step: ### Preparing the sources: exhuberant ctags, has an option: -x ``` Alternatively, ctags can generate a cross reference file which lists, in human readable form, information about the various source objects found in a set of language files. ``` T...
Using cscope to browse Python code with VIM?
3,718,868
13
2010-09-15T14:55:04Z
4,258,315
8
2010-11-23T16:28:46Z
[ "python", "vim", "editor", "cscope" ]
Has anyone managed successfully using `cscope` with Python code? I have VIM 7.2 and the latest version of `cscope` installed, however it doesn't get my code's tags correctly (always off by a couple of lines). I tried the `pycscope` script but its output isn't supported by the modern version of `cscope`. Any ideas? Or ...
This seems to work for me: Change to the top directory of your python code. Create a file called `cscope.files`: ``` find . -name '*.py' > cscope.files cscope -R ``` You may need to perform a `cscope -b` first if the cross references don't get built properly.
Recommended .gitignore file for Python projects?
3,719,243
77
2010-09-15T15:32:42Z
3,719,569
12
2010-09-15T16:06:49Z
[ "python", "django", "git", "pygtk", "gitignore" ]
I'm trying to collect some of my default settings, and one thing I realized I don't have a standard for is .gitignore files. There's a great thread showing a [good .gitignore for Visual Studio projects](http://stackoverflow.com/questions/2143956/gitignore-for-visual-studio-projects-and-solutions), but I don't see many ...
[local\_settings.py](http://djangosnippets.org/snippets/644/), for django projects. \*~ for all projects.
Recommended .gitignore file for Python projects?
3,719,243
77
2010-09-15T15:32:42Z
3,719,679
23
2010-09-15T16:21:55Z
[ "python", "django", "git", "pygtk", "gitignore" ]
I'm trying to collect some of my default settings, and one thing I realized I don't have a standard for is .gitignore files. There's a great thread showing a [good .gitignore for Visual Studio projects](http://stackoverflow.com/questions/2143956/gitignore-for-visual-studio-projects-and-solutions), but I don't see many ...
When using [buildout](http://www.buildout.org/) I have following in `.gitignore` (along with `*.pyo` and `*.pyc`): ``` .installed.cfg bin develop-eggs dist downloads eggs parts src/*.egg-info lib lib64 ``` Thanks to [Jacob Kaplan-Moss](http://jacobian.org/writing/django-apps-with-buildout/) Also I tend to put `.svn`...
Recommended .gitignore file for Python projects?
3,719,243
77
2010-09-15T15:32:42Z
14,058,267
106
2012-12-27T16:58:51Z
[ "python", "django", "git", "pygtk", "gitignore" ]
I'm trying to collect some of my default settings, and one thing I realized I don't have a standard for is .gitignore files. There's a great thread showing a [good .gitignore for Visual Studio projects](http://stackoverflow.com/questions/2143956/gitignore-for-visual-studio-projects-and-solutions), but I don't see many ...
[Github has a great boilerplate .gitignore](https://github.com/github/gitignore/blob/master/Python.gitignore) ``` # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging bin/ build/ develop-eggs/ dist/ eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.c...
Log to the base 2 in python
3,719,631
45
2010-09-15T16:15:31Z
3,719,686
98
2010-09-15T16:23:24Z
[ "python", "logarithm" ]
How should I compute log to the base two in python. Eg. I have this equation where I am using log base 2 ``` import math e = -(t/T)* math.log((t/T)[, 2]) ```
It's good to know that ![alt text](http://i.stack.imgur.com/yt8vU.gif) but also know that `math.log` takes an optional second argument which allows you to specify the base: ``` In [22]: import math In [23]: math.log? Type: builtin_function_or_method Base Class: <type 'builtin_function_or_method'> String Form:...
Log to the base 2 in python
3,719,631
45
2010-09-15T16:15:31Z
3,719,783
7
2010-09-15T16:37:07Z
[ "python", "logarithm" ]
How should I compute log to the base two in python. Eg. I have this equation where I am using log base 2 ``` import math e = -(t/T)* math.log((t/T)[, 2]) ```
Using numpy: ``` In [1]: import numpy as np In [2]: np.log2? Type: function Base Class: <type 'function'> String Form: <function log2 at 0x03049030> Namespace: Interactive File: c:\python26\lib\site-packages\numpy\lib\ufunclike.py Definition: np.log2(x, y=None) Docstring: Retur...
Log to the base 2 in python
3,719,631
45
2010-09-15T16:15:31Z
28,033,134
12
2015-01-19T20:41:19Z
[ "python", "logarithm" ]
How should I compute log to the base two in python. Eg. I have this equation where I am using log base 2 ``` import math e = -(t/T)* math.log((t/T)[, 2]) ```
If all you need is the **integer part** of log base 2, [math.frexp()](https://docs.python.org/2/library/math.html#math.frexp) could be pretty efficient: ``` log2int_slow = int(floor(log(x, 2.0))) log2int_fast = frexp(x)[1]-1 ``` The [C function it calls](http://people.freebsd.org/~jake/frexp.c) just grabs and tweaks ...
Numpy Modular arithmetic
3,719,957
2
2010-09-15T17:02:00Z
3,720,611
7
2010-09-15T18:28:33Z
[ "python", "numpy", "math", "modular" ]
How can I define in numpy a matrix that uses operations modulo 2? For example: ``` 0 0 1 0 1 0 1 1 + 0 1 = 1 0 ``` Thanks!
This operation is called "xor". ``` >>> import numpy >>> x = numpy.array([[0,0],[1,1]]) >>> y = numpy.array([[1,0],[0,1]]) >>> x ^ y array([[1, 0], [1, 0]]) ``` BTW, (element-wise) multiplication modulo 2 can be done with "and". ``` >>> x & y array([[0, 0], [0, 1]]) ```
Easy way of overriding default methods in custom Python classes?
3,720,717
6
2010-09-15T18:44:03Z
3,721,607
11
2010-09-15T20:39:54Z
[ "python", "class", "methods", "override" ]
I have a class called Cell: ``` class Cell: def __init__(self, value, color, size): self._value = value self._color = color self._size = size # and other methods... ``` `Cell._value` will store a string, integer, etc. (whatever I am using that object for). I want all default methods ...
If I understand you correctly, you're looking for an easy way to delegate an object's method to a property of that object? You can avoid some of the repetitiveness by defining a decorator: ``` def delegate(method, prop): def decorate(cls): setattr(cls, method, lambda self, *args, **kwargs: ...
Pass Variable On Import
3,720,740
13
2010-09-15T18:46:09Z
3,720,803
12
2010-09-15T18:54:28Z
[ "python", "import" ]
Let's say you have some time-consuming work to do when a module/class is first imported. This functionality is dependent on a passed in variable. It only needs to be done when the module/class is loaded. All instances of the class can then use the result. For instance, I'm using rpy2: ``` import rpy2.robjects as robj...
Having a module init function isn't unheard of. Pygame does it for the sdl initialization functions. So yes, your best bet is probably ``` import someModule someModule.init(NECESSARY_DATA) x = someModule.someClass(range(1, 5)) ```
Pass Variable On Import
3,720,740
13
2010-09-15T18:46:09Z
28,389,678
8
2015-02-08T01:47:20Z
[ "python", "import" ]
Let's say you have some time-consuming work to do when a module/class is first imported. This functionality is dependent on a passed in variable. It only needs to be done when the module/class is loaded. All instances of the class can then use the result. For instance, I'm using rpy2: ``` import rpy2.robjects as robj...
I had to do something similar for my project. If you don't want to rely on the calling script to run the initialization function, you can add your own Python builtin which is then available to all modules at runtime. Be careful to name your builtin something unique that is unlikely to cause a namespace collision (eg `...
how to reverse color map image to scalar values
3,720,840
8
2010-09-15T18:57:46Z
3,722,674
7
2010-09-15T23:43:07Z
[ "python", "image", "matplotlib", "scipy" ]
How do I invert a color mapped image? I have a 2D image which plots data on a colormap. I'd like to read the image in and 'reverse' the color map, that is, look up a specific RGB value, and turn it into a float. For example: using this image: <http://matplotlib.sourceforge.net/_images/mri_demo.png> I should be able ...
There may be better ways to do this; I'm not sure. If you read `help(cm.jet)` you will see the algorithm used to map values in the interval [0,1] to RGB 3-tuples. You could, with a little paper and pencil, work out formulas to invert the piecewise-linear functions which define the mapping. However, there are a number ...
Example use of assert in Python?
3,721,126
8
2010-09-15T19:31:42Z
3,721,183
20
2010-09-15T19:39:36Z
[ "python", "exception", "assert" ]
I've read about when to use assert vs. exceptions, but I'm still not "getting it". It seems like whenever I think I'm in a situation where I should use assert, later on in development I find that I'm "looking before I leap" to make sure the assert doesn't fail when I call the function. Since there's another Python idio...
A good guideline is using `assert` when its triggering means a **bug** in your code. When your code assumes something and acts upon the assumption, it's recommended to protect this assumption with an `assert`. This `assert` failing means your assumption isn't correct, which means your code isn't correct.
Example use of assert in Python?
3,721,126
8
2010-09-15T19:31:42Z
3,721,186
15
2010-09-15T19:39:44Z
[ "python", "exception", "assert" ]
I've read about when to use assert vs. exceptions, but I'm still not "getting it". It seems like whenever I think I'm in a situation where I should use assert, later on in development I find that I'm "looking before I leap" to make sure the assert doesn't fail when I call the function. Since there's another Python idio...
tend to use assert to check for things that *should never happen*. sort of like a sanity check. Another thing to realize is that [asserts](http://docs.python.org/reference/simple_stmts.html#the-assert-statement) are removed when optimized: > The current code generator emits no code for an assert statement when optimi...
python date interval intersection
3,721,249
9
2010-09-15T19:47:28Z
3,721,301
16
2010-09-15T19:55:36Z
[ "python", "datetime", "intersection" ]
As a matter of general interest I'm wondering if there's a more elegant/efficient way to do this. I have a function that compares two start/end tuples of dates returning true if they intersect. ``` from datetime import date def date_intersection(t1, t2): t1start, t1end = t1[0], t1[1] t2start, t2end = t2[0], t2...
It's not really more Pythonic, but you can simply the logic to decide on an intersection somewhat. This particular problems crops up a lot: ``` return (t1start <= t2start <= t1end) or (t2start <= t1start <= t2end) ``` To see why this works think about the different possible ways that the two intervals can intersect a...
Readable convention for unpacking single value tuple
3,721,477
5
2010-09-15T20:19:29Z
3,721,498
18
2010-09-15T20:23:07Z
[ "python", "coding-style", "tuples" ]
There are some [related](http://stackoverflow.com/questions/3219573/unpacking-a-1-tuple-in-a-list-of-length-1) [questions](http://stackoverflow.com/questions/2111759/whats-the-best-practice-for-handling-single-value-tuples-in-python) about unpacking single-value tuples, but I'd like to know if there is a preferred meth...
How about using explicit parenthesis to indicate that you are unpacking a tuple? ``` (value, ) = long().chained().expression().that().returns().tuple() ``` After all [explicit is better than implicit](http://www.python.org/dev/peps/pep-0020/).
Python vs C : Line of Code Comparison vs Dev Time
3,722,003
3
2010-09-15T21:33:09Z
3,722,732
8
2010-09-15T23:54:34Z
[ "python", "c", "comparison" ]
Hi I'm currently learning Python since the syntax feels so succinct and the idioms match well with my mental model. However I'm also interested in learning about OS internals and reverse engineering software, which ultimately means knowing C in a rather thorough capacity. When originally picking a language I did lots...
> but is it possible with libraries, code reuse etc, to have a development time in C close to that of Python No. You've missed the most important point. Python's interactive. It's not edit-compile-link-execute-break-debug. It's edit-debug.
Adding folder to Python's path permanently
3,722,248
8
2010-09-15T22:12:18Z
3,722,272
8
2010-09-15T22:16:40Z
[ "python" ]
I've written a library in python and I want it to reside in a common location on the file system. From my script, I just want to do: ``` >>> import mylib ``` Now I understand that in order to do this, I *can* do this: ``` >>> import sys >>> sys.path.append(r'C:\MyFolder\MySubFolder') >>> import mylib ``` But I don...
The PYTHONPATH environment variable will do it.
Why aren't persistent connections supported by URLLib2?
3,722,577
7
2010-09-15T23:18:51Z
3,722,635
7
2010-09-15T23:33:08Z
[ "python", "urllib2", "keep-alive" ]
After scanning the `urllib2` source, it seems that connections are automatically closed even if you do specify keep-alive. Why is this? As it is now I just use `httplib` for my persistent connections... but wonder why this is disabled (or maybe just ambiguous) in urllib2.
It's a well-known limit of urllib2 (and urllib as well). IMHO the best attempt so far to fix it and make it right is Garry Bodsworth's [coda\_network](http://blog.programmerslog.com/?p=423) for Python 2.6 or 2.7 -- replacement, patched versions of urllib2 (and some other modules) to support keep-alive (and a bunch of o...
Is it safe to replace MacOS X default Python interpreter?
3,723,183
3
2010-09-16T01:56:41Z
3,723,267
8
2010-09-16T02:18:06Z
[ "python", "osx", "python-3.x", "python-2.x" ]
I have the default Python 2.6.1 installed as `/usr/bin/python` and Python 3.1.2 installed in `/usr/local/bin/python3.1`. Considering that I use only 3.x syntax, is it safe to replace the default interpreter (2.6) with the 3.1 one (python-config included) using symlinks (and removing old Python binary)? Or is the system...
If you're only using Python 3, start your scripts with: ``` #! /usr/bin/env python3.1 ``` And you'll be using the right version, without doinking the system about. edit: BTW this idea is suggested by the Python docs. Each script will be running the version of Python they depend on. Since Python 3 is not backward com...
How do you convert a PIL `Image` to a Django `File`?
3,723,220
38
2010-09-16T02:07:39Z
3,723,384
10
2010-09-16T02:53:05Z
[ "python", "django", "python-imaging-library", "django-file-upload", "django-uploads" ]
I'm trying to convert an `UploadedFile` to a PIL `Image` object to thumbnail it, and then convert the PIL `Image` object that my thumbnail function returns back into a `File` object. How can I do this?
I've had to do this in a few steps, imagejpeg() in php requires a similar process. Not to say theres no way to keep things in memory, but this method gives you a file reference to both the original image and thumb (usually a good idea in case you have to go back and change your thumb size). 1. save the file 2. open it...
How do you convert a PIL `Image` to a Django `File`?
3,723,220
38
2010-09-16T02:07:39Z
4,544,525
74
2010-12-28T07:55:03Z
[ "python", "django", "python-imaging-library", "django-file-upload", "django-uploads" ]
I'm trying to convert an `UploadedFile` to a PIL `Image` object to thumbnail it, and then convert the PIL `Image` object that my thumbnail function returns back into a `File` object. How can I do this?
The way to do this without having to write back to the filesystem, and then bring the file back into memory via an open call, is to make use of StringIO and Django InMemoryUploadedFile. Here is a quick sample on how you might do this. This assumes that you already have a thumbnailed image named 'thumb': ``` import Str...
Is there a neater alternative to `except: pass`?
3,723,302
6
2010-09-16T02:28:45Z
3,723,319
13
2010-09-16T02:34:16Z
[ "python", "exception-handling", "coding-style" ]
I had a function that returned a random member of several groups in order of preference. It went something like this: ``` def get_random_foo_or_bar(): "I'd rather have a foo than a bar." if there_are_foos(): return get_random_foo() if there_are_bars(): return get_random_bar() raise I...
That is exactly how I would write it. It's simple and it makes sense. I see no problem with the `pass` statements. If you want to reduce the repetition and you anticipate adding future types, you could roll this up into a loop. Then you could change the `pass` to a functionally-equivalent `continue` statement, if that...
Preserving styles using python's xlrd,xlwt, and xlutils.copy
3,723,793
40
2010-09-16T04:46:38Z
5,285,650
8
2011-03-12T21:34:49Z
[ "python", "xlrd", "xlwt" ]
I'm using `xlrd`, `xlutils.copy`, and `xlwt` to open up a template file, copy it, fill it with new values, and save it. However, there doesn't seem to be any easy way to preserve the formatting of the cells; it always gets blown away and set to blank. Is there any simple way I can do this? Thanks! /YGA A sample scri...
Here's an example of usage of code that I'll propose as a patch against xlutils 1.4.1 ``` # coding: ascii import xlrd, xlwt # Demonstration of copy2 patch for xlutils 1.4.1 # Context: # xlutils.copy.copy(xlrd_workbook) -> xlwt_workbook # copy2(xlrd_workbook) -> (xlwt_workbook, style_list) # style_list is a conversi...
Preserving styles using python's xlrd,xlwt, and xlutils.copy
3,723,793
40
2010-09-16T04:46:38Z
7,686,555
36
2011-10-07T11:23:24Z
[ "python", "xlrd", "xlwt" ]
I'm using `xlrd`, `xlutils.copy`, and `xlwt` to open up a template file, copy it, fill it with new values, and save it. However, there doesn't seem to be any easy way to preserve the formatting of the cells; it always gets blown away and set to blank. Is there any simple way I can do this? Thanks! /YGA A sample scri...
There are two parts to this. First, you must enable the reading of formatting info when opening the source workbook. The copy operation will then copy the formatting over. ``` import xlrd import xlutils.copy inBook = xlrd.open_workbook('input.xls', formatting_info=True) outBook = xlutils.copy.copy(inBook) ``` Secon...
How can I make this code Pythonic
3,723,850
6
2010-09-16T05:00:35Z
3,724,177
11
2010-09-16T06:22:37Z
[ "oop", "coding-style", "python" ]
So I have this code for an object. That object being a move you can make in a game of rock papers scissor. Now, the object needs to be both an integer (for matching a protocol) and a string for convenience of writing and viewing. ``` class Move: def __init__(self, setMove): self.numToName = {0:"rock", 1:"p...
To me, the concept of code being "pythonic" really comes down to the idea that once you understand what problem you're trying to solve, the code almost writes itself. In this case, without worrying about the deeper abstractions of players, games, throws, etc., you have the following problem: there are a certain number ...
Practical example of Polymorphism
3,724,110
30
2010-09-16T06:03:31Z
3,724,160
102
2010-09-16T06:16:22Z
[ "python", "oop", "polymorphism" ]
Can anyone please give me a real life, practical example of Polymorphism? My professor tells me the same old story I have heard always about the `+` operator. `a+b = c` and `2+2 = 4`, so this is polymorphism. I really can't associate myself with such a definition, since I have read and re-read this in many books. What...
Check the Wikipedia example: it is very helpful at a high level: ``` class Animal: def __init__(self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract meth...
Practical example of Polymorphism
3,724,110
30
2010-09-16T06:03:31Z
3,724,174
7
2010-09-16T06:21:39Z
[ "python", "oop", "polymorphism" ]
Can anyone please give me a real life, practical example of Polymorphism? My professor tells me the same old story I have heard always about the `+` operator. `a+b = c` and `2+2 = 4`, so this is polymorphism. I really can't associate myself with such a definition, since I have read and re-read this in many books. What...
A common real example in Python is [file-like objects](http://docs.python.org/library/stdtypes.html#file-objects). Besides actual files, several other types, including [StringIO](http://docs.python.org/library/stringio.html) and [BytesIO](http://docs.python.org/library/io.html#io.BytesIO), are file-like. A method that ...
Python: Uniqueness for list of lists
3,724,551
9
2010-09-16T07:29:00Z
3,724,558
28
2010-09-16T07:30:11Z
[ "python", "unique" ]
Hello I am curious what would be an effient way of uniquefying such data objects: ``` testdata =[ ['9034968', 'ETH'], ['14160113', 'ETH'], ['9034968', 'ETH'], ['11111', 'NOT'], ['9555269', 'NOT'], ['15724032', 'ETH'], ['15481740', 'ETH'], ['15481757', 'ETH'], ['15481724', 'ETH'], ['10307528', 'ETH'], ['15481757', 'ETH...
You can use a set: ``` unique_data = [list(x) for x in set(tuple(x) for x in testdata)] ``` You can also see [this page](http://www.peterbe.com/plog/uniqifiers-benchmark) which benchmarks a variety of methods that either preserve or don't preserve order.
CMS or Framework?
3,724,878
6
2010-09-16T08:19:14Z
3,724,958
14
2010-09-16T08:30:27Z
[ "php", "python", "frameworks", "content-management-system", "web-applications" ]
I'm looking to build a online store. However, the first question, past the idea of the store, is the platform. I've previously worked with Java and PHP and am quite comfortable with PHP. So my first considerations were Drupal or maybe CodeIgniter (which I have heard lots of good things about) On discussions with frien...
Choosing a framework for a project you already know what will be the purpose will only slow your development down. If your project's main goal is to be an online store, then pick your choice among the many projects already implemented for you with payment gateways, shipping options, product management, etc. A framework...
Python ssl problem with multiprocessing
3,724,900
5
2010-09-16T08:22:32Z
3,724,938
11
2010-09-16T08:27:42Z
[ "python", "ssl", "multiprocessing" ]
I want to send data from a client to the server in a TLS TCP socket from multiple client subprocesses so I share the same ssl socket with all subprocesses. Communication works with one subprocess, but if I use more than one subprocesses, the TLS server crashes with an `ssl.SSLError` (SSL3\_GET\_RECORD:decryption failed...
The problem is that you're re-using the same connection for both processes. The way SSL encrypts data makes this fail -- the two processes would have to communicate with each other about the state of the shared SSL connection. Even if you do make it work, or if you didn't use SSL, the data would arrive at the server al...
Python ctypes, C++ object destruction
3,724,987
3
2010-09-16T08:34:10Z
3,725,028
7
2010-09-16T08:38:33Z
[ "c++", "python", "ctypes" ]
Consider the following python ctypes - c++ binding: ``` // C++ class A { public: void someFunc(); }; A* A_new() { return new A(); } void A_someFunc(A* obj) { obj->someFunc(); } void A_destruct(A* obj) { delete obj; } # python from ctypes import cdll libA = cdll.LoadLibrary(some_path) class A: def __init__(...
You could implement the `__del__` method, which calls a destructor function you would have to define: **C++** ``` class A { public: void someFunc(); }; A* A_new() { return new A(); } void delete_A(A* obj) { delete obj; } void A_someFunc(A* obj) { obj->someFunc(); } ``` **Python** ``` from ctypes import cdll l...
Ruby's tap idiom in Python
3,725,214
7
2010-09-16T09:08:34Z
3,726,124
20
2010-09-16T11:20:34Z
[ "python", "ruby", "idioms" ]
There is a useful Ruby idiom that uses `tap` which allows you to create an object, do some operations on it and return it (I use a list here only as an example, my real code is more involved): ``` def foo [].tap do |a| b = 1 + 2 # ... and some more processing, maybe some logging, etc. a << b end end >...
Short answer: **Ruby encourages method chaining, Python doesn't.** I guess the right question is: What is Ruby's `tap` useful for? Now I don't know a lot about Ruby, but by googling I got the impression that `tap` is conceptually useful as method chaining. In Ruby, the style: `SomeObject.doThis().doThat().andAnother...
Python module for binary plist
3,725,268
10
2010-09-16T09:16:55Z
5,373,266
13
2011-03-21T02:32:29Z
[ "iphone", "python", "plist" ]
Is there any Python project/module working on a binary plist writer? I need one for a REST implementation I'm doing. I would like the server to send a HTTP REsponse containing a binary plist instead of json, for example. The server is Apache with mod\_python and django installed. Considering adding bplist format alongs...
I was afraid I might have to learn SWIG, implement this myself, or switch to another language for this hobby project that involves parsing binary plists -- but after a quick `pip search plist`, I found [biplist](https://github.com/wooster/biplist).
how to compare two arrays in python?
3,726,338
10
2010-09-16T11:49:15Z
3,726,365
24
2010-09-16T11:53:32Z
[ "python" ]
How to compare two arrays in python? ``` date = "Thu Sep 16 13:14:15 CDT 2010" sdate = "Thu Sep 16 14:14:15 CDT 2010" dateArr = [] dateArr = date.split() sdateArr = [] sdateArr = sdate.split() ``` Now I want to compare these two array I guess split returns array. We can do simple comparision in Java like `dateArr[...
You could always do just: ``` a=[1,2,3] b=['a','b'] c=[1,2,3,4] d=[1,2,3] a==b #returns False a==c #returns False a==d #returns True ```
What's the recommended way to return a boolean for a collection being non-empty in python?
3,726,692
4
2010-09-16T12:35:56Z
3,726,714
12
2010-09-16T12:39:33Z
[ "python", "collections" ]
I came across the question [Python: What is the best way to check if a list is empty?](http://stackoverflow.com/questions/53513/python-what-is-the-best-way-to-check-if-a-list-is-empty) on SO. Now if I wanted to return a `True` (`False`) depending on whether a collection `coll` is non-empty (empty) from a function, wha...
You could use ``` return bool(coll) ```
Set variable in jinja
3,727,045
106
2010-09-16T13:18:12Z
4,181,605
234
2010-11-15T05:18:50Z
[ "python", "templates", "variables", "variable-assignment", "jinja2" ]
I would like to know how can I set a variable with another variable in jinja. I will explain, I have got a submenu and I would like show which link is active. I tried this: ``` {% set active_link = {{recordtype}} -%} ``` where recordtype is a variable given for my template.
`{{ }}` tells the template to *print* the value, this won't work in expressions like you're trying to do. Instead, use the `{% set %}` template tag and then assign the value the same way you would in normal python code. ``` {% set testing = 'it worked' %} {% set another = testing %} {{ another }} ``` Result: ``` it ...
Set variable in jinja
3,727,045
106
2010-09-16T13:18:12Z
25,752,608
7
2014-09-09T19:56:31Z
[ "python", "templates", "variables", "variable-assignment", "jinja2" ]
I would like to know how can I set a variable with another variable in jinja. I will explain, I have got a submenu and I would like show which link is active. I tried this: ``` {% set active_link = {{recordtype}} -%} ``` where recordtype is a variable given for my template.
Just Set it up like this ``` {% set active_link = recordtype -%} ```
Problems for parse POST json message Django/GAE
3,727,118
3
2010-09-16T13:27:32Z
3,727,440
7
2010-09-16T14:03:09Z
[ "python", "django", "google-app-engine", "post" ]
When I send a POST message to the GAE with a json parameters using POST the QueryDict parsed by the server is not parsed like a json ... I found a similar problem in this issue: <http://stackoverflow.com/questions/2579235/iphone-json-post-request-to-django-server-creates-querydict-within-querydict> Maybe is a problem...
The first thing you need to remember when working with json is that AppEngine lives with python 2.5. This means json is not a standard part of python yet. To solve that bit I found simplejson somewhere online and packed it together with my code. The API for built-in json and simplejson are essentially the same (or may...
specify dtype of each object in a python numpy array
3,727,369
5
2010-09-16T13:56:05Z
3,728,059
7
2010-09-16T15:14:25Z
[ "python", "arrays", "numpy", "scipy" ]
* [This is a similar question using dtypes in a list](http://stackoverflow.com/questions/3410147/define-dtypes-in-numpy-using-a-list) The following snippet creates a "typical test array", the purpose of this array is to test an assortment of things in my program. Is there a way or is it even possible to change the typ...
The way to do this in numpy is to use a [structured array](http://docs.scipy.org/doc/numpy/user/basics.rec.html). However, in many cases where you're using heterogeneous data, a simple python list is a *much* better choice. (Or, though it wasn't widely available when this answer was written, a `pandas.DataFrame` is ab...
How to use ``xlrd.xldate_as_tuple()``
3,727,916
13
2010-09-16T14:56:20Z
3,728,176
17
2010-09-16T15:25:21Z
[ "python", "date", "xlrd" ]
I am not quite sure how to use the following function: ``` xlrd.xldate_as_tuple ``` for the following data ``` xldate:39274.0 xldate:39839.0 ``` Could someone please give me an example on usage of the function for the data?
Quoth [the documentation](http://www.lexicon.net/sjmachin/xlrd.html): > ## Dates in Excel spreadsheets > > In reality, there are no such things. > What you have are floating point > numbers and pious hope. There are > several problems with Excel dates: > > (1) Dates are not stored as a separate > data type; they are s...
Sorting while preserving order in python
3,728,017
4
2010-09-16T15:09:00Z
3,728,030
14
2010-09-16T15:10:26Z
[ "python", "sorting" ]
What is the best way to sort a list of floats by their value, whiles still keeping record of the initial order. I.e. sorting a: ``` a=[2.3, 1.23, 3.4, 0.4] ``` returns something like ``` a_sorted = [0.4, 1.23, 2.3, 3.4] a_order = [4, 2, 1, 3] ``` If you catch my drift.
You could do something like this: ``` >>> sorted(enumerate(a), key=lambda x: x[1]) [(3, 0.4), (1, 1.23), (0, 2.3), (2, 3.4)] ``` If you need to indexing to start with 1 instead of 0, [`enumerate`](http://docs.python.org/library/functions.html#enumerate) accepts the second parameter.
Testing email sending
3,728,528
46
2010-09-16T16:08:12Z
3,728,540
30
2010-09-16T16:10:54Z
[ "python", "django", "email", "smtp", "django-testing" ]
any tips on testing email sending? Other than maybe creating a gmail account, especially for receiving those emails? I would like to maybe store the emails locally, within a folder as they are sent.
You can use a [file backend for sending emails](http://docs.djangoproject.com/en/dev/topics/email/#file-backend) which is a very handy solution for development and testing; emails are not sent but stored in a folder you can specify!
Testing email sending
3,728,528
46
2010-09-16T16:08:12Z
3,728,594
112
2010-09-16T16:18:09Z
[ "python", "django", "email", "smtp", "django-testing" ]
any tips on testing email sending? Other than maybe creating a gmail account, especially for receiving those emails? I would like to maybe store the emails locally, within a folder as they are sent.
Django test framework has some built in helpers to aid you with testing [e-mail service](https://docs.djangoproject.com/en/dev/topics/testing/tools/#email-services). Example from docs (short version): ``` from django.core import mail from django.test import TestCase class EmailTest(TestCase): def test_send_email...
Adding model-wide help text to a django model's admin form
3,728,617
32
2010-09-16T16:20:20Z
3,728,785
43
2010-09-16T16:41:21Z
[ "python", "django", "django-models", "django-admin" ]
In my django app, I would like to be able to add customized help text to the admin change form for some of my models. Note I'm not talking about the field specific `help_text` attribute that I can set on individual fields. For example, at the top of the change form for `My_Model` in `My_App` I'd like to be able to add ...
Use the admin's [fieldsets](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fieldsets): ``` class MyAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('first', 'second', 'etc'), 'description': "This is a set of fields group into a fiel...