text
stringlengths
226
34.5k
How to send data generated from python to jquery datatable for rendering Question: **A] Summary of the problem:** Using jquery datatable (<http://www.datatables.net/>) on the html page, Want to send data generated by query from python to javascript, so that it can be printed in the table. If someone can provide a sample implementation for this or a starter link, it would be awesome. **B] Models structure:** The hierarchical relationship between the models is as follows: UserReportecCountry (one) to UserReportedCity(many) UserReportedCity(one) to UserReportedStatus(many) class UserReportedCountry(db.Model): country_name = db.StringProperty( required=True, choices=['Afghanistan','Aring land Islands'] ) class UserReportedCity(db.Model): country = db.ReferenceProperty(UserReportedCountry, collection_name='cities') city_name = db.StringProperty(required=True) class UserReportedStatus(db.Model): city = db.ReferenceProperty(UserReportedCity, collection_name='statuses') status = db.BooleanProperty(required=True) date_time = db.DateTimeProperty(auto_now_add=True) **C] HTML code excerpt** The HTML code includes jquery , datatable javascript libraries. The datatable javascript library is configured to allow multicolumn sorting. <!--importing javascript and css files --> <style type="text/css">@import "/media/css/demo_table.css";</style> <script type="text/javascript" language="javascript" src="/media/js/jquery.js"></script> <script type="text/javascript" src="/media/js/jquery.dataTables.js"></script> <!-- Configuring the datatable javascript library to allow multicolumn sorting --> <script type="text/javascript"> /* Define two custom functions (asc and desc) for string sorting */ jQuery.fn.dataTableExt.oSort['string-case-asc'] = function(x,y) { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }; jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) { return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }; $(document).ready(function() { /* Build the DataTable with third column using our custom sort functions */ // #user_reported_data_table is the name of the table which is used to display the data reported by the users $('#user_reported_data_table').dataTable( { "aaSorting": [ [0,'asc'], [1,'asc'] ], "aoColumns": [ null, null, { "sType": 'string-case' }, null ] } ); } ); </script> <!-- Table containing the data to be printed--> <div id="userReportedData"> <table cellpadding="0" cellspacing="0" border="0" class="display" id="user_reported_data_table"> <thead> <tr> <th>Country</th> <th>City</th> <th>Status</th> <th>Reported at</th> </tr> </thead> <tbody> <tr class="gradeA"> <td>United Status</td> <td>Boston</td> <td>Up</td> <td>5 minutes back</td> </tr> </tbody> </table> **C] python code exceprt:** The code excerpt does the query of the data, puts the data in a "template" and send it to the HTML page ( this is off-course not working right now :( ) __TEMPLATE_ALL_DATA_FROM_DATABASE = 'all_data_from_database' def get(self): template_values = { self.__TEMPLATE_ALL_DATA_FROM_DATABASE: self.get_data_reported_by_users() } self.response.out.write(template.render(self.__MAIN_HTML_PAGE, template_values)) def get_data_reported_by_users(self): return db.GqlQuery("SELECT * FROM UserReportedCountry ORDER BY country_name ASC") **D] Technologies being used:** 1] Jquery 2] Jquery datatable 3] Google app engine 4] Python 5] Django. thank you for reading. [EDIT#1] Code based on the response given by @Mark Tried the following <!-- script snippet to setup the properties of the datatable(table which will contain site status reported by the users) --> <script type="text/javascript"> /* Define two custom functions (asc and desc) for string sorting */ jQuery.fn.dataTableExt.oSort['string-case-asc'] = function(x,y) { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }; jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) { return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }; $(document).ready(function() { /* Build the DataTable with third column using our custom sort functions */ // #user_reported_data_table is the name of the table which is used to display the data reported by the users $('#user_reported_data_table').dataTable( { "aaSorting": [ [0,'asc'], [1,'asc'] ], "aoColumns": [ null, null, { "sType": 'string-case' }, null ], /* enabling serverside processing, specifying that the datasource for this will come from file ajaxsource , function populate_world_wide_data */ "bProcessing": true, "bServerSide": true, "sAjaxSource": "/ajaxsource/populate_world_wide_data" } ); } ); </script> <div id="userReportedData"> <table cellpadding="0" cellspacing="0" border="0" class="display" id="user_reported_data_table"> <thead> <tr> <th>Country</th> <th>City</th> <th>Status</th> <th>Reported at</th> </tr> </thead> <tbody> </tbody> </table> Python code, name of the file is ajaxsource.py from django.utils import simplejson from google.appengine.ext import db def populate_world_wide_data(self,request): my_data_object = db.GqlQuery("SELECT * FROM UserReportedCountry ORDER BY country_name ASC") json_object = simplejson.dumps(my_data_object) self.response.out.write( json_object, mimetype='application/javascript') This however only showed "processing" on the table. Couple of queries, How would the datatable know where to print the country, where to print the city and status? [EDIT#2] Code based on the response given by @Abdul Kader <script type="text/javascript" src="/media/js/jquery.dataTables.js"></script> <!-- script snippet to setup the properties of the datatable(table which will contain site status reported by the users) --> <script type="text/javascript"> /* Define two custom functions (asc and desc) for string sorting */ jQuery.fn.dataTableExt.oSort['string-case-asc'] = function(x,y) { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }; jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) { return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }; $(document).ready(function() { /* Build the DataTable with third column using our custom sort functions */ // #user_reported_data_table is the name of the table which is used to display the data reported by the users $('#user_reported_data_table').dataTable( { "aaSorting": [ [0,'asc'], [1,'asc'] ], "aoColumns": [ null, null, { "sType": 'string-case' }, null ] } ); } ); </script> <!-- Table containing the data to be printed--> <div id="userReportedData"> <table cellpadding="0" cellspacing="0" border="0" class="display" id="user_reported_data_table"> <thead> <tr> <th>Country</th> <th>City</th> <th>Status</th> <th>Reported at</th> </tr> </thead> <tbody> <tr class="gradeA"> {% for country in all_data_from_database %} <td>{{country}}</td> {%endfor%} </tr> </tbody> </table> Python code -- __TEMPLATE_ALL_DATA_FROM_DATABASE = 'all_data_from_database' def get(self): template_values = { self.__TEMPLATE_ALL_DATA_FROM_DATABASE: self.get_data_reported_by_users() } #rendering the html page and passing the template_values self.response.out.write(template.render(self.__MAIN_HTML_PAGE, template_values)) def get_data_reported_by_users(self): return db.GqlQuery("SELECT * FROM UserReportedCountry ORDER BY country_name ASC") Item printed in the html page: ![enter image description here](http://i.stack.imgur.com/CkufL.png) [EDIT#3] **EDIT that has worked.** I modified the solution given by @Abdul Kader a bit and the following has worked HTML code: <!-- Table containing the data to be printed--> <div id="userReportedData"> <table cellpadding="0" cellspacing="0" border="0" class="display" id="user_reported_data_table"> <thead> <tr> <th>Country</th> <th>City</th> <th>Status</th> <th>Reported at</th> </tr> </thead> <tbody> {% for country in countries %} {%for city in country.cities %} {%for status in city.statuses %} <tr class="gradeA"> <td>{{country.country_name}}</td> <td>{{city.city_name}}</td> <td>{{status.status}}</td> <td>{{status.date_time }}</td> </tr> {%endfor%} {%endfor%} {%endfor%} </tbody> </table> Python code: def get(self): __TEMPLATE_ALL_DATA_FROM_DATABASE = 'countries' country_query = UserReportedCountry.all().order('country_name') country = country_query.fetch(10) template_values = { self.__TEMPLATE_ALL_DATA_FROM_DATABASE: country } self.response.out.write(template.render(self.__MAIN_HTML_PAGE, template_values)) Enhancement Request: I believe this is a very basic way to do this and there might be a solution that can involve a bit of ajax or more elegance. If someone has a example or a open source project that is using datatables based on python, please let me know. Code review request: Can someone please review the code that i have done and let me know if i am doing a mistake or something that can be done better or in a more efficient manner. Answer: In the DataTables documentation, they show an example of returning data "[server- side](http://www.datatables.net/examples/data_sources/server_side.html)". In their example they are using PHP on the server, but how it's returned is by encoding with JSON. This is easily done with [Python as well](http://docs.python.org/library/json.html). **EDITS** The key is how the data is returned from the server: $(document).ready(function() { $('#example').dataTable( { "bProcessing": true, "bServerSide": true, "sAjaxSource": "url/to/json/returning/python" } ); } ); In the javascript above, it would be calling the python Django view directly and expecting a JSON response. The Django view would be something akin to (I am not a Django user, so this might be off): from django.utils import simplejson def ajax_example(request): ## do your processing ## your return data should be a python object return HttpResponse(simplejson.dumps(my_data_object), mimetype='application/javascript')
Pygame screen freezes when I close it Question: The code loads up a pygame screen window, but when I click the X to close it, it becomes unresponsive. I'm running on a 64-bit system, using a 32-bit python and 32-bit pygame. from livewires import games, color games.init(screen_width = 640, screen_height = 480, fps = 50) games.screen.mainloop() Answer: Mach1723's [answer](http://stackoverflow.com/questions/5615860/pygame-screen- freezes-when-i-close-it/5616374#5616374) is correct, but I would like to suggest another variant of a main loop: while 1: for event in pygame.event.get(): if event.type == QUIT: ## defined in pygame.locals pygame.quit() sys.exit() if event.type == ## Handle other event types here... ## Do other important game loop stuff here.
Create dynamic updated graph with Python Question: I need your help to write a script in Python that will take dynamically changed data, the source of data is not matter here, and display graph on the screen. I know how to use matplotlib, but the problem with matplotlib, that I can display graph only once, at the end of the script. I need to be able not only to display graph one time, but also update it on the fly, each time when data changes. I found that it is possible to use wxPython with matplotlib to do this, but it is little bit complicate to do this for me, because i am not familiar with wxPython at all. So I will be very happy if someone will show me simple example how to use wxPython with matplotlib to show and update simple graph. Or, if it is some other way to do this, it will be good to me too. PS: Ok, since no one answered and looked at matplotlib help noticed by @janislaw and wrote some code. This is some dummy example: import time import matplotlib.pyplot as plt def data_gen(): a=data_gen.a if a>10: data_gen.a=1 data_gen.a=data_gen.a+1 return range (a,a+10) def run(*args): background = fig.canvas.copy_from_bbox(ax.bbox) while 1: time.sleep(0.1) # restore the clean slate background fig.canvas.restore_region(background) # update the data ydata = data_gen() xdata=range(len(ydata)) line.set_data(xdata, ydata) # just draw the animated artist ax.draw_artist(line) # just redraw the axes rectangle fig.canvas.blit(ax.bbox) data_gen.a=1 fig = plt.figure() ax = fig.add_subplot(111) line, = ax.plot([], [], animated=True) ax.set_ylim(0, 20) ax.set_xlim(0, 10) ax.grid() manager = plt.get_current_fig_manager() manager.window.after(100, run) plt.show() This implementation have problems, like script stops if you trying to move the window. But basically it can be used. Answer: As an alternative to matplotlib, the Chaco library provides nice graphing capabilities and is in some ways better-suited for live plotting. See some screenshot examples here with linked code: <http://code.enthought.com/projects/chaco/gallery.php> And in particular, see these examples: <https://github.com/enthought/chaco/blob/2fc52518278c52e81a7e07589bb6aeaaca361770/examples/demo/advanced/data_stream.py> <https://github.com/enthought/chaco/blob/2fc52518278c52e81a7e07589bb6aeaaca361770/examples/demo/advanced/spectrum.py> Chaco has backends for qt and wx, so it handles the underlying details for you rather nicely most of the time.
How to mock a class in Python? Question: I'm new to Python, but I used to work with ruby. I'm trying to do some tests with Python but I can't figure out how I mock a class for my test. Let's say I have this real class: from database import DB class Foo: def do_it(self): x = {'key': 'value'} DB.save(x) # do other stuff with x return x Now, I want to test if everything I'm doing with x returns me the right result, and I want to test if DB.save was called with x as parameter, but I don't want to actually save x to database. To see if DB.save is being called, I can use some mock framework, but how can I tell Foo class that I need it to use the mock object and not the real DB object? Thank You. **EDIT:** Sorry, my example wasn't enough for what I need to accomplish. Let's see this new example: from database import DB class Foo: DB.connect() def do_it(self): x = {'key': 'value'} DB.save(x) # do other stuff with x return x And for instance, let's say the database is down. When I import Foo, it raises the connection error and I do not have time to mock DB. What should I do?? Answer: The answer is, don't write your classes like that. It's a strange way to do so anyway - there shouldn't really be any executable code at the class level, other than attribute and method definitions. You should setup the connection in the `__init__` method. class Foo(object): def __init__(self, *args, **kwargs): DB.connect()
fitting n variable height images into 3 (similar length) column layout Question: I'm looking to make a 3-column layout similar to that of [piccsy.com](http://piccsy.com/). Given a number of images of the same width but varying height, what is a algorithm to order them so that the difference in column lengths is minimal? Ideally in Python or JavaScript... Thanks a lot for your help in advance! Martin Answer: How many images? If you limit the maximum page size, and have a value for the minimum picture height, you can calculate the maximum number of images per page. You would need this when evaluating any solution. I think there were 27 pictures on the link you gave. The following uses the first_fit algorithm mentioned by Robin Green earlier but then improves on this by greedy swapping. The swapping routine finds the column that is furthest away from the average column height then systematically looks for a swap between one of its pictures and the first picture in another column that minimizes the maximum deviation from the average. I used a random sample of 30 pictures with heights in the range five to 50 'units'. The convergenge was swift in my case and improved significantly on the first_fit algorithm. The code (Python 3.2: def first_fit(items, bincount=3): items = sorted(items, reverse=1) # New - improves first fit. bins = [[] for c in range(bincount)] binsizes = [0] * bincount for item in items: minbinindex = binsizes.index(min(binsizes)) bins[minbinindex].append(item) binsizes[minbinindex] += item average = sum(binsizes) / float(bincount) maxdeviation = max(abs(average - bs) for bs in binsizes) return bins, binsizes, average, maxdeviation def swap1(columns, colsize, average, margin=0): 'See if you can do a swap to smooth the heights' colcount = len(columns) maxdeviation, i_a = max((abs(average - cs), i) for i,cs in enumerate(colsize)) col_a = columns[i_a] for pic_a in set(col_a): # use set as if same height then only do once for i_b, col_b in enumerate(columns): if i_a != i_b: # Not same column for pic_b in set(col_b): if (abs(pic_a - pic_b) > margin): # Not same heights # new heights if swapped new_a = colsize[i_a] - pic_a + pic_b new_b = colsize[i_b] - pic_b + pic_a if all(abs(average - new) < maxdeviation for new in (new_a, new_b)): # Better to swap (in-place) colsize[i_a] = new_a colsize[i_b] = new_b columns[i_a].remove(pic_a) columns[i_a].append(pic_b) columns[i_b].remove(pic_b) columns[i_b].append(pic_a) maxdeviation = max(abs(average - cs) for cs in colsize) return True, maxdeviation return False, maxdeviation def printit(columns, colsize, average, maxdeviation): print('columns') pp(columns) print('colsize:', colsize) print('average, maxdeviation:', average, maxdeviation) print('deviations:', [abs(average - cs) for cs in colsize]) print() if __name__ == '__main__': ## Some data #import random #heights = [random.randint(5, 50) for i in range(30)] ## Here's some from the above, but 'fixed'. from pprint import pprint as pp heights = [45, 7, 46, 34, 12, 12, 34, 19, 17, 41, 28, 9, 37, 32, 30, 44, 17, 16, 44, 7, 23, 30, 36, 5, 40, 20, 28, 42, 8, 38] columns, colsize, average, maxdeviation = first_fit(heights) printit(columns, colsize, average, maxdeviation) while 1: swapped, maxdeviation = swap1(columns, colsize, average, maxdeviation) printit(columns, colsize, average, maxdeviation) if not swapped: break #input('Paused: ') The output: columns [[45, 12, 17, 28, 32, 17, 44, 5, 40, 8, 38], [7, 34, 12, 19, 41, 30, 16, 7, 23, 36, 42], [46, 34, 9, 37, 44, 30, 20, 28]] colsize: [286, 267, 248] average, maxdeviation: 267.0 19.0 deviations: [19.0, 0.0, 19.0] columns [[45, 12, 17, 28, 17, 44, 5, 40, 8, 38, 9], [7, 34, 12, 19, 41, 30, 16, 7, 23, 36, 42], [46, 34, 37, 44, 30, 20, 28, 32]] colsize: [263, 267, 271] average, maxdeviation: 267.0 4.0 deviations: [4.0, 0.0, 4.0] columns [[45, 12, 17, 17, 44, 5, 40, 8, 38, 9, 34], [7, 34, 12, 19, 41, 30, 16, 7, 23, 36, 42], [46, 37, 44, 30, 20, 28, 32, 28]] colsize: [269, 267, 265] average, maxdeviation: 267.0 2.0 deviations: [2.0, 0.0, 2.0] columns [[45, 12, 17, 17, 44, 5, 8, 38, 9, 34, 37], [7, 34, 12, 19, 41, 30, 16, 7, 23, 36, 42], [46, 44, 30, 20, 28, 32, 28, 40]] colsize: [266, 267, 268] average, maxdeviation: 267.0 1.0 deviations: [1.0, 0.0, 1.0] columns [[45, 12, 17, 17, 44, 5, 8, 38, 9, 34, 37], [7, 34, 12, 19, 41, 30, 16, 7, 23, 36, 42], [46, 44, 30, 20, 28, 32, 28, 40]] colsize: [266, 267, 268] average, maxdeviation: 267.0 1.0 deviations: [1.0, 0.0, 1.0] Nice problem. * * * Heres the info on reverse-sorting mentioned in my separate comment below. >>> h = sorted(heights, reverse=1) >>> h [46, 45, 44, 44, 42, 41, 40, 38, 37, 36, 34, 34, 32, 30, 30, 28, 28, 23, 20, 19, 17, 17, 16, 12, 12, 9, 8, 7, 7, 5] >>> columns, colsize, average, maxdeviation = first_fit(h) >>> printit(columns, colsize, average, maxdeviation) columns [[46, 41, 40, 34, 30, 28, 19, 12, 12, 5], [45, 42, 38, 36, 30, 28, 17, 16, 8, 7], [44, 44, 37, 34, 32, 23, 20, 17, 9, 7]] colsize: [267, 267, 267] average, maxdeviation: 267.0 0.0 deviations: [0.0, 0.0, 0.0] * * * If you have the reverse-sorting, this extra code appended to the bottom of the above code (in the 'if **name** == ...), will do extra trials on random data: for trial in range(2,11): print('\n## Trial %i' % trial) heights = [random.randint(5, 50) for i in range(random.randint(5, 50))] print('Pictures:',len(heights)) columns, colsize, average, maxdeviation = first_fit(heights) print('average %7.3f' % average, '\nmaxdeviation:') print('%5.2f%% = %6.3f' % ((maxdeviation * 100. / average), maxdeviation)) swapcount = 0 while maxdeviation: swapped, maxdeviation = swap1(columns, colsize, average, maxdeviation) if not swapped: break print('%5.2f%% = %6.3f' % ((maxdeviation * 100. / average), maxdeviation)) swapcount += 1 print('swaps:', swapcount) The extra output shows the effect of the swaps: ## Trial 2 Pictures: 11 average 72.000 maxdeviation: 9.72% = 7.000 swaps: 0 ## Trial 3 Pictures: 14 average 118.667 maxdeviation: 6.46% = 7.667 4.78% = 5.667 3.09% = 3.667 0.56% = 0.667 swaps: 3 ## Trial 4 Pictures: 46 average 470.333 maxdeviation: 0.57% = 2.667 0.35% = 1.667 0.14% = 0.667 swaps: 2 ## Trial 5 Pictures: 40 average 388.667 maxdeviation: 0.43% = 1.667 0.17% = 0.667 swaps: 1 ## Trial 6 Pictures: 5 average 44.000 maxdeviation: 4.55% = 2.000 swaps: 0 ## Trial 7 Pictures: 30 average 295.000 maxdeviation: 0.34% = 1.000 swaps: 0 ## Trial 8 Pictures: 43 average 413.000 maxdeviation: 0.97% = 4.000 0.73% = 3.000 0.48% = 2.000 swaps: 2 ## Trial 9 Pictures: 33 average 342.000 maxdeviation: 0.29% = 1.000 swaps: 0 ## Trial 10 Pictures: 26 average 233.333 maxdeviation: 2.29% = 5.333 1.86% = 4.333 1.43% = 3.333 1.00% = 2.333 0.57% = 1.333 swaps: 4
how to run python script to display webpage for auto login on one click Question: I have my python script which I guess is fine. I want to keep the script on the desktop and upon one click I want the script to run and open a browser(IE or firefox or chrome) and perform the script i.e. to log-in to a website. import urllib, urllib2, cookielib username = 'xyzusername' password = 'xyzpassword' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login_data = urllib.urlencode({'userid' : username, 'pass' : password}) resp = opener.open('http://www.gmail.com') resp.read() print resp How do I run the script? Please help. Answer: Hmmmm, your script is logging into a web site, but it's not opening a browser. If you want to open a browser, you might be better off looking at [Selenium](http://seleniumhq.org/): * <http://coreygoldberg.blogspot.com/2009/09/selenium-rc-with-python-in-30-seconds.html> * <http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html> * <http://seleniumhq.org/>
Is it possible to inject shell/python commands from a configuration file? Question: Say you have a some meta data for a custom file format that your python app reads. Something like a csv with variables that can change as the file is manipulated: var1,data1 var2,data2 var3,data3 So if the user can manipulate this meta data, do you have to worry about someone crafting a malformed meta data file that will allow some arbitrary code execution? The only thing I can imagine if you you made the poor choice to make `var1` be a shell command that you execute with `os.sys(data1)` in your own code somewhere. Also, if this were C then you would have to worry about buffers being blown, but I don't think you have to worry about that with python. If your reading in that data as a string is it possible to somehow escape the string `"\n os.sys('rm -r /')`, this SQL like example totally wont work, but is there similar that is possible? Answer: If you are doing what you say there (plain text, just reading and parsing a simple format), you will be safe. As you indicate, Python is generally safe from the more mundane memory corruption errors that C developers can create if they are not careful. The SQL injection scenario you note is not a concern when simply reading in files in python. **However** , if you are concerned about security, which it seems you are (interjection: good for you! A good programmer should be lazy _and_ paranoid), here are some things to consider: _Validate all input_. Make sure that each piece of data you read is of the expected size, type, range, etc. Error early, and don't propagate tainted variables elsewhere in your code. * Do you know the expected names of the vars, or at least their format? Make sure the validate that it is the kind of thing you expect before you use it. If it should be just letters, confirm that with a regex or similar. * Do you know the expected range or format of the data? If you're expecting a number, make sure it's a number before you use it. If it's supposed to be a short string, verify the length; you get the idea. * What if you get characters or bytes you don't expect? What if someone throws unicode at you? * If any of these are paths, make sure you canonicalize and know that the path points to an acceptable location before you read or write. Some specific things **not** to do: * os.system(attackerControlledString) * eval(attackerControlledString) * `__import__(attackerControlledString)` * pickle/unpickle attacker controlled content ([here's why](http://nadiana.com/python-pickle-insecure)) Also, rather than rolling your own config file format, consider [ConfigParser](http://docs.python.org/library/configparser.html) or something like [JSON](http://www.json.org/). A well understood format (and libraries) helps you get a leg up on proper validation. OWASP would be my normal go-to for providing a "further reading" link, but their Input Validation page needs help. In lieu, this looks like a reasonably pragmatic read: "[Secure Programmer: Validating Input](http://www.ibm.com/developerworks/library/l-sp2.html)". A slightly dated but more python specific one is "[Dealing with User Input in Python](http://tldp.org/LDP/LGNET/83/evans.html)"
List of all imports in python 3 Question: How to find out list of all available imports in python 3 via program? I tried this at first, but couldn't understand what it returned import sys sys.modules I think this isn't the way, although this struck my mind first. I searched the web and found this <http://effbot.org/librarybook/core-modules-index.htm> Can someone tell me whether this is correct or not? Answer: From <http://docs.python.org/library/sys.html> (a good place to look for documentation on python stdlib) > **sys.builtin_module_names** > > is a tuple (a bit like a immutable anonymous structs) of strings giving the > names of all modules that are compiled into this Python interpreter. > > **sys.modules** > > This is a dictionary that maps module names to modules (module objects) > which have already been loaded. This can be manipulated to force reloading > of modules and other tricks. Note that removing a module from this > dictionary is not the same as calling `reload()` on the corresponding module > object. So modules is a dictionary (a mapping of module names to the actual module objects). To get just the names type `sys.modules.keys()` although it probably isn't that usefull.
Transfer Ipython namespace to ipdb Question: I am in the middle of an ipython session. I've loaded a module `foo` which contains a function `foo.bar`. While working, I notice that `foo.bar` gives some weird output when I feed it some input `x`, where `x` is a variable in my local ipython scope. I would like to investigate the behavior in a debugger. How would I set a breakpoint at `foo.bar` and run `foo.bar(x)` in a debugger? I know about `pdb.set_trace()`, but it would require me to open up the code of the `foo` module to insert a breakpoint manually, save it, reload the module in ipython, etc. There has to be a better way. Answer: I believe you can use [`pdb.runcall`](http://docs.python.org/library/pdb.html#pdb.runcall) in this case: import pdb pdb.runcall(foo.bar, x)
A help in concept and a database query question (Django/Python) Question: I am trying to build a kind of news website for learning purposes. class NewsCategory(models.Model): category = models.CharField(max_length=50) Note: A category can be Soccer, Tennis, business ... User can register to different news category. This choice will be saved in their preferences. class Profile(models.Model): user = models.ForeignKey(User, unique=True) gender = models.CharField(max_length=1,blank=True) preference = models.ManyToManyField(NewsCategory) I am currently stuck on how to update the preference list of each user (the list that specifies in which categories he is interested in.) **View:** category = [(item.category) for item in NewsCategory.objects.all()] and then I am sending the `category` to the template below **template:** <div id="c_b"> {% for c in category %} <input type="checkbox" name="category[]" value="{{c}}"> <label for="{{c}}">{{c}}</label> {% endfor %} </div> **Questions:** 1. What is the best way to add the checked tag next to the checkboxes that are already saved in the user's preference when I display the template. I though of getting all the preferences users are registered for: `saved_preference = user.preference.all()` and then checking for each item in `category` if it is in `saved_preference` I am also blanking out on the way to actually write that into code, and whether this should be done in the view or the template. 2. What is a good way to update the user preference list? I was planning on running `user.preference.clear()` and then going through every item in the submitted form and running `user.preference.add(the_new_preference)` Answer: You'll need to pass the complete list of categories and also an index of user- selected categories to your template. You don't need to convert the `NewsCategory` queryset into a list in your view, by the way: **View** categories = NewsCategory.objects.all() user_preferences = [item.id for item in Profile.preference.all()] The `user_preferences` variable will act as a lookup index for our template. Then you loop through all the categories in the template, and check to see if it exists in the list of user preferences: **Template** <div id="c_b"> {% for c in categories %} <input type="checkbox" name="category[]" id="id_{{ c.category }}" value="{{ c.id }}" {% if c.id in user_preferences %}checked="checked"{% endif %} /> <label for="id_{{ c.id }}">{{ c.category }}</label> {% endfor %} </div> **Update - saving user preferences** There is no hard and fast rule here. The main consideration, as far as I am concerned, would be minimising database hits. You can just clear the user preferences, like you say, and add the new ones - in fact, this is how Django's admin handles it. Just make use of Django's transaction management: from django.db import transaction @transaction.commit_manually def add_preferences(user, preferences): user.preference.clear() for pref in preferences: user.preference.add(pref) transaction.commit()
Scraping with Python? Question: I'd like to grab all the index words and its definitions from [here](http://pali.hum.ku.dk/cpd/search.html). Is it possible to scrape web content with Python? Firebug exploration shows the following URL returns my desirable contents including both index and its definition as to 'a'. http://pali.hum.ku.dk/cgi-bin/cpd/pali?acti=xart&arid=14179&sphra=undefined what are the modules used? Is there any tutorial available? I do not know how many words indexed in the dictionary. I`m absolute beginner in the programming. Answer: You should use [urllib2](http://docs.python.org/library/urllib2.html) for gettting the URL contents and [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) for parsing the HTML/XML. Example - retrieving all questions from the StackOverflow.com main page: import urllib2 from BeautifulSoup import BeautifulSoup page = urllib2.urlopen("http://stackoverflow.com") soup = BeautifulSoup(page) for incident in soup('h3'): print [i.decode('utf8') for i in incident.contents] print This code sample was adapted from the [BeautifulSoup documentation](http://www.crummy.com/software/BeautifulSoup/documentation.html).
Why does python thread consume so much memory? Question: Why does python thread consumes so much memory? I measured that spawning one thread consumes 8 megs of memory, almost as big as a whole new python process! OS: Ubuntu 10.10 Edit: due to popular demand I'll give some extraneous examples, here it is: from os import getpid from time import sleep from threading import Thread def nap(): print 'sleeping child' sleep(999999999) print getpid() child_thread = Thread(target=nap) sleep(999999999) On my box, pmap pid will give 9424K Now, let's run the child thread: from os import getpid from time import sleep from threading import Thread def nap(): print 'sleeping child' sleep(999999999) print getpid() child_thread = Thread(target=nap) child_thread.start() # <--- ADDED THIS LINE sleep(999999999) Now pmap pid will give 17620K So, the cost for the extra thread is 17620K - 9424K = 8196K ie. 87% of running a whole new separate process! Now isn't that just, wrong? Answer: This is not Python-specific, and has to do with the separate stack that gets allocated by the OS for every thread. The default maximum stack size on your OS happens to be 8MB. Note that the 8MB is simply a chunk of address space that gets set aside, with very little memory committed to it initially. Additional memory gets committed to the stack when required, up to the 8MB limit. The limit can be tweaked using `ulimit -s`, but in this instance I see no reason to do this. As an aside, `pmap` shows _address space_ usage. It isn't a good way to gauge _memory_ usage. The two concepts are quite distinct, if related.
array filter in python? Question: For example, I have two lists A = [6, 7, 8, 9, 10, 11, 12] subset_of_A = [6, 9, 12]; # the subset of A the result should be [7, 8, 10, 11]; the remaining elements Is there a built-in function in python to do this? Answer: If the order is not important, you should use `set.difference`. However, if you want to retain order, a simple list comprehension is all it takes. result = [a for a in A if a not in subset_of_A] **EDIT:** As delnan says, performance will be substantially improved if `subset_of_A` is an actual `set`, since checking for membership in a `set` is O(1) as compared to O(n) for a list. A = [6, 7, 8, 9, 10, 11, 12] subset_of_A = set([6, 9, 12]) # the subset of A result = [a for a in A if a not in subset_of_A]
ContentHandler is undefined Question: I'm trying to learn Python's SAX module from O'Reilly's _[Python and XML](http://oreilly.com/catalog/9780596001285)_. I'm trying to run the following sample code, but I keep getting an error and I can't figure out why. The first file is `handlers.py`: class ArticleHandler(ContentHandler): """ A handler to deal with articles in XML """ def startElement(self, name, attrs): print "Start element:", name The second file is `art.py`, which imports the first file: #!/usr/bin/env python # art.py import sys from xml.sax import make_parser from handlers import ArticleHandler ch = ArticleHandler( ) saxparser = make_parser( ) saxparser.setContentHandler(ch) saxparser.parse(sys.stdin) When I try to run `art.py`, I get the following: % python art.py < article.xml Traceback (most recent call last): File "art.py", line 7, in <module> from handlers import ArticleHandler File "~/handlers.py", line 1, in <module> class ArticleHandler(ContentHandler): NameError: name 'ContentHandler' is not defined I'm probably missing something obvious. Can anybody help? Thanks! Answer: You have to import ContentHandler in handlers.py as follows: from xml.sax.handler import ContentHandler This should do it.
Sending progress value to progress bar in python Question: In my game I have two modules, **island.py** which loads the islands into my game and the second module is **gui.py** which handles the gui widgets before game starting. My problem is how to send the progress values from the island.py module to the progress bar created in **gui.py** module **EDIT: also with an instance of the loading screen to access the progress bar in it and change its value.** **In the module island.py** def __iter__(self): total = float(len(self.ground_map)) import game.gui for i in self.get_coordinates(): yield i global count count+=1 progress = (count/total) * 100 game.gui.Gui.set_progress(progress) global count count = 0 **In the module gui.py** def show_loading_screen(self): self._switch_current_widget('loadingscreen', center=True, show=True) # Creates the loading screen and its associated widgets, except the progress bar. @staticmethod def set_progress(progress): # Now I have the progress values, and it will be updated automatically... how can I pass it to the progress bar widget? # I need to create the progress bar widget here, but to do that I need to have the self instance to give me the current screen that I will create the progress bar for **AND HERE IS THE PROBLEM!!** def update_loading_screen(progress): """updates the widget.""" **self,current**.findChild(name="progressBar")._set_progress(progress) update_loading_screen(progress) How I can make this update_loading_screen function? Answer: Expanding on rocksport's answer...this is how I did it class GUI: def __init__(self): GUI.self = self @staticmethod def set_progressbar(): print "set progress bar" print GUI.self g = GUI() g.set_progressbar()
Capturing/Return the output message of python logging Question: Is there a way of obtaining/returning the message from a call to logging.debug()? Thanks Answer: Yes, providing a mechanism to easily capture and redirect event details without requiring any modification to the code emitting the events is the entire purpose of the `logging` module. All you need to do is include an appropriate call to [`logging.basicConfig()`](http://docs.python.org/library/logging#logging.basicConfig) as your application starts up and you can send logged events wherever you wish. The simplest is to just log to `stdout`: import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) For more advanced options, I suggest checking out the [logging tutorial](http://docs.python.org/howto/logging.html#logging-basic-tutorial) in the official documentation. If you want programmatic access to the formatted message at the point of making the call... then the `logging` module is the wrong tool for the job. It is designed for emitting events, not for use as an alternative to calling `str.format` directly. For the case you describe in your comment, you may want to consider a [hierarchical logging](http://docs.python.org/howto/logging.html#loggers) setup along the following lines: >>> import logging >>> import sys >>> logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) >>> master = logging.getLogger("master") >>> child1 = logging.getLogger("master.child1") >>> child2 = logging.getLogger("master.child2") >>> child1.debug("Event from child 1") DEBUG:master.child1:Event from child 1 >>> child2.debug("Event from child 2") DEBUG:master.child2:Event from child 2 In this setup, note that I only configured a handler at the root level of the hierarchy (as part of the `basicConfig()` call). `logging` understands the "parent.child" notation in logger names, so it will pass any events passed to the child loggers up to the master logger, which in turn passes them on to the root logger. You can add additional logging handlers at the `master` and `child` levels as necessary in order to redirect the output wherever you wish.
Twisted XML-RPC error Question: I get an exception on both client and server side when I run the first example at <http://buildbot.twistedmatrix.com/builds/sphinx- html/291-15849/projects/web/howto/xmlrpc.html>. The server code I used is below: from twisted.web import xmlrpc, server class Example(xmlrpc.XMLRPC): """An example object to be published.""" def xmlrpc_echo(self, x): """ Return all passed args. """ return x def xmlrpc_add(self, a, b): """ Return sum of arguments. """ return a + b def xmlrpc_fault(self): """ Raise a Fault indicating that the procedure should not be used. """ raise xmlrpc.Fault(123, "The fault procedure is faulty.") if __name__ == '__main__': from twisted.internet import reactor r = Example() reactor.listenTCP(7080, server.Site(r)) reactor.run() Client side is below: import xmlrpclib s = xmlrpclib.Server('http://localhost:7080/') print s.echo('Hello world') The server side exception is: Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/twisted/web/xmlrpc.py", line 150, in render_POST d.addCallback(self._cbRender, request, responseFailed) File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 260, in addCallback callbackKeywords=kw) File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 249, in addCallbacks self._runCallbacks() File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 441, in _runCallbacks self.result = callback(self.result, *args, **kw) --- <exception caught here> --- File "/usr/lib/python2.6/dist-packages/twisted/web/xmlrpc.py", line 170, in _cbRender allow_none=self.allowNone) exceptions.TypeError: dumps() got an unexpected keyword argument 'allow_none' Client side exception is: Traceback (most recent call last): File "./client.py", line 6, in <module> print s.echo('Hello world') File "/usr/local/lib/python2.6/dist-packages/xmlrpclib-1.0.1-py2.6.egg/xmlrpclib.py", line 986, in __call__ return self.__send(self.__name, args) File "/usr/local/lib/python2.6/dist-packages/xmlrpclib-1.0.1-py2.6.egg/xmlrpclib.py", line 1239, in __request verbose=self.__verbose File "/usr/local/lib/python2.6/dist-packages/xmlrpclib-1.0.1-py2.6.egg/xmlrpclib.py", line 1037, in request return self._parse_response(h.getfile(), sock) File "/usr/local/lib/python2.6/dist-packages/xmlrpclib-1.0.1-py2.6.egg/xmlrpclib.py", line 1136, in _parse_response p.close() File "/usr/local/lib/python2.6/dist-packages/xmlrpclib-1.0.1-py2.6.egg/xmlrpclib.py", line 508, in close self._parser.Parse("", 1) # end of data xml.parsers.expat.ExpatError: no element found: line 1, column 0 Answer: Looks like you have an old version of xmlrpclib? What version of python are you using? Where is the xmlrpclib coming from that your xmlrpc server is using, and what version is it? $ python -v >>> import xmlrpclib # /usr/lib/python2.6/xmlrpclib.pyc matches /usr/lib/python2.6/xmlrpclib.py >>> xmlrpclib.__version__ '1.0.1' >>> xmlrpclib.dumps((None,), allow_none=True) '<params>\n<param>\n<value><nil/></value></param>\n</params>\n i.e. this works for me. Perhaps you are somehow using an old version of xmlrpclib?
ImportError: No module named BeautifulSoup Question: I have installed BeautifulSoup using easy_install and trying to run following script from BeautifulSoup import BeautifulSoup import re doc = ['<html><head><title>Page title</title></head>', '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.', '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', '</html>'] soup = BeautifulSoup(''.join(doc)) print soup.prettify() But not sure why this is happening Traceback (most recent call last): File "C:\Python27\reading and writing xml file from web1.py", line 49, in <module> from BeautifulSoup import BeautifulSoup ImportError: No module named BeautifulSoup Could you please help. Thanks Answer: Try this `from bs4 import BeautifulSoup` This might be a problem with Beautiful Soup, version 4, and the beta days. I just read this from the homepage.
How to resolve socket error when connecting to imap.gmail.com via port 993 using imaplib? Question: import imaplib s = imaplib.IMAP4_SSL('imap.gmail.com', 993) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/imaplib.py", line 1138, in __init__ IMAP4.__init__(self, host, port) File "/usr/lib/python2.6/imaplib.py", line 163, in __init__ self.open(host, port) File "/usr/lib/python2.6/imaplib.py", line 1149, in open self.sock = socket.create_connection((host, port)) File "/usr/lib/python2.6/socket.py", line 561, in create_connection raise error, msg socket.error: [Errno 113] No route to host Answer: Looks like a (possible temporary) network error rather than a software problem. Try it again now, or from another machine.
Python FTP uploading bar Question: I am uploading a file with FTPLib in python and have a cli loadingbar with [progressbar 2.2.](http://pypi.python.org/pypi/progressbar/2.2) I need to make a loading bar to tell the progress of the upload. Does anyone have any info on the topic? Thanks, giodamelio * * * As Senthil Kumaran pointed out, there is a callback parameter in the ftplib.storbinary function but I do not know how to use it. I tried this. I expected it to print the message every time a byte was uploaded. import ftplib def callback(): print("This is the callback function") s = ftplib.FTP('myserver.com','login','password') # Connect f = open('test.txt','rb') # file to send s.storbinary('STOR test.txt', f, 1024, callback()) # Send the file f.close() # Close file and FTP s.quit() Answer: Small change to your code: import ftplib def callback(p): print("This is the callback function") s = ftplib.FTP('myserver.com','login','password') # Connect f = open('test.txt','rb') # file to send s.storbinary('STOR test.txt', f, 1024, callback) # Send the file f.close() # Close file and FTP s.quit() The callback needs to be called later on. If you invoke it as you pass it as a parameter, it's return value is passed instead. Since your `callback` function has no return, it would pass in `None`.
efficient python array to numpy array conversion Question: I get a big array (image with 12 Mpix) in the array format from the python standard lib. Since I want to perform operations on those array, I wish to convert it to a numpy array. I tried the following: import numpy import array from datetime import datetime test = array.array('d', [0]*12000000) t = datetime.now() numpy.array(test) print datetime.now() - t I get a result between one or two seconds: equivalent to a loop in python. Is there a more efficient way of doing this conversion? Answer: np.array(test) # 1.19s np.fromiter(test, dtype=np.int) # 1.08s np.frombuffer(test) # 459ns !!!
Pygame, simple physics engine, how to hold points between planes? Question: I'm trying to write [this](http://www.wildbunny.co.uk/blog/2011/04/06/physics- engines-for-dummies/) tutorial in Pygame(Python) and having problems about holding points between planes. My code is: [fiz2.py](https://github.com/osa1/pygame- playground/raw/master/fiz2.py) Vector class: [vector.py](https://github.com/osa1/pygame- playground/raw/master/vector.py) If you move mouse on the Pygame screen, the planes will rotate. And when the planes are rotating, points are passing through planes and going outside. I tried to fix points' positions on every iteration but they still passed the planes. I have no idea about where should I fix their positions. NOTE: I know my code is a little bit messy, this is my first 2d program and I had really hard times getting used to Pygame's coordinate plane and vectors. I will re-write when I solve this. NOTE2: Yes, I wrote the comment about how to hold points between planes on the tutorial, I understand the way he fixes positions but have no idea about how(and where, in code) to implement it. Thanks. Answer: I can't tell looking at the code. My guess is a variable-timestep, causing instability. But I can't verify if the math is right. Although, I have useful information : # Vectors You can simplify code, by using vectors as a class vs list/tuple. (velocity, acceleration, location) are treated as one object, verses separate .x and .y values. # example: pos[0] += vel[0] pos[1] += vel[1] # vs pos += vel There is a python-only implementation: [euclid.py](http://partiallydisassembled.net/euclid.html) You can use to compare with your vector.py. Or use [NumPy](http://numpy.scipy.org/) [ used for 3d graphics, in openGL. ] Is a popular, mature lib. # physics (It looks like you want to learn by writing your own physics), but check out [PyMunk](http://code.google.com/p/pymunk/) # colors You can use: [pygame.Color](http://www.pygame.org/docs/ref/color.html) import pygame from pygame import Color color = Color('white') color2 = Color('lightgray') color3 = Color(0,128,128) # collisions # Look at [pygame.sprite.*collide](http://www.pygame.org/docs/ref/sprite.html) , and [pygame.Rect.*collide](http://www.pygame.org/docs/ref/rect.html) # pygame Game loop with numpy vector's Boilerplate I wrote """ Pygame boilerplate. <ninmonkey>2011/04 pygame main Game() loop, and numpy for vector math. note: this might not be the most effecient way to use numpy as vectors, but it's an intro. And this does not force fixed-timesteps. If you want a stable simulation, you need to use a fixed timestep. see: http://gafferongames.com/game-physics/fix-your-timestep/ Keys: ESC : exit Space : game_init() """ import pygame from pygame.locals import * from pygame import Color, Rect import numpy as np def get_screen_size(): """return screen (width, height) tuple""" screen = pygame.display.get_surface() return screen.get_size() class Actor(): """basic actor, moves randomly. members: loc = position vector velocity = velocity vector width, height """ def __init__(self, loc=None, velocity=None): """optional initial loc and velocity vectors""" self.width = 50 self.height = 50 # if loc or velocity are not set: use random if loc is None: self.rand_loc() else: self.loc = loc if velocity is None: self.rand_velocity() else: self.velocity = velocity def update(self): """update movement""" self.loc += self.velocity def rand_velocity(self): """set a random vector , based on random direction. Using unit circle: x = cos(deg) * speed """ rad = np.radians( np.random.randint(0,360) ) speed = np.random.randint(1,15) x = np.cos(rad) y = np.sin(rad) velocity = np.array( [x,y]) velocity *= speed self.velocity = velocity def rand_loc(self): """random location onscreen""" width,height = get_screen_size() x = np.random.randint(0,width) y = np.random.randint(0,height) self.loc = np.array([x,y]) def is_onscreen(self): """test is screen.colliderect(actor) true?""" x,y = self.loc w,h = get_screen_size() screen = Rect(0, 0, w, h) actor = Rect(x, y, self.width, self.height) if screen.colliderect(actor): return True else: return False class GameMain(): """game Main entry point. handles intialization of game and graphics.""" done = False debug = False color_gray = Color('lightgray') def __init__(self, width=800, height=600, color_bg=None): """Initialize PyGame""" pygame.init() self.width, self.height = width, height self.screen = pygame.display.set_mode(( self.width, self.height )) pygame.display.set_caption( "boilerplate : pygame" ) self.clock = pygame.time.Clock() self.limit_fps = True self.limit_fps_max = 60 if color_bg is None: color_bg = Color(50,50,50) self.color_bg = color_bg self.game_init() def game_init(self): """new game/round""" self.actors = [Actor() for x in range(10)] def loop(self): """Game() main loop""" while not self.done: self.handle_events() self.update() self.draw() if self.limit_fps: self.clock.tick( self.limit_fps_max ) else: self.clock.tick() def update(self): """update actors, handle physics""" for a in self.actors: a.update() if not a.is_onscreen(): a.rand_loc() def handle_events(self): """handle regular events. """ events = pygame.event.get() # kmods = pygame.key.get_mods() # key modifiers for event in events: if event.type == pygame.QUIT: sys.exit() elif event.type == KEYDOWN: if (event.key == K_ESCAPE): self.done = True elif (event.key == K_SPACE): self.game_init() def draw(self): """render screen""" # clear screen self.screen.fill( self.color_bg ) # Actor: draw for a in self.actors: x,y = a.loc w,h = a.width, a.height r = Rect(x, y, w, h) self.screen.fill(self.color_gray, r) # will call update on whole screen Or flip buffer. pygame.display.flip() if __name__ == '__main__': g = GameMain() g.loop()
Using doctests from within unittests Question: I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines import doctest import module1 suite = doctest.DocTestSuite(module1) doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer. Answer: In this code i combined unittests and doctests from imported module import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) class ts1(unittest.TestCase): def test_null(self): self.assertTrue(True) testSuite = unittest.TestSuite() testSuite.addTests(unittest.makeSuite(ts)) testSuite.addTest(unittest.makeSuite(ts1)) import doctest import my_module_with_doctests testSuite.addTest(doctest.DocTestSuite(my_module_with_doctests)) unittest.TextTestRunner(verbosity = 2).run(testSuite)
python regular expression tag Question: I want to change this string `<p><b> hello world </b></p>. I am playing <b> python </b>` to: `<bold><bold>hello world </bold></bold>, I am playing <bold> python </bold>` I used: import re pattern = re.compile(r'\<p>(.*?)\</p>|\<b>(.*?)\</b>') print re.sub(pattern, r'<bold>\1</bold>', "<p><b>hello world</b></p>. I am playing <b> python</b>") It does not output what I want, it complains error: _unmatched group_ It works in this case: re.sub(pattern, r'<bold>\1</bold>', "<p>hello world</p>. I am playing <p> python</p>") `<bold> hello world </bold>`. I am playing `<bold> python</bold>` Answer: If you choose not to use regex, then it simple as this: d = {'<p>':'<bold>','</p>':'</bold>','<b>':'<bold>','</b>':'</bold>'} s = '<p><b> hello world </b></p>. I am playing <b> python </b>' for k,v in d.items(): s = s.replace(k,v)
Python authentication system for a framework with no authentication built in (like web.py)? Question: I'm looking at building a website using Web.py, and there is no built-in authentication system. Having read various things about authentication on websites, a common theme I keep hearing is "Don't roll your own, use someone else's." There are some examples of simple authentication on the site, like [this](http://webpy.org/cookbook/userauth) one, but they all say at the bottom "Don't use this in production code." So then, is there a generic authentication library for Python that I could use with Web.py? Or, is it really not that hard to roll my own? Answer: If you can't find one easily, then probably discarding the advice and rolling your own is not a bad choice. I don't think you'll find anything out of the box. The authentication system, is coupled with and dependent on the architecture (in your case probably it is Web only). Having said that it'll perhaps be easier to integrate django's authentication (django.contrib.auth) by putting some hooks here and there with web.py. Even then, it'll import a lot of django'ish ORM and other stuff behind the scene, but it is definitely possible.
Get revisions of a spreadsheet with gdata Python api Question: I'm trying to get the revisions of a spreadsheet using the key, but it just returns "Invalid resource id". from gdata.alt import appengine from gdata.spreadsheet import service from gdata.docs.client import DocsClient self.ss_svc = service.SpreadsheetsService() # ... login code ... gd_client = DocsClient(self.ss_svc.GetClientLoginToken()) rev_uri = "https://spreadsheets.google.com/feeds/spreadsheets/private/full/%s/revisions" % spreadsheet_key # i also tried: rev_uri = "spreadsheet%" + spreadsheet_key rev_feed = gd_client.get(rev_uri) Nothing works. Please help. Answer: This code is a bit confusing because you refer to `self` but this doesn't appear to be part of a class definition. Also, you say you "also tried" `gd_client.get(rev_uri)` but I don't see what you tried before that -- no other method of `gd_client` is called in the above code. And finally, you're using the `get` method, which performs a http GET form request, which I don't _think_ is what you want mean to do. Seems like what you want is [`get_revisions`](http://gdata-python- client.googlecode.com/svn/trunk/pydocs/gdata.docs.client.html#DocsClient- get_revisions). I'm just guessing -- let me know if this is mistaken.
How to completely reset Python stdlib logging module in an ipython session? Question: I'd like to make repeated calls to Python scripts using %run in an ipython session, and for each of those scripts to log based on cmdline arguments passed via %run. For example while debugging cmd.py I might over time want to run: %run cmd.py ... logs with default behavior, e.g. to STDERR with root level WARN %run cmd.py --log_level DEBUG --log_file /tmp/cmd.out ... logs with root level DEBUG to a file %run cmd.py --log_level ERROR Unfortunately this is difficult because the logging state created by logging.basicConfig persists after the first %run command (as is more generally true of all modules, and often desirable when using %run). I realize that in full generality a series of %run commands like above will not be the same as running each command in a new process. However, it would be very convenient if things like the log_level and log_file could be re- initialized. I've tried something like this in cmd.py: import logging_config # parse logging config from sys.argv reload(logging_config) # re-parse cmdline if using %run multiple times and logging_config.py does (condensed): if logging_initialized: logging.getLogger().setLevel(lvl) else: logging.basicConfig(level=lvl) logging_initialized = True It works for simple cases but not if cmd.py imports libraries that also use logging. I've also experimented with logging.shutdown() (called at conclusion of each cmd.py) but that does not seem to help. Answer: Don't use _basicConfig()_ for this style of usage - it's meant for simple one- off configuration and, as the documentation says, subsequent calls after the first have no effect (it only does anything if the root logger has no handlers). This will be fine when your script is run from the shell prompt, but not from the interactive interpreter, IPython, IDLE, PythonWin, or other similar environment where the process you're interacting with doesn't exit. Instead, use programmatic configuration, or _fileConfig()_ or _dictConfig()_ \- these have modes where the completely replace the existing logging configuration with a new one.
Why is an MD5 hash created by Python different from one created using echo and md5sum in the shell? Question: A Python MD5 hash is different than the one created by the md5sum command on the shell. Why? >>> import hashlib >>> h = hashlib.md5() >>> h.update("mystringforhash") >>> print h.hexdigest() 86b6423cb6d211734fc7d81bbc5e11d3 # Result from Python $ echo mystringforhash | md5sum 686687dd68c5de717b34569dbfb8d3c3 - # Result on the shell Answer: `echo` appends a `\n` since you usually do not want lines not ending with a linebreak in your shell (it looks really ugly if the prompt does not start at the very left). Use the `-n` argument to omit the trailing linebreak and it will print the same checksum as your python script: > echo -n mystringforhash | md5sum 86b6423cb6d211734fc7d81bbc5e11d3 -
Add file name as last column of CSV file Question: I have a Python script which modifies a CSV file to add the filename as the last column: import sys import glob for filename in glob.glob(sys.argv[1]): file = open(filename) data = [line.rstrip() + "," + filename for line in file] file.close() file = open(filename, "w") file.write("\n".join(data)) file.close() Unfortunately, it also adds the filename to the header (first) row of the file. I would like the string "ID" added to the header instead. Can anybody suggest how I could do this? Answer: Have a look at the official [csv module](http://docs.python.org/library/csv.html#examples).
Python networking client, trying to respond to server responses Question: The application is a WxPython client/server setup that has multiple clients connect to the server and engaging in duplex networking protocol. I've had Twisted hooked up with AMP in the past, but it did not fully cut it for the architecture in the application without overly complicating things in the end. So for the server I have got SocketServer with the ThreadingMixIn set up. At the moment I am working on the buffer/command queue for the server, but that's not the issue. On the client side I can do all the normal sending of data, triggered by events in the UI, without too much problems. I am currently stuck trying to get the client to listen for responses without blocking the entire application. So I want to put this in a thread, but should it start at the part that's now commented out or should it be handled completely different and I am just not seeing it? In short: I want the client to send commands to the server and listen for any responses without blocking/stalling the entire application. The code below is prototyping code, please excuse any typical mistakes such as magical values and other hardcoded data, it will be different in the final code. import socket import threading import time class CommandProxy(object): def __init__(self, host, port): self.host = host self.port = port def close(self): if self.connection: self.connection.close() def connect(self): try: self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.connect((self.host, self.port)) except socket.error as e: print "Socket error: {0}".format(e) def send_command(self, command, *kw): datalist = ' '.join(kw) data = command + ' ' + datalist + '\x00' print 'DATA: {0}'.format(data) self._write(data) # while True: # data = self._read() # if data == 0: # break # # print "DATA RECEIVED: {0}".format(data) def _read(self): data = self.connection.recv(1024) return data def _write(self, bytes): self.connection.sendall(bytes) if __name__ == '__main__': HOST, PORT = 'localhost', 1060 proxy = CommandProxy(HOST, PORT) proxy.connect() try: while True: proxy.send_command('ID', '1') time.sleep(2) except KeyboardInterrupt: print "Interrupted by user" except socket.error as e: print "Socket error: {0}".format(e) except Exception as e: print "something went wrong: {0}".format(e) finally: proxy.close() Answer: I think you're mistaken about whether a single-threaded or multi-threaded approach will complicate your application more or less. The problem you're wrestling with now is one of the many that (for example) Twisted solves for you out of the box. The most common complaint people have about Twisted is that it makes them structure their code strangely, in a way they're not used to. However, when you're using a GUI library like wxPython, you have already accepted this constraint. Twisted's event-driven architecture is exactly like the event- driven architecture of all the popular GUI toolkits. As long as you keep using wxPython, also using Twisted isn't going to force you to do anything **else** you don't want to do. On the other hand, switching to threads will mean you need to be very careful about access to shared data structures, you won't be able to unit test effectively, and many problems that arise will only do so when someone else is running your application - because they have a different number of cores than you, or their network has different latency characteristics, or any of a number of other things which cause your threaded code to run in ways you never experienced. With extreme care you can still write something that works, but it will be much more difficult. Since you haven't posted any of your Twisted-based code here, I can't really give any specific advice on how to keep things as simple as possible. However, I recommend that you take another look at a non-threaded solution. Join the twisted-python@twistedmatrix.com mailing list, hop on #twisted on freenode, or post more stackoverflow questions about it. Lots of people will be eager to help. :)
mysqldb interfaceError Question: I have a very weird problem with mysqldb (mysql module for python). I have a file with queries for inserting records in tables. If I call the functions from the file, it works just fine; but when trying to call one of the functions from another file it throws me a > _mysql_exception.InterfaceError: (0, '') I really don't get what I'm doing wrong here.. I call the function from `buildDB.py` : import create create.newFormat("HD", 0,0,0) The function newFormat(..) is in create.py (imported) : from Database import Database db = Database() def newFormat(name, width=0, height=0, fps=0): format_query = "INSERT INTO Format (form_name, form_width, form_height, form_fps) VALUES ('"+name+"',"+str(width)+","+str(height)+","+str(fps)+");" db.execute(format_query) And the class Database is the following : import MySQLdb from MySQLdb.constants import FIELD_TYPE class Database(): def __init__(self): server = "localhost" login = "seq" password = "seqmanager" database = "Sequence" my_conv = { FIELD_TYPE.LONG: int } self.conn = MySQLdb.connection(host=server, user=login, passwd=password, db=database, conv=my_conv) # self.cursor = self.conn.cursor() def close(self): self.conn.close() def execute(self, query): self.conn.query(query) (I put only relevant code) Traceback : Z:\sequenceManager\mysql>python buildDB.py D:\ProgramFiles\Python26\lib\site-packages\MySQLdb\__init__.py:34: DeprecationWa rning: the sets module is deprecated from sets import ImmutableSet INSERT INTO Format (form_name, form_width, form_height, form_fps) VALUES ('HD',0 ,0,0); Traceback (most recent call last): File "buildDB.py", line 182, in <module> create.newFormat("HD") File "Z:\sequenceManager\mysql\create.py", line 52, in newFormat db.execute(format_query) File "Z:\sequenceManager\mysql\Database.py", line 19, in execute self.conn.query(query) _mysql_exceptions.InterfaceError: (0, '') The warning has never been a problem before so I don't think it's related. Answer: I got this error when I was trying to use a closed connection.
Django upgrade succeeds, then reverts back Question: My django version is 1.1 rgross@fun:~$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> print django.VERSION (1, 1, 1, 'final', 0) >>> quit() rgross@fun:~$ So, I [upgrade to the latest version](http://www.djangoproject.com/download/). gross@fun:/tmp/Django-1.3$ sudo python setup.py install running install running build running build_py running build_scripts running install_lib running install_scripts changing mode of /usr/local/bin/django-admin.py to 755 running install_data running install_egg_info Removing /usr/local/lib/python2.6/dist-packages/Django-1.3.egg-info Writing /usr/local/lib/python2.6/dist-packages/Django-1.3.egg-info rgross@fun:/tmp/Django-1.3$ And check the version again, and great success, I get django 1.3 rgross@fun:/tmp/Django-1.3$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> print django.VERSION (1, 3, 0, 'final', 0) BUT, when I open a fresh terminal window and check the version, I find that my version upgrade was not persistent, and the new terminal sees version 1.1! Any idea what is happening? Answer: The problem was caused because I had also installed django by apt-get. To resolve: sudo apt-get remove python-django
python print contents from wx.ListCtrl Question: I have a list created as self.statusListCtrl = wx.ListCtrl(self.panelUpper, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER) I add data to this list using self.statusListCtrl.Append([datetime.datetime.now(),action,result]) When my process is all done I have a nice list showing things that were tried, the result of that attempt and a datetime stamp. Now what I want to do is output that to a text file. my problem is that I cant get the data from my listctrl correctly. This is how I am trying to iterate through the list. fileName = 'd:\ssplogs\sspInstaller.log' FILE = open(fileName,"w") for itemIdx in range(0,self.statusListCtrl.GetItemCount()): line = str(self.statusListCtrl.GetItemText(itemIdx) + "\n") print "line" , line writeLine = line FILE.write(writeLine) FILE.close() The output I am getting though is only my datetime stamp, which is the first column of my list. How do I get this so I see something like datetime, action, result Answer: Use this to get Row x Column data: self.list.GetItem(row, col).GetText() Working example: import wx class MainWindow(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.panel = wx.Panel(self) self.list = wx.ListCtrl(self.panel, style=wx.LC_REPORT) self.list.InsertColumn(0, "Date") self.list.InsertColumn(1, "Action") self.list.InsertColumn(2, "Result") for a in range(5): self.list.Append(["Date %d" % a, "Action %d" % a, "Result %d" % a]) self.sizer = wx.BoxSizer() self.sizer.Add(self.list, proportion=1, flag=wx.EXPAND) self.panel.SetSizerAndFit(self.sizer) self.Show() # Save for row in range(self.list.GetItemCount()): print(", ".join([self.list.GetItem(row, col).GetText() for col in range(self.list.GetColumnCount())])) app = wx.App(False) win = MainWindow(None) app.MainLoop()
Detecting imported objects Question: Given the source code of a Python file, I would like to detect all imported objects. For example, given this source: import mymod from mymod2 import obj1, obj2, obj3 from mymod3 import aobj I want to get: [('mymod2', 'obj1', 'obj2', 'obj3'), ('mymod3', 'aobj')] I have already tried this regex: r'from (?P<mod>[_\w\d]+) import (?:(?P<obj>[_\w\d]+)[,\s]?)+' But I only get the first imported object: [('mymod2', 'obj1'), ('mymod3', 'aobj')] Answer: A better tool than regular expressions is the `ast` module that comes with Python. To find all `from ... import` statements in the outermost scope of `a.py` and print all imported names, you could use import ast code = open("a.py").read() for node in ast.parse(code).body: if isinstance(node, ast.ImportFrom): for name in node.names: print name.name Note that this simple code will miss any statements that are not directly at module level, such as import statements inside a try-block. This can easily be fixed by using `ast.walk()` to walk over all nodes.
Move required files where they need to go Question: I'm working on a Python script that unzips a compressed directory and installs some files. When you unzip the compressed file, there could be files like `./usr/bin/package` or `./var/lib/package`. The unzipped directory contains the names of the dirs where they actually need to go. Lets say the directory structure looks like: ./zippedfile.zip ./usr /bin /package ./var ./lib ./package ` Now I need to move the required files where they need to go. For example I need to move `./usr/bin/package` to the actual `/usr/bin/` directory. Thing is, it's not predictable which folders there may be, so the script needs to find the required directories and move them. Thanks, hopefully I made the question clear. Answer: Use the zipfile module to read the zip file and `extract(name, dest)` to extract each file. For example: import sys import zipfile def unzip(path, root='/'): zh = zipfile.ZipFile(path, 'r') for name in zh.namelist(): zh.extract(name, root) zh.close() unzip(sys.argv[1]) If a file within the zip has a path of `./usr/bin/script` it will be extracted to `/usr/bin/script`. Usage: % python unzip.py myfiles.zip **Update** : To handle tars, use the [tarfile module](http://docs.python.org/library/tarfile.html). This detects the compression type using the file extension (gzip, bzip2): import os import sys import tarfile def untar(path, root='/'): mode = 'r' _, ext = os.path.splitext(path) if ext in ('.gz', '.bz2'): mode += ':' + ext[1:] th = tarfile.open(path, mode) for info in th.getmembers(): th.extract(info, root) th.close() untar(sys.argv[1]) **Updated** If you can't use the zipfile or tarfile modules, you can invoke corresponding system commands to get the same results: import os import subprocess import sys def untar(path, root): subprocess.call(['tar', '-C', root, '-xf', path]) def unzip(path, root): subprocess.call(['unzip', os.path.abspath(path)], cwd=root) path = sys.argv[1] dest = os.path.abspath(sys.argv[2]) if not os.path.exists(dest): os.makedirs(dest) if path.endswith('.zip'): unzip(path, dest) else: untar(path, dest)
Simple random name generator in Python Question: I have a text file containing first and last 'syllables', demarcated with [part1] and [part2]: [part1] Ae Di Mo Fam [part2] dar kil glar tres All I want to do is pick a random line, between [part1] and [part2], and then another random line between [part2] and the end of the file, and concatenate the two together (e.g. "Aedar", "Moglar") to create random names. However I am unsure how to parse the text file effectively with readline(). Is there a better way than scanning through each line sequentially, and storing all of them in a list from whence I can pick a random element? Answer: Serialize ([pickle](http://docs.python.org/library/pickle.html)) a dictionary to a file instead. Example: # create the dict and save it to a file d={ 'part1':[ 'Ae', 'Di', 'Mo', 'Fam',], 'part2':[ 'dar', 'kil', 'glar', 'tres',], } import pickle f=open('syllables','w') pickle.dump(d,f) f.close() # read the dict back in from the file f1=open('syllables','r') sd=pickle.load(f1) f1.close() import random first_part=sd['part1'][random.randint(0,len(sd['part1'])-1)] second_part=sd['part2'][random.randint(0,len(sd['part2'])-1)] print '%s%s'%(first_part,second_part)
rpy2 nls initial parameters choice Question: Hi I am running a code in python importing rpy2 robjects and trying to make a fit to some data (with errors that I consider as weights). I am using a non linear regression and the "formula" i am trying to fit is: A/((x/t1)^b+(x/t1)^c) Unfortunately every time I try to run the code I got the usual singular gradient error: rpy2.rinterface.RRuntimeError: Error in function (formula, data = parent.frame(), start, control = nls.control(), : singular gradient I think is due to my initial value for the parameters (A,t1,b and c). Is there any way I can have a better guess for the initial values instead just try- outs? Thanks, nino Answer: have you checked nlstools in R <http://cran.r-project.org/web/packages/nlstools/>
Speed of fetching web pages with Eventlet and Python? Question: I am writing a relatively simple crawler in Python but I want to use asynchronous networking lib in order to fetch multiple pages concurrently.I saw the examples on their page but when I apply the same logic that is shown and works for ~200 web pages for ~1000/2000 urls , the performance slows down.(Most of the urls were from different domains and i have shuffled them ). What is the fastest way to crawl such number of pages with Eventlet and what speed can i get? (speed like fetches/s) Here is the example: urls = ["http://www.google.com/intl/en_ALL/images/logo.gif", "https://wiki.secondlife.com/w/images/secondlife.jpg", "http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"] import eventlet from eventlet.green import urllib2 def fetch(url): return urllib2.urlopen(url).read() pool = eventlet.GreenPool() for body in pool.imap(fetch, urls): print "got body", len(body) Answer: We created a transformation proxy service with Spawning web server. Spawning is using eventlets internally. The purpose of a service was to expose legacy XML API to mobile applications (iPhone, Android, etc.) <http://pypi.python.org/pypi/Spawning/> 1) The server calls ISS backed backend service which outputs XML using urllib 2) Python reads XML, transforms it to JSON. lxml was used for parsing, simplejson with native C extension compiled in for output 3) The resulting JSON was send to the client The performance with eventlets was awesome > 1000 req/s on a server with 8 virtual cores. The performance was stable (zero error %s). No latencies. We had to do some balancing between number of processes and threads per process and I think we used something like 12 processes each with 20-50 threads. We also tested Twisted and its async page get method. For Twisted, we managed to get performance of only 200 req/s before we started seeing too many errors. With Twisted, also the latencies started to grow quickly and doomed this approach. The performance was measured with complex JMeter scripts which did all funky stuff like authentication, etc. I think the key here was how Spawning monkey-patches urllib to be very async by nature.
How to create a transparent frame with visible borders? Question: I would like to create a transparent frame with visible borders. The code I've written based on hasenj's work of 'shaped-frame' (<http://hasenj.wordpress.com/2009/04/14/making-a-fancy-window-in-wxpython/>) is as follows. But I still have problem making one. I must have missed something. Could anybody point out what's wrong with the program? Thanks. * * * import wx class FancyFrame(wx.Frame): def __init__(self, width, height): wx.Frame.__init__(self, None, style = wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.FRAME_SHAPED, size=(width, height)) self.SetTransparent(50) b = wx.EmptyBitmap(width, height) dc = wx.MemoryDC() dc.SelectObject(b) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetPen(wx.Pen('red', 2)) dc.DrawRectangle(0, 0, width, height) dc.SelectObject(wx.NullBitmap) self.SetShape(wx.RegionFromBitmap(b)) self.Bind(wx.EVT_KEY_UP, self.OnKeyDown) self.Show(True) def OnKeyDown(self, event): """quit if user pressEsc""" if event.GetKeyCode() == 27: #27 is the Esc key self.Close(force=True) else: event.Skip() if __name__ == "__main__": app = wx.App() FancyFrame(300, 300) app.MainLoop() * * * Answer: It is not very good idea to draw stuff outside MainLoop. You should setup your wx application so it is Event driven. The events EVT_PAINT and EVT_SIZE should be handled. The `wx.Timer` can be used for basic movement. import wx #============================================================================= class DrawPanelDB(wx.Panel): def __init__(self, *args, **kwargs): wx.Panel.__init__(self, *args, **kwargs) self.ballPosition = [20, 20] self.ballDelta = [1, 1] self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTime, self.timer) self.timer.Start(20) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) #------------------------------------------------------------------------- def OnPaint(self, event): dc = wx.BufferedPaintDC(self) dc.SetBackground(wx.Brush(wx.BLACK)) dc.Clear() dc.DrawCirclePoint(self.ballPosition, 20) #------------------------------------------------------------------------- def OnSize(self, event): self.Refresh() self.Update() #------------------------------------------------------------------------- def OnEraseBackground(self, event): pass # Or None #------------------------------------------------------------------------- def OnTime(self, event): self.ballPosition[0] += self.ballDelta[0] self.ballPosition[1] += self.ballDelta[1] w, h = self.GetClientSizeTuple() if self.ballPosition[0] > w: self.ballPosition[0] = w self.ballDelta[0] *= -1 if self.ballPosition[1] > h: self.ballPosition[1] = h self.ballDelta[1] *= -1 if self.ballPosition[0] < 0: self.ballPosition[0] = 0 self.ballDelta[0] *= -1 if self.ballPosition[1] < 0: self.ballPosition[1] = 0 self.ballDelta[1] *= -1 self.Refresh() #============================================================================= class MainWindow(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.panel = DrawPanelDB(self) self.Show() #============================================================================= app = wx.App(False) win = MainWindow(None) app.MainLoop() * * * **Edit:** Example with ScreenDC using xor function for non-destructible drawing. import wx #============================================================================= class MainWindow(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.ballPosition = [20, 20] self.lastPosition = None self.ballDelta = [1, 1] self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTime, self.timer) self.timer.Start(20) #------------------------------------------------------------------------- def OnTime(self, event): self.ballPosition[0] += self.ballDelta[0] self.ballPosition[1] += self.ballDelta[1] w, h = wx.DisplaySize() if self.ballPosition[0] > w: self.ballPosition[0] = w self.ballDelta[0] *= -1 if self.ballPosition[1] > h: self.ballPosition[1] = h self.ballDelta[1] *= -1 if self.ballPosition[0] < 0: self.ballPosition[0] = 0 self.ballDelta[0] *= -1 if self.ballPosition[1] < 0: self.ballPosition[1] = 0 self.ballDelta[1] *= -1 dc = wx.ScreenDC() dc.StartDrawingOnTop() dc.SetLogicalFunction(wx.XOR) if self.lastPosition is not None: dc.DrawRectangle(self.lastPosition[0], self.lastPosition[1], 15, 15) self.lastPosition = (self.ballPosition[0], self.ballPosition[1]) dc.DrawRectangle(self.ballPosition[0], self.ballPosition[1], 15, 15) dc.EndDrawingOnTop() #============================================================================= app = wx.App(False) win = MainWindow(None) app.MainLoop() * * * **Edit:** Another possibility is to keep backup copy of that part of the screen. import wx #============================================================================= class MainWindow(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.ballPosition = [20, 20] self.lastPosition = None self.ballDelta = [1, 1] self.patch = wx.EmptyBitmap(20, 20) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTime, self.timer) self.timer.Start(20) #------------------------------------------------------------------------- def OnTime(self, event): self.ballPosition[0] += self.ballDelta[0] self.ballPosition[1] += self.ballDelta[1] w, h = wx.DisplaySize() if self.ballPosition[0] > w: self.ballPosition[0] = w self.ballDelta[0] *= -1 if self.ballPosition[1] > h: self.ballPosition[1] = h self.ballDelta[1] *= -1 if self.ballPosition[0] < 0: self.ballPosition[0] = 0 self.ballDelta[0] *= -1 if self.ballPosition[1] < 0: self.ballPosition[1] = 0 self.ballDelta[1] *= -1 dc = wx.ScreenDC() dc.StartDrawingOnTop() bdc = wx.MemoryDC(self.patch) if self.lastPosition is not None: dc.Blit(self.lastPosition[0] - 2, self.lastPosition[1] - 2, 20, 20, bdc, 0, 0) bdc.Blit(0, 0, 20, 20, dc, self.ballPosition[0] - 2, self.ballPosition[1] - 2) self.lastPosition = (self.ballPosition[0], self.ballPosition[1]) dc.DrawRectangle(self.ballPosition[0], self.ballPosition[1], 15, 15) dc.EndDrawingOnTop() #============================================================================= app = wx.App(False) win = MainWindow(None) app.MainLoop()
Find and copy files to existing Folders with corresponding names in python Question: i have a large number of files that i need to move to a specific existing folder. the problem is that the number code that relates the file and the folder has text on either side of it as shown below the number code is a071137 in the file name and A071137 in the folder name. for example, i need to move file: "a071137_gindalbie.pdf" to folder "A071137 2006 Teck Commginco Pty Ltd" . I would like to do this using python I guess I first find the corresponding file using glob? Then to copy it there ?? not sure?? Answer: Your question is rather vague, but hopefully I can at least point you in the right direction here. Sounds like you will want to be able to list all of the files in a directory, which can be done with `os.listdir(directory)` as described in the [api](http://docs.python.org/library/os.html). You will likely then iterate through these files, and extract the relevant information you will need using a regular expression. You'll need to reference [the api](http://docs.python.org/library/re.html) on that too. For example, you can extract a number using something like: >>> import re >>> r = re.compile('^a(?P<id>[0-9]+)') >>> m = r.match('a123') >>> m.group('id') '123' Next you can move files using things in the `shutil` module. You should be able to use `shutil.move()` for your purposes. For more information, again, checkout [the api](http://docs.python.org/library/shutil.html).
Simple Log to File example for django 1.3+ Question: The release notes say: > Django 1.3 adds framework-level support for Python’s logging module. That's nice. I'd like to take advantage of that. Unfortunately [the documentation](http://docs.djangoproject.com/en/1.3/topics/logging/) doesn't hand it all to me on a silver platter in the form of complete working example code which demonstrates how simple and valuable this is. How do I set up this funky new feature such that I can pepper my code with logging.debug('awesome stuff dude: %s' % somevar) and see the file "/tmp/application.log" fill up with 18:31:59 Apr 21 2011 awesome stuff dude: foobar 18:32:00 Apr 21 2011 awesome stuff dude: foobar 18:32:01 Apr 21 2011 awesome stuff dude: foobar What's the difference between the default Python logging and this 'framework- level support'? Answer: I truly love this so much here is your working example! Seriously this is awesome! Start by putting this in your `settings.py` LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': SITE_ROOT + "/logfile", 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'MYAPP': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, } } Now what does all of this mean? 1. Formaters I like it to come out as the same style as ./manage.py runserver 2. Handlers - I want two logs - a debug text file, and an info console. This allows me to really dig in (if needed) and look at a text file to see what happens under the hood. 3. Loggers - Here is where we nail down what we want to log. In general django gets WARN and above - the exception (hence propagate) is the backends where I love to see the SQL calls since they can get crazy.. Last is my app were I have two handlers and push everything to it. Now how do I enable MYAPP to use it... Per the [documentation](https://docs.djangoproject.com/en/dev/topics/logging/#using- logging) put this at the top of your files (views.py).. import logging log = logging.getLogger(__name__) Then to get something out do this. log.debug("Hey there it works!!") log.info("Hey there it works!!") log.warn("Hey there it works!!") log.error("Hey there it works!!") Log levels are explained [here](https://docs.djangoproject.com/en/dev/topics/logging/#making-logging- calls) and for pure python [here](http://docs.python.org/library/logging.html).
Printing my Mac's serial number in java using Unix commands Question: I am trying to print my mac's [edit: Apple computer] serial number in a java program. I am familiar with the Unix command ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}' which accomplishes this task in terminal. When I try String command = "ioreg -l | awk '/IOPlatformSerialNumber/ { print $4; }'" Runtime terminal = Runtime.getRuntime(); String input = new BufferedReader( new InputStreamReader( terminal.exec(commands).getInputStream())).readLine(); System.out.println(new BufferedReader( new InputStreamReader( terminal.exec(command, args).getInputStream())).readLine()); my serial number is not printed. Instead it prints: <+-o Root class IORegistryEntry, id 0x100000100, retain 10> I think the problem is that `terminal.exec()` is not meant to take the whole command string. Is there something in java similar to the argument `shell = True` in python's `Popen(command, stdout=PIPE, shell=True)` that will allow me to pass the whole command string? Answer: I see two possibilities: 1. Parse the output of `ioreg -l` using, say, [Scanner](http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html). 2. Wrap the command in a shell script and `exec()` it: #!/bin/sh ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}' Addendum: As an example of using [`ProcessBuilder`](http://download.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html), and incorporating a helpful suggestion by [Paul Cager](http://stackoverflow.com/users/683825/paul-cager), here's a third alternative: import java.io.BufferedReader; import java.io.InputStreamReader; public class PBTest { public static void main(String[] args) { ProcessBuilder pb = new ProcessBuilder("bash", "-c", "ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}'"); pb.redirectErrorStream(true); try { Process p = pb.start(); String s; // read from the process's combined stdout & stderr BufferedReader stdout = new BufferedReader( new InputStreamReader(p.getInputStream())); while ((s = stdout.readLine()) != null) { System.out.println(s); } System.out.println("Exit value: " + p.waitFor()); p.getInputStream().close(); p.getOutputStream().close(); p.getErrorStream().close(); } catch (Exception ex) { ex.printStackTrace(); } } }
SwigPyObject and JSON communication inside python code Question: **Intro.** I have a C++ application, I use SWIG to launch `GetObjects` and `PutObjects` methods which are defined in python code. `GetObjects` method opens JSON formated file, takes objects from there and returns back them to C++ application. While the `PutObjects` method gets objects from C++ application, opens JSON formated file for writing and stores them over there. The code is pretty common and uses MyJSONDecode and MyJSONEncode functions to interact between python objects and json dictionaries. **Now the problem.** Swig converts `MyObject` C++ class into python class called `MyObject` located in `abc` module. I use `import abc` statement to use it further in code like `abc.MyObject()`. `abc.MyObject` is a `SwigPyObject` and it does not have dictionary itself (`__dict__` member). So I can't iterate through `MyObject.__dict__` inside MyJSONEncode function to build up a dictionary which should be returned by the function and therefore to create a JSON format. But MyObject has properties, for example url or name and so on. How can I iterate through properties ? If needed, I will provide you with code. Just let me know. Also I hope, in general, my problem is understood. Waiting for kind response :) Answer: You should be able to use the "dir" function to get a list of attributes of an object. Here is example which grabs all non function user created attributes (called "properties"): import inspect class MyObject(object): def __init__(self): self.b = 1 self.c = 'a' def func(self): pass obj = MyObject() # Get all the user created attributes for the object attributes = [d for d in dir(obj) if not d.startswith('__')] # Filter those to get the non functions properties = [a for a in attributes if not inspect.ismethod(getattr(obj,a))]
Taking the results of a bash command and using it in python Question: I am trying to write a code in python that will take some information from top and put it into a file. I want to just write the name of the application and generate the file. The problem i am having is that i can't get the output of the pidof command so i can use it in python. My code looks like this : import os a = input('Name of the application') val=os.system('pidof ' + str(a)) os.system('top -d 30 | grep' + str(val) + '> test.txt') os.system('awk '{print $10, $11}' test.txt > test2.txt') The problem is that val always has 0 but the command is returning the pid i want. Any input would be great. Answer: First up, the use of `input()` is discouraged as it expects the user to type in valid Python expressions. Use `raw_input()` instead: app = raw_input('Name of the application: ') Next up, the return value from `system('pidof')` isn't the PID, it's the exit code from the `pidof` command, i.e. zero on success, non-zero on failure. You want to [capture the output](http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell- backquote) of `pidof`. import subprocess # Python 2.7 only pid = int(subprocess.check_output(['pidof', app])) # Python 2.4+ pid = int(subprocess.Popen(['pidof', app], stdout=subprocess.PIPE).communicate()[0]) # Older (deprecated) pid = int(os.popen('pidof ' + app).read()) The next line is missing a space after the `grep` and would have resulted in a command like `grep1234`. Using the string formatting operator `%` will make this a little easier to spot: os.system('top -d 30 | grep %d > test.txt' % (pid)) The third line is badly quoted and should have caused a syntax error. Watch out for the single quotes inside of single quotes. os.system("awk '{print $10, $11}' test.txt > test2.txt")
Basic inserting of image? Python Question: I use python on Ubuntu, and I am (as my name suggests) a complete noob at it all. I want to insert a very basic image, I have looked around, copied coding etc, but mothing seems to work. I want to insert an image, nothing else, so it just appears on the screen when I run it in shell. Please help? and please explain in simple terms, i'd like to know what I'm actually doing! Thank-you in advance. Answer: you can install PIL imagemagick then: import Image im = Image.open("your_image") im.show()
python: single-line cartesian product for-loop Question: Did you know you can do this? >>> [(x,y) for x in xrange(2) for y in xrange(5)] [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4)] It's neat. Is there a for loop version or can one only do this for list comprehensions? EDIT: I think my question was misunderstood. I want to know if there is special syntax for this: for x in xrange(2) <AND> y in xrange(5): print "do stuff here" print "which doesn't fit into a list comprehension" print "like printing x and y cause print is a statement", x, y I could do this, but it seems a bit repetitive: for x,y in ((x,y) for x in xrange(2) for y in xrange(5)): print x, y Answer: Well there's no syntax for what you want, but there is [`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product). >>> import itertools >>> for x, y in itertools.product([1,2,3,4], [5,6,7,8]): print x, y ... 1 5 1 6 1 7 1 8 [ ... and so on ... ]
Python: Convert email address to HTML link Question: I'm looking for a stand-alone python function that will take in a string and return a string with the email addresses converted to links. Example: >>>s = 'blah blah blah a@at.com blah blah blah' >>>link(s) 'blah blah blah <a href="mailto:a@at.com">a@at.com</a> blah blah blah' Answer: Something like this? import re import xml.sax.saxutils def anchor_from_email_address_match(match): address = match.group(0) return "<a href=%s>%s</a>" % ( xml.sax.saxutils.quoteattr("mailto:" + address), xml.sax.saxutils.escape(address)) def replace_email_addresses_with_anchors(text): return re.sub("\w+@(?:\w|\.)+", anchor_from_email_address_match, text) print replace_email_addresses_with_anchors( "An address: bob@example.com, and another: joe@example.com")
Django loaddata settings error Question: When trying to use loaddata on my local machine (win/sqlite): python django-admin.py loaddata dumpdata.json I get the following error: raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. I am using djangoconfig app if that helps: """ Django-config settings loader. """ import os CONFIG_IDENTIFIER = os.getenv("CONFIG_IDENTIFIER") if CONFIG_IDENTIFIER is None: CONFIG_IDENTIFIER = 'local' # Import defaults from config.base import * # Import overrides overrides = __import__( "config." + CONFIG_IDENTIFIER, globals(), locals(), ["config"] ) for attribute in dir(overrides): if attribute.isupper(): globals()[attribute] = getattr(overrides, attribute) **projects>python manage.py loaddata dumpdata.json --settings=config.base** WARNING: Forced to run environment with LOCAL configuration. Problem installing fixture 'dumpdata.json': Traceback (most recent call last): File "loaddata.py", line 174, in handle obj.save(using=using) ... File "C:\Python26\lib\site-packages\django\db\backends\sqlite3\base.py", line 234, in execute return Database.Cursor.execute(self, query, params) IntegrityError: columns app_label, model are not unique Answer: Don't use `django-admin.py` for anything other than setting up an initial project. Once you have a project, use `manage.py` instead - it sets up the reference to your settings file.
how to transform a OpenCV cvMat back to ndarray in numpy ? Question: I follow the code in OpenCV cookbook for python interface to transform cvMat to numpy array: mat = cv.CreateMat(3,5,cv.CV_32FC1) cv.Set(mat,7) a = np.asarray(mat) but with OpenCV 2.1 on my PC, it does not work. The result **a** here is a object array, using **"print a"** does not print all element in **a** , only print `<cvmat(type=42424005 rows=3 cols=5 step=20 )>`. so how to fully transform a **OpenCV Mat object** to original **numpy.ndarray** object. Answer: Try using appending `[:,:]` to the matrix (ie. use `mat[:,:]` instead of `mat`) in your call to `np.asarray` \- doing this will also allows `asarray` to work on images. Your example: >>> import cv >>> import numpy as np >>> mat = cv.CreateMat( 3 , 5 , cv.CV_32FC1 ) >>> cv.Set( mat , 7 ) >>> a = np.asarray( mat[:,:] ) >>> a array([[ 7., 7., 7., 7., 7.], [ 7., 7., 7., 7., 7.], [ 7., 7., 7., 7., 7.]], dtype=float32) And for an image: >>> im = cv.CreateImage( ( 5 , 5 ) , 8 , 1 ) >>> cv.Set( im , 100 ) >>> im_array = np.asarray( im ) >>> im_array array(<iplimage(nChannels=1 width=5 height=5 widthStep=8 )>, dtype=object) >>> im_array = np.asarray( im[:,:] ) >>> im_array array([[100, 100, 100, 100, 100], [100, 100, 100, 100, 100], [100, 100, 100, 100, 100], [100, 100, 100, 100, 100], [100, 100, 100, 100, 100]], dtype=uint8)
global question (python) Question: I have the code: from Tkinter import * admin = Tk() a = 1 def up(): global a a += 1 def upp(): up() print a print 'its ',a buttton = Button(admin, text='up', command=upp) buttton.pack() mainloop() I want to have the "its ",a go up each time i press the button. so kind of replay the code so that, its # would go up by one each time...help Answer: I tested this: from Tkinter import * import itertools admin = Tk() a = itertools.count(1).next def upp(): print a() buttton = Button(admin, text='up', command=upp) buttton.pack() mainloop() This will start a at a value of 1 and each time its printed it will add one more. So the first time you press it, it will display 1 in standard out.
Web Dev. Framework for RAD Web App Dev. in Shortest Time ( Yii vs. Django ) Question: I googled it and found nothing of much interest , right now me & my Team know/partially know ( Codeigniter, Yii) and also Django (Python Framework) , now after working with codeigniter for past 1 year we have noticed that we are not that efficient and we still have to code most of the stuff( comment system, image upload, rating, voting etc. ) repeatedly ( you can call it progressive enhancement ) . Now , we have started development in Yii and it's superb we are experiencing it but what I find is that I love Python more than PHP , but due to deadlines and time shortage , I cant ask my team to switch to it now . SO, what I'm trying to do is convince myself that which framework among these 3 ( Codeigniter, Yii, Django ) would give us fastest delivery times ? My personal opinion is that Yii & Django are somewhat equal but due to avilability of large no. of Packages [Django Packages](http://djangopackages.com/) , we will be able to develop quicker and faster , although Yii has it's extensions too [Yii Extensions](http://www.yiiframework.com/extensions/) but at this time there are not many and only few of them are highly stable , while others have bugs still (Maybe all this is due to my higher knowledge of PHP & PHP frameworks than Python frameworks & Django ) so, I would be glad if someone who has some practical experience transitioning from PHP to Python based frameworks could shed some light on this ! Edit: I'm looking for a practical response from a programmer who has developed in both frameworks Django vs. Yii ( or has atleast played with them ) and he/she can verify that development time for a typical CMS/Portal/Review Website/Digg clone ... type Web App takes less time in one than other , as Time is what I worry about learning the language / features/ benefits are not that important , scalability too ius a matter of proper DB optimization and other architectural changes , also i would like to highlight that I'm not considering Ruby on Rails as I dont want to learn ruby just for a framework , rather I'm interested in Django vs. Yii in terms of shortest time to market given all other factors ( manpower/skill set/DB design) equal , Kindly help , I have been thinking about this for a week now ! Answer: Vivek, this is one of those questions to which it's hard to give an answer better than "it depends". Personally, I think that the language and its ecosystem is a very important factor in the choice, perhaps more so than the specific framework. Why so? As you mentioned, you found out that you had to write a lot of code from scratch even though you thought a framework would provide it. _This is a basic fact of our programming life_ \- no matter the framework / library, eventually we're going to write some functionality of our own because: * Either it's missing * Or it's not good enough for our needs, for 1000s of possible reasons So in the end, as an application becomes more and more complex, we'll find ourselves implementing more and more functionality because the existing libraries just aren't flexible enough. I think that the recent success of web micro-frameworks in Python has its roots in the same cause. This is why the basis is important, and the basis in your case is PHP and its ecosystem vs. Python and its ecosystem. Both languages have huge amounts of library code available, but which do you find more pleasant to work with _as a language_? Which is the one you and your co-devs know best? Which is the language for which you'll find it easier to hire new devs (if applicable)? * * * P.S. I don't know much about PHP, but for Python/Django, apart from Django Packages, there's also [Pinax](http://pinaxproject.com/).
Blender not working with Python Question: I'm trying to run an external script with blender 2.49b and 2.57 I tried with installing Python versions, 2.4, 2.6 and 2.7. I'm getting this error in the console window. Anyone have a clue of what I'm missing? **Traceback (most recent call last): File "", line 1, in File "C:\Program Files\Blender 2.49b.blender\scripts\blended_cities_24hook.py ", line 77, in from random import randint,random,uniform File "C:\Python24\LIB\random.py", line 41, in from warnings import warn as _warn File "C:\Python24\LIB\warnings.py", line 258, in simplefilter("ignore", category=OverflowWarning, append=1) NameError: name 'OverflowWarning' is not defined** Computer Info: Operating Sys: Win7 x64. CPU: Intel. Answer: Fixed it! In my sys vars, I had the Python path set to the 2.4 version, which doesn't work with these versions of blender.
SWIG C-to-Python Int Array Question: I am trying to access a C function with the following prototype from python using swig: int cosetCoding(int writtenDataIn, int newData, const int memoryCells, int *cellFailure, int failedCell); Swig creates the .so with no problems and I can import it into python, but when I try to access it with the following: cosetCoding.cosetCoding(10,11,8,[0,0,0,0,0,0,0,0],0) I get the following traceback: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: in method 'cosetCoding', argument 4 of type 'int *' The pointer is supposed to be an int array with size defined by memoryCells Answer: Use ctypes if you can. It is simpler. However, since you asked for SWIG, what you need is a typemap describing how to handle the int*. SWIG doesn't know how many integers may be pointed to. Below is hacked from an example in the SWIG documentation on [multi-argument typemaps](http://www.swig.org/Doc2.0/SWIGDocumentation.html#Typemaps_multi_argument_typemaps): %typemap(in) (const int memoryCells, int *cellFailure) { int i; if (!PyList_Check($input)) { PyErr_SetString(PyExc_ValueError, "Expecting a list"); return NULL; } $1 = PyList_Size($input); $2 = (int *) malloc(($1)*sizeof(int)); for (i = 0; i < $1; i++) { PyObject *s = PyList_GetItem($input,i); if (!PyInt_Check(s)) { free($2); PyErr_SetString(PyExc_ValueError, "List items must be integers"); return NULL; } $2[i] = PyInt_AsLong(s); } } %typemap(freearg) (const int memoryCells, int *cellFailure) { if ($2) free($2); } Note that with this definition, when called from Python leave out the `memoryCells` parameter and just pass an array such as `[1,2,3,4]` for `cellFailure`. The typemap will generate the `memoryCells` parameter. P.S. I can post a fully working example (for Windows) if you want it.
How do I override PySerial's "__del__" method in Python? Question: I have a simple Python script set up to send Characters to a device on COM3. (This is running on Windows XP) The device receives the Characters fine, but when the script ends, or I call ser.close() #ser is an instance of the `serial` method `Serial` It sets the DTR Line on the serial port High, Resetting my Device. Perplexed by this, I poked around in the PySerial Documentation (<http://pyserial.sourceforge.net/>) and found that the Module has a `__del__` method, which calls the `ser.close()` function when the Serial instance is deleted. Is there anyway to Override this `__del__` method? _(I would prefer to not have to disconnect the Reset Line of my device from the DTR line)_ Below is the basic code I am using: import serial ser = serial.Serial() ser.port = 2 #actually COM3 ser.baudrate = 9600 ser.open() ser.write("Hello") ser.close() Answer: Sure, go ahead and override it. You can either create a subclass of `Serial` and specify a do-nothing `__del__()` method and use the subclass instead of `Serial`, or delete that method from the actual `Serial` class (monkey- patching) using the `del` statement. The former method is preferred but the second may be necessary if code you don't have any control over is using the serial port. Be sure the `__del__()` method doesn't do anything else important before overriding it, of course. Subclassing: import serial class mySerial(serial.Serial): def __del__(self): pass ser = mySerial() # rest of script the same Monkey-patching: import serial del serial.Serial.__del__ If you have Python source for this module (i.e. it is not written in C), a third approach would be to create your own copy of it and just edit it not to do that. (You can also do this for C modules, but getting it running is a bit more difficult if you don't have C expertise.) Of course, changing the `__del__()` method to not call `ser.close()` isn't going to help much in the code you give, since you're calling `ser.close()` yourself. :-)
Django get() takes exactly 2 arguments (3 given) Question: I am trying to use DetailView generic class in my test app and this is what I have in my view *_updated model *_ from this [example](http://docs.djangoproject.com/en/1.3/topics/class-based-views/#adding-extra-context) class AuthorDetailView(DetailView): context_object_name = "author" queryset = Author.objects.all() slug_field = "id" def get_object(self): object = super(AuthorDetailView, self).get_object() return object as a test and in my urls.py file I got ('^author/(\d+)/$', Author.AuthorDetailView.as_view()), when I navigate to <http://localhost:8000/author/1> I get the following error Typer Error get() takes exactly 2 arguments (3 given) Traceback: File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/Library/Python/2.6/site-packages/django/views/generic/base.py" in view 47. return self.dispatch(request, *args, **kwargs) File "/Library/Python/2.6/site-packages/django/views/generic/base.py" in dispatch 68. return handler(request, *args, **kwargs) Exception Type: TypeError at /author/1/ Exception Value: get() takes exactly 2 arguments (3 given) I don't really understand what is going on in base.py. Answer: Try this urlconf from books.views import AuthorDetailView urlpatterns = patterns('', #... (r'^authors/(?P<pk>\d+)/$', AuthorDetailView.as_view()), ) and navigate to: http://localhost:8000/author/1/
How to resample an array in python Question: I am new in python and I have a question about array/matrix. Below is the matrix I got. A = > [[85 77 83 ..., 59 58 59] > > [80 83 80 ..., 57 60 58] > > [75 76 81 ..., 59 58 60]] I want to re-sample(I don't know if this is the right word) the matrix so it becomes B = > [[ 85 85 85 85 77 77 77 77 83 83 83 83 ....... 59 59 59 59 58 58 58 58 59 59 > 59 59] > > [ 85 85 85 85 77 77 77 77 83 83 83 83 ....... 59 59 59 59 58 58 58 58 59 59 > 59 59] > > [ 85 85 85 85 77 77 77 77 83 83 83 83 ....... 59 59 59 59 58 58 58 58 59 59 > 59 59] > > [ 85 85 85 85 77 77 77 77 83 83 83 83 ....... 59 59 59 59 58 58 58 58 59 59 > 59 59] > > [ 80 80 80 80 83 83 83 83 80 80 80 80 ....... 57 57 57 57 60 60 60 60 58 58 > 58 58] > > [ 80 80 80 80 83 83 83 83 80 80 80 80 ....... 57 57 57 57 60 60 60 60 58 58 > 58 58] > > [ 80 80 80 80 83 83 83 83 80 80 80 80 ....... 57 57 57 57 60 60 60 60 58 58 > 58 58] > > [ 80 80 80 80 83 83 83 83 80 80 80 80 ....... 57 57 57 57 60 60 60 60 58 58 > 58 58] > > [ 75 75 75 75 76 76 76 76 81 81 81 81 ....... 59 59 59 59 58 58 58 58 60 60 > 60 60] > > [ 75 75 75 75 76 76 76 76 81 81 81 81 ....... 59 59 59 59 58 58 58 58 60 60 > 60 60] > > [ 75 75 75 75 76 76 76 76 81 81 81 81 ....... 59 59 59 59 58 58 58 58 60 60 > 60 60]] I searched online and looked at many posts, but still I have no clue how to do this. So please teach me how to do this, and I am greatly appreciated. Answer: Definitely use the info from [Scipy interpolation how to resize/resample 3x3 matrix to 5x5?](http://stackoverflow.com/questions/5586719/scipy- interpolation-how-to-resize-resample-3x3-matrix-to-5x5) from the comments. But I thought I'd mess around and here's what I got: Possibly the worst looking method of all time: >>> import pprint >>> a = [[85, 77, 99], ... [11, 22, 33], ... [44, 55, 66]] >>> >>> def transform(n,matrix): ... return [item for sublist in [[[item for sublist in [[element]*n for element in row] for item in sublist] for _ in range(n)] for row in matrix] for item in sublist] ... >>> pprint.pprint(transform(3,a)) [[85, 85, 85, 77, 77, 77, 99, 99, 99], [85, 85, 85, 77, 77, 77, 99, 99, 99], [85, 85, 85, 77, 77, 77, 99, 99, 99], [11, 11, 11, 22, 22, 22, 33, 33, 33], [11, 11, 11, 22, 22, 22, 33, 33, 33], [11, 11, 11, 22, 22, 22, 33, 33, 33], [44, 44, 44, 55, 55, 55, 66, 66, 66], [44, 44, 44, 55, 55, 55, 66, 66, 66], [44, 44, 44, 55, 55, 55, 66, 66, 66]] >>> pprint.pprint(transform(4,a)) [[85, 85, 85, 85, 77, 77, 77, 77, 99, 99, 99, 99], [85, 85, 85, 85, 77, 77, 77, 77, 99, 99, 99, 99], [85, 85, 85, 85, 77, 77, 77, 77, 99, 99, 99, 99], [85, 85, 85, 85, 77, 77, 77, 77, 99, 99, 99, 99], [11, 11, 11, 11, 22, 22, 22, 22, 33, 33, 33, 33], [11, 11, 11, 11, 22, 22, 22, 22, 33, 33, 33, 33], [11, 11, 11, 11, 22, 22, 22, 22, 33, 33, 33, 33], [11, 11, 11, 11, 22, 22, 22, 22, 33, 33, 33, 33], [44, 44, 44, 44, 55, 55, 55, 55, 66, 66, 66, 66], [44, 44, 44, 44, 55, 55, 55, 55, 66, 66, 66, 66], [44, 44, 44, 44, 55, 55, 55, 55, 66, 66, 66, 66], [44, 44, 44, 44, 55, 55, 55, 55, 66, 66, 66, 66]] >>> pprint.pprint(transform(5,a)) [[85, 85, 85, 85, 85, 77, 77, 77, 77, 77, 99, 99, 99, 99, 99], [85, 85, 85, 85, 85, 77, 77, 77, 77, 77, 99, 99, 99, 99, 99], [85, 85, 85, 85, 85, 77, 77, 77, 77, 77, 99, 99, 99, 99, 99], [85, 85, 85, 85, 85, 77, 77, 77, 77, 77, 99, 99, 99, 99, 99], [85, 85, 85, 85, 85, 77, 77, 77, 77, 77, 99, 99, 99, 99, 99], [11, 11, 11, 11, 11, 22, 22, 22, 22, 22, 33, 33, 33, 33, 33], [11, 11, 11, 11, 11, 22, 22, 22, 22, 22, 33, 33, 33, 33, 33], [11, 11, 11, 11, 11, 22, 22, 22, 22, 22, 33, 33, 33, 33, 33], [11, 11, 11, 11, 11, 22, 22, 22, 22, 22, 33, 33, 33, 33, 33], [11, 11, 11, 11, 11, 22, 22, 22, 22, 22, 33, 33, 33, 33, 33], [44, 44, 44, 44, 44, 55, 55, 55, 55, 55, 66, 66, 66, 66, 66], [44, 44, 44, 44, 44, 55, 55, 55, 55, 55, 66, 66, 66, 66, 66], [44, 44, 44, 44, 44, 55, 55, 55, 55, 55, 66, 66, 66, 66, 66], [44, 44, 44, 44, 44, 55, 55, 55, 55, 55, 66, 66, 66, 66, 66], [44, 44, 44, 44, 44, 55, 55, 55, 55, 55, 66, 66, 66, 66, 66]] >>>
python: pointwise list sum Question: Input: two lists (list1, list2) of equal length Output: one list (result) of the same length, such that: result[i] = list1[i] + list2[i] Is there any concise way to do that? Or is this the best: # Python 3 assert len(list1) == len(list2) result = [list1[i] + list2[i] for i in range(len(list1))] Answer: You can use the builtin [zip](http://docs.python.org/release/3.1.3/library/functions.html#zip) function, or you can also use do it mapping the two lists over the add operator. Like this: from operator import add map(add, list1,list2)
[] and {} vs list() and dict(), which is better? Question: I understand that they are both essentially the same thing, but in terms of style, which is the better (more Pythonic) one to use to create an empty list or dict? Answer: In terms of speed, it's no competition for empty lists/dicts: >>> from timeit import timeit >>> timeit("[]") 0.040084982867934334 >>> timeit("list()") 0.17704233359267718 >>> timeit("{}") 0.033620194745424214 >>> timeit("dict()") 0.1821558326547077 and for non-empty: >>> timeit("[1,2,3]") 0.24316302770330367 >>> timeit("list((1,2,3))") 0.44744206316727286 >>> timeit("list(foo)", setup="foo=(1,2,3)") 0.446036018543964 >>> timeit("{'a':1, 'b':2, 'c':3}") 0.20868602015059423 >>> timeit("dict(a=1, b=2, c=3)") 0.47635635255323905 >>> timeit("dict(bar)", setup="bar=[('a', 1), ('b', 2), ('c', 3)]") 0.9028228448029267 Also, using the bracket notation let's you use list and dictionary comprehensions, which may be reason enough.
easy_install with various versions of python installed, mac osx Question: I have various versions of python on a mac OSX 10.6 machine, some of them installed with macports: > python_select -l Available versions: current none python24 python26 python26-apple python27 The default or system version is `python26-apple`. I am now using python27, which I selected with > sudo python_select python27 I recently tried installing django using `easy_install`, but it got installed with the default python (I can check that by python_selecting python26-apple and importing django). If, instead, I download the django tarball, expand and use > sudo python setup.py install everything works as expected, i.e. I get django in python 2.7. Now the question is, is there a way to get `easy_install` to work with the version of python I have selected with `python_select`? **UPDATE** Apparently `python_select` is deprecated. The following command seems to be equivalent: port select --list python producing: Available versions for python: none python24 python26 python26-apple python27 (active) Answer: If you want your "easy_install" match your updated python version, follow these steps: Download the corresponding .egg file at <http://pypi.python.org/pypi/setuptools#files> Run it as if it were a shell script: sh setuptools-0.6c9-py2.7.egg This will install the new "easy_install" executable, compatible with your current version of python. Hope this helps. (more details at <http://pypi.python.org/pypi/setuptools#cygwin-mac-os-x- linux-other>)
need help with this Kombu error Question: Pardon the copy and paste from the python interpreter but I'm trying to play with Kombu but I can't seem to create a consumer. Please help, I'm utterly in the dark here. >>> from kombu.messaging import Consumer, Producer >>> from kombu.entity import Exchange, Queue >>> x = Exchange("stmt",type="topic") >>> helloQ = Queue("hello", exchange=x, routing_key="stmt.hello") >>> >>> from kombu.connection import BrokerConnection >>> conn = BrokerConnection("scheduledb.lab.compete.com", "clippy", "clippy", "clippy") >>> channel = conn.channel() >>> c = Consumer(channel, helloQ) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/messaging.py", line 231, in __init__ self.declare() File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/messaging.py", line 241, in declare queue.declare() File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/entity.py", line 362, in declare self.name and self.queue_declare(nowait, passive=False), File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/entity.py", line 380, in queue_declare nowait=nowait) File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/syn.py", line 14, in blocking return __sync_current(fun, *args, **kwargs) File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/syn.py", line 30, in __blocking__ return fun(*args, **kwargs) File "build/bdist.cygwin-1.7.8-i686/egg/amqplib/client_0_8/channel.py", line 1294, in queue_declare File "build/bdist.cygwin-1.7.8-i686/egg/amqplib/client_0_8/abstract_channel.py", line 89, in wait File "build/bdist.cygwin-1.7.8-i686/egg/amqplib/client_0_8/connection.py", line 218, in _wait_method File "build/bdist.cygwin-1.7.8-i686/egg/amqplib/client_0_8/abstract_channel.py", line 105, in wait File "build/bdist.cygwin-1.7.8-i686/egg/amqplib/client_0_8/connection.py", line 367, in _close amqplib.client_0_8.exceptions.AMQPConnectionException: (530, u"NOT_ALLOWED - parameters for queue 'hello' in vhost 'clippy' not equivalent", (50, 10), 'Channel.queue_declare') >>> boundX = x(helloQ) >>> c = Consumer(channel, helloQ) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/messaging.py", line 231, in __init__ self.declare() File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/messaging.py", line 241, in declare queue.declare() File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/entity.py", line 361, in declare return (self.name and self.exchange.declare(nowait), File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/entity.py", line 151, in declare nowait=nowait) File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/syn.py", line 14, in blocking return __sync_current(fun, *args, **kwargs) File "/usr/lib/python2.6/site-packages/kombu-1.0.6-py2.6.egg/kombu/syn.py", line 30, in __blocking__ return fun(*args, **kwargs) File "build/bdist.cygwin-1.7.8-i686/egg/amqplib/client_0_8/channel.py", line 839, in exchange_declare File "build/bdist.cygwin-1.7.8-i686/egg/amqplib/client_0_8/abstract_channel.py", line 69, in _send_method AttributeError: 'NoneType' object has no attribute 'method_writer' Answer: Look at the error amqplib.client_0_8.exceptions.AMQPConnectionException: (530, u"NOT_ALLOWED - parameters for queue 'hello' in vhost 'clippy' not equivalent", (50, 10), 'Channel.queue_declare') This means the queue has already been declared, but with other parameters than what you are declaring it with now.
How to see if file is older than 3 months in Python? Question: I'm curious about manipulating time in Python. I can get the (last modified) age of a file using the `os.path.getmtime()` function as such: import os.path, time os.path.getmtime(oldLoc) I need to run some kind of test to see whether this time is within the last three months or not, but I'm thoroughly confused by all the available time options in Python. Can anyone offer any insight? Kind Regards. Answer: time.time() - os.path.getmtime(oldLoc) > (3 * 30 * 24 * 60 * 60)
python sqlite "create table if not exists" problem Question: I'm having an issue using sqlite to create a table only if it doesn't exist. Basically, I have a table that I'm dropping and remaking once in a long while. However, if the table already existed (before I drop and remake it), then I get the following error when trying to insert for the first time: Traceback (most recent call last): File "test.py", line 40, in <module> remake() File "test.py", line 31, in remake insert_record(1) File "test.py", line 36, in insert_record c.execute(sql) sqlite3.OperationalError: no such table: table_name At this point the table does not exist (for some reason), so the next time I run the script no errors occur. Basically, if I keep running the test script, exactly every other run will result in an error, and I'm stumped as to why - but I have determined that creating the database without using `if not exists` fixes the issue. I still don't know what the original problem is though, and I'd appreciate if anyone could point me in the right direction. Test script demonstrating the problem below: import sqlite3 location = 'data' table_name = 'table_name' def init(): global conn global c conn = sqlite3.connect(location) c = conn.cursor() create_database() def create_database(): sql = 'create table if not exists ' + table_name + ' (id integer)' c.execute(sql) conn.commit() def create_database2(): sql = 'create table ' + table_name + '(id integer)' c.execute(sql) conn.commit() def clear_database(): sql = 'drop table ' + table_name c.execute(sql) conn.commit() def remake(): clear_database() create_database() # Replacing this with create_database2() works every time insert_record(1) conn.commit() def insert_record(id): sql = 'insert into ' + table_name + ' (id) values (%d)' % (id) c.execute(sql) print 'Inserted ', id init() remake() Thanks in advance :) Answer: I can duplicate the issue with the following simplified script: import sqlite3 location = 'data' table_name = 'table_name' conn = sqlite3.connect(location) c = conn.cursor() sql = 'create table if not exists ' + table_name + ' (id integer)' c.execute(sql) sql = 'drop table ' + table_name c.execute(sql) sql = 'create table if not exists ' + table_name + ' (id integer)' c.execute(sql) sql = 'insert into ' + table_name + ' (id) values (%d)' % (1) c.execute(sql) conn.commit() To fix that, you have to close and reconnect to the db after creating or dropping the table, i.e., add the following code in between: c.close() conn.close() conn = sqlite3.connect(location) c = conn.cursor() Not sure what is the cause though.
mysql select in java on a column with accented utf8 string Question: I have encountered a problem when trying to select data from a table in MySQL in Java by a text column that is in utf-8. The interesting thing is that with code in Python it works well, in Java it doesn't. The table looks as follows: CREATE TABLE `x` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `text` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; The query looks like this: SELECT * FROM x WHERE text = 'ěščřž'" The Java code that doesn't work as exptected is the following: public class test { public static void main(String [] args) { java.sql.Connection conn = null; System.out.println("SQL Test"); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = java.sql.DriverManager.getConnection( "jdbc:mysql://127.0.0.1/x?user=root&password=root&characterSet=utf8&useUnicode=true&characterEncoding=utf-8&characterSetResults=utf8"); } catch (Exception e) { System.out.println(e); System.exit(0); } System.out.println("Connection established"); try { java.sql.Statement s = conn.createStatement(); java.sql.ResultSet r = s.executeQuery("SELECT * FROM x WHERE text = 'ěščřž'"); while(r.next()) { System.out.println ( r.getString("id") + " " + r.getString("text") ); } } catch (Exception e) { System.out.println(e); System.exit(0); } } } The Python code is: # encoding: utf8 import MySQLdb conn = MySQLdb.connect (host = "127.0.0.1", port = 3307, user = "root", passwd = "root", db = "x") cursor = conn.cursor () cursor.execute ("SELECT * FROM x where text = 'ěščřž'") row = cursor.fetchone () print row cursor.close () conn.close () Both are stored on the filesystem in utf8 encoding (checked with hexedit). I have tried different versions of mysql-connector (currently using 5.1.15). Mysqld is 5.1.54. Mysqld log for the Java code and Python code respectively: 110427 12:45:07 1 Connect root@localhost on x 110427 12:45:08 1 Query /* mysql-connector-java-5.1.15 ( Revision: ${bzr.revision-id} ) */SHOW VARIABLES WHERE Variable_name ='language' OR Variable_name = 'net_write_timeout' OR Variable_name = 'interactive_timeout' OR Variable_name = 'wait_timeout' OR Variable_name = 'character_set_client' OR Variable_name = 'character_set_connection' OR Variable_name = 'character_set' OR Variable_name = 'character_set_server' OR Variable_name = 'tx_isolation' OR Variable_name = 'transaction_isolation' OR Variable_name = 'character_set_results' OR Variable_name = 'timezone' OR Variable_name = 'time_zone' OR Variable_name = 'system_time_zone' OR Variable_name = 'lower_case_table_names' OR Variable_name = 'max_allowed_packet' OR Variable_name = 'net_buffer_length' OR Variable_name = 'sql_mode' OR Variable_name = 'query_cache_type' OR Variable_name = 'query_cache_size' OR Variable_name = 'init_connect' 1 Query /* mysql-connector-java-5.1.15 ( Revision: ${bzr.revision-id} ) */SELECT @@session.auto_increment_increment 1 Query SHOW COLLATION 1 Query SET autocommit=1 1 Query SET sql_mode='STRICT_TRANS_TABLES' 1 Query SELECT * FROM x WHERE text = 'ěščřž' 110427 12:45:22 2 Connect root@localhost on x 2 Query set autocommit=0 2 Query SELECT * FROM x where text = 'ěščřž' 2 Quit Does anybody have any suggestions what might be the cause why the Python code works and why the Java code does not? (by not working I mean not finding the desired data -- the connection works fine) Many thanks. Answer: Okay, my bad. The database was wrongly built. It was built through the mysql client that by default is latin1 so in the database the data were encoded by utf8 twice. The problem and the major difference between the two source codes is in that the Python code doesn't set the default charset (therefore it is latin1) whereas the Java code does (therefore it is utf8). So it was coincidence of many factors that made me think that something peculiar is actually going on. Thanks for your responses anyway.
python - remote hosts timezone vs local Question: I'm building a web frontend for remote logs monitoring, having to manage about 10 different geographic locations I've bumped into the 3 headed hellhound some of you already have. Is there any way to get from a remote HPUX shell variable the following remote info: * zoneinfo (Country/City) * UTC + offset (I can easily get this from the zoneinfo) So far the best I could get is the OS abbreviated timezone (is this enough to iteratively cross the remote time with a statically built pytz.common_timezones collection and reverse convert the abbreviated zones into Country/City or I'm completely going the wrong way?) I can easily get the offset after getting the Country/City (which I haven't) datetime.now(pytz.timezone('Asia/Dili')).strftime('%Z %z') 'TLT +0900' * get remote abbreviated timezone, (Linux has the far more sane grep "ZONE=" /etc/sysconfig/clock output like, ZONE="Europe/London" while HP-UX /etc/TIMEZONE uses abbreviated timezones like TZ=CAT-2 I'd use echo $TZ which would output a little more useful data like CAT-2 but some remote HP-UXes don't even have this configured thus forcing me to rely on the ambiguous RFC822 date, date +%z CAT I've looked both into pytz, datetime.datetime, email.Utils but considering it's a no can do directly converting from abbreviated time into the zoneinfo Country/City (pytz allows the opposite) should I just scratch this Don Quixote quest of autodiscovering the remote timezone and just add a Country/City dropdown list when accepting the user input registering the remote host? **EDIT (Partial solution)** **building on @Mike Pennington answer** from datetime import datetime as dt from datetime import timedelta as td from dateutil.relativedelta import * from email.Utils import mktime_tz, parsedate_tz hpux_remote_date = 'Thu Apr 28 18:09:20 TLT 2011' utctimestamp = mktime_tz(parsedate_tz( hpux_remote_date )) hpux_dt = dt.fromtimestamp( utctimestamp ) delta_offset = relativedelta(dt.utcnow(), hpux_dt) hpux_utc = hpux_dt + delta_offset # Sanity checking to ensure we are correct... hpux_dt datetime.datetime(2011, 4, 28, 18, 9, 20) hpux_utc datetime.datetime(2011, 4, 28, 9, 9, 22, 229148) Answer: You should be able to find your GMT offset like this... ## As a GMT offset, disregarding DST `(time.localtime()[3] - time.localtime()[8]) - time.gmtime()[3]` I am in Central time (GMT - 6) so, this yields `-6` on my system. ## As a GMT offset, including DST compensation `(time.localtime()[3]) - time.gmtime()[3]` This yields `-5` on my system. It's probably easiest to go with the second option and use it to convert those local HPUX times into GMT; then mangle with `pytz` as-required. ## EDIT If you are working with a text representation of remote (non-GMT) timestamps, it is probably easier to work directly with datetime objects... I don't have HPUX handy, but I'll assume the date string is similar to my debian squeeze system. >>> from datetime import datetime as dt >>> from datetime import timedelta as td >>> # using os.popen() to simulate the results of a HPUX shell 'date'... >>> # substitute the real HPUX shell date string in hpux_date >>> hpux_date = os.popen('date').read().strip() >>> hpux_dt = dt.strptime(hpux_date, '%a %b %d %H:%M:%S %Z %Y') >>> # Rounding to the nearest hour because there *will* be slight delay >>> # between shell string capture and python processing >>> offset_seconds = ((dt.utcnow() - hpux_dt).seconds//3600)*3600 >>> hpux_gmt = hpux_dt + td(0,offset_seconds) >>> # Sanity checking to ensure we are correct... >>> hpux_gmt datetime.datetime(2011, 4, 27, 17, 21, 58) >>> hpux_dt datetime.datetime(2011, 4, 27, 12, 21, 58) >>> hpux_date 'Wed Apr 27 12:21:58 CDT 2011' >>>
is MySql good for large databases? Question: I work for a company and we are always accessing an external site for information. The site was developed by an antiquated software development company who doesn't even have a website. They pretty much have a monopoly in my state since the content provider for the database only uses this extremely dysfunctional site to upload their data. The problem with this website is that it is so slow it's not even functional. Having controlled for things like Connection speed and Browser type, it is clear that the problem lies within the website itself. So, I am thinking about redoing the site and then offering it to the content provider as a means for uploading their data. Basically, this project requires a very large database to store hundreds of thousands of names, addresses, and other types of data. My only experience with databases is MySql, and really my only experience with dynamic content is PHP. So, yeah, I'm trying to figure out if the old PHP + MySQL combination is suitable for storing and representing large amounts of data. I have only done this on small projects, but I think the whole HTML templates with placeholders for the dynamic content would work fine. Of course, I truly don't know why this website is so slow. Maybe it's not the DB at all. Maybe it's the server or something else. But the key thing I am trying to accomplish is to improve upon the speed and functionality of this site. I have no experience with other types of databases, so any tips / advice you can offer for doing a project like this would be greatly appreciated. Also, any tips regarding how to generally make a fast and functional site that would need to represent dynamic data from an extremely large database would also be helpful. *Edit: I am learning python so if you think this would be a better side-scripting language then I can certainly try to implement something different than the initial plan above. Answer: If you do a good design, you can have very large databases in MySQL ([this other question may help you](http://stackoverflow.com/questions/1276/how-big- can-a-mysql-database-get-before-performance-starts-to-degrade)). Define properly the **keys** and **indexes** , **optimize** your queries (`EXPLAIN` is your friend here). Select a good **database engine**. There are a lot of things to do to get the best from MySQL. **EDIT: some more ideas...** It's also quite important the way you structure your data and the tables to make easy to write them, recover them or finding a compromise between both (depending on the use case). Also if it grows you can use a **cluster** , partition your data between several MySQL databases in several machines (using a Master-slave schema for instance) it's another option. To improve the performance you should also think on using some kind of **cache** for repetitive queries. There is also tools like [Vitess](http://vitess.io/) that help to scale a MySQL database in a similar way as the NoSQL databases.
Python: how to convert from Windows 1251 to Unicode? Question: I'm trying to convert file content from Windows-1251 (Cyrillic) to Unicode with Python. I found this function, but it doesn't work. #!/usr/bin/env python import os import sys import shutil def convert_to_utf8(filename): # gather the encodings you think that the file may be # encoded inside a tuple encodings = ('windows-1253', 'iso-8859-7', 'macgreek') # try to open the file and exit if some IOError occurs try: f = open(filename, 'r').read() except Exception: sys.exit(1) # now start iterating in our encodings tuple and try to # decode the file for enc in encodings: try: # try to decode the file with the first encoding # from the tuple. # if it succeeds then it will reach break, so we # will be out of the loop (something we want on # success). # the data variable will hold our decoded text data = f.decode(enc) break except Exception: # if the first encoding fail, then with the continue # keyword will start again with the second encoding # from the tuple an so on.... until it succeeds. # if for some reason it reaches the last encoding of # our tuple without success, then exit the program. if enc == encodings[-1]: sys.exit(1) continue # now get the absolute path of our filename and append .bak # to the end of it (for our backup file) fpath = os.path.abspath(filename) newfilename = fpath + '.bak' # and make our backup file with shutil shutil.copy(filename, newfilename) # and at last convert it to utf-8 f = open(filename, 'w') try: f.write(data.encode('utf-8')) except Exception, e: print e finally: f.close() How can I do that? Thank you Answer: import codecs f = codecs.open(filename, 'r', 'cp1251') u = f.read() # now the contents have been transformed to a Unicode string out = codecs.open(output, 'w', 'utf-8') out.write(u) # and now the contents have been output as UTF-8 Is this what you intend to do?
NoReverseMatch for get_absolute_url() newbie question Question: Just started playing around with django and was confused with the get_absolute_url functionality. When I try to access the url for an object I get a NoReverseMatch error. Here is the stack trace $ python manage.py shell Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from food.models import * >>> r = Restaurant.objects.get(pk=1) >>> r <Restaurant: East Side Marios> >>> r.get_absolute_url() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 55, in _curried return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs)) File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 887, in get_absolute_url return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.module_name), func)(self, *args, **kwargs) File "/usr/local/lib/python2.6/dist-packages/django/db/models/__init__.py", line 35, in inner return reverse(bits[0], None, *bits[1:3]) File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py", line 391, in reverse *args, **kwargs))) File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py", line 337, in reverse "arguments '%s' not found." % (lookup_view_s, args, kwargs)) NoReverseMatch: Reverse for 'food.views.restaurant_details' with arguments '()' and keyword arguments '{'restaurant_id': ['1']}' not found. Here's what I have so far **server/urls.py** from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # ADMIN (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin/', include(admin.site.urls)), # Restaurants (r'^restaurants/$', 'food.views.restaurant_index'), (r'^restaurants/(\d+)/$', 'food.views.restaurant_details'), ) **server/food/models.py** class Restaurant(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField() website = models.URLField(verify_exists=True) def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): return ('food.views.restaurant_details', (), {'restaurant_id': [str(self.id)]}) **server/food/views.py** from food.models import * from django.shortcuts import render_to_response, get_object_or_404 # Restaurant def restaurant_index(request): restaurant_list = Restaurant.objects.all() return render_to_response('food/restaurant/index.html', {'restaurant_list': restaurant_list}) def restaurant_details(request, restaurant_id): restaurant = get_object_or_404(Restaurant, pk=restaurant_id) menu_list = Menu.objects.filter(restaurant=restaurant_id) return render_to_response('food/restaurant/detail.html', {'restaurant': restaurant, 'menu_list': menu_list}) The website for restaurant_index renders fine except that, of course, the url for any restaurants is the empty string **template** {% if restaurant_list %} <ul> {% for restaurant in restaurant_list %} <li><a href="{{ restaurant.get_absolute_url }}">{{ restaurant }}</a></li> {% endfor %} </ul> {% else %} <p>No restaurants are currently listed.</p> {% endif %} **html** <ul> <li><a href="">East Side Marios</a></li> </ul> Answer: (r'^restaurants/(\d+)/$', 'food.views.restaurant_details'), Your URL pattern is capturing the `restaurant_id` as non-named group, so you need to either supply `restaurant_id` as positional argument, or change the url pattern to capture `restaurant_id` as named group Change URL pattern to this (r'^restaurants/(?P<restaurant_id>\d+)/$', 'food.views.restaurant_details'), or return this from `get_absolute_url` return ('food.views.restaurant_details', (str(self.id),), {})
Fatal Errors and Deferreds in Twisted, stop a deferred Question: I have a problem, with normal try except blocks in python you can just return if there is a fatal error, ex... try: logon() except 404_Error: retry_logon(try = 2) except AuthenticationProblem: error_label.SetText( "You password or username was wrong. Make sure that CAPS LOCK key is not on." ) return#nothing more we can do here else: #display user information or whatever So how do this with deferreds, if I just return it goes onto execute the callbacks thinking the error is handled but how do I inform the user something went wrong and destroy the down river chain. ==== Update === mg thanks for the help but it didn't work, even with a fatal error the defer still returns to the callbacks afterwords from twisted.internet import reactor from twisted.internet.defer import Deferred as D class NonFatalError(Exception): 'non fatal error' class FatalError(Exception): 'fatal error' def c(s): print "Callback called" print "Data Received: %s" % s def e(f): print "Errorback Called" print "Error Type: %s" % type(f) print "Traceback" f.printTraceback() print "=======================================" f.trap(NonFatalError) return "Error Handled" def e_fatal(f, d): print "Errorback Called" print "Error Type: %s" % type(f) print "Traceback" f.printTraceback() print "=======================================" print "Fatal Error" f.trap(FatalError) return "Fatal Error... Crash and die. No more callbacks should be called." def trigger(): d.errback(FatalError("This error is fatal to the defer")) if __name__ == "__main__": d = D() d.addErrback(e) d.addErrback(e_fatal, d) d.addCallback(c) d.addCallback(c) d.addCallback(c) d.addCallback(c) reactor.callLater(3, trigger) reactor.callLater(10, reactor.stop) reactor.run() raw_input("Done.") Answer: Ok, a whole new answer to explain better how [deferreds](http://twistedmatrix.com/documents/11.0.0/api/twisted.internet.defer.Deferred.html) work. You should think, at least I do, the flow of the program as a state machine. A success or a failure is like an input of that machine that, potentially, change the state. In your case you have two states, logged and non logged, and three inputs: successfully logged in, wrong authentication and could not logged for server problems. Only one of this inputs is recoverable, the case the server could not login the user for same strange problem and in this case you can recover the problem retrying the login. Here the new code: import sys from twisted.internet import reactor, defer class FourOhFourError(Exception): pass class AuthenticationError(Exception): pass def logon(retry=3, success=2, wrong_auth=0): # do stuff d = defer.Deferred() # not_found is the only error recoverable d.addErrback(not_found, retry, success) if wrong_auth: reactor.callLater(0, d.errback, AuthenticationError("wrong auth")) else: if success == 0: reactor.callLater(0, d.callback, "Mario") else: reactor.callLater(0, d.errback, FourOhFourError("Not found")) return d def not_found(failure, retry, success): failure.trap(FourOhFourError) # this is superfluous here print failure.getErrorMessage() if retry == 0: raise AuthenticationError("Max retries") # do stuff print "retring..." d = defer.Deferred() d.addCallback(logon, success-1) reactor.callLater(1, d.callback, retry-1) # not really clean here return d def wrong_auth(failure): failure.trap(AuthenticationError) # this is superfluous here # do stuff print "something goes wrong" print failure.getErrorMessage() def loggedIn(user): print "hello %s" % user def stop(_): reactor.stop() d = logon(*map(int, sys.argv[1:])) d.addCallbacks(loggedIn, wrong_auth) d.addBoth(stop) reactor.run() Invoke the code with three parameters: the maximum number of retries, at which retry the system should login the user and the third is a boolean indicating the correctness of the user credentials. Try the following invocations: `0 0 1`, `3 2 0`, `3 4 0`. I hope this example is more explicative.
Is there a way to specify the build directory for py2exe Question: I can set the final `dist` directory of py2exe using the command line: python setup.py py2exe -d "my/dist/dir" but I can't seem to set the file to use for the interim `build` directory. I've taken a brief look at the source, but unless I am missing something there doesn't appear to be any way to do it. Answer: Any option that you can set on the command line you can set either through a [setup.cfg](http://docs.python.org/distutils/configfile.html) file or in your setup.py file. `-d` is a shortcut for `--dist-dir` which you can add to the py2xe dict in the dictionary passed to the options keyword param of setup as `'dist_dir'`: from distutils.core import setup import py2exe # equivalent command line with options is: # python setup.py py2exe --compressed --bundle-files=2 --dist-dir="my/dist/dir" --dll-excludes="w9xpopen.exe" options = {'py2exe': { 'compressed':1, 'bundle_files': 2, 'dist_dir': "my/dist/dir" 'dll_excludes': ['w9xpopen.exe'] }} setup(console=['myscript.py'], options=options) You could also put [setup.cfg](http://docs.python.org/distutils/configfile.html) next to your setup.py file: [py2exe] compressed=1 bundle_files=2 dist_dir=my/dist/dir dll_excludes=w9xpopen.exe The build directory (`--build-base`) is an option of the build command so you can add it to one of the config files (or the setup.py) as: [build] build_base=my/build/dir
Install Ming on WebFaction Question: I'm trying to install the [Ming](https://github.com/libming/libming) SWF creation library from source on WebFaction. After untarring it, I ran `./configure --prefix=$HOME -enable--python` and then ran `make install`. It seemed to install fine, but when I do a `import ming` from within Python it gives me an import error. These steps worked for me on my local machine. I was hoping someone could help me out. Thanks! Answer: Is the folder containing the library on Python's search path?
Buildout tries to update system-wide Distribute installation and refuses to run Question: Buildout doesn't like my system-wide Distribute installation and refuses to run: plone@s15447224:~/mybuildout$ python bootstrap.py Creating directory '/home/plone/mybuildout/bin'. Creating directory '/home/plone/mybuildout/parts'. Creating directory '/home/plone/mybuildout/eggs'. Creating directory '/home/plone/mybuildout/develop-eggs'. Getting distribution for 'distribute==0.6.14'. Before install bootstrap. Scanning installed packages Setuptools installation detected at /usr/lib/python2.6/dist-packages Non-egg installation Removing elements out of the way... Already patched. /usr/lib/python2.6/dist-packages/setuptools.egg-info already patched. After install bootstrap. Creating /usr/local/lib/python2.6/dist-packages/setuptools-0.6c11-py2.6.egg-info error: /usr/local/lib/python2.6/dist-packages/setuptools-0.6c11-py2.6.egg-info: Permission denied An error occurred when trying to install distribute 0.6.14. Look above this message for any errors that were output by easy_install. While: Bootstrapping. Getting distribution for 'distribute==0.6.14'. Error: Couldn't install: distribute 0.6.14 Is there some way to tell buildout to install its own Distribute and not to mess with system-wide Python installation? I know about virtualenv. But it seems to be an overkill just to install virtualenv to make buildout happy. There must be some other way. Python 2.6. Plone 4.1. Ubuntu 10.4. Answer: Yes, use Buildout 1.5.x which runs Python with the '-S' argument (-S : don't imply 'import site' on initialization). * E.g.: <http://build.pythonpackages.com/buildout/plone/4.1.x> (and you might try upgrading your system-wide Distribute to the latest version too)
Python multiprocessing: synchronizing file-like object Question: I'm trying to make a file like object which is meant to be assigned to sys.stdout/sys.stderr during testing to provide deterministic output. It's not meant to be fast, just reliable. What I have so far _almost_ works, but I need some help getting rid of the last few edge-case errors. Here is my current implementation. try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from os import getpid class MultiProcessFile(object): """ helper for testing multiprocessing multiprocessing poses a problem for doctests, since the strategy of replacing sys.stdout/stderr with file-like objects then inspecting the results won't work: the child processes will write to the objects, but the data will not be reflected in the parent doctest-ing process. The solution is to create file-like objects which will interact with multiprocessing in a more desirable way. All processes can write to this object, but only the creator can read. This allows the testing system to see a unified picture of I/O. """ def __init__(self): # per advice at: # http://docs.python.org/library/multiprocessing.html#all-platforms from multiprocessing import Queue self.__master = getpid() self.__queue = Queue() self.__buffer = StringIO() self.softspace = 0 def buffer(self): if getpid() != self.__master: return from Queue import Empty from collections import defaultdict cache = defaultdict(str) while True: try: pid, data = self.__queue.get_nowait() except Empty: break cache[pid] += data for pid in sorted(cache): self.__buffer.write( '%s wrote: %r\n' % (pid, cache[pid]) ) def write(self, data): self.__queue.put((getpid(), data)) def __iter__(self): "getattr doesn't work for iter()" self.buffer() return self.__buffer def getvalue(self): self.buffer() return self.__buffer.getvalue() def flush(self): "meaningless" pass ... and a quick test script: #!/usr/bin/python2.6 from multiprocessing import Process from mpfile import MultiProcessFile def printer(msg): print msg processes = [] for i in range(20): processes.append( Process(target=printer, args=(i,), name='printer') ) print 'START' import sys buffer = MultiProcessFile() sys.stdout = buffer for p in processes: p.start() for p in processes: p.join() for i in range(20): print i, print sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ print print 'DONE' print buffer.buffer() print buffer.getvalue() This works perfectly 95% of the time, but it has three edge-case problems. I have to run the test script in a fast while-loop to reproduce these. 1. 3% of the time, the parent process output isn't completely reflected. I assume this is because the data is being consumed before the Queue-flushing thread can catch up. I haven't though of a way to wait for the thread without deadlocking. 2. .5% of the time, there's a traceback from the multiprocess.Queue implementation 3. .01% of the time, the PIDs wrap around, and so sorting by PID gives the wrong ordering. In the very worst case (odds: one in 70 million), the output would look like this: START DONE 302 wrote: '19\n' 32731 wrote: '0 1 2 3 4 5 6 7 8 ' 32732 wrote: '0\n' 32734 wrote: '1\n' 32735 wrote: '2\n' 32736 wrote: '3\n' 32737 wrote: '4\n' 32738 wrote: '5\n' 32743 wrote: '6\n' 32744 wrote: '7\n' 32745 wrote: '8\n' 32749 wrote: '9\n' 32751 wrote: '10\n' 32752 wrote: '11\n' 32753 wrote: '12\n' 32754 wrote: '13\n' 32756 wrote: '14\n' 32757 wrote: '15\n' 32759 wrote: '16\n' 32760 wrote: '17\n' 32761 wrote: '18\n' Exception in thread QueueFeederThread (most likely raised during interpreter shutdown): Traceback (most recent call last): File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_inner File "/usr/lib/python2.6/threading.py", line 484, in run File "/usr/lib/python2.6/multiprocessing/queues.py", line 233, in _feed <type 'exceptions.TypeError'>: 'NoneType' object is not callable In python2.7 the exception is slightly different: Exception in thread QueueFeederThread (most likely raised during interpreter shutdown): Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner File "/usr/lib/python2.7/threading.py", line 505, in run File "/usr/lib/python2.7/multiprocessing/queues.py", line 268, in _feed <type 'exceptions.IOError'>: [Errno 32] Broken pipe How do I get rid of these edge cases? Answer: The solution came in two parts. I've successfully run the test program 200 thousand times without any change in output. The easy part was to use multiprocessing.current_process()._identity to sort the messages. This is not a part of the published API, but it is a unique, deterministic identifier of each process. This fixed the problem with PIDs wrapping around and giving a bad ordering of output. The other part of the solution was to use multiprocessing.Manager().Queue() rather than the multiprocessing.Queue. This fixes problem #2 above because the manager lives in a separate Process, and so avoids some of the bad special cases when using a Queue from the owning process. #3 is fixed because the Queue is fully exhausted and the feeder thread dies naturally before python starts shutting down and closes stdin.
python join equivalent Question: I have a dictionary say.. dict = { 'a' : 'b', 'c' : 'd' } In php I would to something like implode ( ',', $dict ) and get the output 'a,b,c,d' How do I do that in python? Answer: This seems to be easiest way: >>> from itertools import chain >>> a = dict(a='b', c='d') >>> ','.join(chain(*a.items())) 'a,b,c,d'
Python: parsing help needed! Question: I am trying to retrieve certain fields within a .lua file. Initially I thought I could just split on commas but the second set of curly brackets ruins that. An example: return { { 6163, 0, "tv", false, {1302}, "ESPN Deportes", "ESPN Deportes es el", nil,"tv","936",nil,"4x3", mediaRestrictions={"m2g" } }, { 57075, 0, "tv", false, {1302}, "Video Rola", "Video \"Música Para Tus Ojos\", uedes ver.", nil,"tv","948",nil,"4x3", mediaRestrictions={"m2g" } }, { 717242, 0, "tv", false, {1302,1301,1288}, "Hits", "asdlfj", nil,"cliplinear","6310",nil,"4x3", mediaRestrictions={"m2g" } }, { 122719, 0, "tv", false, {1302,1301,1288}, "Bombone", "asdf", nil,"tv","74",nil,"4x3", mediaRestrictions={"m2g" } }, } So I would be looking for the following from the first line: "ESPN Deportes"(6th field), tv(9th), 936(10th) God help me...or more likely a stackoverflow ninja. (Python) * * * ## Updated with solution Solution as graciously provided by S.Mark: res = conn.getresponse() data = res.read() # Hackisly transform the lua into json data = re.sub('\w+=', '', data) data = data.replace("return","") data = data.replace("{","[").replace("}","]") data = data.replace("nil","null") data = data.replace(",]","]") data = json.loads(data.strip()) Answer: Probably convert to json. import json text = r"""return { { 6163, 0, "tv", false, {1302}, "ESPN Deportes", "ESPN Deportes es el", nil,"tv","936",nil,"4x3", mediaRestrictions={"m2g" } }, { 57075, 0, "tv", false, {1302}, "Video Rola", "Video \"Música Para Tus Ojos\", uedes ver.", nil,"tv","948",nil,"4x3", mediaRestrictions={"m2g" } }, { 717242, 0, "tv", false, {1302,1301,1288}, "Hits", "asdlfj", nil,"cliplinear","6310",nil,"4x3", mediaRestrictions={"m2g" } }, { 122719, 0, "tv", false, {1302,1301,1288}, "Bombone", "asdf", nil,"tv","74",nil,"4x3", mediaRestrictions={"m2g" } }, }""" obj = json.loads(text.replace("return","").replace("mediaRestrictions=","").replace("{","[").replace("}","]").replace("nil","null").replace("\n","").replace(",]","]").strip()) print obj # [[6163, 0, u'tv', False, [1302], u'ESPN Deportes', u'ESPN Deportes es el', None, u'tv', u'936', None, u'4x3', [u'm2g']], [57075, 0, u'tv', False, [1302], u'Video Rola', u'Video "M\xfasica Para Tus Ojos", uedes ver.', None, u'tv', u'948', None, u'4x3', [u'm2g']], [717242, 0, u'tv', False, [1302, 1301, 1288], u'Hits', u'asdlfj', None, u'cliplinear', u'6310', None, u'4x3', [u'm2g']], [122719, 0, u'tv', False, [1302, 1301, 1288], u'Bombone', u'asdf', None, u'tv', u'74', None, u'4x3', [u'm2g']]] for x in obj: print x[5], x[8], x[9] #ESPN Deportes tv 936 #Video Rola tv 948 #Hits cliplinear 6310 #Bombone tv 74
APScheduler not starting? Question: I would like to run a python script during the night and so I was thinking of using APScheduler. I'll start running it at 1am of the following night and it will run once every night my scheduler script looks like this (scheduler.py): from apscheduler.scheduler import Scheduler from datetime import datetime, timedelta, time, date def myScript(): print "ok" if __name__ == '__main__': sched = Scheduler() startDate = datetime.combine(date.today() + timedelta(days=1),time(1)) sched.start() sched.add_interval_job(myScript, start_date = startDate, days=1) In the shell, I do: `python myScheduler.py & disown` (I'm running it remotely, so I want to run it in the background and disown it. Immediately, a number (PID) appears below the line, as every other python script would do. But when I do ps -e | grep python, that number is not there. I tried to do `kill -9 PID` and I got a message saying that the job does not exist. Is the scheduler running? If yes, how can I stop it? if not, what am I doing wrong? Answer: you have to keep the script running otherwise after the `sched.add_interval_job(myScript, start_date = startDate, days=1)`, the script ends and stop. add a import time while True: time.sleep(10) sched.shutdown() after, and then, the scheduler will still be alive.
Defining a classpath for a Jython virtual environment Question: I have installed [Jython](http://en.wikipedia.org/wiki/Jython), a [virtualenv](http://pypi.python.org/pypi/virtualenv) named "jython-env" and have installed "bottle" for doing some web application development. I have to use some JAR files in this application for consumption by some Python code. I know I have to set the classpath which should include these JAR files. I tried setting the classpath using export classpath=/home/myname/jclasses/foo.jar but when I try to import the class, it says _module not found_. I am very new at Java and am doing this for the first time. Can't the configuration be done such that I can just put the JAR files in the sitepackages directory of my virtualenv and use it from there? Answer: jython -Dpython.path=/path/to/myjar.jar Here's another idea: you could use a `.pth` file. Create a file - `/path/to/jythonenv/Lib/site-packages/myjars.pth`: path/to/jar1.jar path/to/jar2.jar Would also do the trick.
Doing something like Python's "import" in Scala Question: Is it possible to use Scala's `import` without specifying a main function in an object, and without using the `package` keyword in the source file with the code you wish to import? Some explanation: In Python, I can define some functions in some file "Lib.py", write from Lib import * in some other file "Run.py" in the same directory, use the functions from Lib in Run, and then run Run with the command `python Run.py`. This workflow is ideal for small scripts that I might write in an hour. In Scala, it appears that if I want to include functions from another file, I need to start wrapping things in superfluous objects. I would rather not do this. Answer: Writing Python in Scala is unlikely to yield satisfactory results. Objects are not "superfluous" -- it's your program that is not written in an object oriented way. First, methods must be inside objects. You can place them inside a `package object`, and they'll then be visible to anything else that is inside the package of the same name. Second, if one considers solely objects and classes, then all package-less objects and classes whose class files are present in the classpath, or whose scala files are compiled together, will be visible to each other.
How to constantly send STDOUT to my python TCP server? Question: 1. i have simple python echo server which uses sockets , and echoes random numbers to clients . 2. i have another program which prints every 2 second values to stdout. If it was just a script i could have redirected like this 'stdout' | python script.py , and fetch it in the script like this `data = sys.stdin.read()`. But it's a server , and it wont work like this. Question: How to write such a python server, that it could listen/fetch values which come to stdout on Debian, and pass them further. I am not asking for a complete code. Just some ideas on getting stdout, considering the program is a server. **Continuosly coming values > stdout > server.py > send values further** Answer: I think you need something similar to [Python subprocess](http://docs.python.org/library/subprocess.html#replacing-shell- pipeline). In that example, consider `dmesg` as your number generator, and the `grep` as your socket server; however, you will just open a `PIPE` in the socket server instead of spawning a shell command. Assume you have two processes, the talker and server... ## talker.py import time import sys DELAY = int(sys.argv[1]) ii = 1 while 1: sys.stdout.write("Talking every %i seconds, blabbed %i times\n" % (DELAY, ii)) sys.stdout.flush() ii += 1 time.sleep(DELAY) ## server.py from subprocess import Popen, PIPE from os import kill import signal talkpipe = Popen(['python', 'talker.py', '3'], shell=False, stdout=PIPE) try: while True: line = talkpipe.stdout.readline() print "SERVER HEARD", line.strip() except KeyboardInterrupt: print "Killing child..." kill(talkpipe.pid, signal.SIGTERM) Running this with `python server.py` yields... [mpenning@Bucksnort tmp]$ python server.py SERVER HEARD Talking every 3 seconds, blabbed 1 times SERVER HEARD Talking every 3 seconds, blabbed 2 times SERVER HEARD Talking every 3 seconds, blabbed 3 times SERVER HEARD Talking every 3 seconds, blabbed 4 times ^CTraceback (most recent call last): File "talker.py", line 11, in <module> time.sleep(DELAY) KeyboardInterrupt Killing child... [mpenning@Bucksnort tmp]$
Wordlist Generator. Split file Size. How? Question: I am trying to get this python script to create a new file and continue generating word combinations once a certain file size is reached. f=open('wordlist', 'w') def xselections(items, n): if n==0: yield [] else: for i in xrange(len(items)): for ss in xselections(items, n-1): yield [items[i]]+ss # Numbers = 48 - 57 # Capital = 65 - 90 # Lower = 97 - 122 numb = range(48,58) cap = range(65,91) low = range(97,123) choice = 0 while int(choice) not in range(1,8): choice = raw_input(''' 1) Numbers 2) Capital Letters 3) Lowercase Letters 4) Numbers + Capital Letters 5) Numbers + Lowercase Letters 6) Numbers + Capital Letters + Lowercase Letters 7) Capital Letters + Lowercase Letters : ''') choice = int(choice) poss = [] if choice == 1: poss += numb elif choice == 2: poss += cap elif choice == 3: poss += low elif choice == 4: poss += numb poss += cap elif choice == 5: poss += numb poss += low elif choice == 6: poss += numb poss += cap poss += low elif choice == 7: poss += cap poss += low bigList = [] for i in poss: bigList.append(str(chr(i))) MIN = raw_input("What is the min size of the word? ") MIN = int(MIN) MAX = raw_input("What is the max size of the word? ") MAX = int(MAX) for i in range(MIN,MAX+1): for s in xselections(bigList,i): f.write(''.join(s) + '\n') Answer: You can encapsulate the file rotation behavior in a class. When you are writing some data, the write method will first check if the write would exceed the file size limit; then it calls the rotate method which closes the current file and opens a new one, incrementing the sequence number on the filename: import os class LimitWriter(object): def __init__(self, basepath, bytelimit): self._basepath = basepath self._bytelimit = bytelimit self._sequence = 0 self._output = None self._bytes = 0 self._rotate() def _rotate(self): if self._output: self._output.close() path = '%s.%06d' % (self._basepath, self._sequence) self._output = open(path, 'wb') self._bytes = 0 self._sequence += 1 def write(self, data): size = len(data) if (self._bytes + size) > self._bytelimit: self._rotate() self._bytes += size self._output.write(data) out = LimitWriter('wordlist', 1024 * 1024 * 1) for i in range(MIN,MAX+1): for s in xselections(bigList,i): out.write(''.join(s) + '\n') Would output a series of files which are smaller than 1MB: 1.0M wordlist.000000 1.0M wordlist.000001 252K wordlist.000002 **Update** \- A few more tips on using some of the built-in power of Python to help make your code a bit shorter and easier to follow. I've included comments explaining each part. Here are the docs on the modules I use below: [itertools](http://docs.python.org/library/itertools.html), [string](http://docs.python.org/library/string.html). import itertools import os from string import digits, lowercase, uppercase # PUT LimitWriter CLASS DEFINITION HERE LIMIT = 1024 * 1024 * 1 choice = 0 while int(choice) not in range(1,8): choice = raw_input(''' 1) Numbers 2) Capital Letters 3) Lowercase Letters 4) Numbers + Capital Letters 5) Numbers + Lowercase Letters 6) Numbers + Capital Letters + Lowercase Letters 7) Capital Letters + Lowercase Letters : ''') MIN = int(raw_input("What is the min size of the word? ")) MAX = int(raw_input("What is the max size of the word? ")) # replace your ranges and large if/else with this choices = { 1: digits, 2: uppercase, 3: lowercase, 4: uppercase + lowercase, 5: digits + lowercase, 6: digits + uppercase + lowercase, 7: uppercase + lowercase } # pick one of the sets with the user's choice chars = choices[int(choice)] out = LimitWriter('wordlist', LIMIT) # generate all permutations of the characters from min to max for length in range(MIN, MAX+1): for tmp in itertools.permutations(chars, length): out.write(''.join(tmp) + '\n')
Learning pyramid (python) and am struggling with the @view_config decorator. Should it just work out of the box? Question: I am still learning pyramid, and I am at a point where I am trying to learn how to use decorators. Below is a copy of my test view callable. from pyramid.response import Response from pyramid.view import view_config from pyramid.renderers import render_to_response def my_blog(request): return {'project':'tricky'} @view_config( renderer='templates/foo.pt' ) def foo_blog(request): return {'name':'tricky'} From what I can understand about the view_config decorator, it can be used to set application configurations without actually setting them in the config file. In the case of this example, I am setting the renderer to be templates/foo.pt. This does not ever work. However, if I set renderer in the config file (**init**.py) as such: config.add_route( 'foo_blog' , '/blog/{foo}' , view='tricky.views.Blog.blog.foo_blog' renderer='tricky:templates/mytemplate.pt' ) it will work. Am I doing something wrong that is preventing me from being able to use the decorator. Thanks! Answer: In order for the configurations added via @view_config to work, you need to call config.scan() at some point.
tic, toc functions analog in Python Question: What is the best analog of MATLAB tic and toc functions ( <http://www.mathworks.com/help/techdoc/ref/tic.html>) in Python? Answer: Apart from `timeit` which ThiefMaster mentioned, a simple way to do it is just (after importing `time`): t = time.time() # do stuff elapsed = time.time() - t I have a helper class I like to use: class Timer(object): def __init__(self, name=None): self.name = name def __enter__(self): self.tstart = time.time() def __exit__(self, type, value, traceback): if self.name: print '[%s]' % self.name, print 'Elapsed: %s' % (time.time() - self.tstart) It can be used as a context manager: with Timer('foo_stuff'): # do some foo # do some stuff Sometimes I find this technique more convenient than `timeit` \- it all depends on what you want to measure.
ı am new at using python pickle and Question: each dictionary has the form: records[name]=[email,telephone] the dictionary is pickled and stored in a file name recordsfile . the big problem after if ı made above... adds new record to the addresbook ? thanks for helping .. Answer: Well, if I understand your question correctly (Please try and be more clear next time, also use better grammar as we all know anyone who comes on this site can), you would have to unpickle the dictionary, add a key:value pair, than pickle it again. For example, import cPickle as pickle addressBook = {"Foo": "555-555-5555, foo@bar.com"} for key, var in addressBook.iteritems(): print key, ":", var print addressFile = open("address.pickle", "wb") pickle.dump(addressBook, addressFile) addressFile.close() #Now to add a new value to addressBook addressFile = open("address.pickle", "rb") addressBook = pickle.load(addressFile) addressFile.close() addressBook["Bar"] = "012-345-6789, bar@foo.com" for key, var in addressBook.iteritems(): print key, ":", var addressFile = open("address.pickle", "wb") pickle.dump(addressBook, addressFile)�ddressBook, addressFile) Now, I just threw that together in a couple of minutes, so it can obviously be cleaned up. However, it does show you the basics of how to do what you're asking for.
How do i use table data from my sqlite3 database as a python variable Question: My code so far conn = sqlite3.connect('databaserm/database') curs = conn.cursor() curs.execute('SELECT * FROM saves') lvl = curs.fetchone() conn.close() ok maybes its the code i used to add the data to the db i've tried this cn = sqlite3.connect(/databaserm/database") curs = cn.cursor() curs.execute('DROP TABLE saves') curs.execute('CREATE TABLE saves (lvl)') #curs.execute('INSERT INTO saves VALUES (null, ?)', lvl) query = """INSERT INTO saves (lvl) VALUES (?)""" data = [lvl] curs.execute(query, data) cn.commit cn.close() and this conn = sqlite3.connect('/databaserm/database') curs = conn.cursor() curs.execute('INSERT INTO saves VALUES(null, ?,)', (lvl,)) conn.commit Answer: Executing `select` and then `fetchone` will return a tuple. What else do you need? Here's an example: import sqlite3 as sqlite con = sqlite.connect(':memory:') cursor = con.cursor() cursor.execute(''' create table names (id integer primary key, name varchar(50), email varchar(50))''') cursor.execute(''' insert into names values (null, "John Doe", "jdoe@jdoe.zz")''') cursor.execute(''' insert into names values (null, "Mary Sue", "msue@msue.yy")''') name = """Lu'k'e d"fdf" Sma""" email = "use@force.net" cursor.execute( '''insert into names values (null, ?, ?)''', (name, email)) cursor.execute('select * from names') for c in cursor: print c Uses iteration over `cursor` (an alternative way to get result). Prints: (1, u'John Doe', u'jdoe@jdoe.zz') (2, u'Mary Sue', u'msue@msue.yy') (3, u'Lu\'k\'e d"fdf" Sma', u'use@force.net') Using `fetchone` instead of iteration: print cursor.fetchone() cursor.close() Prints: (1, u'John Doe', u'jdoe@jdoe.zz')
What is wrong with this way of showing the progress of the function? Question: Here is my function def f(task_list): results = [] for task_id in task_list: results.append(work(task_id)) print len(results) # show the progress return results I use execfile() in ipython to run this function, but it seems that the progress is showed until the whole function ends ======================= I tried again, it seems okay now... Answer: try to force to flush stdout : import sys def f(task_list): results = [] for task_id in task_list: results.append(work(task_id)) print len(results) # show the progress sys.stdout.flush() # this will force the system to display what is in the stdout queue return results
Python multiprocessing with MySQL Question: I've Googled this topic a lot, but cannot find a solution which fits my needs :( I have a MySQL DB with a table containing e-mail adresses (10,000+). I would like to run a batch job on them every 5 minute. So I'll guess Python is a good choice for retrieving the resultset from MySQL and then call a command-line with the e-mail address' as arguments. How do I do this the best way? I'm think of getting the entire resultset from MySQL and then have a bunch of workes calling the command-line with the arguments until there aren't anymore e-mail address. Can this be done in a simple, yet stable, way? Answer: you could use the multiprocessing module like this : from multiprocessing import Pool p = Pool() # let python choose the optimal number of processes (= number of CPU cores) def treat_email(email_adress): # do the stuff you need with email address email_addresses = grab_the_list_from_mysql() # something like "select mail from my_user_table" p.map(treat_email, email_addresses) # this will treat all the emails in the X processes
[Python]Encoding and execfile Question: I am trying to do something like that using python 2.4: #!/usr/bin/python # -*- coding: utf-8 -*- afile = unicode('C:\\國立國語院.py', 'UTF-8') execfile(afile.encode("UTF-8",'replace')) And I receive this error: IOError: [Errno 2] No such file or directory: 'C:\\\xef\xbb\xbf\xe5\x9c\x8b\xe7\xab\x8b\xe5\x9c\x8b\xe8\xaa\x9e\xe9\x99\xa2.py' So my question is how can I do an execfile if the file I want to exec have a name with Korean chars? Thank you very much Answer: I think you should just be able to do `execfile(afile)` with a unicode argument on Windows, but I can't test it. If not, get the file system encoding: import sys fsenc = sys.getfilesystemencoding() execfile(afile.encode(fsenc))
Cannot install python packages from source-code Question: I need to install `PIL` (python imaging library) on my Ubunto10.4-32bit (EDIT:64bit) machine on my python2.5.4-32bit. This question is also relevant to any other source package I guess (among those that I need are `RPyC`,`psyco` and `numpy`). I downloaded the source-code since I can't find any neat package to do the job and did a `sudo python2.5 setup.py install`. output: Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] Traceback (most recent call last): File "setup.py", line 9, in <module> import glob, os, re, struct, string, sys File "/usr/lib/python2.5/struct.py", line 30, in <module> from _struct import Struct, error ImportError: No module named _struct but > > echo $PYTHONHOME > /usr Well, in the file `struct.py` theres the line `from _struct import Struct, error` This is part of the python source code itself so I really wonder whats wrong with the python installation, since the code fails to import the module. I installed py2.5.4 by doing: ./configure --prefix=/usr make altinstall (using `make altinstall` since I need py26 as default python interpreter) EDIT: This issue might have risen from mistakenly using a 64bit platform :) and 32bit python2.5 . So anyhow problem solved by reducing unnecessary complexities - switching to 32bit machine and porting app to python 2.6. Answer: ### In short: Try using the Ubuntu repository first. If the package isn't there, use `easy_install`. If all fails, download the package directly to your source folder. ### Ubuntu repository (the apt-get approach) Ubuntu (10.04 and newer) has most mainstream packages are available with `apt- get`. The naming convention is `python-NAME`, e.g. `python-imaging` or `python-scipy`. This is the best way to go, since the native package manager will handle any dependencies and updates issues. Run `apt-cache search python | grep "^python-" | less` to see a list of packages available for your system (I have over 1,200 in my 10.04 machine). ### Setuptools For packages that are not part of the Ubuntu repository, you can use the python `easy-install` tool. First, install the setup tool: sudo apt-get install python-setuptools And you can install any Python package, e.g. [colorworld](http://pypi.python.org/pypi/colorworld/0.3), using `easy- install`: sudo easy_install colorworld This gives you some degree of protection (e.g., handles dependencies) but updates are generally manual, and it's a real pain to reinstall all these packages in a new computer. ### Manual download You can always download the source code to some directory and add it to your `PYTHONPATH`. It's the best approach when you just need to evaluate a package or apply some quick-and-dirty solution.
How can I disable web security in selenium through Python? Question: Apparently it's common for google-chrome to get this: <http://jira.openqa.org/browse/SRC-740> The key is to start it without security enabled. To disable security, "--disable-web-security", I'm having trouble wondering how to actually specify these command line arguments, though, so it fails on the `open` invocation here: from selenium import selenium sel = selenium('localhost', 4444, '*googlechrome', 'http://www.google.com/') sel.start() sel.open('/') Here's how I start the selenium server: shogun@box:~$ java -jar selenium-server-standalone-2.0b3.jar Answer: To get this to work, I had to create an external script to wrap the chrome browser. Place a script somewhere your Selenium server can reach it (mine is at `~/bin/startchrome`, and chmod it executable: #!/bin/sh # chrome expects to be run from the .app dir, so cd into it # (the spaces in the path are a Mac thing) cd /Applications/Google\ Chrome.app exec ./Contents/MacOS/Google\ Chrome --disable-security $* Then in your Python code, do this: from selenium import selenium browser = '*googlechrome /Users/pat/bin/startchrome' sel = selenium('localhost', 4444, browser, 'http://www.google.com') sel.start() sel.open('/')
Fast DES for Python Question: i am searching for compiled des implementation for python. M2Crypto don't work for me with error message "ImportError: DLL load failed:". OpenSSLLight installed. Edit: ok, fixed with M2Crypto. For some reasons, if you select during the installation of SSLLight that the libraries should be placed in the program directory, they are not recognised by programs. I reinstalled openssllight with placing the libs into windows dir, and now M2Crypto loads. Answer: [Pycrypto](http://www.dlitz.net/software/pycrypto/) supports DES/DES3 and has [prebuilt Windows installers from Voidspace](http://www.voidspace.org.uk/python/modules.shtml#pycrypto). Quick example: from Crypto.Cipher import DES des = DES.new('13371337', DES.MODE_ECB) des.encrypt('plaintxt') '\xeb\x9d\xe7~&\xb4fp'
Generating all dates within a given range in python Question: I have two string variables which contain dates in yyyy-mm-dd format as follows : date1 = '2011-05-03' date2 = '2011-05-10' I want to write code that generates all dates in the range date1 to date2. How can this be done in Python? Answer: from dateutil import rrule, parser date1 = '2011-05-03' date2 = '2011-05-10' dates = list(rrule.rrule(rrule.DAILY, dtstart=parser.parse(date1), until=parser.parse(date2))) print dates Since [**dateutil**](http://niemeyer.net/python-dateutil) is not a standard library, you will have to install it as a separate package. See the documentation for further details regarding the format (especially `dayfirst` and `yearfirst` switches).
Auto wrap and newlines in wxPython grid Question: I want to implement a grid with the cells that have the following behaviour: 1. cell text should be wrapped if it doesn't fit to the cell 2. newlines (\n) in the cell text should be processed as well i.e. the same behaviour as in table editors like MS Excel, OO Calc, etc. when you enable the 'wrap words' option for cells. I'm trying to do this as follows: import wx import wx.grid class MyGrid(wx.grid.Grid): def __init__(self, parent = None, style = wx.WANTS_CHARS): wx.grid.Grid.__init__(self, parent, -1, style = style) self.CreateGrid(10, 10) self.editor = wx.grid.GridCellAutoWrapStringEditor() self.SetDefaultEditor(self.editor) self.SetDefaultRenderer(wx.grid.GridCellAutoWrapStringRenderer()) self.SetCellValue(0, 0, "Line1\nLine2\nLine3") self.SetRowSize(0, 100) class MyFrame(wx.Frame): def __init__(self, parent = None, title = "Multiline"): wx.Frame.__init__(self, parent, -1, title) self.Bind(wx.EVT_CHAR_HOOK, self.on_frame_char_hook) panel = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(vbox) grid = MyGrid(panel) vbox.Add(grid, 1, wx.EXPAND | wx.ALL, 5) self.grid = grid btn_exit = wx.Button(panel, -1, "Exit") vbox.Add(btn_exit, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 10) #Proceed CTRL+ENTER as newline in the cell editor def on_frame_char_hook(self, event): if event.CmdDown() and event.GetKeyCode() == wx.WXK_RETURN: if self.grid.editor.IsCreated(): self.grid.editor.StartingKey(event) else: event.Skip else: event.Skip() if __name__ == "__main__": app = wx.PySimpleApp() f = MyFrame() f.Center() f.Show() app.MainLoop() But this code doesn't work as expected - newlines processed correctly in the cell editor, but ignored in the cell renderer. If I remove the `self.SetDefaultRenderer(wx.grid.GridCellAutoWrapStringRenderer())` then newlines processed correcly both in the editor and renderer, but obviously auto wrapping in the renderer doesn't work. Does anybody know how to solve this? Answer: Solved this problem by writing a custom renderer: from wx.lib import wordwrap import wx.grid class CutomGridCellAutoWrapStringRenderer(wx.grid.PyGridCellRenderer): def __init__(self): wx.grid.PyGridCellRenderer.__init__(self) def Draw(self, grid, attr, dc, rect, row, col, isSelected): text = grid.GetCellValue(row, col) dc.SetFont( attr.GetFont() ) text = wordwrap.wordwrap(text, grid.GetColSize(col), dc, breakLongWords = False) hAlign, vAlign = attr.GetAlignment() if isSelected: bg = grid.GetSelectionBackground() fg = grid.GetSelectionForeground() else: bg = attr.GetBackgroundColour() fg = attr.GetTextColour() dc.SetTextBackground(bg) dc.SetTextForeground(fg) dc.SetBrush(wx.Brush(bg, wx.SOLID)) dc.SetPen(wx.TRANSPARENT_PEN) dc.DrawRectangleRect(rect) grid.DrawTextRectangle(dc, text, rect, hAlign, vAlign) def GetBestSize(self, grid, attr, dc, row, col): text = grid.GetCellValue(row, col) dc.SetFont(attr.GetFont()) text = wordwrap.wordwrap(text, grid.GetColSize(col), dc, breakLongWords = False) w, h, lineHeight = dc.GetMultiLineTextExtent(text) return wx.Size(w, h) def Clone(self): return CutomGridCellAutoWrapStringRenderer()
translate url with google translate from python script Question: I'm trying to use google translate from a python script: #!/usr/bin/env python from urllib2 import urlopen from urllib import urlencode base_url = "http://www.google.com/translate?" params = (('langpair','en|es'), ('u','http://asdf.com'),) url = base_url+urlencode(params) print "Encoded URL: %s" % url print urlopen(url).read() I'm getting the error 403 when I use it. # ./1.py Encoded URL: http://www.google.com/translate?langpair=en%7Ces&u=http%3A%2F%2Fasdf.com Traceback (most recent call last): ... urllib2.HTTPError: HTTP Error 403: Forbidden However the same URL works fine when accessed from browser. Could anyone spot the error? Or is it that google does not allow this type of usage? Thanks in advance Answer: If Google doesn't let you do this, you could programatically translate the normal website's source via the Google's APIs. I wrote a function for this a little while back: def translate(text, src = '', to = 'en'): parameters = ({'langpair': '{0}|{1}'.format(src, to), 'v': '1.0' }) translated = '' for text in (text[index:index + 4500] for index in range(0, len(text), 4500)): parameters['q'] = text response = json.loads(urllib.request.urlopen('http://ajax.googleapis.com/ajax/services/language/translate', data = urllib.parse.urlencode(parameters).encode('utf-8')).read().decode('utf-8')) try: translated += response['responseData']['translatedText'] except: pass return translated
ImportError when trying to import a custom module in Python Question: _Note that I searched SO for this error and while there were many similar questions, I didn't find one that addressed this particular issue._ I'm working on a Python module that looks like this: /com /company /foo /bar I'm editing a source file within the `bar` directory and attempting to import classes that live in the `foo` directory. I've tried importing the files the following ways: from com.company.foo import * from company.foo import * from foo import * import com.company.foo import company.foo import foo Each of these produces a similar error: ImportError: no module named com.company.foo I have `__init__.py` files in each of the directories, including the directory that contains `com`. Not sure what I'm doing wrong here - thanks in advance for you assistance! Answer: The directory containing `/com` needs to be on the Python path. There are a number of ways to do this: 1. At the command line, every time: ` user@host:~$ PYTHONPATH=/path/to/whatever python some_file.py ` 2. In your shell configuration (`.bashrc`, `.bash_profile`, etc): ` export PYTHONPATH=/path/to/whatever ` 3. In Python code (I don't recommend this, as general practice): ` import sys sys.path.append('/path/to/whatever') ` As some of the commenters said, usually this is handled either by the container (`mod_wsgi`, etc) or by your bootstrap/main script (which might do something like option #3, or might be invoked in an environment set up as in options #1 or #2)
Django form.is_valid always returning true Question: I'm new to Django and python and am trying to learn it from a book. In the code below I'm trying to make sure password1 and password2 are the same but it doesn't seem to run the clean_password2 validation because it always returns true even if they have different values. import re from django.contrib.auth.models import User from django import forms class RegistrationForm(forms.Form): username = forms.CharField(label=u'Username', max_length=30) email = forms.EmailField(label=u'Email') password1 = forms.CharField( label= u'Password', widget = forms.PasswordInput() ) password2 = forms.CharField( label= u'Password (Again)', widget = forms.PasswordInput() ) def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 != password2: raise forms.ValidationError('Passwords do not match.') return password2 Answer: If you are cleaning two fields that depend on each other, you should override the form's `clean()` method. You can read more [here](http://docs.djangoproject.com/en/1.2/ref/forms/validation/#cleaning- and-validating-fields-that-depend-on-each-other).
play framework error Question: I am getting this error when I am simply trying to run play command from command prompt in windows. C:\Users\naveenreddy>play Traceback (most recent call last): File "E:\andrew\structure\play-1.2\play", line 13, in <module> from play.application import PlayApplication File "E:\andrew\structure\play-1.2\framework\pym\play\application.py", line 5, in <module> import socket File "C:\Python27\lib\socket.py", line 47, in <module> import _socket ImportError: DLL load failed: %1 is not a valid Win32 application. C:\Users\naveenreddy> I have set the play directory in path and have installed python already which I use to run django. What could cause this error?! Answer: It is most likely a conflict with python versions. Try taking python out of your path, so play can use the built in python.
HTTPS connection using PEM Certificate Question: I'm trying to POST HTTPS requests using a PEM certificate like following: import httplib CERT_FILE = '/path/certif.pem' conn = httplib.HTTPSConnection('10.10.10.10','443', cert_file =CERT_FILE) conn.request("POST", "/") response = conn.getresponse() print response.status, response.reason conn.close() I have the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/httplib.py", line 914, in request self._send_request(method, url, body, headers) File "/usr/lib/python2.6/httplib.py", line 951, in _send_request self.endheaders() File "/usr/lib/python2.6/httplib.py", line 908, in endheaders self._send_output() File "/usr/lib/python2.6/httplib.py", line 780, in _send_output self.send(msg) File "/usr/lib/python2.6/httplib.py", line 739, in send self.connect() File "/usr/lib/python2.6/httplib.py", line 1116, in connect self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file) File "/usr/lib/python2.6/ssl.py", line 338, in wrap_socket suppress_ragged_eofs=suppress_ragged_eofs) File "/usr/lib/python2.6/ssl.py", line 118, in __init__ cert_reqs, ssl_version, ca_certs) ssl.SSLError: [Errno 336265225] _ssl.c:339: error:140B0009:SSL routines:**SSL_CTX_use_PrivateKey_file**:PEM lib When I remove the cert_file from httplib, I've the following response: 200 ok When I add the Authentication header (like advised by MattH) with empty post payload, it works also. However, when I put the good request with the Path, the Body and the Header, like following (I simplified them...) body = '<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">blablabla</S:Envelope>' URLprov = "/syncaxis2/services/XXXsyncService" auth_header = 'Basic %s' % (":".join(["xxx","xxxxx"]).encode('Base64').strip('\r\n')) conn.request("POST",URLprov,body,{'Authenticate':auth_header}) I have 401 Unauthorized response ! As you can see, first, I'm asked to provide the PrivateKey ! why did I need the PrivateKey if I'm a client ? then, when I remove the PrivateKey and the certificate, and put the Path/Body/headers I have 401 Unauthorized error with the message WWW-Authenticate: Basic realm="SYNCNB Server Realm". Could any one explain this issue? Is there another way to send HTTPS request using a certificate in Python? Answer: It sounds like you need something similar to an answer I have provided before to perform [simple client certificate authentication](http://stackoverflow.com/questions/5700289/using-pyopenssl-to- create-urllib-custom-opener/5707951#5707951). Here is the code for convenience modified slightly for your question: import httplib import urllib2 PEM_FILE = '/path/certif.pem' # Renamed from PEM_FILE to avoid confusion CLIENT_CERT_FILE = '/path/clientcert.p12' # This is your client cert! # HTTPS Client Auth solution for urllib2, inspired by # http://bugs.python.org/issue3466 # and improved by David Norton of Three Pillar Software. In this # implementation, we use properties passed in rather than static module # fields. class HTTPSClientAuthHandler(urllib2.HTTPSHandler): def __init__(self, key, cert): urllib2.HTTPSHandler.__init__(self) self.key = key self.cert = cert def https_open(self, req): #Rather than pass in a reference to a connection class, we pass in # a reference to a function which, for all intents and purposes, # will behave as a constructor return self.do_open(self.getConnection, req) def getConnection(self, host): return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert) cert_handler = HTTPSClientAuthHandler(PEM_FILE, CLIENT_CERT_FILE) opener = urllib2.build_opener(cert_handler) urllib2.install_opener(opener) f = urllib2.urlopen("https://10.10.10.10") print f.code
Parsing an ISO datetime in Python Question: > **Possible Duplicate:** > [Converting string to datetime object in > python](http://stackoverflow.com/questions/2609259/converting-string-to- > datetime-object-in-python) Given the below Python import datetime >>> a '2011-05-04 16:20:09 -0700' >>> datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S %z") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/_strptime.py", line 317, in _strptime (bad_directive, format)) ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z' >>> I don't really understand how `%z` is a bad directive. Reference: <http://docs.python.org/library/datetime.html#strftime-strptime- behavior> This is from hg, which says that it is in ISO8601 format. Answer: Here is the complete story: <http://bugs.python.org/issue6641> and related: [Converting string to datetime object in python](http://stackoverflow.com/questions/2609259/converting-string-to- datetime-object-in-python)
Recursive diff of two python dictionaries (keys and values) Question: So I have a python dictionary, call it `d1`, and a version of that dictionary at a later point in time, call it `d2`. I want to find all the changes between `d1` and `d2`. In other words, everything that was added, removed or changed. The tricky bit is that the values can be ints, strings, lists, or dicts, so it needs to be recursive. This is what I have so far: def dd(d1, d2, ctx=""): print "Changes in " + ctx for k in d1: if k not in d2: print k + " removed from d2" for k in d2: if k not in d1: print k + " added in d2" continue if d2[k] != d1[k]: if type(d2[k]) not in (dict, list): print k + " changed in d2 to " + str(d2[k]) else: if type(d1[k]) != type(d2[k]): print k + " changed to " + str(d2[k]) continue else: if type(d2[k]) == dict: dd(d1[k], d2[k], k) continue print "Done with changes in " + ctx return It works just fine unless the value is a list. I cant quite come up with an elegant way to deal with lists, without having a huge, slightly changed version of this function repeated after a `if(type(d2) == list)`. Any thoughts? EDIT: This differs from [this post](http://stackoverflow.com/questions/4197312/diff-multidimensional- dictionaries-in-python "this post") because the keys can change Answer: In case you want the difference recursively, I have written a package for python: <https://github.com/seperman/deepdiff> ## Installation Install from PyPi: pip install deepdiff ## Example usage Importing >>> from deepdiff import DeepDiff >>> from pprint import pprint >>> from __future__ import print_function # In case running on Python 2 Same object returns empty >>> t1 = {1:1, 2:2, 3:3} >>> t2 = t1 >>> print(DeepDiff(t1, t2)) {} Type of an item has changed >>> t1 = {1:1, 2:2, 3:3} >>> t2 = {1:1, 2:"2", 3:3} >>> pprint(DeepDiff(t1, t2), indent=2) { 'type_changes': { 'root[2]': { 'newtype': <class 'str'>, 'newvalue': '2', 'oldtype': <class 'int'>, 'oldvalue': 2}}} Value of an item has changed >>> t1 = {1:1, 2:2, 3:3} >>> t2 = {1:1, 2:4, 3:3} >>> pprint(DeepDiff(t1, t2), indent=2) {'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}} Item added and/or removed >>> t1 = {1:1, 2:2, 3:3, 4:4} >>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6} >>> ddiff = DeepDiff(t1, t2) >>> pprint (ddiff) {'dic_item_added': ['root[5]', 'root[6]'], 'dic_item_removed': ['root[4]'], 'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}} String difference >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}} >>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}} >>> ddiff = DeepDiff(t1, t2) >>> pprint (ddiff, indent = 2) { 'values_changed': { 'root[2]': {'newvalue': 4, 'oldvalue': 2}, "root[4]['b']": { 'newvalue': 'world!', 'oldvalue': 'world'}}} String difference 2 >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}} >>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}} >>> ddiff = DeepDiff(t1, t2) >>> pprint (ddiff, indent = 2) { 'values_changed': { "root[4]['b']": { 'diff': '--- \n' '+++ \n' '@@ -1,5 +1,4 @@\n' '-world!\n' '-Goodbye!\n' '+world\n' ' 1\n' ' 2\n' ' End', 'newvalue': 'world\n1\n2\nEnd', 'oldvalue': 'world!\n' 'Goodbye!\n' '1\n' '2\n' 'End'}}} >>> >>> print (ddiff['values_changed']["root[4]['b']"]["diff"]) --- +++ @@ -1,5 +1,4 @@ -world! -Goodbye! +world 1 2 End Type change >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}} >>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}} >>> ddiff = DeepDiff(t1, t2) >>> pprint (ddiff, indent = 2) { 'type_changes': { "root[4]['b']": { 'newtype': <class 'str'>, 'newvalue': 'world\n\n\nEnd', 'oldtype': <class 'list'>, 'oldvalue': [1, 2, 3]}}} List difference >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}} >>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}} >>> ddiff = DeepDiff(t1, t2) >>> pprint (ddiff, indent = 2) {'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}} List difference 2: >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}} >>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}} >>> ddiff = DeepDiff(t1, t2) >>> pprint (ddiff, indent = 2) { 'iterable_item_added': {"root[4]['b'][3]": 3}, 'values_changed': { "root[4]['b'][1]": {'newvalue': 3, 'oldvalue': 2}, "root[4]['b'][2]": {'newvalue': 2, 'oldvalue': 3}}} List difference ignoring order or duplicates: (with the same dictionaries as above) >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}} >>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}} >>> ddiff = DeepDiff(t1, t2, ignore_order=True) >>> print (ddiff) {} List that contains dictionary: >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}} >>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}} >>> ddiff = DeepDiff(t1, t2) >>> pprint (ddiff, indent = 2) { 'dic_item_removed': ["root[4]['b'][2][2]"], 'values_changed': {"root[4]['b'][2][1]": {'newvalue': 3, 'oldvalue': 1}}} Sets: >>> t1 = {1, 2, 8} >>> t2 = {1, 2, 3, 5} >>> ddiff = DeepDiff(t1, t2) >>> pprint (DeepDiff(t1, t2)) {'set_item_added': ['root[3]', 'root[5]'], 'set_item_removed': ['root[8]']} Named Tuples: >>> from collections import namedtuple >>> Point = namedtuple('Point', ['x', 'y']) >>> t1 = Point(x=11, y=22) >>> t2 = Point(x=11, y=23) >>> pprint (DeepDiff(t1, t2)) {'values_changed': {'root.y': {'newvalue': 23, 'oldvalue': 22}}} Custom objects: >>> class ClassA(object): ... a = 1 ... def __init__(self, b): ... self.b = b ... >>> t1 = ClassA(1) >>> t2 = ClassA(2) >>> >>> pprint(DeepDiff(t1, t2)) {'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}} Object attribute added: >>> t2.c = "new attribute" >>> pprint(DeepDiff(t1, t2)) {'attribute_added': ['root.c'], 'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}
How can I switch to a new music file while my Python program is running livewires? Question: I load a file and then play it, that works fine. Then if I load another music file neither plays. I need to load one music track, play it, then stop it, then load and play a second track. Is this just not possible? games.music.load("theme.mp3") games.music.play(-1) games.music.load("bonus_theme.mp3") games.music.play(-1) Answer: Why not load both into variables and then use .play() and .stop()? For example: import pygame theme = pygame.mixer.Sound('theme.mp3') bonusTheme = pygame.mixer.Sound('bonus_theme.mp3') theme.play(-1) theme.stop() bonusTheme.play(-1)
MySQLdb installed from pypm doesn't work with 32-bit python on Mac OSX Question: Before proceeding further, here are some details of my Mac and the installed python (ActivePython) and wxpython versions: _**Mac version: 10.6.6 Python version: 2.7.1 (ActiveState Python) wxPython version: wxPython2.8-osx-unicode-py2.7_** Here is a small code that I wrote to test: #! /usr/bin/env arch -i386 /usr/local/bin/python import time import random import re import wx from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin import serial import itertools import datetime import sys import os import MySQLdb print "Hello World" Here is the error that I got from running it: Traceback (most recent call last): File "./sar.pyw", line 13, in <module> import MySQLdb File "/Users/ven/Library/Python/2.7/lib/python/site-packages/MySQLdb/__init__.py", line 19, in <module> import _mysql ImportError: dlopen(/Users/ven/Library/Python/2.7/lib/python/site-packages/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/ven/Library/Python/2.7/lib/python/site-packages/_mysql.so Expected in: flat namespace in /Users/ven/Library/Python/2.7/lib/python/site-packages/_mysql.so As you can see I am using 32-bit python in the shebang line because I need to work with [wxpython](http://code.activestate.com/pypm/wxpython/) which runs only on 32-bit. Now, the only package that has problem with the 32-bit python is the [MySQLdb](http://code.activestate.com/pypm/mysql-python/) which has been installed using: pypm install mysql-python If I just removed the line import MySQLdb from the above piece of code, it runs perfectly and prints "Hello World". If I removed "arch -i386" from the shebang line, the wxpython package doesn't work. I want to use both wxpython and MySQLdb at the same time. How do I do it? Answer: [Duplicate](http://community.activestate.com/node/6641) ;-) This is a [known bug](http://bugs.activestate.com/show_bug.cgi?id=87704) \-- the `mysql-python` package is built only for 64-bit at the moment. > I want to use both wxpython and MySQLdb at the same time. How do I do it? wxPython 2.8 doesn't support 64-bit (due to using Carbon), this is why the PyPM package is built for only 32-bit. You could try using wxPython 2.9. **Workaround** : remove wxpython using pypm (`pypm uninstall wxpython`), and then install the development cocoa binary `wxPython2.9-osx-cocoa-py2.7` from [wxpython.org](http://wxpython.org/download.php#unstable).