text
stringlengths
226
34.5k
Is it possible to coerce 0x11 to 0x00, keeping 0x01 -> 0x01 and 0x -> 10 using only bitwise operations? Question: Is it possible to implement a function that results in this mapping: { (0x01, 0x01), (0x10, 0x10), (0x11, 0x00) } Using only bitwise operations? ## Context In the Flixel framework, there are a set of four constants, FlxObject.LEFT:uint = 0x0001; FlxObject.RIGHT:uint = 0x0010; FlxObject.UP:uint = 0x0100; FlxObject.DOWN:uint = 0x1000; Obviously designed to be manipulated with bitwise operators. I was trying to write a function, using only bitwise operators, that would return the opposite direction of whatever was passed in (in terms of these FlxObject constants). Some example mappings: { (0x0110, 0x1001), (0x0100, 0x1000), (0x1010, 0x0101), (0x0001, 0x0010), (0x1100, 0x0000) } The problem is, my solution tends to break down when you pass it something like 0x0011, 0x1100, 0x1110 and similar, and requires a check against this case. Testing code here (also at <http://pastie.org/3420169>): #!/usr/bin/env python from sys import stdout from os import linesep # Implementation without conditional def horiz(dir): return(dir ^ 0x0011 ^ 0x1100) & 0x0011 def vert(dir): return (dir ^ 0x1100 ^ 0x0011) & 0x1100 def oppositeDirection(dir): return horiz(dir) | vert(dir) # Implementation with conditional def horizFix(dir): dir = horiz(dir) return dir if dir != 0x0011 else 0 def vertFix(dir): dir = vert(dir) return dir if dir != 0x1100 else 0 def oppositeDirectionFix(dir): return horizFix(dir) | vertFix(dir) failcount = 0 testcount = 0 def test(dir, expect, func): global failcount, testcount testcount += 1 result = func(dir) stdout.write('Testing: {0:04x} => {1:04x}'.format(dir, result)) if result != expect: stdout.write('\t GOT {0:04x} expected {1:04x}'.format(result, expect)) failcount += 1 stdout.write(linesep) test_cases =[0x0000, 0x0001, 0x0010, 0x0100, 0x1000, 0x0011, 0x0101, 0x1001, 0x0110, 0x1010, 0x1100, 0x0111, 0x1011, 0x1101, 0x1110, 0x1111] print 'Testing full oppositeDirection function----------------' for case in test_cases: test(case, oppositeDirectionFix(case), oppositeDirection) print '\nTesting horiz function---------------------------------' for case in test_cases: test(case, horizFix(case), horiz) print '\nTesting vert function----------------------------------' for case in test_cases: test(case, vertFix(case), vert) print '{0}Succeeded: {2}/{1}, Failed: {3}/{1}'.format(linesep, testcount, testcount - failcount, failcount) If you run the test, you'll see that in the cases like 0x0011 and 0x0000 horiz will return 0x0011, and for 0x1100 and 0x000 vert will return 0x1100. So close! This is clearly an incredibly insignificant problem, and there will never be any situation in my game code where a direction value would be simultaneously left and right or up and down. But, I'm taking this as an opportunity to hone my bit twiddling skills. Is there some logic principle I'm missing here that will help me either solve it or realize it's an unsolvable problem? Answer: No, you have to make some kind of test because your result depends on two adjacent bits. You could use `XOR` with `1111` and then test if the result contains `1100` or `0011`. But since you only have 16 values to verify would it not be simpler to make a switch/select/match function for the 8 valid values?
Performance issues with Django Question: I'm trying to track down some performance issues I have had with Django. There seems to be a 600-800 ms delay from the time I click refresh to the time the browser gets a response. I set up a simple view and the profile middleware and this is the view and results: the view function: def test(request): return HttpResponse("It works") The profile results( i used <http://www.djangosnippets.org/snippets/186/>): 9 function calls in 0.000 CPU seconds Ordered by: internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 /usr/local/lib/python2.6/dist-packages/Django-1.3.1-py2.6.egg/django/http/__init__.py:487(__init__) 1 0.000 0.000 0.000 0.000 /home/mysite/mysite/mysite/map/views.py:19(test) 1 0.000 0.000 0.000 0.000 /usr/local/lib/python2.6/dist-packages/Django-1.3.1-py2.6.egg/django/http/__init__.py:532(__setitem__) 3 0.000 0.000 0.000 0.000 /usr/local/lib/python2.6/dist-packages/Django-1.3.1-py2.6.egg/django/http/__init__.py:517(_convert_to_ascii) 2 0.000 0.000 0.000 0.000 /usr/local/lib/python2.6/dist-packages/Django-1.3.1-py2.6.egg/django/utils/functional.py:274(__getattr__) 1 0.000 0.000 0.000 0.000 /usr/lib/python2.6/Cookie.py:573(__init__) 0 0.000 0.000 profile:0(profiler) ---- By file ---- tottime 0.0% 0.000 /usr/local/lib/python2.6/dist-packages/Django-1.3.1-py2.6.egg/django/utils/functional.py 0.0% 0.000 /usr/local/lib/python2.6/dist-packages/Django-1.3.1-py2.6.egg/django/http/__init__.py 0.0% 0.000 /usr/lib/python2.6/Cookie.py 0.0% 0.000 /home/mysite/mysite/mysite/map/views.py ---- By group --- tottime 0.0% 0.000 /usr/local/lib/python2.6/dist-packages/Django-1.3.1-py2.6.egg/django/utils 0.0% 0.000 /usr/local/lib/python2.6/dist-packages/Django-1.3.1-py2.6.egg/django/http 0.0% 0.000 /usr/lib/python2.6 0.0% 0.000 /home/mysite/mysite/mysite/map So with that, the profiler isn't returning any numbers, yet Chrome reports a 647 ms delay from requesting the resource to actually getting any response. My ping time to the server is about 50 ms. Any ideas how I can get better profiling so I can see where in Django is causing this slowdown? My WSGI config. I'm using Cherokee with uwsgi. import os import sys path = '/home/mysite/mysite/mysite/' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() I see this delay(within 20 ms) on different computers as well as different networks. I'm also seeing it when I just use manage.py runserver. Answer: Looks like you python interpreter gets reloaded for every request. My guess: The delay happens before the profiling. If you use mod_wsgi, what is your maximum-requests setting? What does your wsgi configuration look like? Or, you use a lot of JavaScript and the delay is in your browser.
Code still runs using old version of Python Question: I have installed python 2.7 on my CentOS server. When I go into the python command line it tells me I'm using 2.7. When I issue a python -v command it reports 2.7. But when I run the script I'm working on and get it to output the version (using import sys print(sys.version)) in use it reports the old version (2.4). Can anyone help me get it to run the code against the new version. Thanks. Answer: Check the first line of your script. The [shebang](http://en.wikipedia.org/wiki/Shebang_%28Unix%29) line (first in the script) will explain to your shell which interpreter it should use in order to execute the contents of the file. When I write scripts for myself I usually use: `#!/usr/bin/env python` Which uses which ever python interpreter is in my environment settings. Since I use `virtualenv`, this is a local customized version of my python install by default, but can be easily switched based on context.
Update list of dictionaries elementwise in Python Question: Say we have a list of dictionaries in Python: A = [{'x': 1, 'y': 2, 'z': 3},{'x': 0, 'y': 10, 'z': 11}] We pick out the 'x'-values using `map()` x = map((lambda i: i['x']), A) and do something with them. Now, what is the cleanest way to update all the `'x'`-values of `A` in a comparable way - ie., without using a for-loop? Answer: >>> r = [{'x': 1, 'y': 2, 'z': 3},{'x': 0, 'y': 10, 'z': 11}] >>> r [{'y': 2, 'x': 1, 'z': 3}, {'y': 10, 'x': 0, 'z': 11}] >>> [i.__setitem__('x', 10) for i in r] [None, None] >>> r [{'y': 2, 'x': 10, 'z': 3}, {'y': 10, 'x': 10, 'z': 11}] It's not horrible, but I think a for loop would be nicer. I'd only do this if 'r' were really large and performance is super important.
Stripping chars in python Question: I know this is not very pretty code and that I'm sure there is an easier way but I'm more concerned on why python is not stripping the characters I requested it to. import urllib, sgmllib zip_code = raw_input('Give me a zip code> ') url = 'http://www.uszip.com/zip/' + zip_code print url conn = urllib.urlopen('http://www.uszip.com/zip/' + zip_code) i = 0 while i < 1000: for line in conn.fp: if i == 1: print line[7:-10] i += 1 elif i == 344: line1 = line.strip() line2 = line1.strip('<td>') #its not stripping the characters print line2[17:-60] i += 1 else: i += 1 Answer: The way you call it, it should remove any occurrence of the `<`, `>`, `t`, and `d` characters, and [_only at the beginning or end of the string_](http://docs.python.org/library/string.html#string.strip): >>> '<p>some test</p>'.strip('<td>') 'p>some test</p' If you want to remove every occurrence of the substring `<td>`, use [`replace`](http://docs.python.org/library/string.html#string.replace): >>> '<td>some test</td>'.replace('<td>', '') 'some test</td>' Note that if you want to use that for some kind of input sanitization, it can be easily circumvented: >>> '<td<td>>some test</td>'.replace('<td>', '') '<td>some test</td>' This is only one of many ways how people typically get screwed if they try to write their own HTML parsing code, so maybe you rather want to use a HTML parsing library like [`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/) or an XML parser like [`lxml`](http://lxml.de/).
Configuring Script Handlers Google App Engine Question: I am trying to make a simple application using Google App Engine. Below is my code `helloworld.py` print "hello" class helloworld(): def myfunc(self): st = "inside class" return st `test.py` import helloworld hw_object = helloworld.helloworld() print hw_object.myfunc() `app.yaml` handlers: - url: /.* script: helloworld.py - url: /.* script: test.py When I run my application via `http://localhost:10000` it prints only `hello` whereas my expected output is `hello` and `inside class`. My directory structure E:\helloworld>dir app.yaml helloworld.py test.py I am pretty sure this has something to do with [Script Handlers](http://code.google.com/appengine/docs/python/config/appconfig.html#Script_Handlers).So, what is the correct way to define handlers and what is wrong in my way of defining them. Answer: When your first handler pattern `/.*` matches `http://localhost:10000`, the remaining handlers are all ignored. You can updated your `app.yaml` handlers: - url: /hello script: helloworld.py - url: /test script: test.py And browse `http://localhost:10000/test`
How to plot cdf in matplotlib in Python? Question: I have a disordered list named `d` that looks like: [0.0000, 123.9877,0.0000,9870.9876, ...] I just simply want to plot a cdf graph based on this list by using Matplotlib in Python. But don't know if there's any function I can use d = [] d_sorted = [] for line in fd.readlines(): (addr, videoid, userag, usertp, timeinterval) = line.split() d.append(float(timeinterval)) d_sorted = sorted(d) class discrete_cdf: def __init__(data): self._data = data # must be sorted self._data_len = float(len(data)) def __call__(point): return (len(self._data[:bisect_left(self._data, point)]) / self._data_len) cdf = discrete_cdf(d_sorted) xvalues = range(0, max(d_sorted)) yvalues = [cdf(point) for point in xvalues] plt.plot(xvalues, yvalues) Now I am using this code, but the error message is : Traceback (most recent call last): File "hitratioparea_0117.py", line 43, in <module> cdf = discrete_cdf(d_sorted) TypeError: __init__() takes exactly 1 argument (2 given) Answer: As mentioned, `cumsum` from `numpy` works well. Make sure that your data is a proper PDF (ie. sums to one), otherwise the CDF won't end at unity [as it should](http://en.wikipedia.org/wiki/Cumulative_distribution_function). Here is a minimal working example: import numpy as np from pylab import * # Create some test data dx = .01 X = np.arange(-2,2,dx) Y = exp(-X**2) # Normalize the data to a proper PDF Y /= (dx*Y).sum() # Compute the CDF CY = np.cumsum(Y*dx) # Plot both plot(X,Y) plot(X,CY,'r--') show() ![enter image description here](http://i.stack.imgur.com/ci2ym.png)
Why is splitting a string slower in C++ than Python? Question: I'm trying to convert some code from Python to C++ in an effort to gain a little bit of speed and sharpen my rusty C++ skills. Yesterday I was shocked when a naive implementation of reading lines from stdin was much faster in Python than C++ (see [this](http://stackoverflow.com/questions/9371238/why-is- reading-lines-from-stdin-much-slower-in-c-than-python)). Today, I finally figured out how to split a string in C++ with merging delimiters (similar semantics to python's split()), and am now experiencing deja vu! My C++ code takes much longer to do the work (though not an order of magnitude more, as was the case for yesterday's lesson). **Python Code:** #!/usr/bin/env python from __future__ import print_function import time import sys count = 0 start_time = time.time() dummy = None for line in sys.stdin: dummy = line.split() count += 1 delta_sec = int(time.time() - start_time) print("Python: Saw {0} lines in {1} seconds. ".format(count, delta_sec), end='') if delta_sec > 0: lps = int(count/delta_sec) print(" Crunch Speed: {0}".format(lps)) else: print('') **C++ Code:** #include <iostream> #include <string> #include <sstream> #include <time.h> #include <vector> using namespace std; void split1(vector<string> &tokens, const string &str, const string &delimiters = " ") { // Skip delimiters at beginning string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first non-delimiter string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters lastPos = str.find_first_not_of(delimiters, pos); // Find next non-delimiter pos = str.find_first_of(delimiters, lastPos); } } void split2(vector<string> &tokens, const string &str, char delim=' ') { stringstream ss(str); //convert string to stream string item; while(getline(ss, item, delim)) { tokens.push_back(item); //add token to vector } } int main() { string input_line; vector<string> spline; long count = 0; int sec, lps; time_t start = time(NULL); cin.sync_with_stdio(false); //disable synchronous IO while(cin) { getline(cin, input_line); spline.clear(); //empty the vector for the next line to parse //I'm trying one of the two implementations, per compilation, obviously: // split1(spline, input_line); split2(spline, input_line); count++; }; count--; //subtract for final over-read sec = (int) time(NULL) - start; cerr << "C++ : Saw " << count << " lines in " << sec << " seconds." ; if (sec > 0) { lps = count / sec; cerr << " Crunch speed: " << lps << endl; } else cerr << endl; return 0; //compiled with: g++ -Wall -O3 -o split1 split_1.cpp Note that I tried two different split implementations. One (split1) uses string methods to search for tokens and is able to merge multiple tokens as well as handle numerous tokens (it comes from [here](http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming- HOWTO-7.html)). The second (split2) uses getline to read the string as a stream, doesn't merge delimiters, and only supports a single delimeter character (that one was posted by several StackOverflow users in answers to string splitting questions). I ran this multiple times in various orders. My test machine is a Macbook Pro (2011, 8GB, Quad Core), not that it matters much. I'm testing with a 20M line text file with three space-separated columns that each look similar to this: "foo.bar 127.0.0.1 home.foo.bar" **Results:** $ /usr/bin/time cat test_lines_double | ./split.py 15.61 real 0.01 user 0.38 sys Python: Saw 20000000 lines in 15 seconds. Crunch Speed: 1333333 $ /usr/bin/time cat test_lines_double | ./split1 23.50 real 0.01 user 0.46 sys C++ : Saw 20000000 lines in 23 seconds. Crunch speed: 869565 $ /usr/bin/time cat test_lines_double | ./split2 44.69 real 0.02 user 0.62 sys C++ : Saw 20000000 lines in 45 seconds. Crunch speed: 444444 What am I doing wrong? Is there a better way to do string splitting in C++ that does not rely on external libraries (i.e. no boost), supports merging sequences of delimiters (like python's split), is thread safe (so no strtok), and whose performance is at least on par with python? **Edit 1 / Partial Solution?:** I tried making it a more fair comparison by having python reset the dummy list and append to it each time, as C++ does. This still isn't exactly what the C++ code is doing, but it's a bit closer. Basically, the loop is now: for line in sys.stdin: dummy = [] dummy += line.split() count += 1 The performance of python is now about the same as the split1 C++ implementation. /usr/bin/time cat test_lines_double | ./split5.py 22.61 real 0.01 user 0.40 sys Python: Saw 20000000 lines in 22 seconds. Crunch Speed: 909090 I still am surprised that, even if Python is so optimized for string processing (as Matt Joiner suggested), that these C++ implementations would not be faster. If anyone has ideas about how to do this in a more optimal way using C++, please share your code. (I think my next step will be trying to implement this in pure C, although I'm not going to trade off programmer productivity to re-implement my overall project in C, so this will just be an experiment for string splitting speed.) Thanks to all for your help. **Final Edit/Solution:** Please see Alf's accepted answer. Since python deals with strings strictly by reference and STL strings are often copied, performance is better with vanilla python implementations. For comparison, I compiled and ran my data through Alf's code, and here is the performance on the same machine as all the other runs, essentially identical to the naive python implementation (though faster than the python implementation that resets/appends the list, as shown in the above edit): $ /usr/bin/time cat test_lines_double | ./split6 15.09 real 0.01 user 0.45 sys C++ : Saw 20000000 lines in 15 seconds. Crunch speed: 1333333 My only small remaining gripe is regarding the amount of code necessary to get C++ to perform in this case. One of the lessons here from this issue and yesterday's stdin line reading issue (linked above) are that one should always benchmark instead of making naive assumptions about languages' relative "default" performance. I appreciate the education. Thanks again to all for your suggestions! Answer: As a guess, Python strings are reference counted immutable strings, so that no strings are copied around in the Python code, while C++ `std::string` is a mutable value type, and is copied at the smallest opportunity. If the goal is fast splitting, then one would use constant time substring operations, which means only _referring_ to parts of the original string, as in Python (and Java, and C#…). The C++ `std::string` class has one redeeming feature, though: it is _standard_ , so that it can be used to pass strings safely and portably around where efficiency is not a main consideration. But enough chat. Code -- and on my machine this is of course faster than Python, since Python's string handling is implemented in C which is a subset of C++ (he he): #include <iostream> #include <string> #include <sstream> #include <time.h> #include <vector> using namespace std; class StringRef { private: char const* begin_; int size_; public: int size() const { return size_; } char const* begin() const { return begin_; } char const* end() const { return begin_ + size_; } StringRef( char const* const begin, int const size ) : begin_( begin ) , size_( size ) {} }; vector<StringRef> split3( string const& str, char delimiter = ' ' ) { vector<StringRef> result; enum State { inSpace, inToken }; State state = inSpace; char const* pTokenBegin = 0; // Init to satisfy compiler. for( auto it = str.begin(); it != str.end(); ++it ) { State const newState = (*it == delimiter? inSpace : inToken); if( newState != state ) { switch( newState ) { case inSpace: result.push_back( StringRef( pTokenBegin, &*it - pTokenBegin ) ); break; case inToken: pTokenBegin = &*it; } } state = newState; } if( state == inToken ) { result.push_back( StringRef( pTokenBegin, &*str.end() - pTokenBegin ) ); } return result; } int main() { string input_line; vector<string> spline; long count = 0; int sec, lps; time_t start = time(NULL); cin.sync_with_stdio(false); //disable synchronous IO while(cin) { getline(cin, input_line); //spline.clear(); //empty the vector for the next line to parse //I'm trying one of the two implementations, per compilation, obviously: // split1(spline, input_line); //split2(spline, input_line); vector<StringRef> const v = split3( input_line ); count++; }; count--; //subtract for final over-read sec = (int) time(NULL) - start; cerr << "C++ : Saw " << count << " lines in " << sec << " seconds." ; if (sec > 0) { lps = count / sec; cerr << " Crunch speed: " << lps << endl; } else cerr << endl; return 0; } //compiled with: g++ -Wall -O3 -o split1 split_1.cpp -std=c++0x Disclaimer: I hope there aren't any bugs. I haven't tested the functionality, but only checked the speed. But I think, even if there is a bug or two, correcting that won't significantly affect the speed.
Compare RPM Packages using Python Question: I'm trying to compare a csv file containing required Linux packages with the current installed packages. The comparison should output any packages not installed or newer than the current installed packages. The problem is that I'm unable to loop through the list of installed packages and show all hits, for instance packages with the same name and version, but different architecture should be shown twice(for instance compat- libstdc++-33), but I only getting the first hit with the script below. #!/usr/bin/python import rpm import csv import sys import os ''' Script to check installed rpms against a csv file containing the package name and version similar to the list below: atk,1.12.2 libart_lgpl,2.3 info,4.9 libsepol,1.15.2 libusb,0.1.12 libfontenc,1.4.2 ''' if len(sys.argv) !=2: print '' print 'Usage: ', sys.argv[0], '/path/to/csv_input_file' print '' sys.exit(1) if not os.path.isfile(sys.argv[1]): print '' print sys.argv[1], 'not found!' print '' sys.exit(1) else: input_csv = sys.argv[1] pkgRequired = csv.reader(open(input_csv),delimiter=',') pkgInstalledName = [] pkgInstalledVersion = [] pkgInstalledArch = [] ts = rpm.TransactionSet() mi = ts.dbMatch() for h in mi: pkgInstalledName.append((h['name'])) pkgInstalledVersion.append((h['version'])) pkgInstalledArch.append((h['arch'])) for row in pkgRequired: pkgRequiredName = row[0] pkgRequiredVersion = row[1] #pkgRequiredArch = row[2] if pkgRequiredName in pkgInstalledName: if pkgInstalledVersion[pkgInstalledName.index(pkgRequiredName)] >= pkgRequiredVersion: pass else: print '\nInstalled: ',pkgInstalledName[pkgInstalledName.index(pkgRequiredName)], pkgInstalledVersion[pkgInstalledName.index(pkgRequiredName)], pkgInstalledArch[pkgInstalledName.index(pkgRequiredName)], ' \nRequired: ', ' ', pkgRequiredName,pkgRequiredVersion Answer: Assuming that there's no problem with the way that you're reading the list of installed packages (I'm not familiar with the rpm module), then your only problem is with using the index() function. This function return the first occurrence of an item with the specified value - and it isn't what you want. A correct implementation (which is also much more efficient) would be: installedPackages = {} #create a hash table, mapping package names to LISTS of installed package versions and architectures for h in mi: l = installedPackages.get(h['name'], list()) #return either the existing list, or a new one if this is the first time that the name appears. l.append( (h['version'], h['arch']) ) ... if requiredPackageName in installedPackages: for ver, arch in installedPackages[requiredPackageName]: print ...
Python OptionMenus keep disappearing and reappearing - how can I make them "stay"? Question: I have a simple school assignment to do - a converter between F, C and K. I'm having problems with OptionMenus, because they keep disappearing and reappearing when I move over with the mouse. For example if I choose from OptionMenu2, OptionMenu1 will disappear. How can I make them "stay"? Code includes 2 pictures. If you want to run the code, you'll need one for button. You can probably just delete the one on top :) I'll appreciate any help on this! # -*- coding: cp1250 -*- from Tkinter import * import tkMessageBox import tkFont from array import * from decimal import Decimal class MojGUI(Frame): def __init__(self, master=None): Frame.__init__(self, master) ##NASLOV image1 = PhotoImage(file="naslov.gif") panel1 = Label(root, image=image1,background="#FFFFFF",height=50,width=400) panel1.pack(side=TOP) panel1.image = image1 panel2 = Label(root,background="#FFFFFF") panel2.pack(side=TOP) self.vnesibesedilofont = tkFont.Font(family="Verdana",size=16,weight="bold") ##VPIS CIFRE self.entryfont = tkFont.Font(family="Verdana",size=14,weight="bold") self.entryWidget = Entry(panel2, width="4",font=self.entryfont,foreground="#FFFFFF", background="#bb0000") self.entryWidget.pack(side=LEFT) ##ENOTA1 self.text1 = StringVar(master) self.text1.set("C") # default value self.enota1 = OptionMenu(panel2, self.text1, "C", "F", "K") self.enota1.pack(side=LEFT) ##ENACAJ self.enacaj = tkFont.Font(family="Verdana",size=16,weight="bold") self.znak = StringVar() self.znak.set(" = ") self.entryLabel = Label(panel2,textvariable=self.znak, background='#FFFFFF',font=self.enacaj) self.entryLabel.pack(side=LEFT) ##VREDNOST self.textvrednost = StringVar() self.vredno = tkFont.Font(family="Verdana",size=14,weight="bold") self.vrednost = Label(panel2,textvariable=self.textvrednost, width="9", foreground='#000000',background='#FFFFFF',font=self.vredno) self.vrednost.pack(side=LEFT) self.textvrednost.set("") ##ENOTA2 self.text2 = StringVar(panel2) self.text2.set("C") # default value self.enota2 = OptionMenu(panel2, self.text2, "C", "F", "K") self.enota2.pack(side=LEFT) ##GUMB image2 = PhotoImage(file="pretvori.gif") entryButton = Button(panel2,text="",bd="0",cursor="hand2",background='#FFFFFF',activebackground="#FFFFFF",command=self.pretvori,image=image2) entryButton.pack(side=LEFT) entryButton.image = image2 self.pack() def pretvori(self): enota1=self.text1.get() enota2=self.text2.get() original=Decimal(self.entryWidget.get()) rezultat= StringVar() rezultat.set(str(original)) if (enota1 == "C") &(enota2 == "K"): rezultat.set(str(round(original+273,2))) if (enota2 == "C") &(enota1 == "K"): rezultat.set(str(round(original-273,2))) if (enota1 == "K") &(enota2 == "F"): rezultat.set(str(round( Decimal(original-273) * Decimal(1.8)+32 ,2))) if (enota2 == "K") &(enota1 == "F"): rezultat.set(str(round( Decimal(original-32) / Decimal(1.8)+273 ,2))) if (enota1 == "C") &(enota2 == "F"): rezultat.set(str(round(original*Decimal(1.8)+32,2))) if (enota2 == "C") &(enota1 == "F"): rezultat.set(str(round((original-32)/Decimal(1.8),2))) self.textvrednost.set(rezultat.get()) self.znak.set(" = ") root = Tk() root.title('Pretvornik') root.wm_minsize(500, 200) root.wm_resizable(0, 0) w = root.winfo_screenwidth() h = root.winfo_screenheight() rootsize = tuple(int(_) for _ in root.geometry().split('+')[0].split('x')) x = (w - 500)/2 y = (h - 200)/2 root.geometry("%dx%d+%d+%d" % (rootsize + (x, y))) root.config(background="#FFFFFF") app = MojGUI(master=root) root.mainloop() Answer: You are doing something very unusual when you use a label as a container for other widgets. The label is not an appropriate widget to use as a container for other widgets. While this should be allowable, it apparently is causing the behavior that you are seeing. If you change panel1 and panel2 to be frames rather than labels, your problem goes away.
How can I find circular relations in a graph with Python and Networkx? Question: Consider I have the following graph: A -> B B -> C C -> D C -> A What is the easiest way to find that A -> B -> C -> A is a circular relation? Is there such a function already built into NetworkX or another easy to use Python library? Answer: [`networkx.simple_cycles`](http://networkx.lanl.gov/reference/generated/networkx.algorithms.cycles.simple_cycles.html#networkx.algorithms.cycles.simple_cycles) does this for you. >>> import networkx as nx >>> G = nx.DiGraph() >>> G.add_edge('A', 'B') >>> G.add_edge('B', 'C') >>> G.add_edge('C', 'D') >>> G.add_edge('C', 'A') >>> nx.simple_cycles(G) [['A', 'B', 'C', 'A']]
Python thread restart Question: I have a thread when it is run it has an infinite loop. When another thread is stopped, I wish to reset all the threads again, There threads have sockets that transfer data between each other. I am using node1._Thread__stop() function to stop the thread runing, but when I try to create a new thread with the same name: node1 = node.node(8081,8082,token,1,"Node A",0) node1.start() It gives out an error [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted. I am not sure if the stop function worked on the threads, because I have a timeout clause for a socket that if it doesn't receive anything to print timeout. This prints after the error occured. What would be a better reset of a thread/socket Answer: I'm not sure about what are you looking for. However, I recommend you to have a look at this [answer](http://stackoverflow.com/a/325528/183066) to a related question. The important point is that isn't a good idea to terminate a thread when it's holding a resource such as a socket as in your case. The right way to do it would be to use any of the synchronization mechanisms (the answer referenced above uses an example with `threading.Event`, but it could be, for example, a `threading.Condition` if it suits your needs better) available to release the resource or, as it seems you need, reset some internal data to start from scratch. I hope this helps.
writing text area in python, implementing sockets Question: I am doing a simulation of a print server in python, files are sent using sockets to a server which has to be placed in a printer queue. When the client initiates communication with the server must provide an ID (user) and PASSWORD, which will be checked against a list on the server can be verified in a file "passwordlist.txt" which has the following format: akira Aaron alazrea Ababa alexander Abbott andy Abe andycapp Abel anxieties Abelian anxiety Abelson bailey Aberdeen batman robin bd Abidjan Both programs must have a graphical interface on the display: * Client: user field, password, file to send to print and disconnect from the server. * Server: A list of files that are queued for printing On the server should be displayed a list of files that have been properly sent to the queue for printing. For this I decided to use a "text area" but I have a problem, only shows me the first file in the command to print text area, when the client terminates the connection and if another client tries to connect to the server just crash the program does and does absolutely nothing. What am I doing wrong? I think the problem is that i'm putting part of the instruction code "root.mainloop ()", i have this doubt. how can resolve this failure? im stuck With This..thanks to all Here's the Client Code: #! /python26/python.exe #! -*- coding: utf-8 -*- from Tkinter import * import Tkinter, Tkconstants, tkFileDialog import Tkinter import sys import socket import tkMessageBox flag = False class Exit_Button(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) self.pack() self.widget1() def salir(): root.destroy() def adjuntar_imprimir(): global flag if (flag==False): tkMessageBox.showinfo("Error", "You must login") salir () else: # get filename filename = tkFileDialog.askopenfilename(**file_opt) # open file on your own if filename: s.send (filename) f= open(filename, 'rb') l = f.read(1024) while (l): s.send(l) l = f.read(512) def iniciar_sesion(): global flag #invoco el metodo connect del socket pasando como parametro la tupla IP , puerto login = value.get() password = value_2.get() if ((len(login) == 0) or (len(password)) == 0): tkMessageBox.showinfo("Error", "insert correct login and password") salir () else: s.send(login) s.send(password) recibido = s.recv(1024) tkMessageBox.showinfo("Notify", recibido) if (recibido=="Error Check user & Password"): salir () else: flag = True ##@@--------------------------------------------------------------------------------@@## root = Tk() s = socket.socket() s.connect(("localhost", 9999)) # define options for opening or saving a file file_opt = options = {} options['defaultextension'] = '' # couldn't figure out how this works options['filetypes'] = [('all files', '.*'), ('text files', '.txt')] options['initialdir'] = 'C:\\' options['initialfile'] = 'myfile.txt' options['parent'] = root options['title'] = 'This is a title' frame = Frame(root) frame.pack(side=LEFT) frame.master.title("Servicio de impresion") value = StringVar() value_2 = StringVar() w = Label(root, text="User Name", fg="red") w.pack(side = LEFT) entry_1 = Entry(root, textvariable=value_2, bd =5, show="*") entry_1.pack(side = RIGHT) z= Label(root, text="Password", fg="red") z.pack(side = RIGHT) entry_0 = Entry(root, textvariable=value, bd =5) entry_0.pack(side = RIGHT) ##---------------login---------------- button_0= Button (frame, text = "login", command= iniciar_sesion, bg='black', foreground ="red") button_0.pack() ##--------------Attach and print File------------ button_3 = Button (frame, text= "print", command=adjuntar_imprimir, bg='black',foreground ="red") button_3.pack(side=LEFT) ##-----------------Exit------------------------ button_1 = Button(frame, text= "exit", command=salir, bg='black', foreground ="red") button_1.pack() root.mainloop() The Server Code: from Tkinter import * import Tkinter, Tkconstants, tkFileDialog import Tkinter import sys import socket import tkMessageBox def onclick(): pass root = Tk() root.title("Print Server") text = Text(root, width=60, height=30) text.pack() s = socket.socket() s.bind(("localhost", 9999)) s.listen(100) i=0 while (True): sc, address = s.accept() print "Connection from: ", address recibido1 = sc.recv(1024) recibido2 = sc.recv(1024) print "login:", recibido1, "password:", recibido2 salida = (str(recibido1)+" "+str(recibido2)+"\n") archivo = open("passwordlist.txt", "r") while True: linea = archivo.readline() #Leo del archivo if (salida==linea): log_ok ="login ok" sc.send(log_ok) break if (len(linea))==0: error= "Error Check user & Password" sc.send(error) break f = open('print_'+ str(i)+".pdf",'wb') #abierto en escritura binaria i=i+1 # recibimos y escribimos en el fichero nombre_archivo = sc.recv(1024) cadena = "On Impresion Queue.."+nombre_archivo+"\n" text.insert(INSERT, cadena) print "On impresion Queue.."+nombre_archivo l = sc.recv(1024) while (l): f.write(l) l = sc.recv(1024) if not l: notification= "Complete transfer" sc.send(notification) break f.close() sc.close() root.mainloop() s.close() The program does not tell me any error just when another client tries to login, the client interface is doing nothing. Answer: I don't know why it crashes, but I know why only one client can connect. Your server just isn't designed to handle multiple clients. When one client connects, all the server does is listen to that client - any other client trying to connect is simply ignored. The solution is simple: Multithreading. Spawn a new thread for each connecting client, and let the "main" thread accept new connections. The resulting "while(True)" loop should look somewhat like this: from threading import Thread tkinterThread= Thread(target=Tk.mainloop, args=[root])#spawn a new Thread object tkinterThread.start()#make the thread execute the tkinter mainloop #please note: I'm not sure if the two lines above actually work; I can't test them because Tkinter won't work for me. def listenToClient(sc, address): recibido1 = sc.recv(1024) recibido2 = sc.recv(1024) print "login:", recibido1, "password:", recibido2 salida = (str(recibido1)+" "+str(recibido2)+"\n") archivo = open("passwordlist.txt", "r") while True: linea = archivo.readline() #Leo del archivo if (salida==linea): log_ok ="login ok" sc.send(log_ok) break if (len(linea))==0: error= "Error Check user & Password" sc.send(error) break f = open('print_'+ str(i)+".pdf",'wb') #abierto en escritura binaria i=i+1 # recibimos y escribimos en el fichero nombre_archivo = sc.recv(1024) cadena = "On Impresion Queue.."+nombre_archivo+"\n" text.insert(INSERT, cadena) print "On impresion Queue.."+nombre_archivo l = sc.recv(1024) while (l): f.write(l) l = sc.recv(1024) if not l: notification= "Complete transfer" sc.send(notification) break f.close() sc.close() while (True): sc, address = s.accept() print "Connection from: ", address clientThread= Thread(target=listenToClient, args=[sc,address])#spawn a new thread object clientThread.start()#start the thread; it'll execute the "listenToClient" function, passing it "sc" and "address" as arguments This code will (well, should) spawn a thread that takes care of the GUI, meanwhile it'll accept connection requests from clients and spawn a new thread for every client, which checks the client's username and password, and then keeps listening until the client disconnects.
Python: How do I parse HTML of a webpage that requires being logged in? Question: I'm trying to parse the HTML of a webpage that requires being logged in. I can get the HTML of a webpage using this script: from urllib2 import urlopen from BeautifulSoup import BeautifulSoup import re webpage = urlopen ('https://www.example.com') soup = BeautifulSoup (webpage) print soup #This would print the source of example.com But trying to get the source of a webpage that I'm logged into proves to be more difficult. I tried replacing the ('https://www.example.com') with ('https://user:[email protected]') but I got an Invalid URL error. Anyone know how I could do this? Thanks in advance. Answer: Selenium WebDriver ( <http://seleniumhq.org/projects/webdriver/> ) might be good for your needs here. You can log in to the page and then print the contents of the HTML. Here's an example: from selenium import webdriver # initiate driver = webdriver.Firefox() # initiate a driver, in this case Firefox driver.get("http://example.com") # go to the url # log in username_field = driver.find_element_by_name(...)) # get the username field password_field = driver.find_element_by_name(...)) # get the password field username_field.send_keys("username") # enter in your username password_field.send_keys("password") # enter in your password password_field.submit() # submit it # print HTML html = driver.page_source print html
losing locale when running fcgi script Question: I'm facing an issue with encoding in running a django app. I finally found out my django app has no locale set. The weird thing is that I did set up the envvars file correctly. With this in envvars : export APACHE_RUN_USER=www-data export APACHE_RUN_GROUP=www-data export APACHE_PID_FILE=/var/run/apache2.pid ## The locale used by some modules like mod_dav export LANG=C ## Uncomment the following line to use the system default locale instead: . /etc/default/locale export LANG locale When I restart apache the locale command gets executed and I get correct fr_FR.UTF-8 settings for LANG and LC_*. Now I set up a little test.fcgi script : #!/usr/bin/python def myapp(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) from commands import getoutput return ["%s"%getoutput("locale")] from flup.server.fcgi import WSGIServer WSGIServer(myapp).run() when I run it with sudo -u www-data test.fcgi I get the correct locale settings as well. But whenever I access the script through a web browser, I get no locale settings : LANG= LC_CTYPE="POSIX" LC_NUMERIC="POSIX" LC_TIME="POSIX" LC_COLLATE="POSIX" LC_MONETARY="POSIX" LC_MESSAGES="POSIX" LC_PAPER="POSIX" LC_NAME="POSIX" LC_ADDRESS="POSIX" LC_TELEPHONE="POSIX" LC_MEASUREMENT="POSIX" LC_IDENTIFICATION="POSIX" LC_ALL= How come Apache has the right setting but my fcgi script hasn't? Answer: I solved it by adding `DefaultInitEnv LANG "en_US.UTF-8"` in my `sites- available/default`. Now the fcgi script tells me UTF-8 !
Suds generates empty elements; how to remove them? Question: [Major Edit based on experience since 1st post two days ago.] I am building a Python SOAP/XML script using Suds, but am struggling to get the code to generate SOAP/XML that is acceptable to the server. I had thought that the issue was that Suds was not generating prefixes for inner elements, but subsequently it turns out that the lack of prefixes (see `Sh-Data` and inner elements) is not an issue, as the `Sh-Data` and `MetaSwitchData` elements declare appropriate namespaces (see below). <SOAP-ENV:Envelope xmlns:ns3="http://www.metaswitch.com/ems/soap/sh" xmlns:ns0="http://www.metaswitch.com/ems/soap/sh/userdata" xmlns:ns1="http://www.metaswitch.com/ems/soap/sh/servicedata" xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <ns2:Body> <ns3:ShUpdate> <ns3:UserIdentity>Meribel/TD Test Sub Gateway 3</ns3:UserIdentity> <ns3:DataReference>0</ns3:DataReference> <ns3:UserData> <Sh-Data xmlns="http://www.metaswitch.com/ems/soap/sh/userdata"> <RepositoryData> <ServiceIndication>Meta_SubG_BaseInformation</ServiceIndication> <SequenceNumber>0</SequenceNumber> <ServiceData> <MetaSwitchData xmlns="http://www.metaswitch.com/ems/soap/sh/servicedata" IgnoreSequenceNumber="False" MetaSwitchVersion="?"> <Meta_SubG_BaseInformation Action="apply"> <NetworkElementName>Meribel</NetworkElementName> <Description>TD Test Sub Gateway 3</Description> <DomainName>test.datcon.co.uk</DomainName> <MediaGatewayModel>Cisco ATA</MediaGatewayModel> <CallFeatureServerControlStatus/> <CallAgentControlStatus/> <UseStaticNATMapping/> <AuthenticationRequired/> <ProviderStatus/> <DeactivationMode/> </Meta_SubG_BaseInformation> </MetaSwitchData> </ServiceData> </RepositoryData> </Sh-Data> </ns3:UserData> <ns3:OriginHost>[email protected]?clientVersion=7.3</ns3:OriginHost> </ns3:ShUpdate> </ns2:Body> </SOAP-ENV:Envelope> But this still fails. The issue is that Suds generates empty elements for optional elements (marked as `Mandatory = No` in the WSDL). But the server requires that an optional element is either present with a sensible value or absent, and I get the following error (because the `<CallFeatureServerControlStatus/>` element is not one of the allowable values. > The user data provided did not validate against the MetaSwitch XML Schema > for user data. > Details: cvc-enumeration-valid: Value '' is not facet-valid with respect to > enumeration '[Controlling, Abandoned, Cautiously controlling]'. It must be a > value from the enumeration. If I take the generated SOAP/XML into SOAPUI and delete the empty elements, the request works just fine. Is there a way to get Suds to either not generate empty elements for optional fields, or for me to remove them in code afterwards? **Major Update** I have solved this problem (which I've seen elsewhere) but in a pretty inelegant way. So I am posting my current solution in the hope that a) it helps others and/or b) someone can suggest a better work-around. It turns out that the problem was not that Suds generates empty elements for optional elements (marked as `Mandatory = No` in the WSDL). But rather that that Suds generates empty elements for optional **complex** elements. For example the following Meta_SubG_BaseInformation elements are simple elements and Suds does not generate anything for them in the SOAP/XML. <xs:element name="CMTS" type="xs:string" minOccurs="0"> <xs:annotation> <xs:documentation> <d:DisplayName firstVersion="5.0" lastVersion="7.4">CMTS</d:DisplayName> <d:ValidFrom>5.0</d:ValidFrom> <d:ValidTo>7.4</d:ValidTo> <d:Type firstVersion="5.0" lastVersion="7.4">String</d:Type> <d:BaseAccess firstVersion="5.0" lastVersion="7.4">RWRWRW</d:BaseAccess> <d:Mandatory firstVersion="5.0" lastVersion="7.4">No</d:Mandatory> <d:MaxLength firstVersion="5.0" lastVersion="7.4">1024</d:MaxLength> </xs:documentation> </xs:annotation> </xs:element> <xs:element name="TAGLocation" type="xs:string" minOccurs="0"> <xs:annotation> <xs:documentation> <d:DisplayName>Preferred location of Trunk Gateway</d:DisplayName> <d:Type>String</d:Type> <d:BaseAccess>RWRWRW</d:BaseAccess> <d:Mandatory>No</d:Mandatory> <d:DefaultValue>None</d:DefaultValue> <d:MaxLength>1024</d:MaxLength> </xs:documentation> </xs:annotation> </xs:element> In contrast the following Meta_SubG_BaseInformation element is a complex element, and even when it is optional and my code does not assign a value to it, it ends up in the generated SOAP/XML. <xs:element name="ProviderStatus" type="tMeta_SubG_BaseInformation_ProviderStatus" minOccurs="0"> <xs:annotation> <xs:documentation> <d:DisplayName>Provider status</d:DisplayName> <d:Type>Choice of values</d:Type> <d:BaseAccess>R-R-R-</d:BaseAccess> <d:Mandatory>No</d:Mandatory> <d:Values> <d:Value>Unavailable</d:Value> <d:Value>Available</d:Value> <d:Value>Inactive</d:Value> <d:Value>Active</d:Value> <d:Value>Out of service</d:Value> <d:Value>Quiescing</d:Value> <d:Value>Unconfigured</d:Value> <d:Value>Pending available</d:Value> </d:Values> </xs:documentation> </xs:annotation> </xs:element> Suds generates the following for ProviderStatus which (as stated above) upsets my server. <ProviderStatus/> The work-around is to set all `Meta_SubG_BaseInformation` elements to `None` after creating the parent element, and before assigning values, as in the following. This is superfluous for the simple elements, but does ensure that non-assigned complex elements do not result in generated SOAP/XML. subGatewayBaseInformation = client.factory.create('ns1:Meta_SubG_BaseInformation') for (el) in subGatewayBaseInformation: subGatewayBaseInformation.__setitem__(el[0], None) subGatewayBaseInformation._Action = 'apply' subGatewayBaseInformation.NetworkElementName = 'Meribel' etc... This results in Suds generating SOAP/XML without empty elements, which is acceptable to my server. But does anyone know of a cleaner way to achieve the same effect? **Solution below is based on answers / comments from both dusan and Roland Smith below.** This solution uses a Suds MessagePlugin to prune "empty" XML of the form `<SubscriberType/>` before Suds puts the request on the wire. We only need to prune on ShUpdates (where we are updating data on the server), and the logic (especially the indexing down into the children to get the service indication element list) is very specific to the WSDL. It would not work for different WSDL. class MyPlugin(MessagePlugin): def marshalled(self, context): pruned = [] req = context.envelope.children[1].children[0] if (req.name == 'ShUpdate'): si = req.children[2].children[0].children[0].children[2].children[0].children[0] for el in si.children: if re.match('<[a-zA-Z0-9]*/>', Element.plain(el)): pruned.append(el) for p in pruned: si.children.remove(p) And then we just need to reference the plugin when we create the client. client = Client(url, plugins=[MyPlugin()]) Answer: You can use a plugin to modify the XML before is sent to the server (my answer is based on Ronald Smith's solution): from suds.plugin import MessagePlugin from suds.client import Client import re class MyPlugin(MessagePlugin): def sending(self, context): context.envelope = re.sub('\s+<.*?/>', '', context.envelope) client = Client(URL_WSDL, plugins=[MyPlugin()]) Citing the [documentation](https://fedorahosted.org/suds/wiki/Documentation#PLUGINS): > The MessagePlugin currently has (5) hooks :: > (...) > **sending()** > Provides the plugin with the opportunity to inspect/modify the message text > before it is sent. Basically Suds will call `sending` before the XML is sent, so you can modify the generated XML (contained in `context.envelope`). You have to pass the plugin class MyPlugin to the `Client` constructor for this to work. **Edit** Another way is to use `marshalled` to modify the XML structure, removing the empty elements (untested code): class MyPlugin(MessagePlugin): def marshalled(self, context): #remove empty tags inside the Body element #context.envelope[0] is the SOAP-ENV:Header element context.envelope[1].prune()
Python code not executing Question: I have the following code which is executed from the command line: import cgi,time,os,json,sys,zipfile,urllib2 from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from time import strftime from poster.encode import multipart_encode, MultipartParam from poster.streaminghttp import register_openers class MyHandler(BaseHTTPRequestHandler): def do_GET(self): try: if self.path.endswith("/"): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write("<HTML> GET OK.<BR>") return return except IOError: self.send_error(404,'File Not Found: %s' % self.path) def do_POST(self): global rootnode ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) if ctype == 'multipart/form-data': query=cgi.parse_multipart(self.rfile, pdict) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() file = query.get('file') zfile = "C:\Users\VM1\Desktop\data.zip" extract_path = "C:\Users\VM1\Desktop\data\\" f = open(zfile, "wb") f.write(file[0]) f.close() self.wfile.write("POST OK. File received from VM Host") print("File received from VM Host.") print("Unzipping zip file") unzip = zipfile.ZipFile(zfile) unzip.extractall(extract_path) print "Files extracted to " + extract_path scan_path = '"C:\Program Files (x86)\AVG\AVG2012\\avgscana.exe" /repok /report=C:\Users\VM1\Desktop\\avg_scan_results.txt /scan=' + extract_path os.system('"%s"' % scan_path) self.write_json_report() self.upload_json_report() return def write_json_report(self): scan_results = open("avg_scan_results.txt", "r") saved = sys.stdout f = file('avg_report.json', 'wb') sys.stdout = f dict2 = {} for line in scan_results: if ".jpg" in line: result = line.split('\\') result_split = result[5].split(' ') filename = result_split[0] raw_status = result_split[3] if "OK" in raw_status: status = "Okay" status_code = "0" elif "Virus identified" in raw_status: status = raw_status status_code = "1" dict2[filename] = {'FileName': filename, 'DateTime': strftime("%Y-%m-%d %H:%M:%S"), 'statusCode': status_code, 'Description': status} print json.dumps(dict2) sys.stdout = saved f.close() print "" print "JSON report written" json_zip = zipfile.ZipFile("avg_report.zip", "w") try: json_zip.write('avg_report.json') finally: json_zip.close() return def upload_json_report(self): av_name = "AVG Free 2012" av_version = "" scan_results = open("avg_scan_results.txt", "r") for line in scan_results: if "Program version" in line: version_split = line.split(', ') program_version_full = version_split[0] program_version_split = program_version_full.split(' ') av_version = program_version_split[2] register_openers() datagen, headers = multipart_encode({"av_name": av_name, "av_version": av_version, "filename": "avg_report.zip", "content": open("avg_report.zip", "rb")}) request = urllib2.Request("http://" + self.client_address[0] + ":8080/", datagen, headers) print "Uploading JSON report" print urllib2.urlopen(request).read() return def main(): try: server = HTTPServer(('', 8080), MyHandler) print 'Server started..' server.serve_forever() except KeyboardInterrupt: print 'KeyboardInterrupt received, shutting down server' server.socket.close() if __name__ == '__main__': main() The rest of the functions worked fine except for `upload_json_report()`. The string `Uploading JSON report` shows but the line after doesn't execute. My server which is listening for the request does not receive anything. Is there anything wrong with the code here? If yes, what is the problem and how do I solve it? Many thanks in advance. **EDIT:** I have created a seperate client with the following lines from the method: register_openers() datagen, headers = multipart_encode({"av_name": av_name, "av_version": av_version, "filename": "avg_report.zip", "content": open("avg_report.zip", "rb")}) request = urllib2.Request("http://" + self.client_address[0] + ":8080/", datagen, headers) print "Uploading JSON report" print urllib2.urlopen(request).read() This worked. I'm confused as to why the same lines of codes could not work in the function. Answer: `BaseHTTPRequestHandler` maintains a single-threaded (and single-process) server. This means that each request has to finish executing before another request can be executed. The `upload_json_report` function is called from within the `do_POST` method. While it is running, your server can't handle anything else. But then at the line: print urllib2.urlopen(request).read() You are actually trying to upload the .zip file _to the same port, 8080._ Thus, `upload_json_report` is waiting for `do_POST` to finish, and `do_POST` is waiting for `upload_json_report` to finish, so of course they will never stop waiting. Incidentally, this explains why it was working on your server (I assume it was multithreaded, though you'd need to provide more details), _and_ why it works when you perform it using a separate client (it's not waiting for itself to finish).
How can I use a pre-made color map for my heat map in matplotlib? Question: I want to use a color map from <http://goo.gl/5P4CT> for my matplotlib heat map. I tried doing this: myHeatMap.imshow(heatMap, extent=ext, cmap=get_cmap(cm.datad["Spectral"])) However, the Python interpreter complains in get_cmap if name in cmap_d: TypeError: unhashable type: 'dict' What is the proper way to use one of these color maps? Answer: It looks like you are simply calling `get_cmap` wrong. Try: from pylab import imshow, show, get_cmap from numpy import random Z = random.random((50,50)) # Test data imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest') show() ![enter image description here](http://i.stack.imgur.com/Mafjl.png) ## What are the named colormaps? Running the code: from pylab import cm print cm.datad.keys() Gives a list of colormaps, any of which can be substituted for `"Spectral"`: ['Spectral', 'summer', 'RdBu', 'Set1', 'Set2', 'Set3', 'brg_r', 'Dark2', 'hot', 'PuOr_r', 'afmhot_r', 'terrain_r', 'PuBuGn_r', 'RdPu', 'gist_ncar_r', 'gist_yarg_r', 'Dark2_r', 'YlGnBu', 'RdYlBu', 'hot_r', 'gist_rainbow_r', 'gist_stern', 'gnuplot_r', 'cool_r', 'cool', 'gray', 'copper_r', 'Greens_r', 'GnBu', 'gist_ncar', 'spring_r', 'gist_rainbow', 'RdYlBu_r', 'gist_heat_r', 'OrRd_r', 'bone', 'gist_stern_r', 'RdYlGn', 'Pastel2_r', 'spring', 'terrain', 'YlOrRd_r', 'Set2_r', 'winter_r', 'PuBu', 'RdGy_r', 'spectral', 'flag_r', 'jet_r', 'RdPu_r', 'Purples_r', 'gist_yarg', 'BuGn', 'Paired_r', 'hsv_r', 'bwr', 'YlOrRd', 'Greens', 'PRGn', 'gist_heat', 'spectral_r', 'Paired', 'hsv', 'Oranges_r', 'prism_r', 'Pastel2', 'Pastel1_r', 'Pastel1', 'gray_r', 'PuRd_r', 'Spectral_r', 'gnuplot2_r', 'BuPu', 'YlGnBu_r', 'copper', 'gist_earth_r', 'Set3_r', 'OrRd', 'PuBu_r', 'ocean_r', 'brg', 'gnuplot2', 'jet', 'bone_r', 'gist_earth', 'Oranges', 'RdYlGn_r', 'PiYG', 'YlGn', 'binary_r', 'gist_gray_r', 'Accent', 'BuPu_r', 'gist_gray', 'flag', 'seismic_r', 'RdBu_r', 'BrBG', 'Reds', 'BuGn_r', 'summer_r', 'GnBu_r', 'BrBG_r', 'Reds_r', 'RdGy', 'PuRd', 'Accent_r', 'Blues', 'Greys', 'autumn', 'PRGn_r', 'Greys_r', 'pink', 'binary', 'winter', 'gnuplot', 'pink_r', 'prism', 'YlOrBr', 'rainbow_r', 'rainbow', 'PiYG_r', 'YlGn_r', 'Blues_r', 'YlOrBr_r', 'seismic', 'Purples', 'bwr_r', 'autumn_r', 'ocean', 'Set1_r', 'PuOr', 'PuBuGn', 'afmhot']
Python: eval() that coerces values to floating point? Question: Is there a way to execute an `eval`-like function that coerces its values to floating point? I am hoping to eval('1/3') and have it return the floating point value .333333 rather than the integer value 0. Answer: Grab the compiler flag for `__future__.division`, pass it and your code to `compile()`, then run `eval()` on the returned code object. **(note by mh)** This has the added advantage of not changing the division operation globally, which might have unexpected side effects. **(end note)** >>> import __future__ >>> eval(compile('1/3', '<string>', 'eval', __future__.division.compiler_flag)) 0.33333333333333331
Redirect stdout to logger in Python Question: Can I redirect all output from `stdout` to a logger I have set up with the standard `logging` module? (I have os.system calls whose output I'd also like to see or occational print statements) Answer: You might be able to make use of the suggestion in [this post](http://plumberjack.blogspot.com/2009/09/how-to-treat-logger-like-output- stream.html), summarised below: import logging class LoggerWriter: def __init__(self, logger, level): self.logger = logger self.level = level def write(self, message): if message != '\n': self.logger.log(self.level, message) def main(): logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger("demo") info_fp = LoggerWriter(logger, logging.INFO) debug_fp = LoggerWriter(logger, logging.DEBUG) print >> info_fp, "An INFO message" print >> debug_fp, "A DEBUG message" if __name__ == "__main__": main() When run, the script prints: INFO:demo:An INFO message DEBUG:demo:An DEBUG message
Image Interpolation in python Question: I am trying to use interpolation to remove chromatic aberration from an image. The code I have generates the following error: TypeError: unhashable type: 'numpy.ndarray'. Below is my code - any help would be greatly appreciated. Thank you- Areej This is an input explanation #splitting an image into its separe bands source = im.split() Cfixed = source[2] Cwarp = source[1] #take the image minus a ew-wide edge roi = [ew+1, xdim-ew, ew+1, ydim-ew]; roi_pad = [roi[0]-ew, roi[1]+ew, roi[2]-ew, roi[3]+ew]; for k in range(0,centers_x.size): cx = centers_x[k] cy = centers_y[k] wz = warps[k] import scipy as sp from scipy import interpolate def warpRegion(Cwarp, roi_pad, (cx, cy, wz)): #Unpack region indices sx, ex, sy, ey = roi_pad xramp, yramp = np.mgrid[sx:ex+1, sy:ey+1] shapeofgrid=xramp.shape print 'shape of x grid'+str(shapeofgrid) xrampc = xramp - cx; yrampc = yramp - cy; xramp1 = 1/wz*xrampc; yramp1 = 1/wz*yrampc; xrampf = xrampc.flatten() yrampf = yrampc.flatten() xramp1f = xramp1.flatten() yramp1f = yramp1.flatten() reg_w = sp.interpolate.interp2d(yrampf,xrampf,Cwarp, yramp1f, xramp1f,'cubic'); Answer: A possible explanation of the error message is that you are trying to use a NumPy array as a dict key or a set element. Look at where the error occurs and study the type of every variable referenced on that line. If you need help, post a runnable example and the full traceback of the exception.
Python parser for Python-like language Question: I'm looking to write a Python import filter or preprocessor for source files that are essentially Python with extra language elements. The goal is to read the source file, parse it to an abstract syntax tree, apply some transforms in order to implement the new parts of the language, and write valid Python source which can then be consumed by CPython. I want to write this thing in Python and am looking for the best parser for the task. The parser built in to Python is not appropriate because it requires the source files be actual Python, which these will not be. There are tons of parsers (or parser generators) that will work with Python, but it's hard to tell which is the best for my needs without a whole bunch of research. In summary, my requirements are: 1. Parser is written in Python or has Python bindings. 2. Comes with a Python grammar that I can tweak, or can easily consume a tweakable Python grammar available elsewhere (such as <http://docs.python.org/reference/grammar.html>). 3. Can re-serialize the AST after transforming it. 4. Should not be too horrific to work with API-wise. Any suggestions? Answer: The first thing that comes to mind is [`lib2to3`](http://docs.python.org/library/2to3.html#module-lib2to3). It is a complete pure-Python implementation of a Python parser. It reads a Python grammar file and parses Python source files according to this grammar. It offers a great infrastructure for performing AST manipulations and writing back nicely formatted Python code -- after all it's purpose is to transform between two Python-like languages with slightly different grammars. Unfortunately it's lacking documentation and doesn't guarantee a stable interface. There are projects that build on top of `lib2to3` nevertheless, and the [source code](http://hg.python.org/cpython/file/80ab0b13eb04/Lib/lib2to3) is quite readable. If API stability is an issue, you can just fork it.
Python C Extension in package - not working? Question: I'm working on packaging my python C extension and I'm running into trouble here: . |-- c_ext/ | |-- __init__.py |-- c_src/ setup.py With this setup.py from distutils.core import setup, Extension setup( name = "Utilities", version = '1.0', description = ('Various utils'), packages = ["utils"], ext_modules = [Extension("utils.c_ext", ['c_src/c_extmodule.c'])] ) I can build without problems but after installing I can't import my module, I just get an ImportError. I'm sure it's something trivial, so what am I missing? Thanks in Advance! Answer: Do you have a function in your module with the following signature: PyMODINIT_FUNC initc_ext(void); When you import a C extension it calls the function init where is the exact name of the extension. (Note that the convention is for C extensions to be named something like _foo and you get a function like init_foo) The exact error would also help diagnose this better.
Django - Error importing storages.backends Question: I have created a custom storage backend, the file is called `storages.py` and is placed in an app called `core`: from django.conf import settings from storages.backends.s3boto import S3BotoStorage class S3StaticBucket(S3BotoStorage): def __init__(self, *args, **kwargs): kwargs['bucket_name'] = getattr(settings, 'static.mysite.com') super(S3BotoStorage, self).__init__(*args, **kwargs) In `settings.py`, I have the follwing: STATICFILES_STORAGE = 'core.storages.S3StaticBucket' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' When I try to do `python manage.py collectstatic` it shows the following error: django.core.exceptions.ImproperlyConfigured: Error importing storage module core.storages: "No module named backends.s3boto" And when I run `python manage.py shell` and try to import the same: >>> >>> from django.conf import settings >>> from storages.backends.s3boto import S3BotoStorage >>> Any idea what I'm doing wrong? Answer: There is a namespace conflict; the `storage` absolute name clashes with a `storage` local name. It may be unintuitive, but you can import from module in itself: // file my_module/clash.py import clash print clash.__file__ Now we run pyhon shell in a dir containing a `my_module`: $ python >>> import my_module.clash my_module.clash.py In short, your module tries to import a backend from itself. You need an absolute import - [Python import with name conflicts](http://stackoverflow.com/questions/1224741/python-import-with-name- conflicts).
setuptools/easy_install does not install *.cfg files and locale directories? Question: I have a little problem with setuptools/easy_install; maybe someone could give me a hint what might be the cause of the problem: To easily distribute one of my python webapps to servers I use setuptools' `sdist` command to build a tar.gz file which is copied to servers and locally installed using `easy_install /path/to/file.tar.gz`. So far this seems to work great. I have listed everything in the `MANIFEST.in` file like this: global-include */*.py */*.mo */*.po */*.pot */*.css */*.js */*.png */*.jpg */*.ico */*.woff */*.gif */*.mako */*.cfg And the resulting tar.gz file does indeed contain all of the files I need. It gets weird as soon as easy_install tries to actually install it on the remote system. For some reason a directory called `locales` and a configuration file called `migrate.cfg` won't get installed. This is odd and I can't find any documentaiton about this, but I guess it's some automatic ignore feature of easy_install? Is there something like that? And if so, how do I get easy_install to install the `locales` and `migrate.cfg` files? Thanks! For reference here is the content of my `setup.py`: from setuptools import setup, find_packages requires = ['flup', 'pyramid', 'WebError', 'wtforms', 'webhelpers', 'pil', 'apns', \ 'pyramid_beaker', 'sqlalchemy', 'poster', 'boto', 'pypdf', 'sqlalchemy_migrate', \ 'Babel'] version_number = execfile('pubserverng/version.py') setup( author='Bastian', author_email='[email protected]', url='http://domain.de/', name = "mywebapp", install_requires = requires, version = __version__, packages = find_packages(), zip_safe=False, entry_points = { 'paste.app_factory': [ 'pubserverng=pubserverng:main' ] }, namespace_packages = ['pubserverng'], message_extractors = { 'pubserverng': [ ('**.py', 'python', None), ('templates/**.html', 'mako', None), ('templates/**.mako', 'mako', None), ('static/**', 'ignore', None), ('migrations/**', 'ignore', None), ] }, ) Answer: The entire package distribution system in python leaves a lot to be desired. My issues were similar to yours and were eventually solved by using `distutils` (rather than `setuptools`) which honored the `include_package_data = True` setting as expected. Using `distutils` allowed me to more or less keep required file list in `MANIFEST.in`and avoid using the `package_data` setting where I would have had to duplicate the source list; the draw back is `find_packages` is not available. Below is my setup.py: from distutils.core import setup package = __import__('simplemenu') setup(name='django-simplemenu', version=package.get_version(), url='http://github.com/danielsokolowski/django-simplemenu', license='BSD', description=package.__doc__.strip(), author='Alex Vasi <[email protected]>, Justin Steward <[email protected]>, Daniel Sokolowski <[email protected]>', author_email='[email protected]', include_package_data=True, # this will read MANIFEST.in during install phase packages=[ 'simplemenu', 'simplemenu.migrations', 'simplemenu.templatetags', ], # below is no longer needed as we are utilizing MANIFEST.in with include_package_data setting #package_data={'simplemenu': ['locale/en/LC_MESSAGES/*', # 'locale/ru/LC_MESSAGES/*'] # }, scripts=[], requires=[], ) And here is a `MANIFEST.in` file: include LICENSE include README.rst recursive-include simplemenu *.py recursive-include simplemenu/locale * prune simplemenu/migrations
Python matplotlib -> 3D bar plot -> adjusting tick label position, transparent bars Question: I am trying to create a 3D bar histogram in Python using bar3d() in Matplotlib. I have got to the point where I can display my histogram on the screen after passing it some data, but I am stuck on the following: 1. Displaying axes labels correctly (currently misses out final (or initial?) tick labels) 2. Either making the ticks on each axis (e.g. that for 'Mon') either point to it's corresponding blue bar, or position the tick label for between the major tick marks. 3. Making the bars semi-transparent. [image of plot uploaded **here**](http://imageshack.us/photo/my- images/831/histogramsample.png/) I have tried passing several different arguments to the 'ax' instance, but have not got anything to work despite and suspect I have misunderstood what to provide it with. I will be very grateful for any help on this at all. Here is a sample of the code i'm working on: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np #from IPython.Shell import IPShellEmbed #sh = IPShellEmbed() data = np.array([ [0,1,0,2,0], [0,3,0,2,0], [6,1,1,7,0], [0,5,0,2,9], [0,1,0,4,0], [9,1,3,4,2], [0,0,2,1,3], ]) column_names = ['a','b','c','d','e'] row_names = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] fig = plt.figure() ax = Axes3D(fig) lx= len(data[0]) # Work out matrix dimensions ly= len(data[:,0]) xpos = np.arange(0,lx,1) # Set up a mesh of positions ypos = np.arange(0,ly,1) xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25) xpos = xpos.flatten() # Convert positions to 1D array ypos = ypos.flatten() zpos = np.zeros(lx*ly) dx = 0.5 * np.ones_like(zpos) dy = dx.copy() dz = data.flatten() ax.bar3d(xpos,ypos,zpos, dx, dy, dz, color='b') #sh() ax.w_xaxis.set_ticklabels(column_names) ax.w_yaxis.set_ticklabels(row_names) ax.set_xlabel('Letter') ax.set_ylabel('Day') ax.set_zlabel('Occurrence') plt.show() Answer: To make the bars semi-transparent, you just have to use the alpha parameter. alpha=0 means 100% transparent, while alpha=1 (the default) means 0% transparent. Try this, it will work out to make the bars semi-transparent: ax.bar3d(xpos,ypos,zpos, dx, dy, dz, color='b', alpha=0.5) Regarding the ticks location, you can do it using something like this (the first list on plt.xticks or plt.yticks contains the "values" where do you want to locate the ticks, and the second list contains what you actually want to call the ticks): #ax.w_xaxis.set_ticklabels(column_names) #ax.w_yaxis.set_ticklabels(row_names) ticksx = np.arange(0.5, 5, 1) plt.xticks(ticksx, column_names) ticksy = np.arange(0.6, 7, 1) plt.yticks(ticksy, row_names) In the end, I get this figure: ![enter image description here](http://i.stack.imgur.com/jqQU4.png)
grouper with a chunk size sequence in python? Question: I have a generator that I want to iterate through at two levels. The first level is unevenly spaced, then I want to chunk the next level into groups of 5, say. I need it to be memory efficient and work on generator inputs, so I'm doing something like the following. I have to think there may be a better way? In particular, I don't want the trailing Nones in the uneven length results. import itertools def dynamic_grouper(iterable, intervals): for i in intervals: inner_iter = list(itertools.islice(iterable, i)) # this is a "group" yield inner_iter iterable = iter(xrange(100)) chunk_sizes = [22,30,38,10] for i,group in enumerate(dynamic_grouper(iterable, chunk_sizes)): args = [iter(group)] * 5 for item in itertools.izip_longest(fillvalue=None, *args): print "Group %i" % i print "Items %s" % list(item) Answer: To avoid the `None`s, you could use [chunks](http://stackoverflow.com/a/312464/190597): def chunks(seq, n): # http://stackoverflow.com/a/312464/190597 (Ned Batchelder) """ Yield successive n-sized chunks from seq.""" for i in xrange(0, len(seq), n): yield seq[i:i + n] for i,group in enumerate(dynamic_grouper(iterable, chunk_sizes)): for item in chunks(group, 5): print "Group %i" % i print "Items %s" % list(item)
Can't convert .py files into .exe files Question: I want to turn python files into .exe files but I can't. I have installed py2exe when I run the program setup.py on the windows command prompt with that command line python setup.py py2exe I get the following error message: no module named py2exe Answer: To quote the [py2exe tutorial](http://www.py2exe.org/index.cgi/Tutorial): > "py2exe" is a new Distutils command that is added when you import py2exe. To > use py2exe you need to create a setup.py file to tell Distutils and py2exe > what you want to do. Here's a setup.py whose simplicity is appropriate for > our sample program... So their example setup.py script is: from distutils.core import setup import py2exe setup(console=['hello.py']) Which can be built with python setup.py py2exe So I think you are just missing the import. Post your full setup.py if this is not the case so we can debug.
creating python keyed arrays Question: im calling them keyed arrays because if i knew what they were called i could find the answer myself =-) ok, for example: parser = OptionParser(conflict_handler="resolve") parser.add_option("-x", dest="var_x", help="") parser.add_option("-y", dest="var_y", help="") (options, args) = parser.parse_args() generates an option object that can be used like this: foobar = options.var_x what are these called and where would i find some documentation on how to create and use them? Answer: One class that does something very similar is [`namedtuple`](http://docs.python.org/library/collections.html#collections.namedtuple): In [1]: from collections import namedtuple In [2]: Point = namedtuple('Point', ['x', 'y']) In [4]: p = Point(1, 2) In [5]: p.x Out[5]: 1 In [6]: p.y Out[6]: 2
can not read correctly from STDIN Question: I have a weird problem to read from STDIN in a python script. Here is my use case. I have rsyslog configured with an output module so rsyslog can pipe log messages to my Python script. My Python script is really trivial : #! /usr/bin/env python # -*- coding: utf-8 -*- import sys fd = open('/tmp/testrsyslogomoutput.txt', 'a') fd.write("Receiving log message : \n%s\n" % ('-'.join(sys.stdin.readlines()))) fd.close() If I run `echo "foo" | mypythonscript.py` I can get "foo" in the target file `/tmp/testrsyslogomoutput.txt`. However when I run it within rsyslog, messages seems to be sent only when I stop/restart rsyslog (I believe some buffer is flushed at some point). I first thought it was a problem with Rsyslog. So I replaced my python program with a shell one, without changing anything to the rsyslog configuration. The shell script works perfectly with rsyslog and as you can see in the code below, the script is really trivial: #! /bin/sh cat /dev/stdin >> /tmp/testrsyslogomoutput.txt Since my shell script works but my Python one does not, I believe I made a mistake somewhere in my Python code but I can not find where. If you could point me to my mistake(s) that would be great. Thanks in advance :) Answer: `readlines` will not return until it has finished reading the file. Since the pipe feeding stdin never finishes, `readlines` never finishes either. Stopping rsyslog closes the pipe and lets it finish.
python string in-place modification Question: folks, Suppose I want to change 'abc' to 'bac' in Python. What would be the best way to do it? I am thinking of the following tmp = list('abc') tmp[0],tmp[1] = tmp[1],tmp[0] result = ''.join(tmp) Answer: You are never editing a string "in place", strings are immutable. You could do it with a list but that is wasting code and memory. Why not just do: x = 'abc' result = x[1] + x[0] + x[2:] or (personal fav) import re re.sub('(.)(.)', r'\2\1','abc') This might be cheating, but if you really want to _edit in place_ , and are using 2.6 or older, then use MutableString(this was deprecated in 3.0). from UserString import MutableString x = MutableString('abc') x[1], x[0] = x[0], x[1] >>>>'bac' With that being said, solutions are generally not as simple as 'abc' = 'bac' You might want to give us more details on how you need to split up your string. Is it always just swapping first digits?
Are there any python libraries to help test external python scripts Question: I'd like to test some python scripts. Are there any python libraries to help test external system behaviors(running scripts, testing the contents of external files, managing input/output files, and similar actions). Also I tried making the scripts more api like to allow imports rather then calling it directly for more unit test like tests. Changes include making scripts easier to run interactively(factor lots of stuff into functions/module values and make it less procedural, add parameter to silence stdout, passing optional args to main) also serializing results in addition to the usual output formats(even though the functions to generate the output files have a medium amount of logic in them)). Is this a good strategy or is it better to attempt to test scripts by running them blackbox style and examining output. Answer: **Test library** I'll go ahead and suggest [unittest](http://docs.python.org/library/unittest.html) _(even though it's the top Google hit for "python unit testing" and you probably already know of it)_. It's a very nice, easy to use, feature-ful library for unit testing. **Test strategy** Writing testable code is _hard_. Testing things like side-effects, environments, and file output can take the **unit** right out of **unit test**. What I typically try to do is structure the code so that as little of it as possible does I/O or other nasty things. Then all of that code can usually be straightforwardly unit-tested. For the parts that are hard to break into units, such as the command-line interface, I test for file output etc. **Conclusion** * use unit tests as much as possible * otherwise, use black-box tests * constantly refactor code to make writing unit tests easier & more effective
how to execute nested python files Question: I have 3 python files.(first.py, second.py, third.py) I'm executing 2nd python file from the 1st python file. 2nd python file uses the 'import' statement to make use of 3rd python file. This is what I'm doing. This is my code. first.py import os file_path = "folder\second.py" os.system(file_path) second.py import third ... (rest of the code) third.py (which contains [ReportLab](http://www.reportlab.com) code for generating PDF ) .... canvas.drawImage('xyz.jpg',0.2*inch, 7.65*inch, width=w*scale, height=h*scale) .... when I'm executing this code, it gives error IOError: Cannot open resource "xyz.jpg" **But when i execute second.py file directly by writing`python second.py` , everything works fine..!!** Even i tried this code, file_path = "folder\second.py" execfile(file_path) But it gives this error, ImportError: No module named third But as i stated everything works fine if i directly execute the second.py file. !! why this is happening? Is there any better idea for executing such a kind of nested python files? Any idea or suggestions would be greatly appreciated. I used this three files just to give the basic idea of my structure. You can consider this flow of execution as a single process. There are too many processes like this and each file contains thousandth lines of codes. That's why i can't change the whole code to be modularize which can be used by import statement. :-( So the question is how to make a single python file which will take care of executing all the other processes. (If we are executing each process individually, everything works fine ) Answer: The way you are doing thing is invalid. You should: create a main application, and import 1,2,3. In 1,2,3: You should define the things as your functions. Then call them from the main application. IMHO: I don't need that you have much code to put into separate files, you just also put them into one file with function definitions and call them properly.
Why won't Python regex work on a formatted string of HTML? Question: from bs4 import BeautifulSoup import urllib import re soup = urllib.urlopen("http://atlanta.craigslist.org/cto/") soup = BeautifulSoup(soup) souped = soup.p print souped m = re.search("\\$.",souped) print m.group(0) I can download and print out the html just fine, but it always breaks when I add the last two lines. I get this error: Traceback (most recent call last): File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 323, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\Python27\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python27\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 655, in run exec cmd in globals, locals File "C:\Users\Zack\Documents\Scripto.py", line 1, in <module> from bs4 import BeautifulSoup File "C:\Python27\lib\re.py", line 142, in search return _compile(pattern, flags).search(string) TypeError: expected string or buffer Thanks lots! Answer: You probably want `re.search("\\$.", str(souped))`.
Creating a Three Dimensional Matrix structure and writing in mat file in Python Question: I am very new to Python. I need to have a 3 dimensional matrix, in order to save 8 by 8 matrix in some length. Let's call 530. The problem is that I used np.array since matrix cannot have more than 2 dimensions as numpy argues. `R = zeros([8,8,530],float)` I calculated my 8 by 8 matrix as a np.matrix `R[:,:,ii] = smallR` And, then I try to save it in mat file as scipy claims to do so. `sio.savemat('R.mat',R)` However, error says 'numpy.ndarray' object has no attribute 'items' `/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio.py:266: FutureWarning: Using oned_as default value ('column') This will change to 'row' in future versions oned_as=oned_as)` `Traceback (most recent call last):` `File "ClassName.py", line 83, in <module> print (buildR()[1])` `File "ClassName.py", line 81, in buildR sio.savemat('R.mat',R)` `File "/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio.py", line 269, in savemat MW.put_variables(mdict)` `File "/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio5.py", line 827, in put_variables` `for name, var in mdict.items(): AttributeError: 'numpy.ndarray' object has no attribute 'items'` Answer: If you type `help(sio.savemat)`, you see: savemat(file_name, mdict, appendmat=True, format='5', long_field_names=False, do_compression=False, oned_as=None) Save a dictionary of names and arrays into a MATLAB-style .mat file. [...] mdict : dict Dictionary from which to save matfile variables. and so even if you don't recognize `.items()` as a dictionary method, it's clear we're going to need to use a dictionary (a set of key, value pairs; google "python dictionary tutorial" if necessary). In this case: >>> from numpy import zeros >>> from scipy import io as sio >>> >>> R = zeros([8,8,530],float) >>> R += 12.3 >>> >>> sio.savemat('R.mat', {'R': R}) >>> >>> S = sio.loadmat('R.mat') >>> S {'R': array([[[ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3], [ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3], [ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3], ..., ..., [ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3], [ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3], [ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3]]]), '__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file Platform: posix, Created on: Sat Feb 25 18:16:02 2012', '__globals__': []} >>> S['R'] array([[[ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3], [ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3], [ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3], ..., ..., [ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3], [ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3], [ 12.3, 12.3, 12.3, ..., 12.3, 12.3, 12.3]]]) Basically, a dictionary is used so that the arrays can be named, as you can store multiple objects in one .mat file.
sqlalchemy tutorial example not working Question: I'm trying to work my way through the example given in the [sqlalchemy tutorial](http://docs.sqlalchemy.org/en/latest/orm/tutorial.html) but I'm getting errors. As far as I can tell I'm following the example to the letter. Here's the code that I have from it so far. It fails when I `.first()` after I query the DB. I'm on version 0.7.5 and python 2.7 from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory:', echo=True) engine.execute("select 1").scalar() # works fine Session = sessionmaker(bind=engine) session = Session() Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __init__(self, name, fullname, password): self.name = name self.fullname = fullname self.password = password def __repr__(self): return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password) jeff_user = User("jeff", "Jeff", "foo") session.add(jeff_user) our_user = session.query(User).filter_by(name='jeff').first() # fails here jeff_user.password = "foobar" session.add_all([ User('wendy', 'Wendy Williams', 'foobar'), User('mary', 'Mary Contrary', 'xxg527'), User('fred', 'Fred Flinstone', 'blah')]) session.dirty # shows nothing as dirty session.new # shows nothing as new Here is the error message 2012-02-25 17:48:33,879 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 2012-02-25 17:48:33,886 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, password) VALUES (?, ?, ?) 2012-02-25 17:48:33,886 INFO sqlalchemy.engine.base.Engine ('jeff', 'Jeff', 'foo') 2012-02-25 17:48:33,887 INFO sqlalchemy.engine.base.Engine ROLLBACK Traceback (most recent call last): File "learning_sql.py", line 35, in <module> our_user = session.query(User).filter_by(name='ed').first() # fails here File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2024, in first ret = list(self[0:1]) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 1918, in __getitem__ return list(res) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2092, in __iter__ self.session._autoflush() File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 983, in _autoflush self.flush() File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1559, in flush self._flush(objects) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1630, in _flush flush_context.execute() File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 331, in execute rec.execute(self) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 475, in execute uow File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/mapper.py", line 2291, in _save_obj execute(statement, params) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1405, in execute params) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1538, in _execute_clauseelement compiled_sql, distilled_params File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1646, in _execute_context context) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1639, in _execute_context context) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 330, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.OperationalError: (OperationalError) no such table: users u'INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)' ('jeff', 'Jeff', 'foo') The expected print out is this >>> our_user = session.query(User).filter_by(name='ed').first() BEGIN (implicit) INSERT INTO users (name, fullname, password) VALUES (?, ?, ?) ('ed', 'Ed Jones', 'edspassword') SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password FROM users WHERE users.name = ? LIMIT 1 OFFSET 0 ('ed',) >>> our_user <User('ed','Ed Jones', 'edspassword')> For some reason my code is causing a ROLLBACK when it should be SELECT. Answer: You are getting this error because database is missing the table structure (you apparently missed this line in the tutorial, it's in the **Declare Mapping** subsection). Create the schema by adding following just after your table/model definitions: Class User(Base) ... # Initialize database schema (create tables) Base.metadata.create_all(engine)
Importing Library into iTunes through Windows SDK (Python) Question: I am using the Windows COM SDK for python in order to manipulate iTunes. I would like to know if there is a way to import a new library in iTunes. The user is able to do that ("MenuBar>File>Library>Import list..."), but is it possible with the SDK? I've already looked into the documentation, but I haven't seen anything. Thanks. Answer: Use `xml.etree.ElementTree` module to generate a iTunes `xml` file: C:\Documents and Settings\User\My Documents\My Music\iTunes\iTunes Music Library.xml
distance formula in python bug Question: I'm calculating the length of a line segment in python, but I don't understand why one piece of code gives me zero and the other gives the right answer. This piece of code gives me zero: def distance(a, b): y = b[1]-a[1] x = b[0]-a[0] ans=y^2+x^2 return ans^(1/2) This one gives me the right answer: import math as math def distance(a, b): y = b[1]-a[1] x = b[0]-a[0] ans=y*y+x*x return math.sqrt(ans) Thank you. Answer: In your first snippet you have written this: ans^(1/2) In Python the power operator is **not** `^`, that's the **XOR** -operator. The power operator in Python is `**`. On top of that, in Python 2.x by default the result of the division of two integers is an integer, so `1/2` will evaluate as `0`. The correct way would be this: ans ** 0.5 And another thing, the function you have implemented here can be done a lot easier with [**`math.hypot`**](http://docs.python.org/library/math.html#math.hypot): import math def distance(a, b): return math.hypot(b[0] - a[0], b[1] - a[1])
Error when making random errors in Python Question: > > import random > import time > loop = [1,2,3,4,5,6,7,8,9,10] > queenstrength = 100 > queendamagenum = 1,20 > print "The queens health is currently: ",queenstrength > > while queenstrength > 0: > queendamage = random.randint((queendamagenum)) > print"" > print "queen damage:", queendamage > queenstrength = queenstrength - queendamage > print queenstrength > time.sleep(1) > > print"" > print"finished" > I'm trying to use this code in a game I am making, but I keep getting the error: **Traceback (most recent call last): File "Untitled.py", line 9, in <module> queendamage = random.randint((queendamagenum)) TypeError: randint() takes exactly 3 arguments (2 given)** what does it mean 3 arguments (2 given)? I thought it only needed a min and a max? Answer: [randint](http://docs.python.org/library/random.html#random.randint) accepts a min and a max, like this: >>> import random >>> random.randint(0,10) 1 but you're passing a tuple: >>> random.randint((0, 10)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: randint() takes exactly 3 arguments (2 given) You can use [argument unpacking (](http://docs.python.org/tutorial/controlflow.html#unpacking-argument- lists)the * operator) to turn your tuple into a series of arguments for randint, if you like: >>> queendamagenum = 1, 20 >>> random.randint(*queendamagenum) 8 As for the fact that the error message says "3 arguments (2 given)", that's because randint is actually a method living in an instance of random.Random, and not a function. methods automatically get an argument passed to them (traditionally called "self") which is the instance itself. So you should translate "3 arguments (2 given)" into "2 non-self arguments (1 given)", and you only passed it 1 tuple, so that make sense.
Python: How to allow duplicates in a set? Question: I ran into a problem regarding set in Python 2.7. Here's the appropriate example code block: letters = set(str(raw_input("Type letters: "))) As you can see, the point is to write some letters to assign to "letters" for later use. But if I type "aaabbcdd", the output of "letters" returns set(['a', 'c', 'b', 'd']) My question is how to write the code, so that the output will allow duplicates like this: set(['a','a','a','b','b','c','d','d']) ? Answer: `set` doesn't store duplicates, which is why it's called a [set](https://en.wikipedia.org/wiki/Set_%28mathematics%29). You should use an ordinary `str` or `list` and sort it if necessary. >>> sorted(raw_input("Type letters: ")) Type letters: foobar ['a', 'b', 'f', 'o', 'o', 'r'] An alternative (but overkill for your example) is the multiset container [`collections.Counter`](http://docs.python.org/dev/library/collections.html#collections.Counter), available from Python 2.7. >>> from collections import Counter >>> c = Counter(raw_input("Type letters: ")) >>> c Counter({'o': 2, 'a': 1, 'r': 1, 'b': 1, 'f': 1}) >>> sorted(c.elements()) ['a', 'b', 'f', 'o', 'o', 'r']
Parsing XPath within non standard XML using lxml Python Question: I’m trying to create a database of all patent information from Google Patents. Much of my work so far has been using this very good answer from MattH in [Python to parse non-standard XML file](http://stackoverflow.com/a/7336718). My Python is too large to display so its linked [here](http://textuploader.com/?p=6&id=CDEZq). The source files [are here](http://commondatastorage.googleapis.com/patents/grant_full_text/2010/ipg100105.zip): a bunch of xml files appended together into one file with multiple headers.The issue is trying to use the correct xpath expression when parsing this unsual "non-standard" XML file which has multiple xml and dtd declarations. I have been trying to use `"-".join(doc.xpath` to tie everything together when its parsed out but the output creates blanks separated by hyphens for the `<document-id>` and `<classification-national>` shown below <references-cited> <citation> <patcit num="00001"> <document-id> <country>US</country> <doc-number>534632</doc-number> <kind>A</kind> <name>Coleman</name> <date>18950200</date> </document-id> </patcit> <category>cited by examiner</category> <classification-national><country>US</country> <main-classification>249127</main-classification></classification-national> </citation> **Note** not all children exist within each `<citation>`, sometimes they are not present at all. How can I parse this xpath while trying to place hyphens between each data entry for multiple entries under `<citation>` ? Answer: From this XML (references.xml), <references-cited> <citation> <patcit num="00001"> <document-id> <country>US</country> <doc-number>534632</doc-number> <kind>A</kind> <name>Coleman</name> <date>18950200</date> </document-id> </patcit> <category>cited by examiner</category> <classification-national> <country>US</country> <main-classification>249127</main-classification> </classification-national> </citation> <citation> <patcit num="00002"> <document-id> <country>US</country> <doc-number>D28957</doc-number> <kind>S</kind> <name>Simon</name> <date>18980600</date> </document-id> </patcit> <category>cited by other</category> </citation> </references-cited> you can get the text content of every descendant of `<citation>` that has any content as follows: from lxml import etree doc = etree.parse("references.xml") cits = doc.xpath('/references-cited/citation') for c in cits: descs = c.xpath('.//*') for d in descs: if d.text and d.text.strip(): print "%s: %s" %(d.tag, d.text) print Output: country: US doc-number: 534632 kind: A name: Coleman date: 18950200 category: cited by examiner country: US main-classification: 249127 country: US doc-number: D28957 kind: S name: Simon date: 18980600 category: cited by other This variation: import sys from lxml import etree doc = etree.parse("references.xml") cits = doc.xpath('/references-cited/citation') for c in cits: descs = c.xpath('.//*') for d in descs: if d.text and d.text.strip(): sys.stdout.write("-%s" %(d.text)) print results in this output: -US-534632-A-Coleman-18950200-cited by examiner-US-249127 -US-D28957-S-Simon-18980600-cited by other
Polymorphism with callables in Python Question: I have an interface class called iResource, and a number of subclasses, each of which implement the "request" method. The request functions use socket I/O to other machines, so it makes sense to run them asynchronously, so those other machines can work in parallel. The problem is that when I start a thread with iResource.request and give it a subclass as the first argument, it'll call the superclass method. If I try to start it with "type(a).request" and "a" as the first argument, I get "" for the value of type(a). Any ideas what that means and how to get the true type of the method? Can I formally declare an abstract method in Python somehow? EDIT: Including code. def getSocialResults(self, query=''): #for a in self.types["social"]: print type(a) tasks = [type(a).request for a in self.types["social"]] argss = [(a, query, 0) for a in self.types["social"]] grabbers = executeChainResults(tasks, argss) return igrabber.cycleGrabber(grabbers) "executeChainResults" takes a list "tasks" of callables and a list "argss" of args-tuples, and assumes each returns a list. It then executes each in a separate thread, and concatenates the lists of results. I can post that code if necessary, but I haven't had any problems with it so I'll leave it out for now. The objects "a" are DEFINITELY not of type iResource, since it has a single constructor that just throws an exception. However, replacing "type(a).request" with "iResource.request" invokes the base class method. Furthermore, calling "self.types["social"][0].request" directly works fine, but the above code gives me: "type object 'instance' has no attribute 'request'". Uncommenting the commented line prints `<type 'instance'>` several times. Answer: You can just use the bound method object itself: tasks = [a.request for a in self.types["social"]] # ^^^^^^^^^ grabbers = executeChainResults(tasks, [(query, 0)] * len(tasks)) # ^^^^^^^^^^^^^^^^^^^^^^^^^ If you insist on calling your methods through the base class you could also do it like this: from abc import ABCMeta from functools import wraps def virtualmethod(method): method.__isabstractmethod__ = True @wraps(method) def wrapper(self, *args, **kwargs): return getattr(self, method.__name__)(*args, **kwargs) return wrapper class IBase(object): __metaclass__ = ABCMeta @virtualmethod def my_method(self, x, y): pass class AddImpl(IBase): def my_method(self, x, y): return x + y class MulImpl(IBase): def my_method(self, x, y): return x * y items = [AddImpl(), MulImpl()] for each in items: print IBase.my_method(each, 3, 4) b = IBase() # <-- crash Result: 7 12 Traceback (most recent call last): File "testvirtual.py", line 30, in <module> b = IBase() TypeError: Can't instantiate abstract class IBase with abstract methods my_method Python doesn't support interfaces as e.g. Java does. But with the `abc` module you can ensure that certain methods must be implemented in subclasses. Normally you would do this with the `abc.abstractmethod()` decorator, but you still could not call the subclasses method through the base class, like you intend. I had a similar question once and I had the idea of the `virtualmethod()` decorator. It's quite simple. It essentially does the same thing as `abc.abstratmethod()`, but also redirects the call to the subclasses method. The specifics of the `abc` module can be found in [the docs](http://docs.python.org/library/abc.html) and in [PEP3119](http://www.python.org/dev/peps/pep-3119/). BTW: I assume you're using Python >= 2.6.
Python - Is it worthwhile to invest time in apparently stagnant modules? Question: To make it quick and dirty - I'm a newb programmer who's looking hard at Pyglet, it looks like a really clean and friendly module to use, unlike something like PyGame which is, even by looking with my own inexperienced eyes, a beast. However. PyGame is constantly being used, updated, reused by lots of people and seems to have quite a following. Pyglet hasn't been updated since January 2010. Most works of art are never finished, only abandoned - but two years and it's still on v 1.1.4 seems troubling. So while I might be specifically asking about Pyglet vs. PyGame, I'm also _not_ , because it leads me wonder about other ghostly modules that might be lurking out there, that had promise once upon a time but, for _some reason_ , got dropped or shoved in a corner and aren't really relevant. Are such abandoned projects not worth the time and brain-space investment? Answer: as the owner of a "dormant" package, my own take is: * a more popular package is going to have better support from the community. for many people i think this overrides any other consideration. it's often better to have support for a mediocre package than battle with an awesome package no-one else is using. * and it may well be popular because it's better. obviously i am biased towards the underdog (see above) here, but it has to be said that if a package never gained many users, perhaps it wasn't a good match to the market. BUT * if the package is mature and working, and it does what you want, why not use it? especially when open source means you can fix bugs yourself, forking if necessary. so, it depends. all other things being equal - use the popular choice. if you need support - use the popular choice. but if a package happens to exactly scratch an itch, and it's open source and out there, i would still consider it. important qualification: this is for personal projects - for work i have a responsibility to use popular projects so that others can support the code i have written. python specific rider: one additional thing to worry about is python 3 support. if a dormant package is stuck on python 2 i would think twice because long-term there's a real chance it will stop working on default python installs.
Using random.randint help in python Question: The following code is my attempt at simulating a lottery. import random def lottery(numbers): lottoNumbers = [randint('0,100') for count in range(3)] if numbers == lottoNumbers: print('YOU WIN $10,000') else: print('YOU LOSE,DUN DUN DUNNN!') return numbers def main(): numbers = int(input('Enter a number: ')) if numbers == lottoNumbers: numbers = lottery(numbers) else: numbers = lottery(numbers) main() Hey guys I've gotten this far with the help you've given me. I'm trying to write the code so that 3 lotto numbers at random will be chosen. Then the user must enter 3 of his/her own lotto numbers. If they get all 3 correct then they win the whole prize, if they get the 3 numbers but not in the correct order they win some of the prize. Obviously if they guess all wrong then a print statement would state that. What I'm confused about is how can I write the code so that the user can enter 3 numbers to try matching the random lottery numbers. I also want to print the 3 lottery numbers after the user inputs his/her choices. Any ideas guys? Thanks for your help everyone. Answer: There are a few things wrong with your implementation, to name a few: if you are trying to compare the output of the function `randm` to x, you will need to include a return value in the function, like so: def randm(): return return_value You appear to be printing all the values but not storing them, in the end you will only end up with the final one, you should attempt to store them in a list like so: list_name = [randint(0,100) for x in range(x)] This will generate `randint(0,100)` `x` times in a list, which will allow you to access all the values later. To fix up your code as close to what you were attempting as possible I would do: import random def randm(user_numbers): number = [] for count in range(3): number.append(random.randint(0, 100)) print(number) return user_numbers == number if randm(x): print('WINNER') * * * If you are looking for a very pythonic way of doing this task, you might want to try something like this: from random import randint def doLotto(numbers): # make the lotto number list lottoNumbers = [randint(0,100) for x in range(len(numbers))] # check to see if the numbers were equal to the lotto numbers if numbers == lottoNumbers: print("You are WinRar!") else: print("You Lose!") I'm assuming from your code (the print() specifically) that you are using python 3.x+
Cannot grok python multiprocessing Question: I need to run a function for the each of the elements of my database. When I try the following: from multiprocessing import Pool from pymongo import Connection def foo(): ... connection1 = Connection('127.0.0.1', 27017) db1 = connection1.data my_pool = Pool(6) my_pool.map(foo, db1.index.find()) I'm getting the following error: > Job 1, 'python myscript.py ' terminated by signal SIGKILL (Forced quit) Which is, I think, caused by `db1.index.find()` eating all the available ram while trying to return millions of database elements... How should I modify my code for it to work? Some logs are here: dmesg | tail -500 | grep memory [177886.768927] Out of memory: Kill process 3063 (python) score 683 or sacrifice child [177891.001379] [<ffffffff8110e51a>] out_of_memory+0xfa/0x250 [177891.021362] Out of memory: Kill process 3063 (python) score 684 or sacrifice child [177891.025399] [<ffffffff8110e51a>] out_of_memory+0xfa/0x250 The actual function below: def create_barrel(item): connection = Connection('127.0.0.1', 27017) db = connection.data print db.index.count() barrel = [] fls = [] if 'name' in item.keys(): barrel.append(WhitespaceTokenizer().tokenize(item['name'])) name = item['name'] elif 'name.utf-8' in item.keys(): barrel.append(WhitespaceTokenizer().tokenize(item['name.utf-8'])) name = item['name.utf-8'] else: print item.keys() if 'files' in item.keys(): for file in item['files']: if 'path' in file.keys(): barrel.append(WhitespaceTokenizer().tokenize(" ".join(file['path']))) fls.append(("\\".join(file['path']),file['length'])) elif 'path.utf-8' in file.keys(): barrel.append(WhitespaceTokenizer().tokenize(" ".join(file['path.utf-8']))) fls.append(("\\".join(file['path.utf-8']),file['length'])) else: print file barrel.append(WhitespaceTokenizer().tokenize(file)) if len(fls) < 1: fls.append((name,item['length'])) barrel = sum(barrel,[]) for s in barrel: vs = re.findall("\d[\d|\.]*\d", s) #versions i.e. numbes such as 4.2.7500 b0 = [] for s in barrel: b0.append(re.split("[" + string.punctuation + "]", s)) b1 = filter(lambda x: x not in string.punctuation, sum(b0,[])) flag = True while flag: bb = [] flag = False for bt in b1: if bt[0] in string.punctuation: bb.append(bt[1:]) flag = True elif bt[-1] in string.punctuation: bb.append(bt[:-1]) flag = True else: bb.append(bt) b1 = bb b2 = b1 + barrel + vs b3 = list(set(b2)) b4 = map(lambda x: x.lower(), b3) b_final = {} b_final['_id'] = item['_id'] b_final['tags'] = b4 b_final['name'] = name b_final['files'] = fls print db.barrels.insert(b_final) I've noticed interesting thing. Then I press ctrl+c to stop process I'm getting the following: python index2barrel.py Traceback (most recent call last): File "index2barrel.py", line 83, in <module> my_pool.map(create_barrel, db1.index.find, 6) File "/usr/lib/python2.7/multiprocessing/pool.py", line 227, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.7/multiprocessing/pool.py", line 280, in map_async iterable = list(iterable) TypeError: 'instancemethod' object is not iterable I mean, why multiprocessing is trying to convert somethin to the list? Isn't it the source of the problem? from the stack trace: brk(0x231ccf000) = 0x231ccf000 futex(0x1abb150, FUTEX_WAKE_PRIVATE, 1) = 1 sendto(3, "+\0\0\0\260\263\355\356\0\0\0\0\325\7\0\0\0\0\0\0data.index\0\0"..., 43, 0, NULL, 0) = 43 recvfrom(3, "Some text from my database."..., 491663, 0, NULL, NULL) = 491663 ... [manymany times] brk(0x2320d5000) = 0x2320d5000 .... manymany times The above sample goes and goes in strace output and for some reason strace -o logfile python myscript.py does not halt. It just eats all the available ram and writes in log file. UPDATE. Using imap instead of map solved my problem. Answer: Since the `find()` operation is returning the cursor the the map function and since you say that this runs without a problem when you do `for item in db1.index.find(): create_barrel(item)` it looks like the `create_barrel` function is OK. Can you try to limit the number of results returned in the cursor and see if this helps? I think the syntax would be: db1.index.find().limit(100) If you could try this and see if it helps it might help to get the cause of the problem. EDIT1: I think you are going about this the wrong way by using the map function - I think you should be using map_reduce in the mongo python driver - that way the map function will be executed by the mongod process.
Reducing duplicates in Python list of lists Question: I am writing a program that reads in a number of files and then indexes the terms in them. I am able to read in the files into a 2d array (list) in python, but then I need to remove the duplicates in the first column and store the index in a new column with the first appearance of the duplicated word. For example: ['when', 1] ['yes', 1] ['', 1] ['greg', 1] ['17', 1] ['when',2] the first column is the term, and the second is the DocID that it came from i want to be able to change this to: ['when', 1, 2] ['yes', 1] ['', 1] ['greg', 1] ['17', 1] removing the duplicate. This is what I have so far: for j in range(0,len(index)): for r in range(1,len(index)): if index[j][0] == index[r][0]: index[j].append(index[r][1]) index.remove(index[r]) i keep getting an out of range error at if index[j][0] == index[r][0]: and i think it is because I'm removing an object from the index so it is becoming smaller. any ideas would be much appreciated (and yes, I know I shouldn't modify the original, but this is just testing it on a small scale) Answer: Wouldn't be more appropiate to build a [`dict`](http://docs.python.org/py3k/library/stdtypes.html#mapping-types- dict)/[`defaultdict`](http://docs.python.org/py3k/library/collections.html#collections.defaultdict)? Something like: from collections import defaultdict ar = [['when', 1], ['yes', 1], ['', 1], ['greg', 1], ['17', 1], ['when',2]] result = defaultdict(list) for lst in ar: result[lst[0]].append(lst[1]) Output: >>> for k,v in result.items(): ... print(repr(k),v) '' [1] 'yes' [1] 'greg' [1] 'when' [1, 2] '17' [1]
Capturing print output from shared library called from python with ctypes module Question: I am working with a shared library that is being called through the ctypes module. I would like to redirect the stdout associated with this module to a variable or a file that I can access in my program. However ctypes uses a separate stdout from sys.stdout. I'll demonstrate the problem I am having with libc. If anyone is copying and pasting the code they might have to change the filename on line 2. import ctypes libc = ctypes.CDLL('libc.so.6') from cStringIO import StringIO import sys oldStdOut = sys.stdout sys.stdout = myStdOut = StringIO() print 'This text gets captured by myStdOut' libc.printf('This text fails to be captured by myStdOut\n') sys.stdout = oldStdOut myStdOut.getvalue() Is there any way I can capture the stdout that is associated with the ctypes loaded shared library? Answer: We can use `os.dup2()` and `os.pipe()` to replace the entire stdout file descriptor (fd 1) with a pipe we can read from ourselves. You can do the same thing with stderr (fd 2). This example uses `select.select()` to see if the pipe (our fake stdout) has data waiting to be written, so we can print it safely without blocking execution of our script. As we are completely replacing the stdout file descriptor for this process and any subprocesses, this example can even capture output from child processes. import os, sys, select # the pipe would fail for some reason if I didn't write to stdout at some point # so I write a space, then backspace (will show as empty in a normal terminal) sys.stdout.write(' \b') pipe_out, pipe_in = os.pipe() # save a copy of stdout stdout = os.dup(1) # replace stdout with our write pipe os.dup2(pipe_in, 1) # check if we have more to read from the pipe def more_data(): r, _, _ = select.select([pipe_out], [], [], 0) return bool(r) # read the whole pipe def read_pipe(): out = '' while more_data(): out += os.read(pipe_out, 1024) return out # testing print methods import ctypes libc = ctypes.CDLL('libc.so.6') print 'This text gets captured by myStdOut' libc.printf('This text fails to be captured by myStdOut\n') # put stdout back in place os.dup2(stdout, 1) print 'Contents of our stdout pipe:' print read_pipe()
Histogram in Pylab when mu is large Question: I ran into this problem; it feels like a bug, but it is probably me missing something, since I am completely new to pylab. When I use the following code: import pylab import random as rn mu = 10 sigma = 5 z = [] for i in xrange(300): z.append(rn.gauss(mu,sigma)) n, bins, patches = pylab.hist(z, 50, normed=1, histtype='stepfilled') pylab.show() everything works fine; the values on the y-axis range from 0 to 0.12, which I would think is a percentage each bin makes up of a whole sample. This makes perfect sense. However, if change mu = 10 to mu = 20, import pylab import random as rn mu = 20 sigma = 5 z = [] for i in xrange(300): z.append(rn.gauss(mu,sigma)) n, bins, patches = pylab.hist(z, 50, normed=1, histtype='stepfilled') pylab.show() my values on y-axis become a lot larger; they now range between 0 and 5, and this makes no sense. The bars become really squished towards the bottom that you can barely see them. This problems occurs for any large mu. One possible solution is to normalize the data such that mu is fairly small, but I feel like there should be a better solution. Does anyone know what's going on? I am using pythonxy on 32bit windows. Thank You Answer: I appears to be a bug. I get roughly the same general shape for mu=5 and mu=20. You can interpret the y-value of a normalized histogram bin as it probability denisty. The total area of all bins = 1.
"SVN Repositories" always comes up blank when you switch workspaces Is there a plugin to get Eclipse to remember them? Question: For example, say you have a project checked out from SVN Repository in one workspace, but it contains several projects (either related or not). You switch to a new workspace and do Window |Perspective | SVN Repository Exploring. Eclipse has now "forgotten" the repository you were just using. You see a blanks list. And you have to go key in the repository link all over again. Is there a plugin that will help Eclipse remember a list of repositories between workspaces? (IntelliJ Idea, for instance, does this automatically)? Thanks! Edit: I had no intention of destroying the separateness or integrity of a workspace. In fact, that's the whole point. You can't. Invading one workspace with multiple repository artifacts is incredibly confusing. Nor is it practical to only have "one" workspace. Computers crash while the workspace is in use. People use different IDEs. People check in material that makes a build crash. Workspaces break. And we have developers who have to use multiple repositories. would like the convenience of having access to multiple repositories. Eclipse is fine when you only have one. But it also needs to be practical in a multi-project work environment, where other developers in other organizations on a project do not even use Eclipse. And it has not seemed practical in Eclipse to only have one workspace (which clearly was the original "intent"). To make one workspace track all the repositories you're going to use? I can't say. However, I realize the original intent of Eclipse might not have been to track your repositories for you. But try and recall, when computers were created they were only used to operate on telemetry data, to break codes and to do the things that John Von Neumann's incredibly rich imagination could think up. The people who originally created Eclipse could not envision that it would be eventually be used to manage for OSGi servers. Or many language: Haskell, Scala Python or Ruby. Or Maven. Or apparently that a single developer might work on more than one project at the same time and might ever need more than one workspace to successfully manage one project. But we do. No one creating an IDE could possibly think of all the eventual uses that it might be put to, or problems it would face many years into the future. Thus plugins are created. I was just asking whether there is a plugin that keeps Eclipse competitive in this area. I'm not trying to defeat the whole intent of the IDE, which I would think is to make life easier. Now, I feel like you're telling me that NOT remembering repositories is "tradition" and I'm like Tevya asking "Would it spoil some vast eternal plan, if we had a persistent SCM repository list?" But life goes on, a project has its own workflow and build flow and developers have to keep up. The tool we have is Eclipse. And to keep up it would be nice if Eclipse could somehow retain a list or repositories that I use, and it would be nice to do this in in a coherent way using the Eclipse IDE, and not requiring yet another program to manage this. If you read this far, thanks for reading. Answer: No, because it is intended to work this way. Workspaces are completely separate. If I have a workspace for e.g. PHP projects why should I pollute its repository browser with repository locations that point to Java projects? If you want to keep settings you have basically two ways: Either you don't create a new workspace but copy the old workspace folder, rename it and delete unneeded projects (delete from within Eclipse!). This way _all_ your settings (like fonts, perspectives) are preserved. Or you export / import specific settings. For this: Menu `File > Export... / Import...` `General > Preferences`. Then you can select the elements you want to export, including SVN repository locations. Certainly there is no "live" update between two workspaces. As I said because it is intended to work this way.
How to implement associative array (not dictionary) in Python? Question: I trying to print out a dictionary in Python: Dictionary = {"Forename":"Paul","Surname":"Dinh"} for Key,Value in Dictionary.iteritems(): print Key,"=",Value Although the item "Forename" is listed first, but dictionaries in Python **seem to be** sorted by values, so the result is like this: Surname = Dinh Forename = Paul How to print out these with the same order in code or **the order when items are appended in** (not sorted by values nor by keys)? Answer: First of all dictionaries are not sorted at all nor by key, nor by value. And basing on your description. You actualy need [collections.OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict) module from collections import OrderedDict my_dict = OrderedDict([("Forename", "Paul"), ("Surname", "Dinh")]) for key, value in my_dict.iteritems(): print '%s = %s' % (key, value) Note that you need to instantiate `OrderedDict` from list of tuples not from another dict as dict instance will shuffle the order of items before OrderedDict will be instantiated.
Python datetime subtracting date oddity Question: I have a datetime object created from which I subtract 13 days as follow: (date.today()-timedelta(days=13)).strftime('%Y-%m-%d') The strangeness occurs when I execute the code at 6AM and 8:30AM. At 6AM, the resulting string is returned as (if today is 2012-02-29): 2012-02-15 which is 14 days before the current! However, running the same line at 8:30AM, the resulting string is returned as: 2012-02-16 Which then correct. So far I have not been able to figure out what the difference is between the small period of time. I use timezone naive datetime objects, if that is important. I would like to know what could cause this change in the resulting string date. Many thanks. **EDIT: (based on eumiro's suggestion below)** datetime.datetime.now() returns: >>> datetime.datetime(2012, 2, 29, 10, 46, 20, 659862) And the timezone is Europe/Vienna on the server and in the django application that runs the line of code. I also tried running a similar line to the one you suggested: (pytz.timezone(settings.TIME_ZONE).localize(datetime.now(), is_dst=True) - \ timedelta(days=13)).strftime('%Y-%m-%d') But with the same results... which is why I think I don't think it has much to do with timezones also. But at the same time not sure where else to look. Answer: You live somewhere in America? This is the place where the timezones are around 6-8 hours behind the UTC and that's the time of UTC midnight. What does `datetime.datetime.now()` return? If you want to get the real local time, use this (replace `"America/New_York"` with your timezone): from datetime import datetime, timedelta import pytz now = datetime.datetime.now(pytz.timezone("America/New_York")) dt = (now - timedelta(days=13)).strftime('%Y-%m-%d') and it should return the same correct values from midnight until midnight.
How would I sum a multi-dimensional array in the most succinct python? Question: The closest was this one [summing columns](http://stackoverflow.com/questions/3223043/how-do-i-sum-the-columns- in-2d-list). So I'll do something similar in my question: Say I've a Python 2D list as below: my_list = [ [1,2,3,4], [2,4,5,6] ] I can get the row totals with a list comprehension: row_totals = [ sum(x) for x in my_list ] In one line, how can I sum the entire 2d-array? 27 Answer: You can do as easy as sum(map(sum, my_list)) or alternatively sum(sum(x) for x in my_list)) and call it a day, if you don't expect more than 2 dimensions. Note that the first solution is most likely not the fastest (as in execution time) solution, due to the usage of `map()`. Benchmark and compare as necessary. Finally, if you find yourself using multidimensional arrays, consider using [NumPy](http://numpy.scipy.org/) and its superior array-friendly functions. Here's a short excerpt for your problem: import numpy as np my_list = np.array([[1,2,3,4], [2,4,5,6]]) np.sum(my_list) This would work for any number of dimensions your arrays might have.
making exe file from python that uses command line arguments Question: I want to create an exe from a python script that uses command line arguments (argv) From what I've seen py2exe doesn't support command-line-arguments What can I do? EDIT: I was using a GUI2Exe tool, so I just missed the Console flag, but the accepted answer is perfectly correct Answer: setup(console=['hello.py']) I believe the line you want to use looks like this. I tested this with 2 files: hello.py import sys for arg in sys.argv: print arg print "Hello World!" And setup.py from distutils.core import setup import py2exe setup(console=['hello.py']) I ran these commands: python setup.py py2exe And then in the dist folder, I ran this: hello.exe foo bar Result: hello.exe foo bar Hello World!
Why simple wxPython application looks broken on the start? Question: I'm trying to create my first simple but real application based on wxPython. And I'm facing many strange things which are not discribed in the basic tutorial on the wxPython home site. Here Here is first one. I made an layout of some control on the frame and see that right after the start of the application the layout is broken. But right after resizing the applocation's window it becomes like I designed... almost So then I used wxGlade for generating code and I got the same problem. Here is the video which can provide details of the problem I faced with <http://screencast.com/t/COmqye7dlwzA> As you can see after resizing it becomes better, but still it has some weird element in the top left coner of the panel 'panel_3' And here is the code generated by wxGlade: #!/usr/bin/env python # -*- coding: iso-8859-15 -*- # generated by wxGlade 0.6.5 (standalone edition) on Wed Feb 29 14:03:09 2012 import wx # begin wxGlade: extracode # end wxGlade class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.panel_2 = wx.Panel(self, -1) self.text_ctrl_3 = wx.TextCtrl(self.panel_2, -1, "") self.text_ctrl_3_copy = wx.TextCtrl(self.panel_2, -1, "") self.text_ctrl_3_copy_1 = wx.TextCtrl(self.panel_2, -1, "") self.button_2 = wx.Button(self.panel_2, -1, "button_2") self.panel_3 = wx.Panel(self.panel_2, -1) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle("frame_1") self.SetSize((519, 333)) self.text_ctrl_3.SetMinSize((50, -1)) self.text_ctrl_3_copy.SetMinSize((50, -1)) self.text_ctrl_3_copy_1.SetMinSize((50, -1)) self.panel_3.SetBackgroundColour(wx.Colour(255, 255, 255)) # end wxGlade def __do_layout(self): # begin wxGlade: MyFrame.__do_layout sizer_1 = wx.BoxSizer(wx.HORIZONTAL) main_sizer_0 = wx.BoxSizer(wx.HORIZONTAL) vsizer_left_1 = wx.BoxSizer(wx.VERTICAL) hsizer_params_2 = wx.BoxSizer(wx.HORIZONTAL) hsizer_params_2.Add(self.text_ctrl_3, 0, wx.LEFT | wx.RIGHT | wx.TOP, 5) hsizer_params_2.Add(self.text_ctrl_3_copy, 0, wx.LEFT | wx.RIGHT | wx.TOP, 5) hsizer_params_2.Add(self.text_ctrl_3_copy_1, 0, wx.LEFT | wx.RIGHT | wx.TOP, 5) vsizer_left_1.Add(hsizer_params_2, 0, wx.EXPAND, 0) vsizer_left_1.Add(self.button_2, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5) main_sizer_0.Add(vsizer_left_1, 0, wx.EXPAND, 0) main_sizer_0.Add(self.panel_3, 1, wx.ALL | wx.EXPAND, 5) self.panel_2.SetSizer(main_sizer_0) sizer_1.Add(self.panel_2, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) self.Layout() # end wxGlade # end of class MyFrame if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop() ================================ Update So what I found out: 1. Widget Inspection Tool showed that panel_3 has panel_2 as a parent. I think it's correct 2. If I put 'sizer_1.Layout()' right before 'self.Layout()' in the __do_layout method it fix everything. And there is no weird thing in the top left coner of the panel_3. I think that was a mark remained by the first TextControl 3. Another interesting thig is that I can remove 'self.Layout()' and the aplication still will look fine. 4. Also I've tried put in the end of the __do_layout method 'self.panel_2.Fit()' or 'self.panel_2.Layout()'. In both cases the application was still looking good I've read about Fit() and found out that does similar thigs as Layout(). Am I wrong ? And what is the difference between them ? And which method is better ? And why do I need to layout top element in the frame to make the application look correct and Frame.Layout() doesn't do its job ? Answer: I am unable to replicate this issue on Windows 7, wxPython 2.9.3.1, Python 2.6.6. However, when you see that issue where you can resize the frame and make everything pop into place, that usually means you need to put a Layout() call somewhere. Usually, you just need to call the frame or the top sizer's Layout() command right before your show it. It looks like you already have that though. The weird widget in panel_3 looks like something has the wrong parent, but since I don't see that issue when I run it, I can't diagnose it. Fortunately, there's a Widget Inspection Tool that you can use to figure out layout problems and lots of other things with. Here's a link: <http://wiki.wxpython.org/Widget%20Inspection%20Tool> You should by able to use that to find out which widget that is and what its parent it too. Which will give you the information needed to fix it. UPDATE: Layout basically makes the widgets lay themselves out. It kind of forces a refresh. Fit will make them take up the smallest amount of space. I'm not sure why the frame's Layout isn't working in this case on your machine. As I mentioned, it works fine for me. Ask on the wxPython mailing list to get a full answer as that's where the wx developers are.
Python in Filemaker Pro Question: I was hoping to calculate fields using some rather complicated functions, which I don't think I can realistically write in filemaker. I would prefer to write a script to extract data into python, perform some procedures and then import it back into filemaker (so a user can see the results "live" in layouts, without having to leave filemaker). Is this possible in Filemaker Pro? Answer: That python module is meant to work with FileMaker server: send GET/POST requests, get back response in XML, and parse it. Technically you can use it to do a lot (add and delete records, run scripts, etc.) but in your case it won't fit. There are some plug-ins that can execute shell commands, so this way you can call Python from a command line. Other than that you cannot do this. But in some time (a few months) there will be a FileMaker plug-in with embedded Python :)
How to iterate/parse Tweepy get_user object Question: In playing around with Tweepy I notice that the 'status' variable returned from a call to get_user is `<tweepy.models.Status object at 0x02AAE050>` Sure, I can call get_user.USER.status, but how can I grab that information from the get_user call? i.e. I want to loop through user.**getstate**() and if I find an object which requires further iteration, loop through that too I've searched high/low of answers, but my newness to Python is causing problems, which I'm pretty sure are easy to solve if I knew the right questions to ask. Thanks for any pointer here... # -*- coding: utf-8 -*- import sys import tweepy import json from pprint import pprint api = tweepy.API() def main(): print "Starting." user = api.get_user('USER',include_entities=1) print "================ type =================" print type(user) print "================ dir =================" print dir(user) print "================ user =================" # # We can see 'status': <tweepy.models.Status object at 0x02AAE050>, .......but how do I "explode" that automagically? # pprint ((user).__getstate__()) print "================ user.status =================" pprint ((user).status.__getstate__()) print "================= end =================" if __name__ == "__main__": main() I was able to get the intended behaviour by using jsonpickle, using the following code. import jsonpickle . . . user = api.get_user('USERNAME',include_entities=1) pickled = jsonpickle.encode(user) print(json.dumps(json.loads(pickled), indent=4, sort_keys=True)) #you could just print pickled, but this makes it pretty I'm still really interested to understand what I'm missing in understanding how to detect and expand that status object. Answer: try this: api = tweepy.API(auth,parser=tweepy.parsers.JSONParser()) user = api.get_user('USER',include_entities=1) now you can user user['status'] and others easily
Mysql and Python on Mac Question: I installed Mysqldb for python but when I run it, I get this error: /Library/Python/2.7/site-packages/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /Library/Python/2.7/site-packages/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg/_mysql.pyc, but /Users/bb/Workspace/MySQL-python-1.2.3 is being added to sys.path Traceback (most recent call last): File "<stdin>", line 1, in <module> File "MySQLdb/__init__.py", line 19, in <module> import _mysql File "build/bdist.macosx-10.7-intel/egg/_mysql.py", line 7, in <module> File "build/bdist.macosx-10.7-intel/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dlopen(/Users/bb/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg-tmp/_mysql.so, 2): no suitable image found. Did find: /Users/bb/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg-tmp/_mysql.so: mach-o, but wrong architecture Any idea on how to run MySQL with Python on MAC. I've spent the last 2 days working on it Answer: I got this same error when I downloaded the 32bit version instead of the 64bit version, Installing the 64bit version fixed it.
Export blob properties from Datastore as binary files Question: I store pictures as Blob properties in Datastore, I am not using Blobstore, just Blob properties. Now I want to migrate my app to a different platform and I'd like to get the pictures out as JPEG files. Is there a way of doing this with the bulkloader tool or using the mapper tool that appengine provides? Thanks! **Update** I tried using the blob_to_file transform helper but could not make it work. This is my bulkloader.yaml file python_preamble: - import: base64 - import: re - import: google.appengine.ext.bulkload.transform - import: google.appengine.ext.bulkload.bulkloader_wizard - import: google.appengine.ext.db - import: google.appengine.api.datastore - import: google.appengine.api.users transformers: - kind: File connector: csv connector_options: encoding: utf-8 columns: from_header property_map: - property: fileId external_name: fileId - property: bytes_content external_name: local_filename export_transform: transform.blob_to_file('fileId', 'pictures') And this is my File model: class File(db.Model): fileId = db.IntegerProperty() bytes_content = db.BlobProperty() I run the bulkloader with the following command: appcfg.py download_data --application=XXXX --kind=File --url=XXXXX/_ah/remote_api --filename=File.csv --config_file=bulkloader.yaml At the end of download all I get is a big binary file and the folder pictures is empty. Thanks for your help! Answer: You can use the "Bulkloader Transform Helper function" blob_to_file(). General information can be found at <http://code.google.com/appengine/docs/python/tools/uploadingdata.html> and Nick Johnson's write-up: <http://blog.notdot.net/2010/04/Using-the-new- bulkloader>. For BlobProperty export in particular, check out the bulkloader sample app: <http://bulkloadersample.appspot.com/> When you look at the 'bulkloader.yaml' file you will find this: python_preamble: - import: google.appengine.ext.bulkload.transform and this: # A sample writing a BlobProperty to an external file. # (Note: not a BlobReferenceProperty.) - model: models.Attachment connector: csv connector_options: encoding: utf-8 columns: from_header property_map: - property: __key__ external_name: ID export_transform: datastore.Key.name - property: filename external_name: filename - property: filecontents external_name: local_filename export_transform: transform.blob_to_file('filename', 'AttachmentBlobs')
Wrapping C++ Library in Python, handling custom types Question: i'm currently writing a NLP application in python which requires a fast POS tagging implementation. the tagger has a c++ wrapper interface: #include "POSTagger.h" extern "C" POSTagger* initTagger(const char* fileName, bool Normalize, double BeamThreshold, bool SentStartHeuristic, int MaxBeamSize) { FILE *file = open_file(fileName, "rb"); POSTagger* tagger = new POSTagger(file, Normalize, BeamThreshold, SentStartHeuristic, MaxBeamSize); fclose(file); return tagger; } extern "C" void getTags(POSTagger* tagger, char** words, int sentLen, char** tags) { Sentence sent(words, sentLen); tagger->annotate(sent); for( size_t i=0; i<sent.token.size(); i++ ) tags[i] = strdup(tagger->tagmap.name(sent.token[i].tag)); } extern "C" void destroyTagger(POSTagger* tagger) { delete tagger; } i've never written a wrapper for c++ in python yet. so there are a couple of questions: 1. Can i store a custom C++ class instance in python? i've never seen that before. all examples that i did go through returned only basic data types. (this pos tagger has to be initialized with a language set, which requires some time to load it into the memory. therefore it is essential to only init and store it rather than rewriting the wrapper to create one for every tagging procedure and just return a tagged string) 2. If 1 is possible: what is the easiest way? Answer: I'd suggest to use _Cython_ for this purpose. Writing C/C++ extension-types is straight forward. Unfortunately, I can't garuantee this code to be fully correct as I can't test it without the header you use. # coding: utf-8 # file: postagger.pyx cimport libc.stdlib as stdlib cdef extern from "Python.h": char* PyString_AsString(object) cdef extern from "yourPOSTagger.c": # note the syntax, to Cython the POSTagger class will be available # as cPOSTagger using this construct cppclass cPOSTagger "POSTagger": # we only need the POSTagger type to be available to cython # but no attributes, so we leave to ``pass`` pass cPOSTagger* initTagger(char*, bint, double, bint, int) void getTags(cPOSTagger*, char**, int, char**) void destroyTagger(cPOSTagger*) cdef class POSTagger: """ Wraps the POSTagger.h ``POSTagger`` class. """ cdef cPOSTagger* tagger def __init__(self, char* fileName, bint Normalize, double BeamTreshold, bint SentStartHeuristic, int MaxBeamSize): self.tagger = initTagger( fileName, Normalize, BeamTreshold, SentStartHeuristic, MaxBeamSize ) if self.tagger == NULL: raise MemoryError() def __del__(self): destroyTagger(self.tagger) def getTags(self, tuple words, int sentLen): if not words: raise ValueError("'words' can not be None.") cdef char** _words = <char**> stdlib.malloc(sizeof(char*) * len(words)) cdef int i = 0 for item in words: if not isinstance(item, basestring): stdlib.free(_words) raise TypeError( "Element in tuple 'words' must be of type " "``basestring``." ) _words[i] = PyString_AsString(item) i += 1 cdef int nTags = len(words) # Really? Dunno.. cdef char** tags = <char**> stdlib.malloc(sizeof(char*) * len(words)) getTags(self.tagger, _words, sentLen, tags) cdef list reval = [] cdef str temp for 0 <= i < nTags: temp = tags[i] reval.append(temp) stdlib.free(tags[i]) stdlib.free(tags) return reval You'd need this code to compile with the `--cplus` flag with _Cython_. **EDIT** : Corrected code, Cython does no more give errors.
beginner: python namespace collision? Question: Disclaimer: i am new to python but have drupal programming experience I am reading the Definitive Guide to Django (http://www.djangobook.com/en/1.0/chapter07/). After issuing python manage.py startapp books python creates the books package with views.py inside. Later in the tutorial, we enter the following into that views.py file: # Create your forms here. from django import forms from django.forms import form_for_model from models import Publisher PublisherForm = forms.form_for_model(Publisher) TOPIC_CHOICES = ( ('general', 'General enquiry'), ('bug', 'Bug report'), ('suggestion', 'Suggestion'), ) class ContactForm(forms.Form): topic = forms.ChoiceField(choices=TOPIC_CHOICES) message = forms.CharField(widget=forms.Textarea()) sender = forms.EmailField(required=False) def clean_message(self): message = self.cleaned_data.get('message', '') num_words = len(message.split()) if num_words < 4: raise forms.ValidationError("Not enough words!") return Unless I typed something wrong or misunderstood something (either is likely), we now (seemingly) have a collision between forms (books/forms.py) and django forms. So, which does Python refer to above in message = forms.CharField(widget=forms.Textarea()) Answer: This statement: from django.forms import form_for_model Really only pulls the name `form_for_model` into the module-global namespace, the already existing name `forms` is not affected. Even this: import django.forms would not be a problem, because it only makes the name available in its fully- qualified form, `django.forms` (which is unambigios and does not collide with `forms`).
Python: ElementTree, get the namespace string of an Element Question: This XML file is named `example.xml`: <?xml version="1.0"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>14.0.0</modelVersion> <groupId>.com.foobar.flubber</groupId> <artifactId>uberportalconf</artifactId> <version>13-SNAPSHOT</version> <packaging>pom</packaging> <name>Environment for UberPortalConf</name> <description>This is the description</description> <properties> <birduberportal.version>11</birduberportal.version> <promotiondevice.version>9</promotiondevice.version> <foobarportal.version>6</foobarportal.version> <eventuberdevice.version>2</eventuberdevice.version> </properties> <!-- A lot more here, but as it is irrelevant for the problem I have removed it --> </project> If I load example.xml and parse it with ElementTree I can see its namespace is `http://maven.apache.org/POM/4.0.0`. >>> from xml.etree import ElementTree >>> tree = ElementTree.parse('example.xml') >>> print tree.getroot() <Element '{http://maven.apache.org/POM/4.0.0}project' at 0x26ee0f0> I have not found a method to call to get just the namespace from an `Element` without resorting to parsing the `str(an_element)` of an Element. It seems like there got to be a better way. Answer: The namespace should be in [`Element.tag`](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tag) right before the "actual" tag: >>> root = tree.getroot() >>> root.tag '{http://maven.apache.org/POM/4.0.0}project' To know more about namespaces, take a look at [ElementTree: Working with Namespaces and Qualified Names](http://effbot.org/zone/element- namespaces.htm).
Using numpy loadtext Question: I have a text file containing 10 columns of numbers. What I would like to be able to do is to create a dictionary in which the first three numbers (of the 10 per line) of each row of the data can be used as a key to access two further numbers in columns 6 and 7 (in the same line). I have been trying to do this using the numpy.loadtext (in Python 2.7) function however I am running into difficulties with the dtype argument? Is this the correct approach or is there a simpler way, and if so, what is the correct way to lay out the function. Many thanks and please let me know if any clarification is required Answer: Given column-spaced the format of your data, 1 0 0 617.09 0.00 9.38 l 0.0000E+00 2 0 0 7169.00 6978.44 94.10 o 0.1913E-05 3 0 0 366.08 371.91 14.06 o 0.6503E-03 4 0 0 5948.04 5586.09 52.95 o 0.2804E-05 5 0 0 3756.34 3944.63 50.69 o 0.6960E-05 -11 1 0 147.27 93.02 23.25 o 0.1320E-02 -10 1 0 -2.31 5.71 9.57 o 0.2533E-02 I think it would be easiest to just use Python string manipulation tools like `split` to parse the file: def to_float(item): try: return float(item) except ValueError: return item def formatter(lines): for line in lines: if not line.strip(): continue yield [to_float(item) for item in line.split()] dct = {} with open('data') as f: for row in formatter(f): dct[tuple(row[:3])] = row[5:7] print(dct) yields {(-11.0, 1.0, 0.0): [23.25, 'o'], (4.0, 0.0, 0.0): [52.95, 'o'], (1.0, 0.0, 0.0): [9.38, 'l'], (-10.0, 1.0, 0.0): [9.57, 'o'], (3.0, 0.0, 0.0): [14.06, 'o'], (5.0, 0.0, 0.0): [50.69, 'o'], (2.0, 0.0, 0.0): [94.1, 'o']} * * * Original answer: `genfromtxt` has a parameter `dtype`, which when set to `None` causes `genfromtxt` to try to guess the appropriate `dtype`: import numpy as np arr = np.genfromtxt('data', dtype = None) dct = {tuple(row[:3]):row[5:7] for row in arr} For example, with `data` like this: 1 2 3 4 5 6 7 8 9 10 1 2 4 4 5 6 7 8 9 10 1 2 5 4 5 6 7 8 9 10 `dct` gets set to {(1, 2, 5): array([6, 7]), (1, 2, 4): array([6, 7]), (1, 2, 3): array([6, 7])}
Swig with cmake and additional libraries Question: I am working on a project where I want to use a C++ library in Python. After a little bit of research I figured out that Swig would be a good way to do it (a small example worked). So now I am trying to include Swig into cmake to make things more comfortable. In my case, I have a really small program to test things: #include "ct.h" using namespace std; int main(int argc, char const *argv[]) { /* code */ return 0; } int test() { Image image(10,11); cout << "hallo"<< endl; return 3; } The Image class is defined in a header "image.h", which is included in "ct.h". This is probably the problem here, since the library, which includes the Image class needs to be linked against the library, which is generated by Swig. I am not sure about this...And, especially, I don't know how to do this. I was not able to find anything in the manual. Anyway, if I want to include the lib in python I get the following error: >>> import kissCT Traceback (most recent call last): File "<stdin>", line 1, in <module> File "kissCT.py", line 25, in <module> _kissCT = swig_import_helper() File "kissCT.py", line 21, in swig_import_helper _mod = imp.load_module('_kissCT', fp, pathname, description) ImportError: ./_kissCT.so: undefined symbol: _ZN5ImageC1Eii The related Swig file looks like this: /* kissCT test module */ %module kissCT %{ #import "ct.h" extern int test(); %} extern int test(); I hope, all this is not to confusing and I would really appreciate if someone has an idea what I did wrong. Edit: the related cmake file looks like [this](http://pastebin.com/m7TTZ1Dv) Answer: Python needs to be able to find the image library at run time. The simplest way is to set LD_LIBRARY_PATH environment variable to the folder containing the image .so file which contains the undefined symbol. If you run the command "ldd _kissCT.so" it should show you the libraries it depends on.
SqlAlchemy: array of Postgresql custom types Question: So in my postgres DB I have the following custom type: create type my_pg_type as ( sting_id varchar(32), time_diff interval, multiplier integer ); To further complicate things, this is being used as an array: alter table my_table add column my_keys my_pg_type []; I'd like to map this with SQLAlchemy (0.6.4) !! (apologies for elixir) from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.types import Enum from elixir import Entity, Field class MyTable(Entity): # -- snip -- my_keys = Field(ARRAY(Enum)) I know 'Enum' is incorrect in the above. For an example of a value coming back from the database for that array column, I've shown below the value in `ARRAY.result_processor(self, dialect, coltype)`: class ARRAY(sqltypes.MutableType, sqltypes.Concatenable, sqltypes.TypeEngine): # -- snip -- def result_processor(self, dialect, coltype): item_proc = self.item_type.result_processor(dialect, coltype) if item_proc: def convert_item(item): if isinstance(item, list): return [convert_item(child) for child in item] else: return item_proc(item) else: def convert_item(item): if isinstance(item, list): return [convert_item(child) for child in item] else: return item def process(value): if value is None: return value """ # sample value: >>> value '{"(key_1,07:23:00,0)","(key_2,01:00:00,20)"}' """ return [convert_item(item) for item in value] return process So the above `process` function incorrectly splits the string, assuming it's already a list. So far, I've successfully subclassed ARRAY to properly split the string, and instead of Enum, I've tried to write my own type (implementing Unicode) to recreate the `(string, timedelta, integer)` tuple, but have run into a lot of difficulties, specifically the proper conversion of the `interval` to the Python `timedelta`. I'm posting here in case I'm missing an obvious precedent way of doing this? Answer: **UPDATE** See the recipe at the bottom for a workaround I worked up some example code to see what psycopg2 is doing here, and this is well within their realm - psycopg2 is not interpreting the value as an array at all. psycopg2 needs to be able to parse out the ARRAY when it comes back as SQLA's ARRAY type assumes at least that much has been done. You can of course hack around SQLAlchemy's ARRAY, which here would mean basically not using it at all in favor of something that parses out this particular string value psycopg2 is giving us back. But what's also happening here is that we aren't even getting at psycopg2's mechanics for converting timedeltas either, something SQLAlchemy normally doesn't have to worry about. In this case I feel like the facilities of the DBAPI are being under-utilized and psycopg2 is a very capable DBAPI. So I'd advise you work with psycopg2's custom type mechanics over at <http://initd.org/psycopg/docs/extensions.html#database-types-casting- functions>. If you want to mail their [mailing list](http://mail.postgresql.org/mj/mj_wwwusr/domain=postgresql.org?func=lists- long-full&extra=psycopg), here's a test case: import psycopg2 conn = psycopg2.connect(host="localhost", database="test", user="scott", password="tiger") cursor = conn.cursor() cursor.execute(""" create type my_pg_type as ( string_id varchar(32), time_diff interval, multiplier integer ) """) cursor.execute(""" CREATE TABLE my_table ( data my_pg_type[] ) """) cursor.execute("insert into my_table (data) " "values (CAST(%(data)s AS my_pg_type[]))", {'data':[("xyz", "'1 day 01:00:00'", 5), ("pqr", "'1 day 01:00:00'", 5)]}) cursor.execute("SELECT * from my_table") row = cursor.fetchone() assert isinstance(row[0], (tuple, list)), repr(row[0]) PG's type registration supports global registration. You can also register the types on a per-connection basis within SQLAlchemy using the [pool listener](http://docs.sqlalchemy.org/en/rel_0_6/core/interfaces.html#connection- pool-events) in 0.6 or [connect event](http://docs.sqlalchemy.org/en/latest/core/events.html#sqlalchemy.events.PoolEvents.connect) in 0.7 and further. **UPDATE** \- due to <https://bitbucket.org/zzzeek/sqlalchemy/issue/3467/array-of-enums-does-not- allow-assigning> I'm probably going to recommend people use this workaround type for now, until psycopg2 adds more built-in support for this: class ArrayOfEnum(ARRAY): def bind_expression(self, bindvalue): return sa.cast(bindvalue, self) def result_processor(self, dialect, coltype): super_rp = super(ArrayOfEnum, self).result_processor(dialect, coltype) def handle_raw_string(value): inner = re.match(r"^{(.*)}$", value).group(1) return inner.split(",") def process(value): return super_rp(handle_raw_string(value)) return process
Adding attributes to instance methods in Python Question: I would like to add an attribute to an instance method in one of my classes. I tried the answer given in [this question](http://stackoverflow.com/questions/279561/what-is-the-python- equivalent-of-static-variables-inside-a-function), but this answer only works for functions -- as far as I can tell. As an example, I would like to be able to do something like: class foo(object): ... def bar(self): self.bar.counter += 1 return self.bar.counter bar.counter = 1 ... but, when I call foo().bar() I get: AttributeError: 'instancemethod' object has no attribute 'counter' My goal in doing this is to try to impress that the 'counter' variable is local to the bar() method, and also to avoid cluttering my class namespace with yet another attribute. Is there a way to do this? Is there a more pythonic way of doing this? Answer: In Python 3 your code would work, but in Python 2 there is some wrapping that takes place when methods are looked up. # Class vs Instance * class level: storing `counter` with the function (either directly, or by using a mutable default) effectively makes it a class level attribute as there is only ever one of the function, no matter how many instances you have (they all share the same function object). * instance level: to make `counter` an instance level attribute you have to create the function in `__init__`, then wrap it with `functools.partial` (so it behaves like a normal method), and then store it on the instance -- now you have one function object for every instance. # Class Level The accepted practice for a static-like variable is to use a mutable default argument: class foo(object): ... def bar(self, _counter=[0]): _counter[0] += 1 return _counter[0] If you want it to be prettier you can define your own mutable container: class MutableDefault(object): def __init__(self, start=0): self.value = start def __iadd__(self, other): self.value += other return self def value(self): return self.value and change your code like so: class foo(object): def bar(self, _counter=MutableDefault()): _counter += 1 return _counter.value # Instance level from functools import partial class foo(object): def __init__(self): def bar(self, _counter=MutableDefault(1)): # create new 'bar' each time value = _counter.value _counter += 1 return value self.bar = partial(bar, self) # Summary As you can see, readability took a serious hit when moving to instance level for `counter`. I strongly suggest you reevaluate the importance of emphasizing that `counter` is part of `bar`, and if it is truly important maybe making `bar` its own class whose instances become part of the instances of `foo`. If it's not really important, do it the normal way: class foo(object): def __init__(self): self.bar_counter = 0 def bar(self): self.bar_counter += 1 return self.bar_counter
Backend technology for front-end technologies like Twitter Bootstrap Question: This a noob alike question, but here we go. I´ve read about Twitter Bootstrap (among other presentation frameworks), which gives the designer/programmer the tools to build easily the front end of a webapp. What I don´t know is how to integrate that with a, for example, Java EE backend. I mean, do those presentation frameworks allow to integrate them with any backend technology (such as Java, PHP, Python, etc)? or are they linked to a specific technology? I've built a few Java EE web applications using GWT for the presentation layer and Java in the server side; but as I´ve pointed before, I still don´t catch how it would be integrate Bootstrap with Java for example. I know it´s a very general question but I´d appreciate any help. Answer: Twitter Bootstrap is a frontend toolkit, so it's basically css and HTML. That means it's not tied to any specific backend technology. From the [blog post](https://dev.twitter.com/blog/bootstrap-twitter) announcing it: > At its core, Bootstrap is just CSS, but it's built with Less, a flexible > pre-processor that offers much more power and flexibility than regular CSS. > With Less, we gain a range of features like nested declarations, variables, > mixins, operations, and color functions. Additionally, since Bootstrap is > purely CSS when compiled via Less, we gain two important benefits: > > First, Bootstrap remains very easy to implement; just drop it in your code > and go. Compiling Less can be accomplished via Javascript, an unofficial Mac > application, or via Node.js (read more about this at <http://lesscss.org>). > > Second, once complied, Bootstrap contains nothing but CSS, meaning there are > no superfluous images, Flash, or Javascript. All that remains is simple and > powerful CSS for your web development needs. What that means is that you can use it in any way you want. You can generate the markup server-side and serve it to the client (JSP for instance), you can serve a static fil from the server and add dynamic content via ajax (the backend could be servlets or some higher abstraction like Spring MVC or Jersey), or something in between like server-side generated "base" with some dynamic content/behavior via JavaScript/ajax. Another choice could be to drop the servlet container all together and use something like [Play! Framework](http://www.playframework.org/). **Edit:** I don't think Bootstrap creates the HTML elements for you, it creates the css using Less. You have to write the markup yourself on the server, and use the styles and idioms described in the docs: twitter.github.com/bootstrap/components.html You add dynamic values from java through technologies like JSP or template engines like Velocity, Freemarker, StringTemplate etc. Reading values from users is done by handling HTTP GET/POST actions and reading the attributes. Typically you handle a GET by 1. Reading the parameters 2. Select the template/JSP by the url 3. Interpolate dynamic values calculated by java. For instance if a user does a GET on `./order.html?orderId=1` you select the order.html template, interpolate values from `orderService.getOrder(1)`. Have a look at the [Freemarker examples](http://freemarker.sourceforge.net/docs/xgui_imperative_learn.html) to understand how a template engine work. You basically pass in a `Map<String, Object>` and the value associated by a ${key} is rendered in the page before it's sent to the browser.
SQLAlchemy raises None, causes TypeError Question: I'm using the declarative extension in SQLAlchemy, and I noticed a strange error when I attempted to save an instance of a mapped class with incorrect data (specifically a column declared with nullable=False with a value of None). The class (simplified): class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True, autoincrement=True) userid = Column(String(50), unique=True, nullable=False) Causing the error (session is a SQLAlchemy session): >>> u = User() >>> session.add(u) >>> session.commit() ... TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType Looking at the code that causes this exception, I found (in sqlalchemy.orm.session): except: transaction.rollback(_capture_exception=True) raise The exception being caught in this case is a sqlalchemy.exc.OperationalError. If I change these lines to: except Exception as e: transaction.rollback(_capture_exception=True) raise e then the problem goes away, and the OperationalError gets thrown instead of None. Shouldn't the original code work in any recent version of Python though? (I'm using 2.7.2) Is this error somehow specific to my application? Python 2.7.2 SQLAlchemy 0.7.5 UPDATE: the error seems to be specific to my application in some way. I'm wrapping an eventlet.db_pool with a SQLAlchemy engine, which appears to be the source of the problem somehow. Running my simple test with either in-memory SQLite or basic MySQL engine doesn't have this problem, but with the db_pool it does. Test case: <https://gist.github.com/1980584> The full traceback is: Traceback (most recent call last): File "test_case_9525220.py", line 41, in <module> session.commit() File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 645, in commit self.transaction.commit() File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 313, in commit self._prepare_impl() File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 297, in _prepare_impl self.session.flush() File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1547, in flush self._flush(objects) File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1635, in _flush raise TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType Answer: Here is what I've discovered: * The exception (an `OperationalError`) is ok until the failed transaction rolls back (in `Session._flush()`). * The transaction rollback is handled by mysqldb through `eventlet.tpool`. Specifically, `eventlet.tpool.execute` is called, which involves creating an `eventlet.Event` and calling its `wait` method. * While waiting, a few complicated thread-related things happen, one of is checking for an exception and passing it to the Event to handle. It picks up the `OperationalError` which is still in `sys.exc_type`, and ultimately clears it in `eventlet.event.hubs.hub.BaseHub.switch`. * Control returns to `Session._flush`, and the exception is re-raised (using `raise`), but at this point there is no exception so it tries to `raise None`. This behaviour can be reproduced with a simple example: from eventlet import tpool def m(): pass try: raise TypeError except: tpool.execute(m) raise Its a bit unclear exactly what eventlet should be doing in this situation, so I don't know whether the bug should be reported to sqlalchemy or eventlet, or both. The easiest way to rectify it is, as you've already noted, to change the last few lines of `sqlalchemy.orm.session.Session._flush` from except Exception: transaction.rollback(_capture_exception=True) raise to except Exception, e: transaction.rollback(_capture_exception=True) raise e **Edit:** I have raised an [issue](https://bitbucket.org/eventlet/eventlet/issue/118/exceptions-are- cleared-during) on eventlet's issue tracker. It might be worth raising it on sqlalchemy too though.
Parsing hostname and port from string or url Question: I can be given a string in any of these formats: * url: e.g <http://www.acme.com:456> * string: e.g www.acme.com:456, www.acme.com 456, or www.acme.com I would like to extract the host and if present a port. If the port value is not present I would like it to default to 80. I have tried [urlparse](http://docs.python.org/library/urlparse.html), which works fine for the url, but not for the other format. When I use urlparse on hostname:port for example, it puts the hostname in the scheme rather than netloc. I would be happy with a solution that uses urlparse and a regex, or a single regex that could handle both formats. Answer: You can use urlparse to get hostname from URL string: from urlparse import urlparse print urlparse("http://www.website.com/abc/xyz.html").hostname # prints www.website.com
Can Python's argparse permute argument order like gnu getopt? Question: GNU getopt, and command line tools that use it, allow options and arguments to be interleaved, known as permuting options (see <http://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html#Using- Getopt>). Perl's Getopt::Long module also supports this (with qw(:config gnu_getopt)). argparse seems to not support (or even mention) permuting options. There are many SO questions related to arg/opt order, but none seem answer this question: Can argparse be made to permute argument order like getopt? The use case is a prototypical command line signature like GNU sort: sort [opts] [files] in which 1) options and files are permuted, and 2) the file list may contain zero or more arguments. For example: import argparse p = argparse.ArgumentParser(); p.add_argument('files',nargs='*',default=['-']); p.add_argument('-z',action='store_true') p.parse_args(['-z','bar','foo']) # ok p.parse_args(['bar','foo','-z']) # ok p.parse_args(['bar','-z','foo']) # not okay usage: ipython [-h] [-z] [files [files ...]] I've tried: * p.parse_known_args -- doesn't complain, but doesn't actually permute either and it doesn't balk about arguments that look like invalid options (e.g., --bogus or -b above). * p.add_argument('files',nargs=argparse.REMAINDER) -- option -z is included in files unless before positional args * p.add_argument('files',nargs='*',action='append'); I want to implement something close to the GNU sort prototype above. I am not interested in a flag that can be specified for each file (e.g., -f file1 -f file2). Answer: Here's a quick solution which decodes the argument list one (options, positional arguments) pair at a time. import argparse class ExtendAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): items = getattr(namespace, self.dest, None) if items is None: items = [] items.extend(values) setattr(namespace, self.dest, items) parser = argparse.ArgumentParser() parser.add_argument('files', nargs='*', action=ExtendAction) parser.add_argument('-z', action='store_true') parser.add_argument('-v', action='count') parser.add_argument('args_tail', nargs=argparse.REMAINDER) def interleaved_parse(argv=None): opts = parser.parse_args(argv) optargs = opts.args_tail while optargs: opts = parser.parse_args(optargs, opts) optargs = opts.args_tail return opts print(interleaved_parse('-z bar foo'.split())) print(interleaved_parse('bar foo -z'.split())) print(interleaved_parse('bar -z foo'.split())) print(interleaved_parse('-v a -zv b -z c -vz d -v'.split())) Output: Namespace(args_tail=[], files=['bar', 'foo'], v=None, z=True) Namespace(args_tail=[], files=['bar', 'foo'], v=None, z=True) Namespace(args_tail=[], files=['bar', 'foo'], v=None, z=True) Namespace(args_tail=[], files=['a', 'b', 'c', 'd'], v=4, z=True) Note: Don't try to use this with other non-flag arguments (besides a single `nargs='*'` argument and the `args_tail` argument). The parser won't know about previous invocations of `parse_args` so it will store the wrong value for these non-flag arguments. As a workaround, you can parse the `nargs='*'` argument manually after using `interleaved_parse`.
How can I iterate image processing through a directory of image files in a sub folder within Python? Question: Needing help specifically with how to connect an iterated list (declared as fileListL) which is dynamically built from a sequence of image files within a sub directory (left) and loops through until it reaches the end of the frame range. All of the script works as intended on a single frame but I am not able to get this to loop through multiple frames. Ideas, thoughts? # this module runs within a root directory that contains one sub folder named 'left' and 15 sub folders expressed in the dirL as ('left/01','left/02, . . . .) # each folder can have any number of sequential .jpg images in the format 'name.0000.jpg' import os import sys import glob import Image from itertools import izip, count # create Master List of files in Left Directories along with a count of files global fileListL fileListL = [] for root, dirs, files in os.walk(r'left/'): for file in files: if file.endswith('.jpg'): fileListL.append('left/'+file) print fileListL # Iterator global inFrame global outFrame inFrame = 'left/test.0000.jpg' # testing temp needs dynamic variable, trying to use fileList L list to dynamically increment thru frames outFrame = inFrame[5:-5] crops = ((0, 0, 1920, 1080),(1920, 0, 3840, 1080), (3840, 0, 5760, 1080), (5760, 0, 7680, 1080), (7680, 0, 9600, 1080), (9600, 0, 11520, 1080), (11520, 0, 13440, 1080), (13440, 0, 15360, 1080), (15360, 0, 17280, 1080), (17280, 0, 19200, 1080), (19200, 0, 21120, 1080), (21120, 0, 23040, 1080), (23040, 0, 24960, 1080), (24960, 0, 26880, 1080), (26880, 0, 28800, 1080)) quads = ('01_', '02_', '03_', '04_', '05_', '06_', '07_', '08_', '09_', '10_', '11_', '12_', '13_', '14_', '15_') dirL= ('left/01/', 'left/02/', 'left/03/', 'left/04/', 'left/05/', 'left/06/', 'left/07/', 'left/08/', 'left/09/', 'left/10/', 'left/11/', 'left/12/', 'left/13/', 'left/14/', 'left/15/') for i in fileListL: for infile in glob.glob( os.path.join(inFrame) ): print "current file is: " + infile oL = Image.open(inFrame) # needs dynamic variable for frames for i, each_quad, each_frame, each_dirL in izip(count(), crops, quads, dirL): print i, each_quad, each_frame, each_dirL frame = oL.crop(((each_quad))) frame.save((each_dirL)+(each_frame)+(outFrame)+'.png') Answer: There are so many "copy&paste" mistakes in your code that is hard to grasp it's purpose. * nested `for` loops using the same name for loop variable (`i`). * `os.path.join(inFrame)` expects a list containing path components, `inFrame` seems to be a string * what is the purpose of the first for loop (`for i in fileListL`), seems like you are discarding `i`. * and so on... Please update the question with your file tree layout and the steps that work for a single file and perhaps we may help you. [update] Seems like your code could be simplified to something like: for i, file_name in enumerate(glob.glob('left/*.jpg')): out_frame = 'left/%02d/%s.png' % (i+1, file_name[5:-5]) print "current input file is: '%s', output file is: %s" % (file_name, out_frame) img = Image.open(file_name) for i, crop in enumerate(crops): frame = img.crop(crop) frame.save(out_frame) It's untested code just to point you the right direction.
Python re.findall regex problems Question: I'm trying to find some very specific data in a string. The problem is I'm not finding all of the data with the current regex I'm using. Here is some sample data: [img:2gcfa9cc]http&#58;//img823&#46;imageshack&#46;us/img823/3295/pokaijumonlogo&#46;jpg[/img:2gcfa9cc] Making these little guys into Kaiju monsters. Again, I know nothing about them, other then which ones I thought would make for cool possible Kaiju (of the original 150) so here's Day 01 [b:2gcfa9cc][size=150:2gcfa9cc]BULBASAUR[/size:2gcfa9cc][/b:2gcfa9cc] [i:2gcfa9cc]Feb 01[/i:2gcfa9cc] [ddf2k12:2gcfa9cc]http&#58;//img853&#46;imageshack&#46;us/img853/2185/dailydrawfeb2012day01&#46;jpg[/ddf2k12:2gcfa9cc] Setting myself up with the same &quot;parameters&quot; as last year I may be breaking my own Challenge rules right now but...well I started this last night and I couldn't just leave 'em out in the cold all unfinished 'n' shit. Obligatory Skyrim drawing. [ddf2k12:2ytorpmj]http&#58;//4&#46;bp&#46;blogspot&#46;com/-UIUSNXvnHz4/TynYf1BZ9oI/AAAAAAAAAl4/pRLHVP0Ny3U/s1600/01_cheatingcheaterwarmup1&#46;jpg[/ddf2k12:2ytorpmj] What I'm trying to get is the data between the `ddf2k12` tags and the `img` tags. I've only worked on the `ddf2k12` tags thus far (I figure the latter will be the former with img instead of `ddf2k12`) and out of the 1586 tags I should have found, I'm only getting 5. Here's my regex: ddf2k12_regex = '(\[[ddf2k12]+\:[A-Za-z0-9]+\])(.*?)(\[[ddf2k12]+\:[A-Za-z0-9]+\])' ddf2k12_find = re.findall(ddf2k12_regex, post) Obviously there's something wrong with my regex, but after banging my head against a wall I can't sort it out, so any help is appreciated. Thanks. Answer: You will do yourself a big favor by breaking down that big regex into parts and use composition. This seems to work correctly, and it's more obvious how to debug it. import re start_tag = '(\[{tagname}:[^\]]+\])' end_tag = start_tag.replace('\[', '\[\/', 1) content = '((?:.|\n)*?)' # The ?: indicates a non-capturing group. tag = start_tag + content + end_tag ddf_tag=tag.format(tagname='ddf2k12') for match in re.findall(ddf_tag, post): print match
What is the optimal way to organize infinitely looped work queue? Question: I have about 1000-10000 jobs which I need to run on a constant basis each minute or so. Sometimes new job comes in or other needs to be cancelled but it's rare event. Jobs are tagged and must be disturbed among workers each of them processes only jobs of specific kind. For now I want to use cron and load whole database of jobs in some broker -- RabbitMQ or beanstalkd (haven't decided which one to use though). But this approach seems ugly to me (using timer to simulate infinity, loading the whole database, etc) and has the disadvantage: for example if some kind of jobs are processed slower than added into the queue it may be overwhelmed and message broker will eat all ram, swap and then just halt. Is there any other possibilities? Am I not using right patterns for a job? (May be I don't need queue or something..?) p.s. I'm using python if this is important. Answer: You create your initial batch of jobs and add them to the queue. You have n-consumers of the queue each running the jobs. Adding consumers to the queue simply round-robins the distribution of jobs to each listening consumer, giving you arbitrary horizontal scalability. Each job can, upon completion, be responsible for resubmitting itself back to the queue. This means that your job queue won't grow beyond the length that it was when you initialised it. The master job can, if need be, spawn sub-jobs and add them to the queue. For different types of jobs it is probably a good idea to use different queues. That way you can balance the load more effectively by having different quantities/horsepower of workers running the jobs from the different queues. The fact that you are running Python isn't important here, it's the pattern, not the language that you need to nail first.
Error with multiple panels in one frame WXPYTHON Question: I have 3 panels in 1 frame the function onSwitchPanels take me from panel to panel,know i want to make a check and if this check is ok then i want to SwitchPanels there is the problem, i stack what i am doing wrong (sorry for my english) Can anyone helpme please? The code is below: import wx import wx.grid as gridlib ######################################################################## class PanelOne(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent=parent) self.txt = wx.TextCtrl(self) button =wx.Button(self, label="Save", pos=(200, 0)) button.Bind(wx.EVT_BUTTON, self.Check) def Check(self,event): passw=self.txt.GetValue() if passw=="1": print "true" self.onSwitchPanels(self) ######################################################################## class PanelTwo(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent=parent) grid = gridlib.Grid(self) grid.CreateGrid(25,12) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(grid, 0, wx.EXPAND) self.SetSizer(sizer) button =wx.Button(self, label="Save", pos=(0, 500)) button.Bind(wx.EVT_BUTTON, parent.onSwitchPanels) class PanelThree(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent=parent) txt = wx.TextCtrl(self) button =wx.Button(self, label="Save", pos=(200, 325)) button.Bind(wx.EVT_BUTTON, parent.onSwitchPanels) ######################################################################## class MyForm(wx.Frame): #---------------------------------------------------------------------- def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "Panel Switcher Tutorial", size=(800,600)) self.panel_one = PanelOne(self) self.panel_two = PanelTwo(self) self.panel_three = PanelThree(self) self.panel_two.Hide() self.panel_three.Hide() self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.panel_one, 1, wx.EXPAND) self.sizer.Add(self.panel_two, 1, wx.EXPAND) self.SetSizer(self.sizer) menubar = wx.MenuBar() fileMenu = wx.Menu() switch_panels_menu_item = fileMenu.Append(wx.ID_ANY, "Switch Panels", "Some text") self.Bind(wx.EVT_MENU, self.onSwitchPanels, switch_panels_menu_item) menubar.Append(fileMenu, '&File') self.SetMenuBar(menubar) #---------------------------------------------------------------------- def onSwitchPanels(self, event): if self.panel_one.IsShown(): self.SetTitle("Panel Two Showing") self.panel_one.Hide() self.panel_two.Show() self.panel_three.Hide() elif self.panel_two.IsShown() or self.panel_three.IsShown(): self.SetTitle("Panel One Showing") self.panel_one.Show() self.panel_two.Hide() self.panel_three.Hide() else: self.SetTitle("Panel Three Showing") self.panel_one.Hide() self.panel_two.Hide() self.panel_three.Show() self.Layout() # Run the program if __name__ == "__main__": app = wx.App(False) frame = MyForm() frame.Show() app.MainLoop() Answer: I find the answer guys this is the code below: import wx import wx.grid as gridlib ######################################################################## class PanelOne(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent=parent) self.s=parent self.txt = wx.TextCtrl(self) button =wx.Button(self, label="Save", pos=(200, 0)) button.Bind(wx.EVT_BUTTON, self.Check) def Check(self,event): passw=self.txt.GetValue() if passw=="1": print "true" self.s.onSwitchPanels(self) ######################################################################## class PanelTwo(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent=parent) grid = gridlib.Grid(self) grid.CreateGrid(25,12) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(grid, 0, wx.EXPAND) self.SetSizer(sizer) button =wx.Button(self, label="Save", pos=(0, 500)) button.Bind(wx.EVT_BUTTON, parent.onSwitchPanels) class PanelThree(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent=parent) txt = wx.TextCtrl(self) button =wx.Button(self, label="Save", pos=(200, 325)) button.Bind(wx.EVT_BUTTON, parent.onSwitchPanels) ######################################################################## class MyForm(wx.Frame): #---------------------------------------------------------------------- def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "Panel Switcher Tutorial", size=(800,600)) self.panel_one = PanelOne(self) self.panel_two = PanelTwo(self) self.panel_three = PanelThree(self) self.panel_two.Hide() self.panel_three.Hide() self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.panel_one, 1, wx.EXPAND) self.sizer.Add(self.panel_two, 1, wx.EXPAND) self.SetSizer(self.sizer) menubar = wx.MenuBar() fileMenu = wx.Menu() switch_panels_menu_item = fileMenu.Append(wx.ID_ANY, "Switch Panels", "Some text") self.Bind(wx.EVT_MENU, self.onSwitchPanels, switch_panels_menu_item) menubar.Append(fileMenu, '&File') self.SetMenuBar(menubar) #---------------------------------------------------------------------- def onSwitchPanels(self, event): if self.panel_one.IsShown(): self.SetTitle("Panel Two Showing") self.panel_one.Hide() self.panel_two.Show() self.panel_three.Hide() elif self.panel_two.IsShown() or self.panel_three.IsShown(): self.SetTitle("Panel One Showing") self.panel_one.Show() self.panel_two.Hide() self.panel_three.Hide() else: self.SetTitle("Panel Three Showing") self.panel_one.Hide() self.panel_two.Hide() self.panel_three.Show() self.Layout() # Run the program if __name__ == "__main__": app = wx.App(False) frame = MyForm() frame.Show() app.MainLoop()
Import csv files containing data with commas into MySQL Question: I have more than 10GB .csv files. I m trying to import the data from these files into MySQL using python. Since csv files are comma separated files, and I have data which itself contains commas, therefore I can not use ',' here for splitting. There please suggest some other option for splitting the csv file. I want to import the data from the csv file(where the data itself contains comma) to MySQL (i am using Wamp server for the same). I have data like 'london, u.k.', '2010', 'credit, saving' Answer: A good answer has been provided for importing using Python. But I'm unclear as to why you need Python to do it. MySQL has built-in commands for importing CSV data---see the [load data](http://dev.mysql.com/doc/refman/5.0/en/load- data.html) manual page. For example, LOAD DATA LOCAL INFILE 'source_data.csv' INTO TABLE my_table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' IGNORE 1 LINES; That last part ignores the first line (use if your CSV file has a "header").
How do I use the Python Scrapy module to list all the URLs from my website? Question: I want to use the Python [Scrapy module](http://scrapy.org/) to scrape all the URLs from my website and write the list to a file. I looked in the examples but didn't see any simple example to do this. Answer: Here's the python program that worked for me: from scrapy.selector import HtmlXPathSelector from scrapy.spider import BaseSpider from scrapy.http import Request DOMAIN = 'example.com' URL = 'http://%s' % DOMAIN class MySpider(BaseSpider): name = DOMAIN allowed_domains = [DOMAIN] start_urls = [ URL ] def parse(self, response): hxs = HtmlXPathSelector(response) for url in hxs.select('//a/@href').extract(): if not ( url.startswith('http://') or url.startswith('https://') ): url= URL + url print url yield Request(url, callback=self.parse) Save this in a file called `spider.py`. You can then use a shell pipeline to post process this text: bash$ scrapy runspider spider.py > urls.out bash$ cat urls.out| grep 'example.com' |sort |uniq |grep -v '#' |grep -v 'mailto' > example.urls This gives me a list of all the unique urls in my site.
Change color in SQlite based application Question: let me explain this clearly: i'm decide to learn about how to store my data with SQLite, and i decide to download sample code and examine it. So, i have a .csv file with data, when my program launch, first thing user see is rows of elements. (Its like when you enter "Contacts" in your iPhone, just rows with names on it). When user tap an element, next view display data about it (not really matter what data is, there is a xib controller and its easy to manage). My question is - how to change color of rows? I don't want it to be "standard white" color, maybe some color i want to import (or default colors, but not just white). This sqlite3 file was created using .csv file, sqlite command tab (terminal), and python. Then imported to application in Xcode. Please help me! Answer: Color display is controlled by your "sample code". If you really want to change the colors you'll need to ask more specifically in case someone else has seen it. To do it yourself, you need to dig into the source (or in its documentation), find where and how it sets the colors, and change it. A possible short-cut would be to search for common color names using an all-file search (if your IDE offers it, or using grep if you're developing on linux/osx). This might lead you to the places where colors are defined. But if your goal is to learn SQL, my advice would be not to waste your time on the application. Ignore the ugly colors and move on to a different environment as soon as you get the chance.
@classmethod with Abstract Base Class Question: I have an Abstract Base Class and subclasses defined as follows (Python 2.7): import abc import MyDatabaseModule class _DbObject(object): __metaclass__ = abc.ABCMeta def _GetObjectType(self): raise NotImplementedError, "Please override in the derived class" ObjectType = abc.abstractproperty(_GetObjectType, None) class Entry(_DbObject): _objectTypeID = 'ENTRY' def _GetObjectType(self): return MyDatabaseModule.DoesSomethingWith(self._objectTypeID) ObjectType = property(_GetObjectType, None) This works fine, meaning that the base class `_DbObject` cannot be instantiated because it has only an abstract version of the property getter method. try: dbObject = _DbObject() print "dbObject.ObjectType: " + dbObject.ObjectType except Exception, err: print 'ERROR:', str(err) Now I can do: entry = Entry() print entry.ObjectType to get access to the `ObjectType` property. However, what I would like to be able to do is just: print Entry.ObjectType However, wherever I try to insert `@classmethod`, I get the error `classmethod object is not callabale`. Answer: The problem is not your `ABC` but the simple fact, that there is no such thing as a `classproperty` in python, you have to create it on your own. Actually there is a good [question + answer on SO](http://stackoverflow.com/questions/128573/using-property-on-classmethods) about that. It actually should be no problem using it with your ABC aswell.
urllib.urlretreive getting images, but images are broken Question: I'm currently teaching myself python (coming from no programming background, but a lot of sys admin, scripting experience) and have gone about creating a script/program that looks at a site and grabs all the images. I've struggled quite a bit but I've gotten it working to an extent. Now, my current issue is that when I do urllib.urlretrieve(url, out_path) on a url like: `http://www.testsite.com/images/img.jpg` \- it works fine but something like `http://www.testsite.com/../images/img.jpg` doesn't work. When you hit that path in your browser it works fine, and urllib.urlretrieve retrieves the images but it's broken when you try and open it in an image viewer. This is my code currently: <http://pastebin.com/E9hutEGn> \- sorry for the pastebin post, the code was a bit too much and I didn't want to make the post read badly. Can anyone recognize why it isn't working? Answer: first of all, the pastebin is good (and also is a good reason why you used it). for your problem, i think that may be an issue of the path joined with the base url. let me explain with an example: >>>> import urlparse >>>> base="http://somesite.com/level1/" >>>> path="../page.html" >>>> urlparse.urljoin(base,path) > 'http://somesite.com/page.html' >>>> base="http://somesite.com/" >>>> urlparse.urljoin(base,path) > 'http://somesite.com/../page.html' so i guess you have to take away your ../ manually little add: i was searching for your problem around and found [this post](http://stackoverflow.com/questions/4114225/python-urlparse-small-issue) that may be useful too
Python's Tkinter simpledialog.askstring not working from command prompt Question: > **Possible Duplicate:** > [Script works in IDLE, but .py-file doesn't > work](http://stackoverflow.com/questions/8319022/script-works-in-idle-but- > py-file-doesnt-work) So i wrote a gui in python's tkinter using python 3.2.2's IDLE. When i run the program from the IDLE in interative mode everything works just fine but when i run it by double clicking on it or from the command prompt it produces an error and doesnt start the program. i know the problem is with this line: path_da=self.simdia.askstring("Path to start","Paths must be relative!") i have imported all from tkinter. path_da is suposed to be the string from the askstring dialog. i set simdia to simpledialog as a public variable in my class. I just don't understand why this works when running it using F5 in IDLE but not from the command prompt Answer: I flagged this as a dupe since the error received for using `simpledialog.askstring` without importing `simpledialog` from the `tkinter` module, is the same error you would get if just `simpledialog` was being used. If it's not considered a duplicate, here is the answer: Quoting [Roger's answer](http://stackoverflow.com/a/8353233/404469) to a similar question: > IDLE uses Tkinter as its graphical environment. It is possible that your > code is relying on a side effect of an import by IDLE itself. This is > especially true if you use IDLE without a subprocess. > > The simpledialog module does not import when using from tkinter import* Try adding this to your code: import tkinter.simpledialog as simpledialog
Communicate with Java program from Python Question: My Python progam is "check.py" import os.path,subprocess from subprocess import STDOUT,PIPE def compile_java(java_file): subprocess.check_call(['javac', java_file]) def execute_java(java_file): java_class,ext = os.path.splitext(java_file) cmd = ['java', java_class] proc = subprocess.Popen(cmd,stdout=PIPE,stdin-PIPE,stderr=STDOUT) stdout,stderr = proc.communicate("viraj") print stdout My Java program is "Test.java" import java.util.*; class Test { public static void main(String args[]) { System.out.println("Tested Successfully"); Scanner t=new Scanner(System.in); System.out.println("Enter the string"); String str=t.nextLine(); System.out.println("Hello "+str); } } Here, in `check.py`, I am passing a parameter `viraj` as `proc.communicate("viraj")` and hence my output is > Tested Successfully > Enter the string > Hello viraj However, I don't want to pass the parameter. Instead I want the output as > Tested Successfully > Enter the String and then after I enter the string as `viraj`, it should get printed as `Hello viraj` How can I do this? Answer: To interact with the java program, simply call `communicate()` with no arguments. def execute_java(java_file): java_class,ext = os.path.splitext(java_file) cmd = ['java', java_class] proc = subprocess.Popen(cmd) proc.communicate()
Do I need to create a separate class in my models.py when using the django.contrib.auth.models import user? Question: The import statement import the needed parts. but is the "user" class already made when you put that into your installed apps? or do you still need to clarify in models.py in order to make the table in the db? or can someone expand on how to use django users and sessions? I'm looking over the django docs right now and they all just go over how to use the thing once. they never put the code in a syntax where users are going to be the ones using the code through a browser and not you through a python shell. Answer: All installed apps can contribute to the database schema. `django.contrib.auth.models` contributes, among others, the `auth_user` table behind the `django.contrib.auth.models.User` model, therefore you do not have to worry about recreating it unless you have a specific reason to do so.
How do I write to .csv from text entry? Question: I'm working on my computing project for school, and I'm having trouble getting anything the user inputs to save to a .csv file. I'm using Python 3.2.2 and Tkinter as the GUI. No matter what I enter into the fields I get the wrong output into the csv, similar to ".54540776.54541280," etc. I've basically had to teach myself this stuff as I've gone along so I'm probably just making a stupid mistake somewhere. I've tried using the csv module in Python and I can't get that working. I haven't been able to find anything similar (that I understand to be the same anyway). I've uploaded my code to pastebin to make it more readable: <http://pastebin.com/FarMtWdZ> Answer: _note: I didn't read all of the code, but this addresses the crux of the problem._ The problem is with how you are pulling the contents of an `Entry`. Don't use `str(your_entry)`, rather use `your_entry.get()`. from Tkinter import * root = Tk() e = Entry(root) e.insert(0, "a default value") e.pack() print "str(e) =>", str(e) # str() just gives us Tk's internal identifier print "e.get() =>", e.get() # use get() for contents of Entry root.mainloop() gives str(e) => .33906776 e.get() => a default value
Scan through txt, append certain data to an empty list in Python Question: I have a text file that I am reading in python . **I'm trying to extract certain elements from the text file that follow keywords to append them into empty lists** . The file looks like this: ![enter image description here](http://i.stack.imgur.com/vuqLh.png) so I want to make two empty lists * 1st list will append the sequence names * 2nd list will be a list of lists which will include be in the format `[Bacteria,Phylum,Class,Order, Family, Genus, Species]` most of the organisms will be Uncultured bacterium . I am trying to add the Uncultured bacterium with the following IDs that are separated by ; **Is there anyway to scan for a certain word and when the word is found, take the word that is after it [separated by a '\t'] ?** I need it to create a dictionary of the Sequence Name to be translated to the taxonomic data . I know i will need an empty list to append the names to: seq_names=[ ] a second list to put the taxonomy lists into taxonomy=[ ] and a 3rd list that will be reset after every iteration temp = [ ] _I'm sure it can be done in Biopython but i'm working on my python skills_ Answer: Yes there is a way. You can split the string which you get from reading the file into an array using the inbuilt function split. From this you can find the index of the word you are looking for and then using this index plus one to get the word after it. For example using a text file called test.text that looks like so (the formatting is a bit weird because SO doesn't seem to like hard tabs). one two three four five six seven eight nine The following code f = open('test.txt','r') string = f.read() words = string.split('\t') ind = words.index('seven') desired = words[ind+1] will return desired as 'eight' Edit: To return every following word in the list f = open('test.txt','r') string = f.read() words = string.split('\t') desired = [words[ind+1] for ind, word in enumerate(words) if word == "seven"] This is using list comprehensions. It enumerates the list of words and if the word is what you are looking for includes the word at the next index in the list. Edit2: To split it on both new lines and tabs you can use regular expressions import re f = open('testtest.txt','r') string = f.read() words = re.split('\t|\n',string) desired = [words[ind+1] for ind, word in enumerate(words) if word == "seven"]
Where in the world is com.ibm.ws.scripting.adminCommand.AdminTask? Question: Frustrated with the damn awful API provided by WebSphere Admin Server, I'm writing my own Java DSL wrapper. My jython files now simply read: from my.package import MyDSL config = MyDSL(AdminConfig, AdminTask) config.goGoGadgetSkates() # or something like that The essential part is that I send through the (#%$$!@#) god objects `AdminConfig` and `AdminTask` so that the DSL can use them to perform operations in WAS. In order to compile the DSL I need to include the class files for this two objects. I find them by first setting the constructor as: public MyDSL(Object a, Object b) { System.out.println(a.getClass()); System.out.println(b.getClass()); } The output showed that the AdminConfig object is an instance of `com.ibm.ws.scripting.AdminConfigClient`. I easily located the jar that contains this class and all is well. But AdminTask is an instance of `com.ibm.ws.scripting.adminCommand.AdminTask`. Despite being present at runtime, this class does not exist anywhere in my classpath or indeed anywhere on my computer's hard drive. I can only assume `com.ibm.ws.scripting.adminCommand.AdminTask` is constructed magically by WSAdmin in the jython layer. Perhaps it is defined as a python class? Before I [resort to reflection](http://stackoverflow.com/questions/9595782/call-method-via- reflection-when-argument-is-of-type-object), can someone please explain where `com.ibm.ws.scripting.adminCommand.AdminTask` might live and how I might extract a copy of the class file? Answer: The AdminConfigClient class is not API/SPI, so you are creating a fragile infrastructure by relying on that class. The API/SPI entry point is [ConfigServiceFactory](http://publib.boulder.ibm.com/infocenter/wasinfo/v8r0/topic/com.ibm.websphere.javadoc.doc/web/apidocs/com/ibm/websphere/management/configservice/ConfigServiceFactory.html). The AdminTask object is backed by the data in [CommandMgr](http://publib.boulder.ibm.com/infocenter/wasinfo/v8r0/topic/com.ibm.websphere.javadoc.doc/web/apidocs/com/ibm/websphere/management/cmdframework/CommandMgr.html). It should be possible to use CommandMgr to do anything you can do with AdminTask.
Python: Update XML-file using ElementTree while conserving layout as much as possible Question: I have a document which uses an XML namespace for which I want to increase `/group/house/dogs` by one: (the file is called `houses.xml`) <?xml version="1.0"?> <group xmlns="http://dogs.house.local"> <house> <id>2821</id> <dogs>2</dogs> </house> </group> My current result using the code below is: (the created file is called `houses2.xml`) <ns0:group xmlns:ns0="http://dogs.house.local"> <ns0:house> <ns0:id>2821</ns0:id> <ns0:dogs>3</ns0:dogs> </ns0:house> </ns0:group> I would like to fix two things (if it is possible using ElementTree. If it isn´t, I´d be greatful for a suggestion as to what I should use instead): 1. I want to keep the `<?xml version="1.0"?>` line. 2. I do not want to prefix all tags, I´d like to keep it as is. In conclusion, **I don´t want to mess with the document more than I absolutely have to.** My current code (which works except for the above mentioned flaws) generating the above result follows. I have made a utility function which loads an XML file using ElementTree and returns the elementTree and the namespace (as I do not want to hard code the namespace, and am willing to take the risk it implies): def elementTreeRootAndNamespace(xml_file): from xml.etree import ElementTree import re element_tree = ElementTree.parse(xml_file) # Search for a namespace on the root tag namespace_search = re.search('^({\S+})', element_tree.getroot().tag) # Keep the namespace empty if none exists, if a namespace exists set # namespace to {namespacename} namespace = '' if namespace_search: namespace = namespace_search.group(1) return element_tree, namespace This is my code to update the number of dogs and save it to the new file `houses2.xml`: elementTree, namespace = elementTreeRootAndNamespace('houses.xml') # Insert the namespace before each tag when when finding current number of dogs, # as ElementTree requires the namespace to be prefixed within {...} when a # namespace is used in the document. dogs = elementTree.find('{ns}house/{ns}dogs'.format(ns = namespace)) # Increase the number of dogs by one dogs.text = str(int(dogs.text) + 1) # Write the result to the new file houses2.xml. elementTree.write('houses2.xml') Answer: An XML based solution to this problem is to write a helper class for ElementTree which: * Grabs the XML-declaration line before parsing as ElementTree at _the time of writing_ is unable to write an XML-declaration line without also writing an encoding attribute(I checked the source). * Parses the input file once, grabs the namespace of the root element. Registers that namespace with ElementTree as having the empty string as prefix. When that is done the source file is parsed using ElementTree _again_ , with that new setting. It has one major drawback: * **XML-comments are lost.** Which I have learned is not acceptable for this situation(I initially didn´t think the input data had any comments, but it turns out it has). My helper class with example: from xml.etree import ElementTree as ET import re class ElementTreeHelper(): def __init__(self, xml_file_name): xml_file = open(xml_file_name, "rb") self.__parse_xml_declaration(xml_file) self.element_tree = ET.parse(xml_file) xml_file.seek(0) root_tag_namespace = self.__root_tag_namespace(self.element_tree) self.namespace = None if root_tag_namespace is not None: self.namespace = '{' + root_tag_namespace + '}' # Register the root tag namespace as having an empty prefix, as # this has to be done before parsing xml_file we re-parse. ET.register_namespace('', root_tag_namespace) self.element_tree = ET.parse(xml_file) def find(self, xpath_query): return self.element_tree.find(xpath_query) def write(self, xml_file_name): xml_file = open(xml_file_name, "wb") if self.xml_declaration_line is not None: xml_file.write(self.xml_declaration_line + '\n') return self.element_tree.write(xml_file) def __parse_xml_declaration(self, xml_file): first_line = xml_file.readline().strip() if first_line.startswith('<?xml') and first_line.endswith('?>'): self.xml_declaration_line = first_line else: self.xml_declaration_line = None xml_file.seek(0) def __root_tag_namespace(self, element_tree): namespace_search = re.search('^{(\S+)}', element_tree.getroot().tag) if namespace_search is not None: return namespace_search.group(1) else: return None def __main(): el_tree_hlp = ElementTreeHelper('houses.xml') dogs_tag = el_tree_hlp.element_tree.getroot().find( '{ns}house/{ns}dogs'.format( ns=el_tree_hlp.namespace)) one_dog_added = int(dogs_tag.text.strip()) + 1 dogs_tag.text = str(one_dog_added) el_tree_hlp.write('hejsan.xml') if __name__ == '__main__': __main() The output: <?xml version="1.0"?> <group xmlns="http://dogs.house.local"> <house> <id>2821</id> <dogs>3</dogs> </house> </group> If someone has an improvement to this solution please don´t hesitate to grab the code and improve it.
Include .pyd module files in py2exe compilation Question: I'm trying to compile a python script. On executing the exe I got:- C:\Python27\dist>visualn.exe Traceback (most recent call last): File "visualn.py", line 19, in <module> File "MMTK\__init__.pyc", line 39, in <module> File "Scientific\Geometry\__init__.pyc", line 30, in <module> File "Scientific\Geometry\VectorModule.pyc", line 9, in <module> File "Scientific\N.pyc", line 1, in <module> ImportError: No module named Scientific_numerics_package_id I can see the file Scientific_numerics_package_id.pyd at the location `"C:\Python27\Lib\site-packages\Scientific\win32"`. I want to include this module file into the compilation. I tried to copy the above file in the "dist" folder but no good. Any idea? **Update:** Here is the script: from MMTK import * from MMTK.Proteins import Protein from Scientific.Visualization import VRML2; visualization_module = VRML2 protein = Protein('3CLN.pdb') center, inertia = protein.centerAndMomentOfInertia() distance_away = 8.0 front_cam = visualization_module.Camera(position= [center[0],center[1],center[2]+distance_away],description="Front") right_cam = visualization_module.Camera(position=[center[0]+distance_away,center[1],center[2]],orientation=(Vector(0, 1, 0),3.14159*0.5),description="Right") back_cam = visualization_module.Camera(position=[center[0],center[1],center[2]-distance_away],orientation=(Vector(0, 1, 0),3.14159),description="Back") left_cam = visualization_module.Camera(position=[center[0]-distance_away,center[1],center[2]],orientation=(Vector(0, 1, 0),3.14159*1.5),description="Left") model_name = 'vdw' graphics = protein.graphicsObjects(graphics_module = visualization_module,model=model_name) visualization_module.Scene(graphics, cameras=[front_cam,right_cam,back_cam,left_cam]).view() Answer: Py2exe lets you specify additional Python modules (both .py and .pyd) via the `includes` option: setup( ... options={"py2exe": {"includes": ["Scientific.win32.Scientific_numerics_package_id"]}} ) EDIT. The above should work if Python is able to import Scientific.win32.Scientific_numerics_package_id
How to use "range_key_condition" to query a DynamoDB table with boto? Question: To get range_key between (0,9999), can I do it this way? conn = boto.connect_dynamodb() table = conn.get_table("mytable") ... result = table.query( hash_key = "66", range_key_condition = {"0":"GE", "9999":"LE"} ) # with boto v2.2.2-dev, I always get empty results EDIT: This is a another error sample: In [218]: qa = taa.query(hash_key = "1") In [219]: qa.next() Out[219]: {u'attra': u'this is attra', u'key': u'1', u'range': 1.1} ## It's OK without "range_key_condition" above In [220]: qa = taa.query(hash_key = "1", range_key_condition = {0.1: "GE"}) In [221]: qa.next() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /home/user/python/enva/<ipython-input-221-dba0a498b6e1> in <module>() ----> 1 qa.next() /home/user/python/enva/local/lib/python2.7/site-packages/boto-2.2.2_dev-py2.7.egg/boto/dynamodb/layer2.pyc in query(self, table, hash_key, range_key_condition, attributes_to_get, request_limit, max_results, consistent_read, scan_index_forward, exclusive_start_key, item_class) 559 """ 560 if range_key_condition: --> 561 rkc = self.dynamize_range_key_condition(range_key_condition) 562 else: 563 rkc = None /home/user/python/enva/local/lib/python2.7/site-packages/boto-2.2.2_dev-py2.7.egg/boto/dynamodb/layer2.pyc in dynamize_range_key_condition(self, range_key_condition) 83 structure required by Layer1. 84 """ ---> 85 return range_key_condition.to_dict() 86 87 def dynamize_scan_filter(self, scan_filter): AttributeError: 'dict' object has no attribute 'to_dict' Answer: If you are using the latest version of boto (and it looks like you are) the way conditions have been changed from previous versions in an attempt to make the query more readable. Try this: from boto.dynamodb.condition import * conn = boto.connect_dynamodb() table = conn.get_table("mytable") ... result = table.query( hash_key = "66", range_key_condition = BETWEEN(0, 9999)) It should work although you will have to update your boto code since I just discovered a bug in BETWEEN while investigating this question (see <https://github.com/boto/boto/issues/620>).
adding each member of an array again, right after itself Question: if I have this Python array: mac_tags = [ "global_rtgn", "global_mogn" ] And I want this Python array: mac_tags = [ "global_rtgn", "global_rtgn", "global_mogn","global_mogn" ] How might I create it programmatically? Answer: new_mac_tags = [] for tag in mac_tags: new_mac_tags += [tag, tag] or from itertools import chain, izip new_mac_tags = list(chain.from_iterable(izip(mac_tags, mac_tags)))
python paths and import order Question: Ok so I really want to get this right because I keep running into it when generating some big py2app/py2exe packages. So I have my package that contains a lot of modules/packages that might also be in the users site packages/default location (if a user has a python distribution) but I want my distributed packages to take effect before them when running from my distribution. Now from what I've read [here](http://docs.python.org/using/windows.html) **PYTHONPATH** should be the 1st thing added to sys.path after the current directory, however from what I've tested on my machine that is not the case and all the folders defined in `$site-packages$/easy-install.pth` take precedence over this. So could someone please give me some more in depth explanation about this import order//help me find a way to set the environmental variables in such a way that the packages I distribute take precedence over the default installed ones. So far my attempt is, for example on Mac-OS py2app, in my entry point script: os.environ['PYTHONPATH'] = DATA_PATH + ':' os.environ['PYTHONPATH'] = os.environ['PYTHONPATH'] + os.path.join(DATA_PATH , 'lib') + ':' os.environ['PYTHONPATH'] = os.environ['PYTHONPATH'] + os.path.join( DATA_PATH, 'lib', 'python2.7', 'site-packages') + ':' os.environ['PYTHONPATH'] = os.environ['PYTHONPATH'] + os.path.join( DATA_PATH, 'lib', 'python2.7', 'site-packages.zip') This is basically the structure of the package generated by py2app. Then I just: SERVER = subprocess.Popen([PYTHON_EXE_PATH, '-m', 'bin.rpserver' , cfg.RPC_SERVER_IP, cfg.RPC_SERVER_PORT], shell=False, stdin=IN_FILE, stdout=OUT_FILE, stderr=ERR_FILE) Here PYTHON_EXE_PATH is the path to the python exe that is added by py2app to the package. Now this works fine on a machine that doesn't have a python installed. However when python distribution is already present, their site- packages take precedence. Answer: Python searches the paths in `sys.path` in order (see <http://docs.python.org/tutorial/modules.html#the-module-search-path>). easy_install changes this list directly (see the last line in your easy- install.pth file): import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new) This basically takes whatever directories are added and inserts them at the beginning of the list. Also see [Eggs in path before PYTHONPATH environment variable](http://stackoverflow.com/questions/5984523/eggs-in-path-before- pythonpath-environment-variable).
wxPython: MenuBar Bound Events Execute on Init Question: Hello StackOverflow Hive Mind; I am in the process of learning how to use wxPython it make a GUI for an application I am writing. I've been slogging through that well enough until I noticed that I could not properly make a menu bar. Whatever I am doing wrong is causing my event bindings to be executed upon the running of the program. Here is the code in question. Minor misspellings should be ignored, I am retyping this off of my development machine which is offline so I might miss a key here or there. def onDocClick(): message = wx.MessageBox("did it work?","Question",wx.YES_NO) def onAboutClick(): pass frame = wx.Frame(parent=None,title="RVR GUI",size=(315,490)) frame.Show() panel = wx.Panel(frame,-1,size=(315,490) menubar = wx.MenuBar() fileMenu = wx.Menu() documentation = fileMenu.Append(wx.ID_NEW,"Documentation") about = fileMenu.Append(wx.ID_ABOUT,"About") menuBar.Append(fileMenu,'File') frame.SetMenuBar(menubar) menubar.Bind(wx.EVT_MENU,onDocClick(),documentation) menubar.Bind(wx.EVT_MENU,onAboutClick(),about) There is alot more to the GUI than that but the rest of the code works fine so I don't think you need it. Basically what is happening, is that the message box in onDocClick() is executed as soon as I run the script that opens the GUI. One I click amy button the rest of the GUI initializes fine and a click on the "Documentation" menu entry sees absolutly nothin at all happen. I have a feeling I am probobly missing something simple, perhaps wx.EVT_MENU is not the right one to use in this situation? If that is the case what would the right one to use be? Every single tutorial I have seen on wxPython has done it this way without explaination. Honestly I have been appalled at the lack of meaningful documentation for wxPython. The Zetcode tutorials and even the ever helpful Mouse vs Python just seems to glaze right over the fundamentals of how the toolkit works. But I digress and I've been making do, I've just been completely befuddled by this. Anyway thanks and I appreciate any responses! Michael Answer: You should have a really close look at your code. I think you are doing everything alright in terms of using wxPython, but the event binding is not done properly. You should pass _method names_ as arguments for the `Bind` method. Instead, you make a _method call_ (this causes the bound methods to be executed during UI construction). To fix it, you have to leave out the parentheses. The last two lines of your listing should become this: ~~ menubar.Bind(wx.EVT_MENU, onDocClick, documentation) menubar.Bind(wx.EVT_MENU, onAboutClick, about) ~~ I tried out your code, and BrtH was right, I was not successul with binding from the menubar, you should bind events from the `wx.Frame` instance instead. Your complete, runnable example now looks like this: import wx def onDocClick(evt): message = wx.MessageBox("did it work?","Question",wx.YES_NO) def onAboutClick(evt): print "clicked" app = wx.App() frame = wx.Frame(parent=None,title="RVR GUI",size=(315,490)) frame.Show() panel = wx.Panel(frame,-1,size=(315,490)) menubar = wx.MenuBar() fileMenu = wx.Menu() documentation = fileMenu.Append(wx.ID_NEW,"Documentation") about = fileMenu.Append(wx.ID_ABOUT,"About") menubar.Append(fileMenu,'File') frame.SetMenuBar(menubar) frame.Bind(wx.EVT_MENU,onDocClick,documentation) frame.Bind(wx.EVT_MENU,onAboutClick,about) app.MainLoop()
lxml error "IOError: Error reading file" when parsing facebook mobile in a python scraper script Question: I use a modified script from [Logging into facebook with python](http://stackoverflow.com/questions/2030652/logging-into-facebook-with- python) post : #!/usr/bin/python2 -u # -*- coding: utf8 -*- facebook_email = "[email protected]" facebook_passwd = "YOUR_PASSWORD" import cookielib, urllib2, urllib, time, sys from lxml import etree jar = cookielib.CookieJar() cookie = urllib2.HTTPCookieProcessor(jar) opener = urllib2.build_opener(cookie) headers = { "User-Agent" : "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7", "Accept" : "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,text/png,*/*;q=0.5", "Accept-Language" : "en-us,en;q=0.5", "Accept-Charset" : "utf-8", "Content-type": "application/x-www-form-urlencoded", "Host": "m.facebook.com" } try: params = urllib.urlencode({'email':facebook_email,'pass':facebook_passwd,'login':'Log+In'}) req = urllib2.Request('http://m.facebook.com/login.php?m=m&refsrc=m.facebook.com%2F', params, headers) res = opener.open(req) html = res.read() except urllib2.HTTPError, e: print e.msg except urllib2.URLError, e: print e.reason[1] def fetch(url): req = urllib2.Request(url,None,headers) res = opener.open(req) return res.read() body = unicode(fetch("http://www.facebook.com/photo.php?fbid=404284859586659&set=a.355112834503862.104278.354259211255891&type=1"), errors='ignore') tree = etree.parse(body) r = tree.xpath('/see_prev') print r.text When I execute the code, problems appears : $ ./facebook_fetch_coms.py Traceback (most recent call last): File "./facebook_fetch_coms_classic_test.py", line 42, in <module> tree = etree.parse(body) File "lxml.etree.pyx", line 2957, in lxml.etree.parse (src/lxml/lxml.etree.c:56230) File "parser.pxi", line 1533, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:82313) File "parser.pxi", line 1562, in lxml.etree._parseDocumentFromURL (src/lxml/lxml.etree.c:82606) File "parser.pxi", line 1462, in lxml.etree._parseDocFromFile (src/lxml/lxml.etree.c:81645) File "parser.pxi", line 1002, in lxml.etree._BaseParser._parseDocFromFile (src/lxml/lxml.etree.c:78554) File "parser.pxi", line 569, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:74498) File "parser.pxi", line 650, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:75389) File "parser.pxi", line 588, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:74691) IOError: Error reading file '<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head><title>Facebook</title><meta name="description" content="Facebook helps you connect and share with the people in your life." The goal is first to get the link with `id=see_prev` with `lxml`, then using a while loop to open all comments, to finally fetch all messages in a file. Any help will be very appreciated ! **Edit** : I use Python 2.7.2 on archlinux x86_64 and lxml 2.3.3. Answer: This is your problem: tree = etree.parse(body) The [documentation](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.parse) says that "`source` is a filename or file object containing XML data." You have provided a string, so lxml is taking the text of your HTTP response body as the **name** of the file you wish to open. No such file exists, so you get an `IOError`. The error message you get even says "Error reading file" and then gives your XML string as the _name of the file it's trying to read,_ which is a mighty big hint about what's going on. You probably want [`etree.XML()`](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.XML), which takes input from a string. Or you could just do `tree = etree.parse(res)` to read directly from the HTTP request into lxml (the result of `opener.open()` is a file-like object, and `etree.parse()` should be perfectly happy to consume it).
"TypeError: 'str' object is not callable' raised when method is called in an if statement (Python) Question: I get a TypeError when I call a method in an if-block, but the method runs find when it is called outside an if block: randenzyme() randomly chooses a key from a dictionary called enzymes: def randenzyme(self): an_enzyme = choice(self.enzymes.keys()) It runs correctly with: x = TCA() x.randenzyme() But "TypeError: 'str' object is not callable" is raised with: x = TCA() user_input = raw_input('> ') if user_input == "1": x.randenzyme() What is happening when the method is called in the if block? UPDATE: Here is the full code from random import * import sys class TCA(object): def __init__(self): self.enzymes = {} self.enzymes['citrate synthase'] = ('oxaloacetate', 'citrate') self.enzymes['aconitase'] = ('citrate', 'isocitrate') self.enzymes['isocitrate dehydrogenase'] = ('isocitrate', 'alpha-ketoglutarate') self.enzymes['alpha-ketoglutarate dehydrogenase'] = ('alpha-ketoglutarate', 'succinyl-CoA') self.enzymes['succinyl-CoA synthetase'] = ('succinyl-CoA', 'succinate') self.enzymes['succinate dehydrogenase'] = ('succinate', 'fumarate') self.enzymes['fumarase'] = ('fumarate', 'malate') self.enzymes['malate dehydrogenase'] = ('malate', 'oxaloacetate') def randenzyme(self): an_enzyme = choice(self.enzymes.keys()) print "Reaction (enzyme): %s" % an_enzyme return an_enzyme x = TCA() print 'Enter "1" for a random enzyme or "2" to exit' choice = raw_input("> ") if choice == '1': x.randenzyme() elif choice == '2': sys.exit() The error I get is: Traceback (most recent call last): File "/Users/sloria1/TCASO.py", line 24, in <module> x.randenzyme() File "/Users/sloria1/TCASO.py", line 16, in randenzyme an_enzyme = choice(self.enzymes.keys()) TypeError: 'str' object is not callable Answer: It's impossible to be certain without a traceback, but you probably did something silly like stomp on `choice` or the like.
How to parse json in bash or pass curl output to python script Question: I'm looking to find some way to have pretty print of curl's output in json. I wrote short python script for this purpose, but it won't work with pipe Also I don't want to use subprocesses and run curl from them: So python: #!/usr/bin/python import simplejson from pprint import pprint import sys print pprint(simplejson.loads(sys.argv[1])) And json information is: {"response": {"utilization": {"eic": [{"date": "2012.03.06", "usage": []}, {"date": "2012.03.07", "usage": [{"srvCode": "SVC302", "upload": 267547188, "api-calls": {"fileGetInfo": 30, "getUserStorageQuota": 0, "setUserStorageQuota": 0, "fileUploadFlashInit": 31, "getAPISessionUser": 0, "setFileAccessControl": 0, "fileGetPreviewUrl": 0, "fileStartMultipartUpload": 0, "getServiceQuota": 0, "fileGetPreviewUrlsForBunch": 10, "xcodingGetStreamUrl": 0, "getSessionTimeLimit": 0, "fileGetCoversUrlsForBunch": 27, "makePreviews": 0, "setServiceQuota": 0, "getAPISessionTrusted": 3, "getFileAccessControl": 0, "xcodingGetFormats": 0, "getQuotaNotificationEmail": 0, "fileGetDownloadUrl": 0, "xcodingGetStreamInfo": 0, "fileUploadDone": 30, "getLocalServiceUtilization": 9, "getServiceUtilization": 0, "fileDelete": 19, "setSessionTimeLimit": 0, "fileGetMultipartUploadUrl": 0, "fileUploadInit": 0, "extractFileMetadata": 30, "setQuotaNotificationEmail": 0}, "average-storage": 3801210959.4961309, "download": 0, "transcoding": 0}]}]}}} Answer: Using `json.tool` from the shell to validate and pretty-print: $ echo '{"json":"obj"}' | python -mjson.tool { "json": "obj" }
File not being released Question: Ok so I have to run some queries in access 07 then compact and repair it. I am using python and win32com to do this. The code I'm currently using is this. import os; import win32com.client; DB1 = 'db1.mdb' DB2 = 'db1N.mdb' DB3 = 'db2.mdb' DBR = r'db1.mdb' access = win32com.client.Dispatch("Access.Application") access.OpenCurrentDatabase(DBR) DB = access.CurrentDb() access.DoCmd.OpenQuery("1") access.DoCmd.OpenQuery("2") access.DoCmd.OpenQuery("3") access.CloseCurrentDatabase() access.Application.Quit(); os.system('copy "db1.mdb" "db2.mdb"') access = win32com.client.Dispatch("Access.Application") access.CompactRepair(DB3,DB2) access.Application.Quit(); os.remove("db2.mdb") os.remove("db1.mdb") os.rename("db1N.mdb","db1.mdb") The problem is that I get this error. WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'db1.mdb' I dont know why I am getting this error seeing as I am quiting access which should close the file. Any Idea how to fix this would be greatly appreciated. Answer: Your code includes this line: DB = access.CurrentDb() When that line executes, `CurrentDb()` references _db1.mdb_. Then you later get _WindowsError_ at: os.remove("db1.mdb") So I'm wondering if the variable DB still holds a reference to _db1.mdb_. Perhaps you could first try `del DB` before `os.remove()`. Or, since your code isn't actually using that DB variable, just get rid of it.
Access to deleted entity in Appengine NDB Question: I am using NDB in an Appengine project. I am using _post_delete_hook for doing some operations after some entity is deleted. In this method I have the key. But when I do key.get() I get an error. Here is some example code. [friends/models.py] from ndb import models from users.models import User class FriendShip(models.Model): user = models.KeyProperty(kind=User) friend = models.KeyProperty(kind=User) @classmethod def _post_delete_hook(cls, key, future): signals.post_delete.send(cls, instance=key) [some-other-filer.py] # connected method to post_detele_hook def ended_friendship(sender, **kwargs): key = kwargs.get('instance', None) if key: user = key.get().user # raise a non existing entity error Some help? This is the doc about hooks. <http://code.google.com/appengine/docs/python/ndb/entities.html#hooks> Answer: For your use case (wanting to access the entity in your method), a _pre_delete_hook might make more sense. See <http://code.google.com/appengine/docs/python/ndb/modelclass.html#Model__pre_delete_hook> .
"".join(list) if list contains a nested list in python? Question: I know that `"".join(list)` converts the list to a string, but what if that list contains a nested list? When I try it returns a `TypeError` due to unexpected list type. I'm guessing it's possible with error handling, but so far my attempts have been fruitless. Answer: Well, if the list is nested, simply [flatten](http://stackoverflow.com/questions/406121/flattening-a-shallow-list- in-python) it beforehand: >>> import itertools >>> lst = [['a', 'b'], ['c', 'd']] >>> ''.join(itertools.chain(*lst)) 'abcd'
CORS Access-Control-Allow-Origin despite correct headers Question: I am trying to set up simple Cross-Origin Resource Sharing using jQuery (1.7.1) powered ajax on the client and apache served python (django) server. According to all the instructions I have read my headers are set correctly, but I keep getting the following error: > XMLHttpRequest cannot load <http://myexternaldomain.com/get_data>. Origin > <http://localhost:8080> is not allowed by Access-Control-Allow-Origin. The header being I am trying to (I am not sure it is even getting past the browser) send is: Request URL:http://myexternaldomain.com/get_data Accept:application/json, text/javascript, */*; q=0.01 Origin:http://localhost:8080 Referer:http://localhost:8080/static/js/test-zetta.html User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11 The javascript code is var request = $.ajax({ url : "http://myexternaldomain.com/get_data", type : "POST", dataType : "json", crossDomain : true }); Note that `origin` is set correctly. The server adds the header `Access- Control-Allow-Origin = *` using the following python code def process_response(self, response): if response.has_header('Access-Control-Allow-Origin'): return response response['Access-Control-Allow-Origin'] = '*' return response def get_orders(request): """ Tell worker what to do """ response_data = {} response_data['action'] = 'probe' response = process_response(HttpResponse(json.dumps(response_data), mimetype="application/json")) return response If I visit the address directly, it appears to confirm that the header is being set correctly Access-Control-Allow-Origin:* Content-Type:application/json Date:Thu, 08 Mar 2012 05:06:25 GMT Server:Apache/2.2.20 (Ubuntu) Transfer-Encoding:chunked However in the cross domain setting it always fails (tried both chrome and firefox). I've tried implementing the code exactly as per the selected answer to [this](http://stackoverflow.com/questions/5251689/cross-domain-post-query- using-cross-origin-resource-sharing-getting-no-data-back) question, but get the same error **Update** I am quite sure that the problem is server side, as I have managed to get my ajax calls working with a different public CORS enabled server. When I compare the headers coming back from this public server, and the ones returned from mine (when I test from same domain), I cannot see any major difference which could account for difference (see below). One subtlety that I excluded, which may or may be important is that the actual domain is an amazon domain of multiple subdomains. The **real address** is <http://ec2-23-20-27-108.compute-1.amazonaws.com/get_orders> , feel free to probe it to see what I am doing wrong. **From Public server** Access-Control-Allow-Origin:* Connection:Keep-Alive Content-Encoding:gzip Content-Length:622 Content-Type:text/html Date:Thu, 08 Mar 2012 15:33:20 GMT Keep-Alive:timeout=15, max=99 Server:Apache/2.2.14 (Ubuntu) Vary:Accept-Encoding X-Powered-By:Perl/5.8.7, PHP/4.4.0 **From my server - (not working cross domain)** Access-Control-Allow-Origin:* Content-Encoding:gzip Content-Type:text/plain Date:Thu, 08 Mar 2012 15:32:24 GMT Server:Apache/2.2.20 (Ubuntu) Transfer-Encoding:chunked Vary:Accept-Encoding Answer: You have to implement a "pre-flighted" request and response because your situation counts as a "[not so simple](http://www.html5rocks.com/en/tutorials/cors/)" request. Basic CORS, that only requires the Origin header, can only have content types of "application/x-www-form-urlencoded", "multipart/form-data", and "text/plain". Since you return "application/json", you don't meet this requirement. I don't know anything about Django, but I found it easier to implement CORS support outside of my application through the use of a [Tomcat filter](https://bitbucket.org/jsumners/corsfilter). It looks like you can [do the same thing](https://github.com/elevenbasetwo/django-cors) with Django. **2013-08-11:** It looks like the GitHub repo is no longer with us. But the Django package looks to still be available at <https://pypi.python.org/pypi/django-cors/0.1>
Using Linux kernel add_key and keyctl syscalls with group keyring Question: I'm building an application that needs to use the Linux group keyring to share some sensitive data between processes with different owners. Whenever I try to access the group keyring (e.g."@g" or "-6") using either the keyctl command or the underlying API, I get an error. I'm guessing I have to set some kind of state to let it know which of my groups to get the keyring for, but documentation on this kernel feature is sparse. Anybody know how to make it work for groups? The method call (currently using Python's ctypes, which will directly call shared library functions, which works fine for all other keyrings): >>> import ctypes >>> keyutils = ctypes.CDLL('libkeyutils.so.1') >>> key_id = 'foo' >>> key_value = 'bar' >>> keyutils.add_key('user', key_id, key_value, len(key_value), -5) 268186515 >>> keyutils.add_key('user', key_id, key_value, len(key_value), -6) -1 Answer: Based on looking at the man page for keyctl it would seem that group based keyrings aren't implemented in the kernel yet. (*) Group specific keyring: @g or -6 This is a place holder for a group specific keyring, but is not actually implemented yet in the kernel. Taking a look at the most recent stable kernel source it also backs up what the man page says: <http://lxr.linux.no/#linux+v3.2.9/security/keys/process_keys.c#L641> So your code is correct... but it's attempting to use functionality that isn't there yet.
Installing MySQLdb 1.2.3 with Python For Django on Mac OSX? Question: I am a beginner Java developer and newbie to Python and I want to install Django and from what i understood that i need to install MySQLdb 1.2.3 with Python and I have MySQL already installed so I am trying to do so and all the guides I find is for 1.2.2 and what I did after installing is sudo python setup.py and this is what I get Traceback (most recent call last): File "setup.py", line 5, in <module> from setuptools import setup, Extension ImportError: No module named setuptools So, is there a simple guide I can follow or a fix to that error to get MySQLdb installed and running ? By the way I am using Lion. Update 1 : i've found this tutorial and followed it [Here](http://djangrrl.com/post/installing-django-with-mysql-on-mac-os-x/) and the result now i get when i run and i've downloaded the version 1.2.2 and did the work on it python setup.py build that's what i get running build running build_py copying MySQLdb/release.py -> build/lib.macosx-10.6-intel-2.7/MySQLdb running build_ext building '_mysql' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.6.sdk -g -O2 -DNDEBUG -g -O3 -Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/usr/local/mysql/include -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.6-intel-2.7/_mysql.o -Os -g -fno-common -fno-strict-aliasing -arch x86_64 unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 So what can i do ? Answer: You have to make sure that all components were built for the same architecture. A 32 bit MySQL only works with 32bit Python. Unfortunately lion only supports 64bit MySQL. I just ended up using [mariadb](http://mariadb.org/). That was much easier than installing MySQL and MySQL_Python. brew install mariadb To run django you should also install PIL (Python Image Library), lxml: sudo pip install PIL sudo pip install lxml and gettext (Translations) using [brew](http://mxcl.github.com/homebrew/) brew install gettext
Hard typecasts in ctypes possible? int -> "pointer to struct" for example Question: I have am inside a callback that allows me to access the pointers passed to it as `int` (i.e. the Python `type()` function returns `int`). What so I have to do if I want convert this into a pointer of a `struct` whose layout I know and can define as a `ctypes` class. Say I have this already: class data_t(Structure): _fields = [ ("foo", c_int), ("bar", c_wchar_p), ("baz", c_char_p) ] How can a variable `x` for which `type(x)` gives the output `int` now be cast into a pointer to the above `struct` type? **The gist:** I have no influence on the declaration of the callback function or the declaration of the arguments I get to see, so I need some way to get from the Python `int` type to a `ctypes` pointer and access the `struct` members from there ... This is Python 2.6, but I reckon most 2.x will be similar enough at least. I can't get rid of this version requirement as it is embedded into a product that requires _this particular_ Python version. Answer: You can use `ctypes.cast`, or just declare the callback to return a `POINTER(data_t)`. Examples of both below and tested on Python 2.7 and Python 3.2: ### test DLL code (Windows) typedef struct data { int foo; wchar_t* bar; char* baz; } data_t; typedef void (*CALLBACK)(data_t* p); CALLBACK g_callback = 0; extern "C" __declspec(dllexport) void set_callback(CALLBACK f) { g_callback = f; } extern "C" __declspec(dllexport) void call_callback() { data_t data; data.foo = 123; data.bar = L"马克"; data.baz = "Mark"; g_callback(&data); } ### Python from ctypes import * class data_t(Structure): _fields_ = [ ("foo", c_int), ("bar", c_wchar_p), ("baz", c_char_p)] dll = CDLL('test') @CFUNCTYPE(None,c_int) def callback(n): p = cast(n,POINTER(data_t)).contents print(p.foo,p.bar,p.baz) @CFUNCTYPE(None,POINTER(data_t)) def callback2(n): p = n.contents print(p.foo,p.bar,p.baz) dll.set_callback(callback) dll.call_callback() dll.set_callback(callback2) dll.call_callback() ### Output 123 马克 b'Mark' 123 马克 b'Mark'