content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to execute JS from Python, that uses 'Document' and/or 'Window' I am currently working on getting JavaScript to execute successfully from within Python. I have implemented a JS engine (v8) using the PyV8 package. From here I can execute primitive JavaScript ("1+2", etc). However, for JavaScript that uses references to "document" or "window" the code will throw an error. I am looking, ideally, for a Python implementation however a JavaScript implementation would work as well as I could prepend it to my script before executing it what my JavaScript engine. To summarize: How can I execute JavaScript, that uses 'Document' and/or 'Window', from within JavaScript? A: I was having the same problem when using Spidermonkey (a command-line JavaScript interpreter) and trying to run a script that relied on the non-existent document and window objects. I solved it by using the Env-JS project, which sets up independent "fake" objects for them.
How to execute JS from Python, that uses 'Document' and/or 'Window'
I am currently working on getting JavaScript to execute successfully from within Python. I have implemented a JS engine (v8) using the PyV8 package. From here I can execute primitive JavaScript ("1+2", etc). However, for JavaScript that uses references to "document" or "window" the code will throw an error. I am looking, ideally, for a Python implementation however a JavaScript implementation would work as well as I could prepend it to my script before executing it what my JavaScript engine. To summarize: How can I execute JavaScript, that uses 'Document' and/or 'Window', from within JavaScript?
[ "I was having the same problem when using Spidermonkey (a command-line JavaScript interpreter) and trying to run a script that relied on the non-existent document and window objects.\nI solved it by using the Env-JS project, which sets up independent \"fake\" objects for them.\n" ]
[ 3 ]
[]
[]
[ "javascript", "python", "v8" ]
stackoverflow_0003182034_javascript_python_v8.txt
Q: Python - render HTML content to GIF image How can I render HTML content to GIF image? I found how to render it to PDF using reportlab, but no luck with GIF. I want something like xhtml2pdf.com but final result should be not in pdf, but in image. A: There's a similar SO question, Python library for rendering HTML and javascript , but I'm not sure the answers are satisfying. I might try two-stage rendering: HTML -> pdf -> gif. In that case, reportlab gets you pdf, and PythonMagick (http://wiki.python.org/moin/ImageMagick) can convert the pdf to GIF.
Python - render HTML content to GIF image
How can I render HTML content to GIF image? I found how to render it to PDF using reportlab, but no luck with GIF. I want something like xhtml2pdf.com but final result should be not in pdf, but in image.
[ "There's a similar SO question, Python library for rendering HTML and javascript , but I'm not sure the answers are satisfying.\nI might try two-stage rendering: HTML -> pdf -> gif. In that case, reportlab gets you pdf, and PythonMagick (http://wiki.python.org/moin/ImageMagick) can convert the pdf to GIF.\n" ]
[ 2 ]
[]
[]
[ "gif", "html", "python" ]
stackoverflow_0003159367_gif_html_python.txt
Q: Django File Uploads and Model FileField I'm sooo close... but I don't quite see the connection from the upload view to the model. When I use the callback in the model's FileField the upload works, but I'm not sure where the actual file copy is taking place. The goal is to make sure that chunking is happening, but the file copy action seems to be hidden somewhere? Here's what I have: Model: def get_media_upload_dir(instance, filename): user_id = instance.user.id upload_dir = "%s/%d/%s" % (settings.MEDIA_ROOT, user_id, filename) print "Upload dir set to: %s" % upload_dir return upload_dir class MediaFile(models.Model): media_file = models.FileField(upload_to=get_media_upload_dir) download_count = models.PositiveIntegerField(default=0) View: def file_upload(request, course_id): if request.method == 'POST': form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): uploaded = form.cleaned_data['file_upload'] mediaFile = MediaFile(media_file=uploaded, owner=request.user.profile, creator=request.user.profile) mediaFile.save() return HttpResponseRedirect('/course/%s/' % course_id) else: form = FileUploadForm() return render_to_response('course/file_upload.html', {'form':form,'course':course}, context_instance=RequestContext(request)) A: The storing happens here: http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/files.py#L90. Django uses it's own API for accessing the file storage: http://docs.djangoproject.com/en/dev/ref/files/storage/. But if chunking is what you need you can go with Bartek's proposal!
Django File Uploads and Model FileField
I'm sooo close... but I don't quite see the connection from the upload view to the model. When I use the callback in the model's FileField the upload works, but I'm not sure where the actual file copy is taking place. The goal is to make sure that chunking is happening, but the file copy action seems to be hidden somewhere? Here's what I have: Model: def get_media_upload_dir(instance, filename): user_id = instance.user.id upload_dir = "%s/%d/%s" % (settings.MEDIA_ROOT, user_id, filename) print "Upload dir set to: %s" % upload_dir return upload_dir class MediaFile(models.Model): media_file = models.FileField(upload_to=get_media_upload_dir) download_count = models.PositiveIntegerField(default=0) View: def file_upload(request, course_id): if request.method == 'POST': form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): uploaded = form.cleaned_data['file_upload'] mediaFile = MediaFile(media_file=uploaded, owner=request.user.profile, creator=request.user.profile) mediaFile.save() return HttpResponseRedirect('/course/%s/' % course_id) else: form = FileUploadForm() return render_to_response('course/file_upload.html', {'form':form,'course':course}, context_instance=RequestContext(request))
[ "The storing happens here: http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/files.py#L90. Django uses it's own API for accessing the file storage: http://docs.djangoproject.com/en/dev/ref/files/storage/. But if chunking is what you need you can go with Bartek's proposal!\n" ]
[ 1 ]
[]
[]
[ "django", "file", "python", "upload" ]
stackoverflow_0003181574_django_file_python_upload.txt
Q: How do I make it so a two top level widgets can't be open simultaneously? I have a top level widget that is created when a button is pressed. How do I make it so when that same button is pressed again, while the top level widget is still open it simply moves the top level widget into focus? A: Imagine you have the following method in a class. This method is called when you press the button. You will also have an instance attribute defined in the __init__ method: self.toplevel = None. def button_press(self): if self.toplevel is None: self.toplevel = ... # another method to create toplevel widget else: # set focus to self.toplevel # you can use self.toplevel.deiconify() if self.toplevel is minimised # also look at self.toplevel.lift() to bring the window to the top You will also need to reset self.toplevel to None when the toplevel widget is destroyed. Also look at the focus_set method of widgets. You may have to set the take_focus attribute to True for a toplevel widget. But maybe you want to set the focus to a particular widget (eg a Textbox) on the toplevel widget.
How do I make it so a two top level widgets can't be open simultaneously?
I have a top level widget that is created when a button is pressed. How do I make it so when that same button is pressed again, while the top level widget is still open it simply moves the top level widget into focus?
[ "Imagine you have the following method in a class. This method is called when you press the button. You will also have an instance attribute defined in the __init__ method: self.toplevel = None.\ndef button_press(self):\n if self.toplevel is None:\n self.toplevel = ... # another method to create toplevel ...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003182198_python_tkinter.txt
Q: Retrieving flickr favorites I can't get this to work... what could be the problem? import flickrapi api_key = '1234...' flickr = flickrapi.FlickrAPI(api_key) user = '43699959@N02' favs = flickr.favorites_getPublicList(user_id = user) >>> favs.items() [('stat', 'ok')] >>> favs.text '\n' Where are my favorite photo's? Note: It does work via this testing page: http://www.flickr.com/services/api/explore/?method=flickr.favorites.getPublicList A: The result is correct -- as per the URL you gave, the XML nodes are empty (plus/minus newline and whitespace characters, apparently). favs.text would return the content, but what you're looking for is in the attributes. Try this: for photo in favs.find('photos').findall('photo'): print photo.get('id') Result: '445267544' '3334987037' Or for all child nodes, starting from the root: for elm in favs.getiterator(): print elm.items() Result: [('stat', 'ok')] [('total', '2'), ('perpage', '100'), ('page', '1'), ('pages', '1')] [('isfamily', '0'), ('title', 'The Giants of Africa'), ('farm', '1'), ('ispublic', '1'), ('server', '218'), ('isfriend', '0'), ('secret', '992df924aa'), ('owner', '49746597@N00'), ('id', '445267544'), ('date_faved', '1273873654')] [('isfamily', '0'), ('title', 'Lava Light - Maui, Hawaii'), ('farm', '4'), ('ispublic', '1'), ('server', '3401'), ('isfriend', '0'), ('secret', '2fa1856916'), ('owner', '7765891@N08'), ('id', '3334987037'), ('date_faved', '1273873515')]
Retrieving flickr favorites
I can't get this to work... what could be the problem? import flickrapi api_key = '1234...' flickr = flickrapi.FlickrAPI(api_key) user = '43699959@N02' favs = flickr.favorites_getPublicList(user_id = user) >>> favs.items() [('stat', 'ok')] >>> favs.text '\n' Where are my favorite photo's? Note: It does work via this testing page: http://www.flickr.com/services/api/explore/?method=flickr.favorites.getPublicList
[ "The result is correct -- as per the URL you gave, the XML nodes are empty (plus/minus newline and whitespace characters, apparently). favs.text would return the content, but what you're looking for is in the attributes. Try this:\nfor photo in favs.find('photos').findall('photo'):\n print photo.get('id')\n\nRes...
[ 4 ]
[]
[]
[ "api", "flickr", "python" ]
stackoverflow_0003182269_api_flickr_python.txt
Q: What is a good first-implementation for learning machine learning? I find learning new topics comes best with an easy implementation to code to get the idea. This is how I learned genetic algorithms and genetic programming. What would be some good introductory programs to write to get started with machine learning? Preferably, let any referenced resources be accessible online so the community can benefit A: What language(s) will you develop in? If you are flexible, I recommend Matlab, python and R as good candidates. These are some of the more common languages used to develop and evaluate algorithms. They facilitate rapid algorithm development and evaluation, data manipulation and visualization. Most of the popular ML algorithms are also available as libraries (with source). I'd start by focusing on basic classification and/or clustering exercises in R2. It's easier to visualize, and it's usually sufficient for exploring issues in ML, like risk, class imbalance, noisy labels, online vs. offline training, etc. Create a data set from everyday life, or a problem you are interested in. Or use a classic, like the Iris data set, so you can compare your progress to published literature. You can find the Iris data set at: http://en.wikipedia.org/wiki/Iris_flower_data_set , or http://archive.ics.uci.edu/ml/datasets/Iris One of its nice features is that it has one class, 'setosa', that is easily linearly separable from the others. Once you pick a couple of interesting data sets, begin by implementing some standard classifiers and examining their performance. This is a good short list of classifiers to learn: k-nearest neighbors linear discriminant analysis decision trees (e.g., C4.5) support vector machines (e.g., via LibSVM) boosting (with stumps) naive bayes classifier With the Iris data set and one of the languages I mention, you can easily do a mini-study using any of the classifiers quickly (minutes to hours, depending on your speed). Edit: You can google "Iris data classification" to find lots of examples. Here is a classification demo document by Mathworks using Iris data set: http://www.mathworks.com/products/statistics/demos.html?file=/products/demos/shipping/stats/classdemo.html A: I think you can write a "Naive Bayes" classifier for junk email filtering. You can get a lot of information from this book. http://nlp.stanford.edu/IR-book/information-retrieval-book.html A: Decision tree. It is frequently used in classification tasks and has a lot of variants. Tom Mitchell's book is a good reference to implement it. A: Neural nets may be the easiest thing to implement first, and they're fairly thoroughly covered throughout literature.
What is a good first-implementation for learning machine learning?
I find learning new topics comes best with an easy implementation to code to get the idea. This is how I learned genetic algorithms and genetic programming. What would be some good introductory programs to write to get started with machine learning? Preferably, let any referenced resources be accessible online so the community can benefit
[ "What language(s) will you develop in? If you are flexible, I recommend Matlab, python and R as good candidates. These are some of the more common languages used to develop and evaluate algorithms. They facilitate rapid algorithm development and evaluation, data manipulation and visualization. Most of the popul...
[ 12, 4, 1, 1 ]
[ "There is something called books; are you familiar with those? When I was exploring AI two decades ago, there were many books. I guess now that the internet exists, books are archaic, but you can probably find some in an ancient library.\n" ]
[ -8 ]
[ "artificial_intelligence", "computer_science", "machine_learning", "python" ]
stackoverflow_0003176967_artificial_intelligence_computer_science_machine_learning_python.txt
Q: add append update and extend in python Is there an article or forum discussion or something somewhere that explains why lists use append/extend but sets and dicts use add/update. I frequently find myself converting lists into sets and this difference makes that quite tedious so for my personal sanity I'd like to know what the rationalization is. The need to convert between these occurs regularly as we iterate on development. Over time as the structure of the program morphs various structures gain and lose requirements like ordering and duplicates. For example something that starts out as an unordered bunch of stuff in a list might pick up the the requirement that there be no duplicates and so need to be converted to a set. All such changes require finding and changing all places where the relevant structure is added/appended and extended/updated. So I'm curious to see the original discussion that led to this language choice, unfortunately I've had no luck googling for it. A: append has a popular definition of "add to the very end", and extend can be read similarly (in the nuance where it means "...beyond a certain point"); sets have no "end", nor any way to specify some "point" within them or "at their boundaries" (because there are no "boundaries"!), so it would be highly misleading to suggest that these operations could be performed. x.append(y) always increases len(x) by exactly one (whether y was already in list x or not); no such assertion holds for s.add(z) (s's length may increase or stay the same). Moreover, in these snippets, y can have any value (i.e., the append operation never fails [except for the anomalous case in which you've run out of memory]) -- again no such assertion holds about z (which must be hashable, otherwise the add operation fails and raises an exception). Similar differences apply to extend vs update. Using the same name for operations with such drastically different semantics would be very misleading indeed. it seems pythonic to just use a list on the first pass and deal with the performance on a later iteration Performance is the least of it! lists support duplicate items, ordering, and any item type -- sets guarantee item uniqueness, have no concept of order, and demand item hashability. There is nothing Pythonic in using a list (plus goofy checks against duplicates, etc) to stand for a set -- performance or not, "say what you mean!" is the Pythonic Way;-). (In languages such as Fortran or C, where all you get as a built-in container type are arrays, you might have to perform such "mental mapping" if you need to avoid using add-on libraries; in Python, there is no such need). Edit: the OP asserts in a comment that they don't know from the start (e.g.) that duplicates are disallowed in a certain algorithm (strange, but, whatever) -- they're looking for a painless way to make a list into a set once they do discover duplicates are bad there (and, I'll add: order doesn't matter, items are hashable, indexing/slicing unneeded, etc). To get exactly the same effect one would have if Python's sets had "synonyms" for the two methods in question: class somewhatlistlikeset(set): def append(self, x): self.add(x) def extend(self, x): self.update(x) Of course, if the only change is at the set creation (which used to be list creation), the code may be much more challenging to follow, having lost the useful clarity whereby using add vs append allows anybody reading the code to know "locally" whether the object is a set vs a list... but this, too, is part of the "exactly the same effect" above-mentioned!-) A: set and dict are unordered. "Append" and "extend" conceptually only apply to ordered types. A: It's written that way to annoy you. Seriously. It's designed so that one can't simply convert one into the other easily. Historically, sets are based off dicts, so the two share naming conventions. While you could easily write a set wrapper to add these methods ... class ListlikeSet(set): def append(self, x): self.add(x) def extend(self, xs): self.update(xs) ... the greater question is why you find yourself converting lists to sets with such regularity. They represent substantially different models of a collection of objects; if you have to convert between the two a lot, it suggests you may not have a very good handle on the conceptual architecture of your program.
add append update and extend in python
Is there an article or forum discussion or something somewhere that explains why lists use append/extend but sets and dicts use add/update. I frequently find myself converting lists into sets and this difference makes that quite tedious so for my personal sanity I'd like to know what the rationalization is. The need to convert between these occurs regularly as we iterate on development. Over time as the structure of the program morphs various structures gain and lose requirements like ordering and duplicates. For example something that starts out as an unordered bunch of stuff in a list might pick up the the requirement that there be no duplicates and so need to be converted to a set. All such changes require finding and changing all places where the relevant structure is added/appended and extended/updated. So I'm curious to see the original discussion that led to this language choice, unfortunately I've had no luck googling for it.
[ "append has a popular definition of \"add to the very end\", and extend can be read similarly (in the nuance where it means \"...beyond a certain point\"); sets have no \"end\", nor any way to specify some \"point\" within them or \"at their boundaries\" (because there are no \"boundaries\"!), so it would be highly...
[ 6, 3, 2 ]
[]
[]
[ "dictionary", "list", "python", "set" ]
stackoverflow_0003182760_dictionary_list_python_set.txt
Q: Displaying other language characters in PyQt Is there a way to display other language characters in PyQt4? and if there is, what's the approach/direction that I should take? Thanks in advance. A: Qt uses Unicode and should be able to display (Unicode) text in any language you have a suitable font for. For example, Roberto Alesina's simple "Hello World" program on the PyQt Wiki -- which I transcribe for readability (and w/o the comments for brevity) since it's pretty unreadable in the wiki -- should let you use as the button's text any such Unicode text (so I've taken the liberty of translating it so it uses an accented letter;-)...: # -*- coding: utf-8 -*- # (or w/ever other coding you use for unicode literals;-) import qt, sys a=qt.QApplication(sys.argv) w=qt.QPushButton(u"Olá Mundo", None) w.show() a.exec_loop()
Displaying other language characters in PyQt
Is there a way to display other language characters in PyQt4? and if there is, what's the approach/direction that I should take? Thanks in advance.
[ "Qt uses Unicode and should be able to display (Unicode) text in any language you have a suitable font for. For example, Roberto Alesina's simple \"Hello World\" program on the PyQt Wiki -- which I transcribe for readability (and w/o the comments for brevity) since it's pretty unreadable in the wiki -- should let ...
[ 5 ]
[]
[]
[ "pyqt", "pyqt4", "python", "unicode" ]
stackoverflow_0003183044_pyqt_pyqt4_python_unicode.txt
Q: Any reason not to modify another class's variables? Forms have Fields. Fields have a Widget. If a Field name is omitted, it takes the variable name specified in the form. For example, MyForm(Form): username = Field(name=None, widget=MyWidget(args)) The field name would become "username". However, this can't be established until the form is constructed. Would it be so awful to set the field.name attribute inside the form initializer, but after the field has already been constructed? Similarly, would it be so awful to set some field.widget.xxx attributes inside the form initializer to "pass in" some variables that are used in various functions inside the widget class? Or should I explicitly pass them in to each and every function call? Why? A: Some OO purists might perhaps object, but IMHO there is really no problem in setting public attributes in instances of other classes -- worst case, if later on you find that instance needs to take some action when certain attributes are set, you'll just turn the attribute into a property, so that a "setter method" is automatically called when the attribute is assigned to (just make sure to always use new style classes -- e.g. by inheriting from object when a class would otherwise have no bases -- so that property works properly when you need it!-).
Any reason not to modify another class's variables?
Forms have Fields. Fields have a Widget. If a Field name is omitted, it takes the variable name specified in the form. For example, MyForm(Form): username = Field(name=None, widget=MyWidget(args)) The field name would become "username". However, this can't be established until the form is constructed. Would it be so awful to set the field.name attribute inside the form initializer, but after the field has already been constructed? Similarly, would it be so awful to set some field.widget.xxx attributes inside the form initializer to "pass in" some variables that are used in various functions inside the widget class? Or should I explicitly pass them in to each and every function call? Why?
[ "Some OO purists might perhaps object, but IMHO there is really no problem in setting public attributes in instances of other classes -- worst case, if later on you find that instance needs to take some action when certain attributes are set, you'll just turn the attribute into a property, so that a \"setter method...
[ 3 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0003183150_design_patterns_python.txt
Q: reading file data mixing strings and numbers in python I would like to read different files in one directory with the following structure: # Mj = 1.60 ff = 7580.6 gg = 0.8325 I would like to read the numbers from each file and associate every one to a vector. If we assume I have 3 files, I will have 3 components for vector Mj, ... How can I do it in Python? Thanks for your help. A: I'd use a regular expression to take the line apart: import re lineRE = re.compile(r''' \#\s* Mj\s*=\s*(?P<Mj>[-+0-9eE.]+)\s* ff\s*=\s*(?P<ff>[-+0-9eE.]+)\s* gg\s*=\s*(?P<gg>[-+0-9eE.]+) ''', re.VERBOSE) for filename in filenames: for line in file(filename, 'r'): m = lineRE.match(line) if not m: continue Mj = m.group('Mj') ff = m.group('ff') gg = m.group('gg') # Put them in whatever lists you want here. A: Here's a pyparsing solution that might be easier to manage than a regex solution: text = "# Mj = 1.60 ff = 7580.6 gg = 0.8325 " from pyparsing import Word, nums, Literal # subexpression for a real number, including conversion to float realnum = Word(nums+"-+.E").setParseAction(lambda t:float(t[0])) # overall expression for the full line of data linepatt = (Literal("#") + "Mj" + "=" + realnum("Mj") + "ff" + "=" + realnum("ff") + "gg" + "=" + realnum("gg")) # use '==' to test for matching line pattern if text == linepatt: res = linepatt.parseString(text) # dump the matched tokens and all named results print res.dump() # access the Mj data field print res.Mj # use results names with string interpolation to print data fields print "%(Mj)f %(ff)f %(gg)f" % res Prints: ['#', 'Mj', '=', 1.6000000000000001, 'ff', '=', 7580.6000000000004, 'gg', '=', 0.83250000000000002] - Mj: 1.6 - ff: 7580.6 - gg: 0.8325 1.6 1.600000 7580.600000 0.832500
reading file data mixing strings and numbers in python
I would like to read different files in one directory with the following structure: # Mj = 1.60 ff = 7580.6 gg = 0.8325 I would like to read the numbers from each file and associate every one to a vector. If we assume I have 3 files, I will have 3 components for vector Mj, ... How can I do it in Python? Thanks for your help.
[ "I'd use a regular expression to take the line apart:\nimport re\nlineRE = re.compile(r'''\n \\#\\s*\n Mj\\s*=\\s*(?P<Mj>[-+0-9eE.]+)\\s*\n ff\\s*=\\s*(?P<ff>[-+0-9eE.]+)\\s*\n gg\\s*=\\s*(?P<gg>[-+0-9eE.]+)\n ''', re.VERBOSE)\n\nfor filename in filenames:\n for line in file(filename, 'r'):\n ...
[ 1, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003181460_file_io_python.txt
Q: Using python function callbacks with PyObjC? I'm trying to use an Objective-C class made in Python to do this but Objective-C can't call the method which calls the python function. Here's the framework code which the Objective-C code: // // scalelib.h // Scalelib Cocoa Framework // // Created by Matthew Mitchell on 04/07/2010. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import <Cocoa/Cocoa.h> @interface Game : NSObject { id current_pyfunc; } -(void) addPyFunc: (id) pyfunc; -(void) callPyFunc; @end // // scalelib.m // Scalelib Cocoa Framework // // Created by Matthew Mitchell on 04/07/2010. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import "Game.h" @implementation Game -(void) addPyFunc: (id) pyfunc{ current_pyfunc = pyfunc; } -(void) callPyFunc{ [current_pyfunc call]; //Segmentation fault. Method doesn't exist for some reason. } @end Here is the python script which loads the framework and tests the use of callbacks with failure. #!/usr/bin/env python2.3 from objc import * import os,sys loadBundle("Scalelib Cocoa Framework",globals(),os.path.dirname(sys.argv[0]) + "/Scalelib Cocoa Framework/build/Release/Scalelib Cocoa Framework.framework/") class PythonCallback(NSObject): def setCallback_withArgs_(self, python_function,args): #Python initialisation of class, add the callback function and arguments self.python_function = python_function self.args = args return self def call(self): #Used by Objective-C to call python function self.python_function(*self.args) def create_callback(function,args): return PythonCallback.alloc().init().setCallback_withArgs_(function,args) def square(num): print num**2 instance = Game.alloc().init() callback = create_callback(square,[3]) callback.call() instance.addPyFunc_(create_callback(square,[5])) instance.callPyFunc() I get the output: 9 Segmentation fault The segmentation fault is because the call method made in python doesn't exist apparently. So how to I make it exist for Objective-C? Even if the code did work it would be useless but I'm only testing things at the moment. Once I have the callbacks working, I'll be able to make my library for python. Thank you for any help. A: My guess would be retain counts. You don't retain the result of create_callback() that you pass into the addPyFunc_ As such, it probably gets garbage collected away before you call it.
Using python function callbacks with PyObjC?
I'm trying to use an Objective-C class made in Python to do this but Objective-C can't call the method which calls the python function. Here's the framework code which the Objective-C code: // // scalelib.h // Scalelib Cocoa Framework // // Created by Matthew Mitchell on 04/07/2010. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import <Cocoa/Cocoa.h> @interface Game : NSObject { id current_pyfunc; } -(void) addPyFunc: (id) pyfunc; -(void) callPyFunc; @end // // scalelib.m // Scalelib Cocoa Framework // // Created by Matthew Mitchell on 04/07/2010. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import "Game.h" @implementation Game -(void) addPyFunc: (id) pyfunc{ current_pyfunc = pyfunc; } -(void) callPyFunc{ [current_pyfunc call]; //Segmentation fault. Method doesn't exist for some reason. } @end Here is the python script which loads the framework and tests the use of callbacks with failure. #!/usr/bin/env python2.3 from objc import * import os,sys loadBundle("Scalelib Cocoa Framework",globals(),os.path.dirname(sys.argv[0]) + "/Scalelib Cocoa Framework/build/Release/Scalelib Cocoa Framework.framework/") class PythonCallback(NSObject): def setCallback_withArgs_(self, python_function,args): #Python initialisation of class, add the callback function and arguments self.python_function = python_function self.args = args return self def call(self): #Used by Objective-C to call python function self.python_function(*self.args) def create_callback(function,args): return PythonCallback.alloc().init().setCallback_withArgs_(function,args) def square(num): print num**2 instance = Game.alloc().init() callback = create_callback(square,[3]) callback.call() instance.addPyFunc_(create_callback(square,[5])) instance.callPyFunc() I get the output: 9 Segmentation fault The segmentation fault is because the call method made in python doesn't exist apparently. So how to I make it exist for Objective-C? Even if the code did work it would be useless but I'm only testing things at the moment. Once I have the callbacks working, I'll be able to make my library for python. Thank you for any help.
[ "My guess would be retain counts.\nYou don't retain the result of create_callback() that you pass into the addPyFunc_\nAs such, it probably gets garbage collected away before you call it.\n" ]
[ 2 ]
[]
[]
[ "cocoa", "objective_c", "pyobjc", "python", "segmentation_fault" ]
stackoverflow_0003180385_cocoa_objective_c_pyobjc_python_segmentation_fault.txt
Q: Where to store field data and how to provide access to it? Forms have Fields, Fields have a value. However, they only get a value after the form has been submitted. How should I store this value? Should I give every field a value attribute, field.value, leave it as None prior to posting, and fill it in afterwords? Omit it completely, and dynamically add it? Store it on the form instead, like form.data['field']. Create a a wrapper class FieldWithData to avoid any inconsistent states (if you have an object of this type, you know it has data) and allows me to set the data in the initializer rather than accessing attributes directly (although I guess this isn't so different from using a setter) How should I provide access to the field data through the Form object? Options: form.fields['name'].value (how it's presently being stored internally) form.data['field'] (create a proxy "data" class that retrieves the real data off the field, or re-arrange the internals to actually store the data like this) form.field.value - looks fairly nice, but then I'd have two references to the same field, one as form.field and one as form.fields['field'] which I need internally so that I can iterate over them Too many design decisions. Driving me nuts. This is what sucks about solo'ing a project. A: It really depends on how you interact with the structures in question. Do you manipulate Form and Field objects prior to assigning them values? Do you need to frequently iterate over all the given Fields? Do you need Form once it's been submitted? Etc. I'd suggest writing some/all of the code that uses Form and figure out how you want to interact with Form data, and what your ideal interface would look like. A: I would keep a form's definition and the form's values from submission separate. I.e. I would not have a value attribute on the Field(Definition) objects. To work with submitted values, I would probably use a dict. You could let the Form class handle the creation of this dict: # assuming my_form is a Form object and request represents the HTTP request form_values = my_form.values_from_request(request) print(form_values["Name"]) The values_from_request method would iterate through the Form's Field(Definition)s to get the submitted data from the HTTP request. The method could also do stuff like validation and data type conversion.
Where to store field data and how to provide access to it?
Forms have Fields, Fields have a value. However, they only get a value after the form has been submitted. How should I store this value? Should I give every field a value attribute, field.value, leave it as None prior to posting, and fill it in afterwords? Omit it completely, and dynamically add it? Store it on the form instead, like form.data['field']. Create a a wrapper class FieldWithData to avoid any inconsistent states (if you have an object of this type, you know it has data) and allows me to set the data in the initializer rather than accessing attributes directly (although I guess this isn't so different from using a setter) How should I provide access to the field data through the Form object? Options: form.fields['name'].value (how it's presently being stored internally) form.data['field'] (create a proxy "data" class that retrieves the real data off the field, or re-arrange the internals to actually store the data like this) form.field.value - looks fairly nice, but then I'd have two references to the same field, one as form.field and one as form.fields['field'] which I need internally so that I can iterate over them Too many design decisions. Driving me nuts. This is what sucks about solo'ing a project.
[ "It really depends on how you interact with the structures in question. Do you manipulate Form and Field objects prior to assigning them values? Do you need to frequently iterate over all the given Fields? Do you need Form once it's been submitted? Etc.\nI'd suggest writing some/all of the code that uses Form and f...
[ 1, 1 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0003183431_design_patterns_python.txt
Q: Unable to modify a global int, but can modify a list. How? LISTL = [] VAR1 = 0 def foo(): ... VAR1 += 1 ... return VAR1 ... On calling foo(), I get this error: UnboundLocalError: local variable 'VAR1' referenced before assignment However, consider the list LISTL >>> def foo(x): ... LISTL.append(x) ... return LISTL ... >>> foo(5) [5] This works as expected. The question is why the append on a list works but I can't change the int? Also, is this the right way to declare a global in Python? (Right after the import statements) A: The reason for this difference has to do with how Python namespaces the names. If you're inside a function definition (def foo():), and you ACCESS a name (VAR1 or LISTL), it will first search your local namespace, where it will find nothing, and then it will search the namespace of the module the function was defined in, all the way up to the global namespace until it finds a match, or fails. However, ACCESSING a name, and ASSIGNING a name, are two different concepts. If you're again within your function definition, and you say VAR1 = 2, you're declaring a new variable with the new local name VAR1 inside the function. This makes sense if you consider that otherwise you would encounter all sorts of naming collisions if there was no such namespacing at work. When you append to a list, you are merely ACCESSING the list, and then calling a method on it which happens to change its conceptual value. When you use do +=, you're actually ASSIGNING a value to a name. If you would like to be able to assign values to names defined outside of the current namespace, you can use the global keyword. In that case, within your function, you would first say global VAR1, and from there the name VAR1 would be the name in the outer namespace, and any assignments to it would take effect outside of the function. A: If you assign to a variable within a function, that variable is assumed to be local unless you declare it global.
Unable to modify a global int, but can modify a list. How?
LISTL = [] VAR1 = 0 def foo(): ... VAR1 += 1 ... return VAR1 ... On calling foo(), I get this error: UnboundLocalError: local variable 'VAR1' referenced before assignment However, consider the list LISTL >>> def foo(x): ... LISTL.append(x) ... return LISTL ... >>> foo(5) [5] This works as expected. The question is why the append on a list works but I can't change the int? Also, is this the right way to declare a global in Python? (Right after the import statements)
[ "The reason for this difference has to do with how Python namespaces the names. If you're inside a function definition (def foo():), and you ACCESS a name (VAR1 or LISTL), it will first search your local namespace, where it will find nothing, and then it will search the namespace of the module the function was defi...
[ 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003183633_python.txt
Q: How do I upload data to Google App Engine periodically? I'm writing an aggregation application which scrapes data from a couple of web sources and displays that data with a novel interface. The sites from which I'm scraping update every couple of minutes, and I want to make sure the data on my aggregator is up-to-date. What's the best way to periodically submit fresh data to my App Engine application from an automated script? Constraints: The application is written in Python. The scraping process for each site takes longer than one second, thus I cannot process the data in an App Engine handler. The host on which the updater script would run is shared, so I'd rather not store my password on disk. I'd like to check the code for the application into to our codebase. While my associates aren't malicious, they're pranksters, and I'd like to prevent them from inserting fake data into my app. I'm aware that App Engine supports some remote_api thingey, but I'd have to put that entry point behind authentication (see constraint 3) or hide the URL (see constraint 4). Suggestions? A: Write a Task Queue task or an App Engine cron job to handle this. I'm not sure where you heard that there's a limit of 1 second on any sort of App Engine operations - requests are limited to 30 seconds, and URL fetches have a maximum deadline of 10 seconds. A: The only way to get data into AppEngine is to call up a Web app of yours (as a Web app) and feed it data through the usual HTTP-ish means, i.e. as parameters to a GET request (for short data) or to a POST (if long or binary). In other words, you'll have to craft your own little dataloader, which you will access as a Web app and which will in turn stash the data into the database behind AppEngine. You'll probably want at least password protection on that app so nobody loads bogus data into your app. A: Can you break up the scraping process into independent chunks that can each finish in the timeframe of an appengine request? (which can run longer than one second btw). Then you can just spawn a bunch of tasks using the task API that when combined, accomplish the full scrape. Then use the cron API to spawn off those tasks every N minutes. A: I asked around and some friends came up with two solutions: Upload a file with a shared secret token along with the application, but when committing to the codebase, change the token. Create a small datastore model with one row, a secret token. In both cases the token can be used to authenticate POST requests used to upload new data. A: App engine has tools to upload data. Refer to http://code.google.com/appengine/docs/python/tools/uploadingdata.html
How do I upload data to Google App Engine periodically?
I'm writing an aggregation application which scrapes data from a couple of web sources and displays that data with a novel interface. The sites from which I'm scraping update every couple of minutes, and I want to make sure the data on my aggregator is up-to-date. What's the best way to periodically submit fresh data to my App Engine application from an automated script? Constraints: The application is written in Python. The scraping process for each site takes longer than one second, thus I cannot process the data in an App Engine handler. The host on which the updater script would run is shared, so I'd rather not store my password on disk. I'd like to check the code for the application into to our codebase. While my associates aren't malicious, they're pranksters, and I'd like to prevent them from inserting fake data into my app. I'm aware that App Engine supports some remote_api thingey, but I'd have to put that entry point behind authentication (see constraint 3) or hide the URL (see constraint 4). Suggestions?
[ "Write a Task Queue task or an App Engine cron job to handle this. I'm not sure where you heard that there's a limit of 1 second on any sort of App Engine operations - requests are limited to 30 seconds, and URL fetches have a maximum deadline of 10 seconds.\n", "The only way to get data into AppEngine is to call...
[ 3, 0, 0, 0, 0 ]
[]
[]
[ "automation", "google_app_engine", "python", "security" ]
stackoverflow_0001689570_automation_google_app_engine_python_security.txt
Q: Python and C coupling I tried loading C shared library .so in Python using ctypes.CDLL class (Linux). Here is the link to which tells what I did. As I see the documentation it says CDLL class assumes that function returns int types. I've a doubt here what if I need to return variable of type other than the int type from a function in C?. And to what extent we can use C functions in Python i mean what are the limits/restrictions on using C shared libraries and functions Thanks in Advance A: By default, it assumes int, but you can set restype to any of the supported types to override that. E.g., from the docs: strchr.restype = c_char_p This means that strchr returns a pointer to a char, which corresponds to a Python string (or None, for a NULL pointer).
Python and C coupling
I tried loading C shared library .so in Python using ctypes.CDLL class (Linux). Here is the link to which tells what I did. As I see the documentation it says CDLL class assumes that function returns int types. I've a doubt here what if I need to return variable of type other than the int type from a function in C?. And to what extent we can use C functions in Python i mean what are the limits/restrictions on using C shared libraries and functions Thanks in Advance
[ "By default, it assumes int, but you can set restype to any of the supported types to override that. E.g., from the docs:\nstrchr.restype = c_char_p\n\nThis means that strchr returns a pointer to a char, which corresponds to a Python string (or None, for a NULL pointer).\n" ]
[ 4 ]
[]
[]
[ "c", "python" ]
stackoverflow_0003183740_c_python.txt
Q: Calling custom Objective-C from a pyobjc application? This question is basically the inverse of this other question: Calling Python from Objective-C I have implemented my iPhone application logic in Objective-C (obviously), and am now trying to re-use as much as possible from my XCode project in the server component to save on double-implementation. I have successfully loaded the CoreData data model from Python, however, can't see a way to actually call into the Objective-C logic from Python. Basically I'm trying to access the Objective-C classes and methods in my iPhone project from Python to save myself duping out all the implementations. Is this even vaguely possible, or is dupe-implementation the only solution here? Seems like the kind of thing Boost::Python might be used for, but I'm not really sure. edit: Boost::Python won't work because it is C++ based and I need Objective-C. I knew there was a reason why that didn't work. A: If your Objective-C code is in a framework and you would like to essentially write a Python application that uses your framework, then you can use objc.loadBundle, and then use objc.lookUpClass or NSClassFromString to get access to your classes. From there, you can use your classes like any other bridged Objective-C class. If you're running your Python code within a process that already has the Objective-C runtime up, and your classes are already registered with it, then you can skip the loadBundle step.
Calling custom Objective-C from a pyobjc application?
This question is basically the inverse of this other question: Calling Python from Objective-C I have implemented my iPhone application logic in Objective-C (obviously), and am now trying to re-use as much as possible from my XCode project in the server component to save on double-implementation. I have successfully loaded the CoreData data model from Python, however, can't see a way to actually call into the Objective-C logic from Python. Basically I'm trying to access the Objective-C classes and methods in my iPhone project from Python to save myself duping out all the implementations. Is this even vaguely possible, or is dupe-implementation the only solution here? Seems like the kind of thing Boost::Python might be used for, but I'm not really sure. edit: Boost::Python won't work because it is C++ based and I need Objective-C. I knew there was a reason why that didn't work.
[ "If your Objective-C code is in a framework and you would like to essentially write a Python application that uses your framework, then you can use objc.loadBundle, and then use objc.lookUpClass or NSClassFromString to get access to your classes. From there, you can use your classes like any other bridged Objective...
[ 1 ]
[]
[]
[ "iphone", "objective_c", "pyobjc", "python" ]
stackoverflow_0003180574_iphone_objective_c_pyobjc_python.txt
Q: Using variables in Django urlpatterns The components of the URLs of the Django app I'm working on are very 'pluggable', and different combinations of them get used in various urlpatterns, so our urls.py looks something like: rev = r'(/R\.(?P<rev>\d+))?' repo_type= r'^(?P<repo_type>svn|hg)/' path = r'/dir/(?P<path>.*)$' # etc. urlpatterns = patterns('', (repo_type_param + r'view-source' + opt_rev_param + path_param, view_source), (repo_type_param + r'history' + path_param, history), (repo_type_param + r'revision' + opt_rev_param + r'/$', revision), ) #etc. Which seems like a nice way to keep things clean. However, I found I kept getting NoReverseMatch errors when I tried to reverse any of the views pointed to by the urlpatterns. After a lot of tinkering, I found that using the full raw string in the pattern, rather than concatenating the substrings, fixed the problem. So, is it really necessary to use only raw strings in urlpatterns? I couldn't find this documented anywhere. Bug or feature? Having to copy and paste regex patterns that get used repeatedly seems like a violation of DRY. A: I found that this pattern works for redirects and might help in your case (unless I am interpreting your question incorrectly). I couldn't reverse a pattern within the same tuple but if I defined a new tuple and then concatenated a new tuple to the original Djanogo would reflect without issue. ex: urlpatterns = patterns('', ('^foo/$','foo.views.foo') ) urlpatterns+= patterns('',('^$','django.views.generic.simple.redirect_to',{'url':reverse('foo.views.foo')})) A: I'm not sure about concatenation, but I know you can format raw strings and use them in urlpatterns. See BlogView.urlpatterns for an example. A: You can use a name to identify your url pattern like this: urlpatterns = patterns('', url(repo_type_param + r'view-source' + opt_rev_param + path_param, view_source, name='myurlname'), ) Note the url and name, and then reverse match like this: reverse('myurlname', kwargs={'groupname': 'value'}) Hope it helps
Using variables in Django urlpatterns
The components of the URLs of the Django app I'm working on are very 'pluggable', and different combinations of them get used in various urlpatterns, so our urls.py looks something like: rev = r'(/R\.(?P<rev>\d+))?' repo_type= r'^(?P<repo_type>svn|hg)/' path = r'/dir/(?P<path>.*)$' # etc. urlpatterns = patterns('', (repo_type_param + r'view-source' + opt_rev_param + path_param, view_source), (repo_type_param + r'history' + path_param, history), (repo_type_param + r'revision' + opt_rev_param + r'/$', revision), ) #etc. Which seems like a nice way to keep things clean. However, I found I kept getting NoReverseMatch errors when I tried to reverse any of the views pointed to by the urlpatterns. After a lot of tinkering, I found that using the full raw string in the pattern, rather than concatenating the substrings, fixed the problem. So, is it really necessary to use only raw strings in urlpatterns? I couldn't find this documented anywhere. Bug or feature? Having to copy and paste regex patterns that get used repeatedly seems like a violation of DRY.
[ "I found that this pattern works for redirects and might help in your case (unless I am interpreting your question incorrectly). I couldn't reverse a pattern within the same tuple but if I defined a new tuple and then concatenated a new tuple to the original Djanogo would reflect without issue.\nex:\n urlpatterns ...
[ 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003174174_django_python.txt
Q: Is it OK to exchange tuples between Python modules? I have a small Python program consisting of very few modules (about 4 or so). The main module creates a list of tuples, thereby representing a number of records. These tuples are available to the other modules through a simple function that returns them (say, get_records()). I am not sure if this is good design however. The problem being that the other modules need to know the indexes of each element in the tuple. This increases coupling between the modules, and isn't very transparent to someone who wants to use the main module. I can think of a couple of alternatives: Make the index values of the tuple elements available as module constants (e.g., IDX_RECORD_TITLE, IDX_RECORD_STARTDATE, etc.). This avoids the need of magic numbers like title = record[3]. Don't use tuples, but create a record class, and return a list of these class objects. The advantage being that the class methods will have self-explaining names like record.get_title(). Don't use tuples, but dictionaries instead. So in this scenario, the function would return a list of dictionaries. The advantage being that the dictionary keys are also self-explanatory (though someone using the module would need to know them). But this seems like a huge overhead. I find tuples to be one of the great strengths of Python (very easy to pass compound data around without the coding overhead of classes/objects), so I currently use (1), but still wonder what would be the best approach. A: http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields A: i do not see any overhead or complexity in passing objects over tuples(tuples are also objects) IMO if tuple serves your purpose easily use it, but as you have seen the constraints just switch to a class which represent your data cleanily e.g. class MyData(object): def __init__(self, title, desc): self.title = title self.desc = desc You need not add any getter or setter method . A: In those cases, I tend to use dictionaries. If only to have things easily understandable for myself when I come back a bit later to use the code. I don't know if it's a "huge overhead". I guess it depends on how often you do it and what it is used for. I start off with the easiest solution and optimize when I really need to. It surprisingly seldom I need to change something like that.
Is it OK to exchange tuples between Python modules?
I have a small Python program consisting of very few modules (about 4 or so). The main module creates a list of tuples, thereby representing a number of records. These tuples are available to the other modules through a simple function that returns them (say, get_records()). I am not sure if this is good design however. The problem being that the other modules need to know the indexes of each element in the tuple. This increases coupling between the modules, and isn't very transparent to someone who wants to use the main module. I can think of a couple of alternatives: Make the index values of the tuple elements available as module constants (e.g., IDX_RECORD_TITLE, IDX_RECORD_STARTDATE, etc.). This avoids the need of magic numbers like title = record[3]. Don't use tuples, but create a record class, and return a list of these class objects. The advantage being that the class methods will have self-explaining names like record.get_title(). Don't use tuples, but dictionaries instead. So in this scenario, the function would return a list of dictionaries. The advantage being that the dictionary keys are also self-explanatory (though someone using the module would need to know them). But this seems like a huge overhead. I find tuples to be one of the great strengths of Python (very easy to pass compound data around without the coding overhead of classes/objects), so I currently use (1), but still wonder what would be the best approach.
[ "http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields\n", "i do not see any overhead or complexity in passing objects over tuples(tuples are also objects)\nIMO if tuple serves your purpose easily use it, but as you have seen the constraints just switch to a clas...
[ 5, 4, 0 ]
[]
[]
[ "coupling", "python", "tuples" ]
stackoverflow_0003184089_coupling_python_tuples.txt
Q: Google App Engine with local Django 1.1 gets Intermittent Failures I'm using the Windows Launcher development environment for Google App Engine. I have downloaded Django 1.1.2 source, and un-tarrred the "django" subdirectory to live within my application directory (a peer of app.yaml) At the top of each .py source file, I do this: import settings import os os.environ["DJANGO_SETTINGS_MODULE"] = 'settings' In my file settings.py (which lives at the root of the app directory, as well), I do this: DEBUG = True TEMPLATE_DIRS = ('html') INSTALLED_APPS = ('filters') import os os.environ["DJANGO_SETTINGS_MODULE"] = 'settings' from google.appengine.dist import use_library use_library('django', '1.1') from django.template import loader Yes, this looks a bit like overkill, doesn't it? I only use django.template. I don't explicitly use any other part of django. However, intermittently I get one of two errors: 1) Django complains that DJANGO_SETTINGS_MODULE is not defined. 2) Django complains that common.html (a template I'm extending in other templates) doesn't exist. 95% of the time, these errors are not encountered, and they randomly just start happening. Once in that state, the local server seems "wedged" and re-booting it generally fixes it. What's causing this to happen, and what can I do about it? How can I even debug it? Here is the traceback from the error: Traceback (most recent call last): File "C:\code\kwbudget\edit_budget.py", line 34, in get self.response.out.write(t.render(template.Context(values))) File "C:\code\kwbudget\django\template\__init__.py", line 165, in render return self.nodelist.render(context) File "C:\code\kwbudget\django\template\__init__.py", line 784, in render bits.append(self.render_node(node, context)) File "C:\code\kwbudget\django\template\__init__.py", line 797, in render_node return node.render(context) File "C:\code\kwbudget\django\template\loader_tags.py", line 71, in render compiled_parent = self.get_parent(context) File "C:\code\kwbudget\django\template\loader_tags.py", line 66, in get_parent raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent TemplateSyntaxError: Template u'common.html' cannot be extended, because it doesn't exist And edit_budget.py starts with exactly the lines that I included up top. All templates live in a directory named "html" in my root directory, and "html/common.html" exists. I know the template engine finds them, because I start out with "html/edit_budget.html" which extends common.html. It looks as if the settings module somehow isn't applied (because that's what adds html to the search path for templates). A: Firstly, although django is now a LOT more compatible with app engine than it once, some major incompatibilities still exist between the two platforms, meaning that you can't just dump a stock copy of django into your appengine directory and have it work out of the box. Things will error in strange ways. There are a number of projects which aim to improve compatibility between the two projects, the most prominent is app-engine-patch. I highly suggest reading the following article http://code.google.com/appengine/articles/app-engine-patch.html and the rest of the articles located at code.google.com/appengine/articles/ under the django tab. as for some of you're specific problems, you could try this within your setup script: #setup django environment from django.core.management import setup_environ import settings setup_envion(settings) this is what django uses internally for setting up the environment within manage.py and is the accepted best practice for setting up django for use with scripts (like app engine). A: I'm having exactly the same issue, and I haven't been able to work around it... though I've noticed it happens a LOT less with the real GAE than it does with the development server I run on my Linux workstation.
Google App Engine with local Django 1.1 gets Intermittent Failures
I'm using the Windows Launcher development environment for Google App Engine. I have downloaded Django 1.1.2 source, and un-tarrred the "django" subdirectory to live within my application directory (a peer of app.yaml) At the top of each .py source file, I do this: import settings import os os.environ["DJANGO_SETTINGS_MODULE"] = 'settings' In my file settings.py (which lives at the root of the app directory, as well), I do this: DEBUG = True TEMPLATE_DIRS = ('html') INSTALLED_APPS = ('filters') import os os.environ["DJANGO_SETTINGS_MODULE"] = 'settings' from google.appengine.dist import use_library use_library('django', '1.1') from django.template import loader Yes, this looks a bit like overkill, doesn't it? I only use django.template. I don't explicitly use any other part of django. However, intermittently I get one of two errors: 1) Django complains that DJANGO_SETTINGS_MODULE is not defined. 2) Django complains that common.html (a template I'm extending in other templates) doesn't exist. 95% of the time, these errors are not encountered, and they randomly just start happening. Once in that state, the local server seems "wedged" and re-booting it generally fixes it. What's causing this to happen, and what can I do about it? How can I even debug it? Here is the traceback from the error: Traceback (most recent call last): File "C:\code\kwbudget\edit_budget.py", line 34, in get self.response.out.write(t.render(template.Context(values))) File "C:\code\kwbudget\django\template\__init__.py", line 165, in render return self.nodelist.render(context) File "C:\code\kwbudget\django\template\__init__.py", line 784, in render bits.append(self.render_node(node, context)) File "C:\code\kwbudget\django\template\__init__.py", line 797, in render_node return node.render(context) File "C:\code\kwbudget\django\template\loader_tags.py", line 71, in render compiled_parent = self.get_parent(context) File "C:\code\kwbudget\django\template\loader_tags.py", line 66, in get_parent raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent TemplateSyntaxError: Template u'common.html' cannot be extended, because it doesn't exist And edit_budget.py starts with exactly the lines that I included up top. All templates live in a directory named "html" in my root directory, and "html/common.html" exists. I know the template engine finds them, because I start out with "html/edit_budget.html" which extends common.html. It looks as if the settings module somehow isn't applied (because that's what adds html to the search path for templates).
[ "Firstly, although django is now a LOT more compatible with app engine than it once, some major incompatibilities still exist between the two platforms, meaning that you can't just dump a stock copy of django into your appengine directory and have it work out of the box. Things will error in strange ways.\nThere ar...
[ 1, 0 ]
[]
[]
[ "debugging", "django", "google_app_engine", "intermittent", "python" ]
stackoverflow_0002986258_debugging_django_google_app_engine_intermittent_python.txt
Q: Alternate host/IP for python script I want my Python script to access a URL through an IP specified in the script instead of through the default DNS for the domain. Basically I want the equivalent of adding an entry to my /etc/hosts file, but I want the change to apply only to my script instead of globally on the whole server. Any ideas? A: Whether this works or not will depend on whether the far end site is using HTTP/1.1 named-based virtual hosting or not. If they're not, you can simply replace the hostname part of the URL with their IP address, per @Greg's answer. If they are, however, you have to ensure that the correct Host: header is sent as part of the HTTP request. Without that, a virtual hosting web server won't know which site's content to give you. Refer to your HTTP client API (Curl?) to see if you can add or change default request headers. A: You can use an explicit IP number to connect to a specific machine by embedding that into the URL: http://127.0.0.1/index.html is equivalent to http://localhost/index.html That said, it isn't a good idea to use IP numbers instead of DNS entries. IPs change a lot more often than DNS entries, meaning your script has a greater chance of breaking if you hard-code the address instead of letting it resolve normally.
Alternate host/IP for python script
I want my Python script to access a URL through an IP specified in the script instead of through the default DNS for the domain. Basically I want the equivalent of adding an entry to my /etc/hosts file, but I want the change to apply only to my script instead of globally on the whole server. Any ideas?
[ "Whether this works or not will depend on whether the far end site is using HTTP/1.1 named-based virtual hosting or not.\nIf they're not, you can simply replace the hostname part of the URL with their IP address, per @Greg's answer.\nIf they are, however, you have to ensure that the correct Host: header is sent as ...
[ 2, 0 ]
[]
[]
[ "dns", "hosts", "python", "urllib" ]
stackoverflow_0003183617_dns_hosts_python_urllib.txt
Q: Zooming into a Clutter CairoTexture while re-drawing I am using python-clutter 1.0 My question in the form of a challenge Write code to allow zooming up to a CairoTexture actor, by pressing a key, in steps such that at each the actor can be re-drawn (by cairo) so that the image remains high-res but still scales as expected, without re-sizing the actor. Think of something like Inkscape and how you can zoom into the vectors; how the vectors remain clean at any magnification. Put a path (bunch of cairo line_to commands, say) onto an CairoTexture actor and then allow the same trick to happen. More detail I am aiming at a small SVG editor which uses groups of actors. Each actor is devoted to one path. I 'zoom' by using SomeGroup.set_depth(z) and then make z bigger/smaller. All fine so far. However, the closer the actor(s) get to the camera, the more the texture is stretched to fit their new apparent size. I can't seem to find a way to get Clutter to do both: Leave the actor's actual size static (i.e. what it started as.) Swap-out its underlying surface for larger ones (on zooming in) that I can then re-draw the path onto (and use a cairo matrix to perform the scaling of the context.) If I use set_size or set_surface_size, the actor gets larger which is not intended. I only want it's surface (underlying data) to get larger. (I'm not sure of the terminology for this, mipmapping perhaps? ) Put another way: a polygon is getting larger, increase the size of its texture array so that it can map onto the larger polygon. I have even tried an end-run around clutter by keeping a second surface (using pycairo) that I re-create to the apparent size of the actor (get_transformed_size) and then I use clutter's set_from_rgb_data and point it at my second surface, forcing a re-size of the surface but not of the actor's dimensions. The problem with this is that a)clutter ignores the new size and only draws into the old width/height and b)the RGBA vs ARGB32 thing kind of causes a colour meltdown. I'm open to any alternative ideas, I hope I'm standing in the woods missing all the trees! \d A: Well, despite all my tests and hacks, it was right under my nose all along. Thanks to Neil on the clutter-project list, here's the scoop: CT = SomeCairoTextureActor() # record the old height, once: old_width, old_height = CT.get_size() Start a loop: # Do stuff to the depth of CT (or it's parent) ... # Get the apparent width and height (absolute size in pixels) appr_w,appr_h = CT.get_transformed_size() # Make the new surface to the new size CT.set_surface_size( appr_w, appr_h ) # Crunch the actor back down to old size # but leave the texture surface something other! CT.set_size(old_width, old_height) loop back again The surface size and the size of the actor don't have to be the same. The surface size is just by default the preferred size of the actor. You can override the preferred size by just setting the size on the actor. If the size of the actor is different from the surface size then the texture will be squished to fit in the actor size (which I think is what you want). Nice to put this little mystery to bed. Thanks clutter list! \d
Zooming into a Clutter CairoTexture while re-drawing
I am using python-clutter 1.0 My question in the form of a challenge Write code to allow zooming up to a CairoTexture actor, by pressing a key, in steps such that at each the actor can be re-drawn (by cairo) so that the image remains high-res but still scales as expected, without re-sizing the actor. Think of something like Inkscape and how you can zoom into the vectors; how the vectors remain clean at any magnification. Put a path (bunch of cairo line_to commands, say) onto an CairoTexture actor and then allow the same trick to happen. More detail I am aiming at a small SVG editor which uses groups of actors. Each actor is devoted to one path. I 'zoom' by using SomeGroup.set_depth(z) and then make z bigger/smaller. All fine so far. However, the closer the actor(s) get to the camera, the more the texture is stretched to fit their new apparent size. I can't seem to find a way to get Clutter to do both: Leave the actor's actual size static (i.e. what it started as.) Swap-out its underlying surface for larger ones (on zooming in) that I can then re-draw the path onto (and use a cairo matrix to perform the scaling of the context.) If I use set_size or set_surface_size, the actor gets larger which is not intended. I only want it's surface (underlying data) to get larger. (I'm not sure of the terminology for this, mipmapping perhaps? ) Put another way: a polygon is getting larger, increase the size of its texture array so that it can map onto the larger polygon. I have even tried an end-run around clutter by keeping a second surface (using pycairo) that I re-create to the apparent size of the actor (get_transformed_size) and then I use clutter's set_from_rgb_data and point it at my second surface, forcing a re-size of the surface but not of the actor's dimensions. The problem with this is that a)clutter ignores the new size and only draws into the old width/height and b)the RGBA vs ARGB32 thing kind of causes a colour meltdown. I'm open to any alternative ideas, I hope I'm standing in the woods missing all the trees! \d
[ "Well, despite all my tests and hacks, it was right under my nose all along. \nThanks to Neil on the clutter-project list, here's the scoop:\nCT = SomeCairoTextureActor()\n\n# record the old height, once:\nold_width, old_height = CT.get_size()\n\nStart a loop:\n# Do stuff to the depth of CT (or it's parent)\n...\n\...
[ 2 ]
[]
[]
[ "cairo", "clutter", "python", "scaletransform", "zooming" ]
stackoverflow_0003176011_cairo_clutter_python_scaletransform_zooming.txt
Q: Python List Division/Splitting Possible Duplicate: How do you split a list into evenly sized chunks in Python? Hello, I'm trying to find a simpler way to do the following: def list_split(list, size): result = [[]] while len(list) > 0: if len(result[-1]) >= size: result.append([]) result[-1].append(list.pop(0)) return result Example usage: >>> list_split([0, 1, 2, 3, 4, 5, 6], 2) [[0, 1], [2, 3], [4, 5], [6]] >>> list_split([0, 1, 2, 3, 4, 5, 6], 3) [[0, 1, 2], [3, 4, 5], [6]] I can't tell if there's a built-in way to do this, possibly with slicing or something. This is similar but not the same to the post at How to split a list into a given number of sub-lists in python Thanks EDIT: As is commented on by Anurag Uniyal, this is a duplicate of How do you split a list into evenly sized chunks?, and should be closed, which I cannot do. A: You could use slices to get subsets of a list. Example: >>> L = [0, 1, 2, 3, 4, 5, 6] >>> n = 3 >>> [L[i:i+n] for i in range(0, len(L), n)] [[0, 1, 2], [3, 4, 5], [6]] >>> A: def list_split(L, size): return [L[i*size:(i+1)*size] for i in range(1+((len(L)-1)//size))] If you prefer a generator instead of a list, you can replace the brackets with parens, like so: def list_split(L, size): return (L[i*size:(i+1)*size] for i in range(1+((len(L)-1)//size))) A: You have a simple functional solution in the itertools recipes (grouper): http://docs.python.org/library/itertools.html#recipes Whereas this function adds padding, you can easily write a non-padded implementation taking advantage of the (usually overlooked) iter built-in used this way: iter(callable, sentinel) -> iterator def grouper(n, it): "grouper(3, 'ABCDEFG') --> ABC DEF G" return iter(lambda: list(itertools.islice(it, n)), []) list(grouper(3, iter(mylist))) These solutions are more generic because they both work with sequences and iterables (even if they are infinite). A: from itertools import izip_longest def list_split(L, size): return [[j for j in i if j is not None] for i in izip_longest(*[iter(L)]*size)] >>> list_split([0, 1, 2, 3, 4, 5, 6], 2) [[0, 1], [2, 3], [4, 5], [6]] >>> list_split([0, 1, 2, 3, 4, 5, 6], 3) [[0, 1, 2], [3, 4, 5], [6]] >>> list_split([0, 1, 2, 3, 4, 5, 6], 4) [[0, 1, 2, 3], [4, 5, 6]] >>> list_split([0, 1, 2, 3, 4, 5, 6], 5) [[0, 1, 2, 3, 4], [5, 6]]
Python List Division/Splitting
Possible Duplicate: How do you split a list into evenly sized chunks in Python? Hello, I'm trying to find a simpler way to do the following: def list_split(list, size): result = [[]] while len(list) > 0: if len(result[-1]) >= size: result.append([]) result[-1].append(list.pop(0)) return result Example usage: >>> list_split([0, 1, 2, 3, 4, 5, 6], 2) [[0, 1], [2, 3], [4, 5], [6]] >>> list_split([0, 1, 2, 3, 4, 5, 6], 3) [[0, 1, 2], [3, 4, 5], [6]] I can't tell if there's a built-in way to do this, possibly with slicing or something. This is similar but not the same to the post at How to split a list into a given number of sub-lists in python Thanks EDIT: As is commented on by Anurag Uniyal, this is a duplicate of How do you split a list into evenly sized chunks?, and should be closed, which I cannot do.
[ "You could use slices to get subsets of a list.\nExample:\n>>> L = [0, 1, 2, 3, 4, 5, 6]\n>>> n = 3\n>>> [L[i:i+n] for i in range(0, len(L), n)]\n[[0, 1, 2], [3, 4, 5], [6]]\n>>>\n\n", "def list_split(L, size):\n return [L[i*size:(i+1)*size] for i in range(1+((len(L)-1)//size))]\n\nIf you prefer a generator in...
[ 9, 1, 1, 0 ]
[]
[]
[ "list", "python", "split" ]
stackoverflow_0003183919_list_python_split.txt
Q: Tree matching algorithm? I am working on a tree library, and part of the required functionality, is to be able to search a node for child nodes that match a pattern. A 'pattern' is a specification (or criteria) that lays out the structure, as well as attributes of nodes in the subtree(s) to be matched. For example, suppose a tree represents data regarding a particular species of bird. Further assume that the nodes of such a tree have the following attributes: location sex wingspan weight brood_size Given a parent node, I would like to issue a search in plain English thus: "Fetch me all male birds that are descendants of this bird, and live in XXX city and have a weight > 100g. Any such bird found should also have at least 2 brothers and one sister, and must itself have at least one child" < note > Just to clarify, I do not expect to be able to query using plain English as I have done above. I only used the "plain English query" to illustrate the type of matching I would like to be performing on the tree. I fully expect to use symbols for the matching (as opposed to plain text) in practice. < /note > I am thinking of possibly using a regex type pattern matching to match trees. One way would be to have a string representation of each node, so I could use a normal regex - but this is likely of be quite inefficient, as there will be a lot of repeated data - i.e. string representation of child nodes will be supersets of their parent representation, which will be supersets of their parents representational string, and so on, recursively, up the tree - this could very easily become unwieldy for event modestly sized trees - there has to be a better way. Is anyone aware of an algorithm that will allow me to select nodes (subtrees) in a node, based on a pattern? Although I asked for a general algorithm, I am implementing this in Python. any snippets that further illustrate such an algorithm (if one can indeed be written), would be immensely useful. A: What's wrong with writing a Lisp Sexpression with wildcards to describe the tree match? Parentheses group a node. Elements from left to right match the root followed by the children. Subtree matches use nested Sexpressions to describe the subtree. The following would match a tree with arbitrary root node, first child being a leaf A, third child being a subtree rooted with X, first child 1 and third child A: (?root A ? (X 1 A)) This idea isn't unique to me; the Lisp guys have been writing such patterns since the early sixties. Here's a LISP pattern matcher (as an example you wanted) that only goes back 20 years: http://norvig.com/paip/patmatch.lisp However, coding this yourself is pretty easy. This is typically assigned as a homework exercise for people learning LISP. A: This depends on your tree. If your tree is rooted and ordered, you should be able to check for an exact match in sublinear time, and if not, you should be able to check for a match in linear time. Several faster algorithms also exist for approximate matching. For finding material and algorithms for topics like this, Google Scholar is your friend. A search for subtree matching or similar should get you there. EDIT: Judging by your updated entry, I suggest you take a look at how XPath and similar query languages are implemented. XML is a rooted tree, and XPath can search for sub trees in that tree with complex matching operators like the ones in your example. I also advice you not to implement this on your own, but rather use an existing library (like PyLucene or some other search engine, which seems appropriate given the example you put out).
Tree matching algorithm?
I am working on a tree library, and part of the required functionality, is to be able to search a node for child nodes that match a pattern. A 'pattern' is a specification (or criteria) that lays out the structure, as well as attributes of nodes in the subtree(s) to be matched. For example, suppose a tree represents data regarding a particular species of bird. Further assume that the nodes of such a tree have the following attributes: location sex wingspan weight brood_size Given a parent node, I would like to issue a search in plain English thus: "Fetch me all male birds that are descendants of this bird, and live in XXX city and have a weight > 100g. Any such bird found should also have at least 2 brothers and one sister, and must itself have at least one child" < note > Just to clarify, I do not expect to be able to query using plain English as I have done above. I only used the "plain English query" to illustrate the type of matching I would like to be performing on the tree. I fully expect to use symbols for the matching (as opposed to plain text) in practice. < /note > I am thinking of possibly using a regex type pattern matching to match trees. One way would be to have a string representation of each node, so I could use a normal regex - but this is likely of be quite inefficient, as there will be a lot of repeated data - i.e. string representation of child nodes will be supersets of their parent representation, which will be supersets of their parents representational string, and so on, recursively, up the tree - this could very easily become unwieldy for event modestly sized trees - there has to be a better way. Is anyone aware of an algorithm that will allow me to select nodes (subtrees) in a node, based on a pattern? Although I asked for a general algorithm, I am implementing this in Python. any snippets that further illustrate such an algorithm (if one can indeed be written), would be immensely useful.
[ "What's wrong with writing a Lisp Sexpression with wildcards to describe the tree match? Parentheses group a node. Elements from left to right match the root followed by the children. Subtree matches use nested Sexpressions to describe the subtree.\nThe following would match a tree with arbitrary root node, first...
[ 5, 3 ]
[]
[]
[ "algorithm", "python", "tree" ]
stackoverflow_0003185530_algorithm_python_tree.txt
Q: Alternatives to my slow method of using BeautifulSoup and Python to parse Amazon API XML? As the title says, I'm using the BS module in Python to parse XML pages that I access from the Amazon API (i create the signed url, load it with liburl2, and then parse with BS). It takes about 4 seconds to do two pages, but there has to be a faster way Would PHP be faster? What's making it slow, the BS parsing or the liburl loading? A: If you want to find out what's making it slow, use one of the profilers. I suspect it's the network access (and their underlying database retrieval) that's slower than the rest.
Alternatives to my slow method of using BeautifulSoup and Python to parse Amazon API XML?
As the title says, I'm using the BS module in Python to parse XML pages that I access from the Amazon API (i create the signed url, load it with liburl2, and then parse with BS). It takes about 4 seconds to do two pages, but there has to be a faster way Would PHP be faster? What's making it slow, the BS parsing or the liburl loading?
[ "If you want to find out what's making it slow, use one of the profilers. I suspect it's the network access (and their underlying database retrieval) that's slower than the rest.\n" ]
[ 2 ]
[]
[]
[ "beautifulsoup", "parsing", "python", "xml" ]
stackoverflow_0003185747_beautifulsoup_parsing_python_xml.txt
Q: Controlling Linux Compiz Brightness Programmatically with Python or Vala Several laptops on the market have problems with Linux for brightness controls. However, recently I found out that you can use CompizConfig settings to dim at least a particular window. Many people, however, want to dim all windows. I know Compiz can do this in the API somewhere because look what happens when you do Super + Tab in Compiz. So this got me thinking...what I need to build is a GNOME applet in either Python, or perhaps this new Vala language, that interfaces with the Compiz API and lets me dim the entire screen. Does anyone know where I might find some programming resources to learn how to use Compiz API in Python or Vala to dim the screen? A: You want to look into gnome-compiz especially into gtk-window-decorator and gnome-xgl-settings.
Controlling Linux Compiz Brightness Programmatically with Python or Vala
Several laptops on the market have problems with Linux for brightness controls. However, recently I found out that you can use CompizConfig settings to dim at least a particular window. Many people, however, want to dim all windows. I know Compiz can do this in the API somewhere because look what happens when you do Super + Tab in Compiz. So this got me thinking...what I need to build is a GNOME applet in either Python, or perhaps this new Vala language, that interfaces with the Compiz API and lets me dim the entire screen. Does anyone know where I might find some programming resources to learn how to use Compiz API in Python or Vala to dim the screen?
[ "You want to look into gnome-compiz especially into gtk-window-decorator and gnome-xgl-settings.\n" ]
[ 1 ]
[]
[]
[ "compiz", "gnome", "python", "vala" ]
stackoverflow_0003177057_compiz_gnome_python_vala.txt
Q: python threading and queues for infinite data input (stream) I would like to use thread to process a streaming input. How can make the below code for an infinite input generate for example by using itertools.count The code below will work if: 'for i in itertools.count():' is replaced by 'for i in xrange(5):' from threading import Thread from Queue import Queue, Empty import itertools def do_work(q): while True: try: x = q.get(block=False) print (x) except Empty: break if __name__ == "__main__": work_queue = Queue() for i in itertools.count(): work_queue.put(i) threads = [Thread(target=do_work, args=(work_queue,)) for i in range(8)] for t in threads: t.start() for t in threads: t.join() A: The problem is that itertools.count generates an infinite sequence. This means the for loop will never end. You should put that in it's own function and make it a separate thread. This way you will have the queue growing while the worker threads get data off the queue. A: You need to fill the queue with a thread. You need to manage the queue size. Especially if the workers are taking time to process items. You need to mark queue items done. If this is related to your other question about twitter and "extremely fast" input, then you have an awful lot more to do with regards to database inserts. Your questions have been too vague on pretty complicated topics. You don't seem to understand enough about even what you're trying to achieve to know that it's not easy. I recommend that you are a little more specific in what you are trying to do. Here's an example of filling and consuming a queue with threads. The queue size isn't being managed. from threading import Thread from Queue import Queue, Empty, Full import itertools from time import sleep def do_work(q,wkr): while True: try: x = q.get(block=True,timeout=10) q.task_done() print "Wkr %s: Consuming %s" % (wkr,x) sleep(0.01) except Empty: print "Wkr %s exiting, timeout/empty" % (wkr) break sleep(0.01) def fill_queue(q,limit=1000): count = itertools.count() while True: n = count.next() try: q.put(n,block=True,timeout=10) except Full: print "Filler exiting, timeout/full" break if n >= limit: print "Filler exiting, reached limit - %s" % limit break sleep(0.01) work_queue = Queue() threads = [Thread(target=do_work, args=(work_queue,i)) for i in range(2)] threads.insert(0,Thread(target=fill_queue,args=(work_queue,100))) for t in threads: t.start() for t in threads: t.join() Wkr 0: Consuming 0 Wkr 1: Consuming 1 Wkr 0: Consuming 2 Wkr 1: Consuming 3 .... Wkr 1: Consuming 99 Filler exiting, reached limit - 100 Wkr 0: Consuming 100 Wkr 1 exiting, timeout/empty Wkr 0 exiting, timeout/empty A: Maybe I'm missing something, but isn't it as simple as creating and starting the threads before the for loop? Also, having your threads terminate when there's no work seems like a bad idea, as there may be more work showing up in future. Surely you want them to block until some work is available?
python threading and queues for infinite data input (stream)
I would like to use thread to process a streaming input. How can make the below code for an infinite input generate for example by using itertools.count The code below will work if: 'for i in itertools.count():' is replaced by 'for i in xrange(5):' from threading import Thread from Queue import Queue, Empty import itertools def do_work(q): while True: try: x = q.get(block=False) print (x) except Empty: break if __name__ == "__main__": work_queue = Queue() for i in itertools.count(): work_queue.put(i) threads = [Thread(target=do_work, args=(work_queue,)) for i in range(8)] for t in threads: t.start() for t in threads: t.join()
[ "The problem is that itertools.count generates an infinite sequence. This means the for loop will never end. You should put that in it's own function and make it a separate thread. This way you will have the queue growing while the worker threads get data off the queue.\n", "You need to fill the queue with a thre...
[ 2, 2, 1 ]
[]
[]
[ "multiprocessing", "multithreading", "python", "queue" ]
stackoverflow_0003185261_multiprocessing_multithreading_python_queue.txt
Q: shuffling a word How do I shuffle a word's letters randomly in python? For example, the word "cat" might be changed into 'act', 'tac' or 'tca'. I would like to do this without using built-in functions A: import random word = "cat" shuffled = list(word) random.shuffle(shuffled) shuffled = ''.join(shuffled) print(shuffled) ...or done in a different way, inspired by Dominic's answer... import random shuffled = ''.join(random.sample(word, len(word))) A: Take a look at the Fisher-Yates shuffle. It's extremely space and time-efficient, and easy to implement. A: return "".join(random.sample(word, len(word))) Used like: import random word = "Pocketknife" print("".join(random.sample(word, len(word)))) >>> teenockpkfi A: This cookbook recipe has a simple implementation of Fisher-Yates shuffling in Python. Of course, since you have a string argument and must return a string, you'll need a first statement (say the argument name is s) like ary = list(s), and in the return statement you'll use ''.join to put the array of characters ary back into a single string. A: To be very slightly more low level, this just swaps the current letter with a random letter which comes after it. from random import randint hi = "helloworld" def shuffle(word): wordlen = len(word) word = list(word) for i in range(0, wordlen - 1): pos = randint(i + 1, wordlen - 1) word[i], word[pos] = word[pos], word[i] word = "".join(word) return word print(shuffle(hi)) This won't create all possible permutations with equal probability, but still might be alright for what you want A: Here is a way that doesn't use random.shuffle. Hopefully random.choice is ok. You should add any restrictions to the question >>> from random import choice >>> from itertools import permutations >>> "".join(choice(list(permutations("cat")))) 'atc' This method is not as efficient as random.shuffle, so will be slow for long words A: from random import random def shuffle(x): for i in reversed(xrange(1, len(x))): j = int(random() * (i+1)) x[i], x[j] = x[j], x[i]
shuffling a word
How do I shuffle a word's letters randomly in python? For example, the word "cat" might be changed into 'act', 'tac' or 'tca'. I would like to do this without using built-in functions
[ "import random\nword = \"cat\"\nshuffled = list(word)\nrandom.shuffle(shuffled)\nshuffled = ''.join(shuffled)\nprint(shuffled)\n\n...or done in a different way, inspired by Dominic's answer...\nimport random\nshuffled = ''.join(random.sample(word, len(word)))\n\n", "Take a look at the Fisher-Yates shuffle. It's ...
[ 10, 7, 4, 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003182964_python.txt
Q: Convert HTTP Proxy to HTTPS Proxy in Twisted Recently I have been playing around with the HTTP Proxy in twisted. After much trial and error I think I finally I have something working. What I want to know though, is how, if it is possible, do I expand this proxy to also be able to handle HTTPS pages? Here is what I've got so far: from twisted.internet import reactor from twisted.web import http from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient class HTTPProxyClient(ProxyClient): def handleHeader(self, key, value): print "%s : %s" % (key, value) ProxyClient.handleHeader(self, key, value) def handleResponsePart(self, buffer): print buffer ProxyClient.handleResponsePart(self, buffer) class HTTPProxyFactory(ProxyClientFactory): protocol = HTTPProxyClient class HTTPProxyRequest(ProxyRequest): protocols = {'http' : HTTPProxyFactory} def process(self): print self.method for k,v in self.requestHeaders.getAllRawHeaders(): print "%s : %s" % (k,v) print "\n \n" ProxyRequest.process(self) class HTTPProxy(Proxy): requestFactory = HTTPProxyRequest factory = http.HTTPFactory() factory.protocol = HTTPProxy reactor.listenSSL(8001, factory) reactor.run() As this code demonstrates, for the sake of example for now I am just printing out whatever is going through the connection. Is it possible to handle HTTPS with the same classes? If not, how should I go about implementing such a thing? A: If you want to connect to an HTTPS website via an HTTP proxy, you need to use the CONNECT HTTP verb (because that's how a proxy works for HTTPS). In this case, the proxy server simply connects to the target server and relays whatever is sent by the server back to the client's socket (and vice versa). There's no caching involved in this case (but you might be able to log the hosts you're connecting to). The exchange will look like this (client to proxy): C->P: CONNECT target.host:443 HTTP/1.0 C->P: P->C: 200 OK P->C: After this, the proxy simply opens a plain socket to the target server (no HTTP or SSL/TLS yet) and relays everything between the initial client and the target server (including the TLS handshake that the client initiates). The client upgrades the existing socket it has to the proxy to use TLS/SSL (by starting the SSL/TLS handshake). Once the client has read the '200' status line, as far as the client is concerned, it's as if it had made the connection to the target server directly. A: I'm not sure about twisted, but I want to warn you that if you implement a HTTPS proxy, a web browser will expect the server's SSL certificate to match the domain name in the URL (address bar). The web browser will issue security warnings otherwise. There are ways around this, such as generating certificates on the fly, but you'd need the root certificate to be trusted on the browser.
Convert HTTP Proxy to HTTPS Proxy in Twisted
Recently I have been playing around with the HTTP Proxy in twisted. After much trial and error I think I finally I have something working. What I want to know though, is how, if it is possible, do I expand this proxy to also be able to handle HTTPS pages? Here is what I've got so far: from twisted.internet import reactor from twisted.web import http from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient class HTTPProxyClient(ProxyClient): def handleHeader(self, key, value): print "%s : %s" % (key, value) ProxyClient.handleHeader(self, key, value) def handleResponsePart(self, buffer): print buffer ProxyClient.handleResponsePart(self, buffer) class HTTPProxyFactory(ProxyClientFactory): protocol = HTTPProxyClient class HTTPProxyRequest(ProxyRequest): protocols = {'http' : HTTPProxyFactory} def process(self): print self.method for k,v in self.requestHeaders.getAllRawHeaders(): print "%s : %s" % (k,v) print "\n \n" ProxyRequest.process(self) class HTTPProxy(Proxy): requestFactory = HTTPProxyRequest factory = http.HTTPFactory() factory.protocol = HTTPProxy reactor.listenSSL(8001, factory) reactor.run() As this code demonstrates, for the sake of example for now I am just printing out whatever is going through the connection. Is it possible to handle HTTPS with the same classes? If not, how should I go about implementing such a thing?
[ "If you want to connect to an HTTPS website via an HTTP proxy, you need to use the CONNECT HTTP verb (because that's how a proxy works for HTTPS). In this case, the proxy server simply connects to the target server and relays whatever is sent by the server back to the client's socket (and vice versa). There's no ca...
[ 15, 2 ]
[]
[]
[ "http", "https", "proxy", "python", "twisted" ]
stackoverflow_0003118602_http_https_proxy_python_twisted.txt
Q: How to initialize model with calculated value I have a Django model Reminder related to Event model. class Reminder(models.Model): email = models.EmailField("e-mail") event = models.ForeignKey(Event, unique=True, related_name='event',) date = models.DateTimeField(_(u"Remind date"), auto_now_add=False,) class Event(models.Model): date = models.DateTimeField(_(u"Event Date"), auto_now_add=True,) How, using __init__ set Reminder's date field value to the date of Event model related to it - 7 days ? Is it possible ? A: I don't know what exactly you need, but: 1) If you need Reminder.date always return Event.date - 7 import datetime class Reminder(models.Model): email = models.EmailField("e-mail") event = models.ForeignKey(Event, unique=True, related_name='event',) def date(self): return self.event.date - datetime.timedelta(days=7) class Event(models.Model): date = models.DateTimeField(_(u"Event Date"), auto_now_add=True,) 2) If you need to set the date on event save or on reminder save, do this: import datetime class Reminder(models.Model): email = models.EmailField("e-mail") event = models.ForeignKey(Event, unique=True, related_name='event',) date = models.DateTimeField(_(u"Remind date"), auto_now_add=False,) # update date on save def save(self, *args, **kwargs): self.date = self.event.date - datetime.timedelta(days=7) super(Reminder, self).save(*args, **kwargs) class Event(models.Model): date = models.DateTimeField(_(u"Event Date"), auto_now_add=True,) # update all reminders on event save def save(self, *args, **kwargs): reminder_date = self.date - datetime.timedelta(days=7) self.reminders.update(date=reminder_date) super(Event, self).save(*args, **kwargs) Please note that I haven't tested the code and there might be typos. A: just add this to the ____init____ method of your Reminder class. If you are setting this in the ____init____ method then you need to create the Event at the same time. e = Event() self.event = e self.date = e.date e.put()
How to initialize model with calculated value
I have a Django model Reminder related to Event model. class Reminder(models.Model): email = models.EmailField("e-mail") event = models.ForeignKey(Event, unique=True, related_name='event',) date = models.DateTimeField(_(u"Remind date"), auto_now_add=False,) class Event(models.Model): date = models.DateTimeField(_(u"Event Date"), auto_now_add=True,) How, using __init__ set Reminder's date field value to the date of Event model related to it - 7 days ? Is it possible ?
[ "I don't know what exactly you need, but:\n1) If you need Reminder.date always return Event.date - 7\nimport datetime\n\n\nclass Reminder(models.Model):\n email = models.EmailField(\"e-mail\")\n event = models.ForeignKey(Event, unique=True, related_name='event',)\n\n def date(self):\n return self.ev...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "initialization", "python" ]
stackoverflow_0003183133_django_django_models_initialization_python.txt
Q: Python regex \w doesn't match combining diacritics? I have a UTF8 string with combining diacritics. I want to match it with the \w regex sequence. It matches characters that have accents, but not if there is a latin character with combining diacritics. >>> re.match("a\w\w\wz", u"aoooz", re.UNICODE) <_sre.SRE_Match object at 0xb7788f38> >>> print u"ao\u00F3oz" aoóoz >>> re.match("a\w\w\wz", u"ao\u00F3oz", re.UNICODE) <_sre.SRE_Match object at 0xb7788f38> >>> re.match("a\w\w\wz", u"aoo\u0301oz", re.UNICODE) >>> print u"aoo\u0301oz" aóooz (Looks like the SO markdown processer is having trouble with the combining diacritics in the above, but there is a ́ on the last line) Is there anyway to match combining diacritics with \w? I don't want to normalise the text because this text is from filename, and I don't want to have to do a whole 'file name unicode normalization' yet. This is Python 2.5. A: I've just noticed a new "regex" package on pypi. (if I understand correctly, it is a test version of a new package that will someday replace the stdlib re package). It seems to have (among other things) more possibilities with regard to unicode. For example, it supports \X, which is used to match a single grapheme (whether it uses combining or not). It also supports matching on unicode properties, blocks and scripts, so you can use \p{M} to refer to combining marks. The \X mentioned before is equivalent to \P{M}\p{M}* (a character that is NOT a combining mark, followed by zero or more combining marks). Note that this makes \X more or less the unicode equivalent of ., not of \w, so in your case, \w\p{M}* is what you need. It is (for now) a non-stdlib package, and I don't know how ready it is (and it doesn't come in a binary distribution), but you might want to give it a try, as it seems to be the easiest/most "correct" answer to your question. (otherwise, I think your down to explicitly using character ranges, as described in my comment to the previous answer). See also this page with information on unicode regular expressions, that might also contain some useful information for you (and can serve as documentation for some of the things implemented in the regex package). A: You can use unicodedata.normalize to compose the combining diacritics into one unicode character. >>> import re >>> from unicodedata import normalize >>> re.match(u"a\w\w\wz", normalize("NFC", u"aoo\u0301oz"), re.UNICODE) <_sre.SRE_Match object at 0x00BDCC60> I know you said you didn't want to normalize, but I don't think there will be a problem with this solution, as you're only normalizing the string to match against, and do not have to change the filename itself or something.
Python regex \w doesn't match combining diacritics?
I have a UTF8 string with combining diacritics. I want to match it with the \w regex sequence. It matches characters that have accents, but not if there is a latin character with combining diacritics. >>> re.match("a\w\w\wz", u"aoooz", re.UNICODE) <_sre.SRE_Match object at 0xb7788f38> >>> print u"ao\u00F3oz" aoóoz >>> re.match("a\w\w\wz", u"ao\u00F3oz", re.UNICODE) <_sre.SRE_Match object at 0xb7788f38> >>> re.match("a\w\w\wz", u"aoo\u0301oz", re.UNICODE) >>> print u"aoo\u0301oz" aóooz (Looks like the SO markdown processer is having trouble with the combining diacritics in the above, but there is a ́ on the last line) Is there anyway to match combining diacritics with \w? I don't want to normalise the text because this text is from filename, and I don't want to have to do a whole 'file name unicode normalization' yet. This is Python 2.5.
[ "I've just noticed a new \"regex\" package on pypi. (if I understand correctly, it is a test version of a new package that will someday replace the stdlib re package). \nIt seems to have (among other things) more possibilities with regard to unicode. For example, it supports \\X, which is used to match a single gra...
[ 7, 2 ]
[]
[]
[ "diacritics", "python", "regex", "unicode", "unicode_normalization" ]
stackoverflow_0003141032_diacritics_python_regex_unicode_unicode_normalization.txt
Q: Boost.Python on Mac OS X: "TypeError: Attribute name must be string" I recently installed Boost using MacPorts, with the intent to do some Python embedding in C++. I then decided to check if I configured Xcode correctly with an example found on Python's website: #include <boost/python.hpp> using namespace boost::python; int main( int argc, char ** argv ) { try { Py_Initialize(); object main_module(handle<>(borrowed(PyImport_AddModule("__main__")))); object main_namespace = main_module.attr("__dict__"); handle<> ignored(PyRun_String("print \"Hello, World\"", Py_file_input, main_namespace.ptr(), main_namespace.ptr())); } catch( error_already_set ) { PyErr_Print(); } } It compiles correctly, but when I launch it, the call to attr() throws an exception, and the resulting error message is "TypeError: attribute name must be string, not 'str'". Which suspiciously sounds like a placeholder. I looked it up on Google, but no luck. I use Boost v1.39, Python 2.5 and GCC 4.0, on Leopard. A: Your code worked for me with the following configuration: Snow Leopard gcc version 4.2.1 (AppleInc. build 5646) Boost 1.41.0 installed to /usr/local/boost/1_41_0/ Stock OSX Python 2.5 Compiled using: g++ -I/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/ -I/usr/local/boost/1_41_0/include -L/usr/local/boost/1_41_0/lib/ -boost_python -L/usr/lib/python2.6/config -lpython2.6 test.cpp
Boost.Python on Mac OS X: "TypeError: Attribute name must be string"
I recently installed Boost using MacPorts, with the intent to do some Python embedding in C++. I then decided to check if I configured Xcode correctly with an example found on Python's website: #include <boost/python.hpp> using namespace boost::python; int main( int argc, char ** argv ) { try { Py_Initialize(); object main_module(handle<>(borrowed(PyImport_AddModule("__main__")))); object main_namespace = main_module.attr("__dict__"); handle<> ignored(PyRun_String("print \"Hello, World\"", Py_file_input, main_namespace.ptr(), main_namespace.ptr())); } catch( error_already_set ) { PyErr_Print(); } } It compiles correctly, but when I launch it, the call to attr() throws an exception, and the resulting error message is "TypeError: attribute name must be string, not 'str'". Which suspiciously sounds like a placeholder. I looked it up on Google, but no luck. I use Boost v1.39, Python 2.5 and GCC 4.0, on Leopard.
[ "Your code worked for me with the following configuration:\n\nSnow Leopard \ngcc version 4.2.1 (AppleInc. build 5646) \nBoost 1.41.0 installed to /usr/local/boost/1_41_0/\nStock OSX Python 2.5\n\nCompiled using:\ng++ -I/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Python.framework/Versions/2.6/include/py...
[ 1 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0003089586_boost_python_c++_python.txt
Q: Python scripts (curses + pysqlite) hanging after parent shell goes away I've written a python script which does some curses and pysqlite stuff, but I've noticed that in occasions where I've been running this script over ssh when that ssh session is killed for whatever reason the python script doesn't actually exit, instead it ends up as being a child of init and just stays there forever. I can't kill -9 them or anything. They also increase the reported system load by 1. Currently I have 8 of these mostly dead processes hanging around, and the server has a load average of 8.abit. I take it this is because there is some sort of resource that these scripts are waiting on, but lsof shows nothing actually open by them, all data files they were using are listed as deleted etc... and they are using no cpu time whatsoever. I'm doing some signal checking in the script, calling out to do some refresh routines on a HUP, but nothing else, not forking or anything and I'm at a loss as to why the scripts are not just shuffling off when I close my ssh session. Thanks Chris A: Well, the reason they're not shutting down when your ssh session terminates is because HUP is the signal used by a parent to inform its children that they should shut down. If you're overriding the behavior of this signal, then your processes will not automatically shut down when the SSH session is closed. As for why you cannot kill -9 them, however, I'm at a loss. The only thing I've seen that causes that behavior is processes blocked on misbehaving filesystems (nfs & unionfs being the two I've encountered the problem with).
Python scripts (curses + pysqlite) hanging after parent shell goes away
I've written a python script which does some curses and pysqlite stuff, but I've noticed that in occasions where I've been running this script over ssh when that ssh session is killed for whatever reason the python script doesn't actually exit, instead it ends up as being a child of init and just stays there forever. I can't kill -9 them or anything. They also increase the reported system load by 1. Currently I have 8 of these mostly dead processes hanging around, and the server has a load average of 8.abit. I take it this is because there is some sort of resource that these scripts are waiting on, but lsof shows nothing actually open by them, all data files they were using are listed as deleted etc... and they are using no cpu time whatsoever. I'm doing some signal checking in the script, calling out to do some refresh routines on a HUP, but nothing else, not forking or anything and I'm at a loss as to why the scripts are not just shuffling off when I close my ssh session. Thanks Chris
[ "Well, the reason they're not shutting down when your ssh session terminates is because HUP is the signal used by a parent to inform its children that they should shut down. If you're overriding the behavior of this signal, then your processes will not automatically shut down when the SSH session is closed. As for ...
[ 1 ]
[]
[]
[ "exit", "python", "signals", "ssh" ]
stackoverflow_0003184974_exit_python_signals_ssh.txt
Q: how to parse a string to spider from another script I am new to python and scrapy . I am running the scrapy-ctl.py from another python script using subprocess module.But I want to parse the 'start url' to the spider from this script itself.Is it possible to parse start_urls(which are determined in the script from which scrapy-ctl is run) to the spider? I will be greatful for any suggestions or ideas regarding this....:) Thanking in advance.... A: You can override the start_requests() method in your spider to get the starting requests (which, by default, are generated using the urls in the start_urls attribute).
how to parse a string to spider from another script
I am new to python and scrapy . I am running the scrapy-ctl.py from another python script using subprocess module.But I want to parse the 'start url' to the spider from this script itself.Is it possible to parse start_urls(which are determined in the script from which scrapy-ctl is run) to the spider? I will be greatful for any suggestions or ideas regarding this....:) Thanking in advance....
[ "You can override the start_requests() method in your spider to get the starting requests (which, by default, are generated using the urls in the start_urls attribute).\n" ]
[ 2 ]
[]
[]
[ "python", "scrapy", "web_crawler", "windows" ]
stackoverflow_0003179979_python_scrapy_web_crawler_windows.txt
Q: one field with different data types [SQLAlchemy] I have a value that can be integer, float or string, and I created different columns: #declarative class MyClass(Base): #id and other Columns _value_str = Column(String(100)) _value_int = Column(Integer) _value_float = Column(Float) def __init__(self,...,value): self._value_str = value if isinstance(value,(str,unicode)) else None self._value_int = value if isinstance(value,int) else None self._value_float = value if isinstance(value,float) else None and i would like to do something like this: >>> value = 'text' >>> my_class = MyClass(value, ...) >>> my_class.value >>> 'text' >>> session.add(my_class) >>> session.commit() #specialy this >>> result = session.query(Myclass).filter(Myclass.value == 'text').one() >>> print result.value >>> 'text' Maybe i have a design problem, i accept any good idea I'm newbe in SQLAlchemy Thanks A: Probably a design problem - a bit of a mismatch between your DB and Python. In SQL variables (columns) have a type, whereas in python values have the type. One possibility would be to use a single column (a string), but pickle the value before you store it. This can be accomplished automatically with a sqlalchemy custom type. Something along the lines of the following (uses jsonpickle to do the conversion rather than cpickle): import sqlalchemy.types as types import jsonpickle from copy import deepcopy class JsonType(types.MutableType, types.TypeDecorator): impl = types.Unicode def process_bind_param(self, value, engine): return unicode(jsonpickle.encode(value)) def process_result_value(self, value, engine): if value: rv = jsonpickle.decode(value) return rv else: return None def copy_value(self, value): return deepcopy(value) def compare_values(self, x, y): return x == y And then use it as follows: class MyClass(base): value = Column(JsonType())
one field with different data types [SQLAlchemy]
I have a value that can be integer, float or string, and I created different columns: #declarative class MyClass(Base): #id and other Columns _value_str = Column(String(100)) _value_int = Column(Integer) _value_float = Column(Float) def __init__(self,...,value): self._value_str = value if isinstance(value,(str,unicode)) else None self._value_int = value if isinstance(value,int) else None self._value_float = value if isinstance(value,float) else None and i would like to do something like this: >>> value = 'text' >>> my_class = MyClass(value, ...) >>> my_class.value >>> 'text' >>> session.add(my_class) >>> session.commit() #specialy this >>> result = session.query(Myclass).filter(Myclass.value == 'text').one() >>> print result.value >>> 'text' Maybe i have a design problem, i accept any good idea I'm newbe in SQLAlchemy Thanks
[ "Probably a design problem - a bit of a mismatch between your DB and Python. In SQL variables (columns) have a type, whereas in python values have the type.\nOne possibility would be to use a single column (a string), but pickle the value before you store it.\nThis can be accomplished automatically with a sqlalchem...
[ 4 ]
[]
[]
[ "database_design", "python", "sqlalchemy" ]
stackoverflow_0003167842_database_design_python_sqlalchemy.txt
Q: migrating django 1.1.1 -> 1.2.1: {% url %} doesn't work I am migrating a django project from 1.1.1 to 1.2.1 Now neither the {% url %} tag works nor the @models.permalink-decorated get_absulute_url works i.e. I get TemplateSyntaxError at / Caught TypeError while rendering: __init__() got an unexpected keyword argument 'error_message' for <li><a href="{% url archive_talks %}">talks</a></li> while the url-pattern looks like this: url(r'^archive/talks/$', 'talkapp.views.archive_talks', name="archive_talks"), Did anyone run into the same problem? Is there a solution? traceback Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.2.1 Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.humanize', 'django.contrib.markup', 'pinax.templatetags', 'notification', 'django_openid', 'emailconfirmation', 'django_extensions', 'robots', 'mailer', 'messages', 'announcements', 'oembed', 'djangodblog', 'pagination', 'threadedcomments', 'threadedcomments_extras', 'timezones', 'voting', 'voting_extras', 'tagging', 'blog', 'ajax_validation', 'avatar', 'flag', 'locations', 'uni_form', 'django_sorting', 'django_markup', 'staticfiles', 'analytics', 'profiles', 'account', 'signup_codes', 'tag_app', 'topics', 'groups', 'django.contrib.admin', 'smartif', 'annoying', 'haystack', 'talkapp'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_openid.consumer.SessionConsumer', 'account.middleware.LocaleMiddleware', 'django.middleware.doc.XViewMiddleware', 'pagination.middleware.PaginationMiddleware', 'django_sorting.middleware.SortingMiddleware', 'djangodblog.middleware.DBLogMiddleware', 'pinax.middleware.security.HideSensistiveFieldsMiddleware', 'django.middleware.transaction.TransactionMiddleware') Template error: In template /Users/vikingosegundo/Coding/horizonte/social/templates/base.html, error at line 76 Caught TypeError while rendering: __init__() got an unexpected keyword argument 'error_message' 66 : </ul> 67 : </div> 68 : {% endif %} 69 : 70 : {% get_sorted_items talkapp.semester all by -semesterStart as semesters %} 71 : 72 : {% if semesters%} 73 : <div class="portlet"> 74 : <h3>Archive</h3> 75 : <ul> 76 : <li><a href=" {% url archive_of_talks %} ">talks</a></li> 77 : <li><a href="{% url archive_of_lectures %}">persons</a></li> 78 : <li><a href="{% url archive_of_semesters %}">semester</a></li> 79 : </ul> 80 : <ul> 81 : {% for n in semesters %} 82 : <li> 83 : <a href="{{ n.get_absolute_url }}">{{ n.semester_name }}</a> 84 : </li> 85 : {% endfor %} 86 : </ul> Traceback: File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/views/generic/simple.py" in direct_to_template 18. return HttpResponse(t.render(c), mimetype=mimetype) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 173. return self._render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/loader_tags.py" in render 125. return compiled_parent._render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/loader_tags.py" in render 125. return compiled_parent._render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/loader_tags.py" in render 62. result = block.nodelist.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django_smartif-0.1-py2.6.egg/smartif/templatetags/smartif.py" in render 278. return self.nodelist_true.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/defaulttags.py" in render 366. url = reverse(self.view_name, args=args, kwargs=kwargs, current_app=context.current_app) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in reverse 350. *args, **kwargs))) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in reverse 271. possibilities = self.reverse_dict.getlist(lookup_view) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _get_reverse_dict 193. self._populate() File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _populate 173. for name in pattern.reverse_dict: File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _get_reverse_dict 193. self._populate() File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _populate 162. for pattern in reversed(self.url_patterns): File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _get_url_patterns 243. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _get_urlconf_module 238. self._urlconf_module = import_module(self.urlconf_name) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/utils/importlib.py" in import_module 35. __import__(name) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/pinax/apps/blog/urls.py" in <module> 3. from blog import views, models File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/pinax/apps/blog/views.py" in <module> 13. from blog.forms import * File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/pinax/apps/blog/forms.py" in <module> 7. class BlogForm(forms.ModelForm): File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/pinax/apps/blog/forms.py" in BlogForm 11. error_message = _("This value must contain only letters, numbers, underscores and hyphens.")) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/forms/fields.py" in __init__ 184. super(CharField, self).__init__(*args, **kwargs) Exception Type: TemplateSyntaxError at / Exception Value: Caught TypeError while rendering: __init__() got an unexpected keyword argument 'error_message' A: This problem has nothing to do with the actual {% url %} tag. The reason you're hitting it on that tag is that the process of URL reversing actually imports all your Django views, and there is an error in a completely different place: the BlogForm class. Without the code of that form it's hard to tell exactly what's wrong there, although it does seem to be passing the error_message parameter, instead of error_messages (with an s).
migrating django 1.1.1 -> 1.2.1: {% url %} doesn't work
I am migrating a django project from 1.1.1 to 1.2.1 Now neither the {% url %} tag works nor the @models.permalink-decorated get_absulute_url works i.e. I get TemplateSyntaxError at / Caught TypeError while rendering: __init__() got an unexpected keyword argument 'error_message' for <li><a href="{% url archive_talks %}">talks</a></li> while the url-pattern looks like this: url(r'^archive/talks/$', 'talkapp.views.archive_talks', name="archive_talks"), Did anyone run into the same problem? Is there a solution? traceback Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.2.1 Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.humanize', 'django.contrib.markup', 'pinax.templatetags', 'notification', 'django_openid', 'emailconfirmation', 'django_extensions', 'robots', 'mailer', 'messages', 'announcements', 'oembed', 'djangodblog', 'pagination', 'threadedcomments', 'threadedcomments_extras', 'timezones', 'voting', 'voting_extras', 'tagging', 'blog', 'ajax_validation', 'avatar', 'flag', 'locations', 'uni_form', 'django_sorting', 'django_markup', 'staticfiles', 'analytics', 'profiles', 'account', 'signup_codes', 'tag_app', 'topics', 'groups', 'django.contrib.admin', 'smartif', 'annoying', 'haystack', 'talkapp'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_openid.consumer.SessionConsumer', 'account.middleware.LocaleMiddleware', 'django.middleware.doc.XViewMiddleware', 'pagination.middleware.PaginationMiddleware', 'django_sorting.middleware.SortingMiddleware', 'djangodblog.middleware.DBLogMiddleware', 'pinax.middleware.security.HideSensistiveFieldsMiddleware', 'django.middleware.transaction.TransactionMiddleware') Template error: In template /Users/vikingosegundo/Coding/horizonte/social/templates/base.html, error at line 76 Caught TypeError while rendering: __init__() got an unexpected keyword argument 'error_message' 66 : </ul> 67 : </div> 68 : {% endif %} 69 : 70 : {% get_sorted_items talkapp.semester all by -semesterStart as semesters %} 71 : 72 : {% if semesters%} 73 : <div class="portlet"> 74 : <h3>Archive</h3> 75 : <ul> 76 : <li><a href=" {% url archive_of_talks %} ">talks</a></li> 77 : <li><a href="{% url archive_of_lectures %}">persons</a></li> 78 : <li><a href="{% url archive_of_semesters %}">semester</a></li> 79 : </ul> 80 : <ul> 81 : {% for n in semesters %} 82 : <li> 83 : <a href="{{ n.get_absolute_url }}">{{ n.semester_name }}</a> 84 : </li> 85 : {% endfor %} 86 : </ul> Traceback: File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/views/generic/simple.py" in direct_to_template 18. return HttpResponse(t.render(c), mimetype=mimetype) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 173. return self._render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/loader_tags.py" in render 125. return compiled_parent._render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/loader_tags.py" in render 125. return compiled_parent._render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/loader_tags.py" in render 62. result = block.nodelist.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django_smartif-0.1-py2.6.egg/smartif/templatetags/smartif.py" in render 278. return self.nodelist_true.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/template/defaulttags.py" in render 366. url = reverse(self.view_name, args=args, kwargs=kwargs, current_app=context.current_app) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in reverse 350. *args, **kwargs))) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in reverse 271. possibilities = self.reverse_dict.getlist(lookup_view) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _get_reverse_dict 193. self._populate() File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _populate 173. for name in pattern.reverse_dict: File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _get_reverse_dict 193. self._populate() File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _populate 162. for pattern in reversed(self.url_patterns): File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _get_url_patterns 243. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/core/urlresolvers.py" in _get_urlconf_module 238. self._urlconf_module = import_module(self.urlconf_name) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/utils/importlib.py" in import_module 35. __import__(name) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/pinax/apps/blog/urls.py" in <module> 3. from blog import views, models File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/pinax/apps/blog/views.py" in <module> 13. from blog.forms import * File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/pinax/apps/blog/forms.py" in <module> 7. class BlogForm(forms.ModelForm): File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/pinax/apps/blog/forms.py" in BlogForm 11. error_message = _("This value must contain only letters, numbers, underscores and hyphens.")) File "/Users/vikingosegundo/Coding/horizonte/pinax-env/lib/python2.6/site-packages/django/forms/fields.py" in __init__ 184. super(CharField, self).__init__(*args, **kwargs) Exception Type: TemplateSyntaxError at / Exception Value: Caught TypeError while rendering: __init__() got an unexpected keyword argument 'error_message'
[ "This problem has nothing to do with the actual {% url %} tag. The reason you're hitting it on that tag is that the process of URL reversing actually imports all your Django views, and there is an error in a completely different place: the BlogForm class. \nWithout the code of that form it's hard to tell exactly wh...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003186502_django_python.txt
Q: Django without additional tables? is it possible to write Django apps, for example for internal/personal use with existing databases, without having the 'overhead' of Djangos own tables that are usually installed when starting a project? I would like to use existing tables via models, but not have all the other stuff that is surely useful on normal webpages. The reason would be to build small personal inspection/admin tools without being to invasive on legacy databases. A: Django doesn't install any tables by itself. It comes with some pre-fabricated applications, which install tables, but those are easily disabled by removing them from the INSTALLED_APPS setting. A: You can also just add an extra database (set it as default) for keeping the extra django overhead stuff in: DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.sqlite', 'NAME' : 'djangoOverhead', 'USER' : '', 'PASSWORD' : '', 'HOST' : 'localhost' }, 'legacyAppTables': { 'ENGINE' : 'django.db.backends.mysql', 'NAME' : 'legacyAppTables', 'USER' : '', 'PASSWORD' : '', 'HOST' : 'someRemoteHost' }, } A: The most noticable app with database tables defined is django.contrib.auth, which implements its own auth backend in the database. You could probably skip auth all together if your app is firewalled and you trust all the people that have access to it. If otherwise, you want to create your own auth mechanism using existing infrastructure, you most likely want to use another backend. If your web-server sets REMOTE_USER, you can use another builtin backend and you should be off and running. Otherwise you will have to implement your own to refer to other auth sources. From there you only need to set up your models to use existing database tables instead of letting them make their own. You can have very fine control over this, for example class MyModel(django.db.Model): MyTextField = django.db.TextField(db_column="mytextfield", primary_key=True) class Meta: db_table = "my_table" This way you can specify the exact table and columns from which each field of each model shall represent. Note that You can set the primary key to be a type other than integer. A limitation of django's ORM is that every model must have exactly one primary key, though. So if you don't have a primary key for your table, either add one, or you have to get along without the help of django's ORM. Also, since you are tying in to an existing data-set, possibly that relates to other apps, you won't likely want to use ./manage.py syncdb since it may do some undesireable things. A: Don't install any of Django's built-in apps and don't use any models.py in your apps. Your database will have zero tables in it. You won't have users, sites or sessions -- those are Django features that use the database. AFAIK you should still, however, have a SQLite database. I think that parts of Django assume you've got a database connection and it may try to establish this connection. It's an easy experiment to try. A: Just commentize the django app strings of the INSTALLED_APPS tuple in your project settings.py file (at the beginning of the project, before running syncdb).
Django without additional tables?
is it possible to write Django apps, for example for internal/personal use with existing databases, without having the 'overhead' of Djangos own tables that are usually installed when starting a project? I would like to use existing tables via models, but not have all the other stuff that is surely useful on normal webpages. The reason would be to build small personal inspection/admin tools without being to invasive on legacy databases.
[ "Django doesn't install any tables by itself. It comes with some pre-fabricated applications, which install tables, but those are easily disabled by removing them from the INSTALLED_APPS setting.\n", "You can also just add an extra database (set it as default) for keeping the extra django overhead stuff in:\nDATA...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0001313362_database_django_python.txt
Q: is it possible to connect a href link in QTextBrowser to a slot? is it possible to connect a href link in QTextBrowser to a slot? I want to make something that looks like a link in a QTextBrowser, but when user clicked on it, it will call one of the methods. Is that possible? if that is not, what is a good alternative? Thanks in advance. A: i finally found out how. there's a signal call anchorClicked(QUrl) that should do the trick :)
is it possible to connect a href link in QTextBrowser to a slot?
is it possible to connect a href link in QTextBrowser to a slot? I want to make something that looks like a link in a QTextBrowser, but when user clicked on it, it will call one of the methods. Is that possible? if that is not, what is a good alternative? Thanks in advance.
[ "i finally found out how.\nthere's a signal call anchorClicked(QUrl)\nthat should do the trick :)\n" ]
[ 1 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0003186576_pyqt4_python.txt
Q: Organizing multiple Python applications and shared library packages Suppose that I am writing two applications for my employer, we'll call them App1 and App2. These applications depend on some packages containing code needed by both. Let's say that App1 depends on PackageA and PackageB. App2 depends on PackageB and PackageC. The organizing strategy that seems natural to me would be to check everything into version control like this: repo_root +--- App1 | +--- App1.py | +--- ... and so on +--- App2 | +--- ... files for App2 +--- PackageA | +--- __init__.py | +--- ... and more files +--- PackageB | +--- ... files for PackageB +--- PackageC +--- ... files for PackageC The problem comes with importing the packages. For example, App1 and App2 both need to import PackageB, but I can't just put "import PackageB" into the main file for each of these applications. Python doesn't search the parent directory for packages to import. I know a couple of options to do this, but they both seem a little ugly. One strategy that I've used before is to put the main file for App1 and App2 into the "repo_root" directory. Then the two main files can import the packages without any problems. Another option is to use sys.path.append and file to figure out what the parent directory is and add it to the path that Python searches for modules. Is there a clean, elegant way to do something like this? Thanks for your help. Update: While the virtualenv solution can help a great deal when it comes to dealing with packages and dependencies, it almost seems like overkill for a problem that could be solved by a relative import. Carrying out a relative import seems to be fiendishly complicated, however. There is PEP 366, but that is quite complicated and probably wouldn't allow importing outside of a package anyway. I spent some time looking at importlib, but I'm pretty sure that doesn't allow importing outside of a package either. Many people seem to use munging of the sys.path, of which this seems to be the best example that I've found. But, as I mentioned, this seems a rather hackish way to do things. I've spent nearly all day on investigating this, and I don't think that there is an answer. Correct me if I'm wrong, but I now believe there is no clean, non-hackish way to do a relative import without bringing in a heavy-hitter like virtualenv and some .pth files. Anyway, thanks again for your help. I'll mark this as answered since virtualenv is the only option. A: One solution you can use for this is to have a virtualenv for each of your apps, and then use a relative .pth file to point to the Packages. This gives you fine control over the environment each of the apps is being developed in and avoids the "but I've got package_x on my machine!" problems in testing. A: virtualenv is a clean and elegant way to deal with such issues. Read the primer, then the summary on pypi, then install it and give it a try!
Organizing multiple Python applications and shared library packages
Suppose that I am writing two applications for my employer, we'll call them App1 and App2. These applications depend on some packages containing code needed by both. Let's say that App1 depends on PackageA and PackageB. App2 depends on PackageB and PackageC. The organizing strategy that seems natural to me would be to check everything into version control like this: repo_root +--- App1 | +--- App1.py | +--- ... and so on +--- App2 | +--- ... files for App2 +--- PackageA | +--- __init__.py | +--- ... and more files +--- PackageB | +--- ... files for PackageB +--- PackageC +--- ... files for PackageC The problem comes with importing the packages. For example, App1 and App2 both need to import PackageB, but I can't just put "import PackageB" into the main file for each of these applications. Python doesn't search the parent directory for packages to import. I know a couple of options to do this, but they both seem a little ugly. One strategy that I've used before is to put the main file for App1 and App2 into the "repo_root" directory. Then the two main files can import the packages without any problems. Another option is to use sys.path.append and file to figure out what the parent directory is and add it to the path that Python searches for modules. Is there a clean, elegant way to do something like this? Thanks for your help. Update: While the virtualenv solution can help a great deal when it comes to dealing with packages and dependencies, it almost seems like overkill for a problem that could be solved by a relative import. Carrying out a relative import seems to be fiendishly complicated, however. There is PEP 366, but that is quite complicated and probably wouldn't allow importing outside of a package anyway. I spent some time looking at importlib, but I'm pretty sure that doesn't allow importing outside of a package either. Many people seem to use munging of the sys.path, of which this seems to be the best example that I've found. But, as I mentioned, this seems a rather hackish way to do things. I've spent nearly all day on investigating this, and I don't think that there is an answer. Correct me if I'm wrong, but I now believe there is no clean, non-hackish way to do a relative import without bringing in a heavy-hitter like virtualenv and some .pth files. Anyway, thanks again for your help. I'll mark this as answered since virtualenv is the only option.
[ "One solution you can use for this is to have a virtualenv for each of your apps, and then use a relative .pth file to point to the Packages. This gives you fine control over the environment each of the apps is being developed in and avoids the \"but I've got package_x on my machine!\" problems in testing.\n", "v...
[ 3, 1 ]
[]
[]
[ "package", "python" ]
stackoverflow_0003187064_package_python.txt
Q: How do I call a Python/Perl script in bin folder from a Bash script? I previously used to copy Python/Perl scripts to access from my bash script. Duplication is not a good idea I know! Is there a way to call them from bin or libs folder that we have set up? For instance : My python script resides in /home/ThinkCode/libs/python/script.py My bash script resides in /home/ThinkCode/NewProcess/ProjectA/run.sh Now I want to use/call script.py from run.sh Thank you! A: Make this the first line of your python script (bash will then know this is a python script and it should be run with python): #/usr/bin/env python EDIT: my bad, it should be #!/usr/bin/env python not #!/usr/bin/python. It is better to do it this way. Then chmod your script with u+x (if not a+x). Now your python script works as an executable. Your bash script, then, can call it like you'd call any executable. A: Just do python /path/to/my/python/script.py. A: In a bash script, you execute programs the same way you do from the bash command prompt. /home/ThinkCode/libs/python/script.py If this doesn't launch the script directly, you may need to add python to the beginning (like this: python /home/ThinkCode/libs/python/script.py) and/or ensure that the script is executable (with chmod +x /home/ThinkCode/libs/python/script.py).
How do I call a Python/Perl script in bin folder from a Bash script?
I previously used to copy Python/Perl scripts to access from my bash script. Duplication is not a good idea I know! Is there a way to call them from bin or libs folder that we have set up? For instance : My python script resides in /home/ThinkCode/libs/python/script.py My bash script resides in /home/ThinkCode/NewProcess/ProjectA/run.sh Now I want to use/call script.py from run.sh Thank you!
[ "Make this the first line of your python script (bash will then know this is a python script and it should be run with python):\n#/usr/bin/env python\n\nEDIT: my bad, it should be #!/usr/bin/env python not #!/usr/bin/python. It is better to do it this way.\nThen chmod your script with u+x (if not a+x). \nNow your p...
[ 4, 3, 1 ]
[]
[]
[ "bash", "perl", "python" ]
stackoverflow_0003187301_bash_perl_python.txt
Q: How can I get the CPU temperature in Python? Possible Duplicate: Getting CPU temperature using Python? What is the simplest method of going about this? Also preferably in Celsius. A: There's no standard Python library for this, but on various platforms you may be able to use a Python bridge to a platform API to access this information. For example on Windows this is available through the Windows Management Instrumentation (WMI) APIs, which are available to Python through the PyWin32 library. There is even a Python WMI library which wraps PyWin32 to provide a more convenient interface. To get the temperature you'll need to use one of these libraries to access the root/WMI namespace and the MSAcpi_ThermalZone Temperature class. This gives the temperature in tenths of a Kelvin, so you'll need to convert to Celsius by deducting 2732 and dividing by 10. Not sure about about Linux or Mac I'm afraid, but there may be equivalent libraries you can use. A quick Google indicated that /proc/acpi/thermal_zone/THM/temperature may be what yoiu're after if your distro supports the proc virtual filesystem for accessing kernel information. A: On Linux, that info is in /proc/acpi/thermal_zone/
How can I get the CPU temperature in Python?
Possible Duplicate: Getting CPU temperature using Python? What is the simplest method of going about this? Also preferably in Celsius.
[ "There's no standard Python library for this, but on various platforms you may be able to use a Python bridge to a platform API to access this information.\nFor example on Windows this is available through the Windows Management Instrumentation (WMI) APIs, which are available to Python through the PyWin32 library. ...
[ 5, 0 ]
[]
[]
[ "cpu", "python", "temperature" ]
stackoverflow_0003184012_cpu_python_temperature.txt
Q: what is the system function in python I want to play with system command in python . for example we have this function in perl : system("ls -la"); and its run ls -la what is the system function in python ? Thanks in Advance . A: It is os.system: import os os.system('ls -la') But this won't give you any output. So subprocess.check_output is probably more what you want: >>> import subprocess >>> subprocess.check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' A: import os os.system("") From here A: In the os module there is os.system(). But if you want to do more advanced things with subprocesses the subprocess module provides a higher level interface with more possibilities that is usually preferable.
what is the system function in python
I want to play with system command in python . for example we have this function in perl : system("ls -la"); and its run ls -la what is the system function in python ? Thanks in Advance .
[ "It is os.system:\nimport os\nos.system('ls -la')\n\nBut this won't give you any output. So subprocess.check_output is probably more what you want:\n>>> import subprocess\n>>> subprocess.check_output([\"ls\", \"-l\", \"/dev/null\"])\n'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\\n'\n\n", "import os\nos.sys...
[ 6, 1, 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0003187933_function_python.txt
Q: combinations/permutations with no repeats across groupings I'm looking for C or Python code to implement either of the two pseudocode functions: function 1: list1 = [0,1,2] #any list of single-integer elements list2 = [0,3,4] list3 = [0,2,4] function1(list1, list2, list3) >>> (0,3,2),(0,3,4),(0,4,2),(1,0,2),(1,0,4),(1,3,0),(1,3,2),(1,3,4), (1,4,0),(1,4,2),(2,0,4),(2,3,0),(2,3,4),(2,4,0) Basically, it's generating all permutations that are valid, as defined by having a) one element from each list and b) no elements with the same value. function 2: list1 = [(0,1),(0,2),(0,3)] #any list of double-integer tuples list2 = [(0,4),(1,4),(2,4)] function2(list1, list2) >>> ((0,1),(2,4)) , ((0,2),(1,4)) , ((0,3),(1,4)) , ((0,3),(2,4)) Function 2 generates any permutation that has one tuple from each list and no elements within each tuple repeated. I looked at the Python itertools help and couldn't find anything that replicated these pseudo-functions. Any ideas? Thanks, Mike A: from itertools import product def function1(*seqs): return (x for x in product(*seqs) if len(x) == len(set(x))) >>> list(function1([0,1,2], [0,3,4], [0,2,4])) [(0, 3, 2), (0, 3, 4), (0, 4, 2), (1, 0, 2), (1, 0, 4), (1, 3, 0), (1, 3, 2), (1, 3, 4), (1, 4, 0), (1, 4, 2), (2, 0, 4), (2, 3, 0), (2, 3, 4), (2, 4, 0)] A: Pär Wieslander gave a good general solution for function1. Here is a general solution for function2 from itertools import product def function2(*args): return [i for i in product(*args) if (lambda x: len(x) == len(set(x)))([k for j in i for k in j])] Of course you can return a generator expression instead if it suits your purpose better. For example: def function2(*args): return (i for i in product(*args) if (lambda x: len(x) == len(set(x)))([k for j in i for k in j])) A: >>> [(x,y,z) for x in list1 for y in list2 for z in list3 if (x != y and y != z and x != z)] [(0, 3, 2), (0, 3, 4), (0, 4, 2), (1, 0, 2), (1, 0, 4), (1, 3, 0), (1, 3, 2), (1 , 3, 4), (1, 4, 0), (1, 4, 2), (2, 0, 4), (2, 3, 0), (2, 3, 4), (2, 4, 0)] for the first one A: def f2(first, second): for a in first: for b in second: if len(set(a + b)) == 4: yield (a, b) A: For anyone wondering, here was the final implementation: def function2(arg1, arg2): return [i for i in product(*arg1) if (lambda x: len(x) == len(set(x))) ([k for j in i for k in j] + arg2)] Two changes from gnibbler's excellent solution: 1) arg1 is now a list that includes every list that would have been in args*. Rather than having to list out each of args*, I just pass arg1 and unpack it in the product(*arg1). Not sure if there's a better way to do this... 2) arg2 is a list of things I want to exclude from any of the combinations. Including them in the parameters for the lambda function lets me further constrain the results of the product(*arg1) without introducing combinations. With named variables to show you what I'm doing with it, here's the exact code: def makeMyMenu(allmeals, dont_eat): return [menu for menu in product(*allmeals) if (lambda x: len(x) == len(set(x))) ([ingredient for meal in menu for ingredient in meal] + dont_eat)]
combinations/permutations with no repeats across groupings
I'm looking for C or Python code to implement either of the two pseudocode functions: function 1: list1 = [0,1,2] #any list of single-integer elements list2 = [0,3,4] list3 = [0,2,4] function1(list1, list2, list3) >>> (0,3,2),(0,3,4),(0,4,2),(1,0,2),(1,0,4),(1,3,0),(1,3,2),(1,3,4), (1,4,0),(1,4,2),(2,0,4),(2,3,0),(2,3,4),(2,4,0) Basically, it's generating all permutations that are valid, as defined by having a) one element from each list and b) no elements with the same value. function 2: list1 = [(0,1),(0,2),(0,3)] #any list of double-integer tuples list2 = [(0,4),(1,4),(2,4)] function2(list1, list2) >>> ((0,1),(2,4)) , ((0,2),(1,4)) , ((0,3),(1,4)) , ((0,3),(2,4)) Function 2 generates any permutation that has one tuple from each list and no elements within each tuple repeated. I looked at the Python itertools help and couldn't find anything that replicated these pseudo-functions. Any ideas? Thanks, Mike
[ "from itertools import product\ndef function1(*seqs):\n return (x for x in product(*seqs) if len(x) == len(set(x)))\n\n>>> list(function1([0,1,2], [0,3,4], [0,2,4]))\n[(0, 3, 2), (0, 3, 4), (0, 4, 2), (1, 0, 2), (1, 0, 4), (1, 3, 0), (1, 3, 2), (1, 3, 4), (1, 4, 0), (1, 4, 2), (2, 0, 4), (2, 3, 0), (2, 3, 4), (2, ...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "c", "combinatorics", "permutation", "python" ]
stackoverflow_0003177409_c_combinatorics_permutation_python.txt
Q: Is there a fast XML parser in Python that allows me to get start of tag as byte offset in stream? I am working with potentially huge XML files containing complex trace information from on of my projects. I would like to build indexes for those XML files so that one can quickly find sub sections of the XML document without having to load it all into memory. If I have created a "shelve" index that could contains information like "books for author Joe" are at offsets [22322, 35446, 54545] then I can just open the xml file like a regular text file and seek to those offsets and then had that to one of the DOM parser that takes a file or strings. The part that I have not figured out yet is how to quickly parse the XML and create such an index. So what I need as a fast SAX parser that allows me to find the start offset of tags in the file together with the start events. So I can parse a subsection of the XML together with the starting point into the document, extract the key information and store the key and offset in the shelve index. A: Since locators return line and column numbers in lieu of offset, you need a little wrapping to track line ends -- a simplified example (could have some offbyones;-)...: import cStringIO import re from xml import sax from xml.sax import handler relinend = re.compile(r'\n') txt = '''<foo> <tit>Bar</tit> <baz>whatever</baz> </foo>''' stm = cStringIO.StringIO(txt) class LocatingWrapper(object): def __init__(self, f): self.f = f self.linelocs = [] self.curoffs = 0 def read(self, *a): data = self.f.read(*a) linends = (m.start() for m in relinend.finditer(data)) self.linelocs.extend(x + self.curoffs for x in linends) self.curoffs += len(data) return data def where(self, loc): return self.linelocs[loc.getLineNumber() - 1] + loc.getColumnNumber() locstm = LocatingWrapper(stm) class Handler(handler.ContentHandler): def setDocumentLocator(self, loc): self.loc = loc def startElement(self, name, attrs): print '%s@%s:%s (%s)' % (name, self.loc.getLineNumber(), self.loc.getColumnNumber(), locstm.where(self.loc)) sax.parse(locstm, Handler()) Of course you don't need to keep all of the linelocs around -- to save memory, you can drop "old" ones (below the latest one queried) but then you need to make linelocs a dict, etc.
Is there a fast XML parser in Python that allows me to get start of tag as byte offset in stream?
I am working with potentially huge XML files containing complex trace information from on of my projects. I would like to build indexes for those XML files so that one can quickly find sub sections of the XML document without having to load it all into memory. If I have created a "shelve" index that could contains information like "books for author Joe" are at offsets [22322, 35446, 54545] then I can just open the xml file like a regular text file and seek to those offsets and then had that to one of the DOM parser that takes a file or strings. The part that I have not figured out yet is how to quickly parse the XML and create such an index. So what I need as a fast SAX parser that allows me to find the start offset of tags in the file together with the start events. So I can parse a subsection of the XML together with the starting point into the document, extract the key information and store the key and offset in the shelve index.
[ "Since locators return line and column numbers in lieu of offset, you need a little wrapping to track line ends -- a simplified example (could have some offbyones;-)...:\nimport cStringIO\nimport re\nfrom xml import sax\nfrom xml.sax import handler\n\nrelinend = re.compile(r'\\n')\n\ntxt = '''<foo>\n <ti...
[ 3 ]
[]
[]
[ "indexing", "parsing", "python", "sax", "xml" ]
stackoverflow_0003187964_indexing_parsing_python_sax_xml.txt
Q: Can i use dictionaries as matrices in python? I am just a beginner in python. Recently i am learning to use dictionaries but my knowledge in it is still limited. I have this idea popping out from my head but i am not sure whether it is workable in python. I have 3 document looks like this: DOCNO= 5 nanofluids :0.6841 introduction:0.2525 module :0.0000 to :0.0000 learning :0.0000 DOCID= 1 nanofluids :0.0000 introduction:0.2372 module :0.0000 to :0.0000 learning :0.1185 DOCNO= 12 nanofluids :0.0000 introduction:0.0000 module :0.5647 to :0.0000 learning :0.2084 I know how to store a single value in dictionary. For example: data={5: 0.67884, 1:0.1567, 12:3455} But what i want to do now is storing an array with corresponding document number which looks like: import array data={ 5:array([0.6841,0.2525,0.0000.0000,0.0000]), 1:array([0.0000,0.2372,0.0000,0.0000,0.1185]), 12:array([0.0000,0.0000,0.5647,0.0000,0.2084])} * My python v2.6.5 doesn't seem to let me do this.* If assume that the above operation works, i want to perform dot product or matrix product to find the similarity between pairs of documents. My idea is to arrange the array in 3x5 matrix and multiply by its transpose which is 5x3. This will return a 3x3 matrix which tells me the relationship between two documents. for example: [ 5:[0.6841,0.2525,0.0000,0.0000,0.0000], 1:[0.0000, 0.2372,0.0000,0.0000,0.1185], 12:[0.0000,0.0000,0.5647,0.0000,0.2084] ] and multiply by its transpose( i am not sure how to do that) and the result will be 3x3 matrix that corresponded to "DOCNO" by "DOCNO". Bottom line is i need to be able to retrieve the DOCNO. For example (5,1) shows the relationship between document 5 and 1. Or ( 1,12) shows the relationship between document 1 and 12. I am not sure whether this is possible in python but other similar resolution will be appreciated. Thanks for your time. A: First, you should look at the Python documentation for arrays. There are three things wrong with your sample code: You've imported the array module, but not the array class. Try this: from array import array You've got 0.0000.0000 as a float in your list. array takes two arguments; a typecode and the initialization values. Change your array([...]) calls to array('f', [...]) calls, and it should work. But truth be told, Python doesn't have many basic tools for this built in (you can always write your own). If you're doing matrix algebra you should probably use NumPy. It can handle both arrays and matrices, along with all the relevant transforms. A: To fix your data assigment try something like this: from array import array data={ 5:array('d',[0.6841,0.2525,0.0000,0.0000,0.0000]), 1:array('d',[0.0000,0.2372,0.0000,0.0000,0.1185]), 12:array('d',[0.0000,0.0000,0.5647,0.0000,0.2084])} That way or another I would use NumPy for rest of calculations.
Can i use dictionaries as matrices in python?
I am just a beginner in python. Recently i am learning to use dictionaries but my knowledge in it is still limited. I have this idea popping out from my head but i am not sure whether it is workable in python. I have 3 document looks like this: DOCNO= 5 nanofluids :0.6841 introduction:0.2525 module :0.0000 to :0.0000 learning :0.0000 DOCID= 1 nanofluids :0.0000 introduction:0.2372 module :0.0000 to :0.0000 learning :0.1185 DOCNO= 12 nanofluids :0.0000 introduction:0.0000 module :0.5647 to :0.0000 learning :0.2084 I know how to store a single value in dictionary. For example: data={5: 0.67884, 1:0.1567, 12:3455} But what i want to do now is storing an array with corresponding document number which looks like: import array data={ 5:array([0.6841,0.2525,0.0000.0000,0.0000]), 1:array([0.0000,0.2372,0.0000,0.0000,0.1185]), 12:array([0.0000,0.0000,0.5647,0.0000,0.2084])} * My python v2.6.5 doesn't seem to let me do this.* If assume that the above operation works, i want to perform dot product or matrix product to find the similarity between pairs of documents. My idea is to arrange the array in 3x5 matrix and multiply by its transpose which is 5x3. This will return a 3x3 matrix which tells me the relationship between two documents. for example: [ 5:[0.6841,0.2525,0.0000,0.0000,0.0000], 1:[0.0000, 0.2372,0.0000,0.0000,0.1185], 12:[0.0000,0.0000,0.5647,0.0000,0.2084] ] and multiply by its transpose( i am not sure how to do that) and the result will be 3x3 matrix that corresponded to "DOCNO" by "DOCNO". Bottom line is i need to be able to retrieve the DOCNO. For example (5,1) shows the relationship between document 5 and 1. Or ( 1,12) shows the relationship between document 1 and 12. I am not sure whether this is possible in python but other similar resolution will be appreciated. Thanks for your time.
[ "First, you should look at the Python documentation for arrays. There are three things wrong with your sample code:\n\nYou've imported the array module, but not the array class. Try this:\nfrom array import array\nYou've got 0.0000.0000 as a float in your list.\narray takes two arguments; a typecode and the initi...
[ 3, 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0003188058_arrays_python.txt
Q: Split field to array when accessed I have Django model that looks like this: class Categories(models.Model): """ Model for storing the categories """ name = models.CharField(max_length=8) keywords = models.TextField() spamwords = models.TextField() translations = models.TextField() def __unicode__(self): return self.name class Meta: verbose_name = _('Category') verbose_name_plural = _('Categories') The fields keywords, spamwords and translations contain huge chunks of comma-separated text. Could someone tell how I could write a function inside the model which for a particular fieldname, returns the value a list so that I could access it something like this: cat = Categories.objects.get(id=1) print cat.keywords.to_array() ...it returns the field data, split into an array. (The splitting bit is very simple and i know how to do that - string.split(',') Thanks A: You can easily add an instance method to your Categories class like this: class Categories(models.Model): ... rest of your definition ... def get_spamwords_as_list(self): return self.spamwords.split(',') You could use it like this: cat = Categories.objects.get(id=1) print cat.get_spamwords_as_list() But I'm curious about your underlying data model -- why aren't you using a ManyToManyField to model your categories? UPDATE: Adding an alternative generic version: def get_word_list(self, name): if name in ['keywords', 'spamwords', 'translations']: return getattr(self, name).split(',') # or even def __getattr__(self, name): if name[-5:] == '_list' and name[:-5] in ['keywords', 'spamwords', 'translations']: return getattr(self, name[:-5]).split(',') else raise AttributeError cat = Categories.get(pk=1) cat.get_word_list('keywords') # ['word 1', 'word 2', ...] cat.keywords_list # ['word 1', 'word 2', ...] with 2nd approach cat.keywords # 'word 1, word 2' -- remains CSV A: I did it this way: class Categories(models.Model): """ Model for storing the categories """ name = models.CharField(max_length=8) keywords = models.TextField() spamwords = models.TextField() translations = models.TextField() def __unicode__(self): return self.name def __getattribute__(self, name): if name not in ['keywords', 'spamwords', 'translations']: return object.__getattribute__(self, name) else: return object.__getattribute__(self, name).split(',') class Meta: verbose_name = _('Category') verbose_name_plural = _('Categories')
Split field to array when accessed
I have Django model that looks like this: class Categories(models.Model): """ Model for storing the categories """ name = models.CharField(max_length=8) keywords = models.TextField() spamwords = models.TextField() translations = models.TextField() def __unicode__(self): return self.name class Meta: verbose_name = _('Category') verbose_name_plural = _('Categories') The fields keywords, spamwords and translations contain huge chunks of comma-separated text. Could someone tell how I could write a function inside the model which for a particular fieldname, returns the value a list so that I could access it something like this: cat = Categories.objects.get(id=1) print cat.keywords.to_array() ...it returns the field data, split into an array. (The splitting bit is very simple and i know how to do that - string.split(',') Thanks
[ "You can easily add an instance method to your Categories class like this:\nclass Categories(models.Model):\n ... rest of your definition ...\n\n def get_spamwords_as_list(self):\n return self.spamwords.split(',')\n\nYou could use it like this:\ncat = Categories.objects.get(id=1)\nprint cat.get_spamwords_...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003187961_django_django_models_python.txt
Q: Generation of 8 bit palette from png file via Python What would be the best python based library for generating 8-bit palette from the given .png file. As in photoshop generating under .pal format. PS: Input PNG is already in 8 bit format. (paletted) Regards A: I've not been able to find a spec for .PAL (Photoshop calls it "Microsoft PAL"), but the format is easily reverse-engineered. This works: def extractPalette(infile,outfile): im=Image.open(infile) pal=im.palette.palette if im.palette.rawmode!='RGB': raise ValueError("Invalid mode in PNG palette") output=open(outfile,'wb') output.write('RIFF\x10\x04\x00\x00PAL data\x04\x04\x00\x00\x00\x03\x00\x01') # header output.write(''.join(pal[i:i+3]+'\0' for i in range(0,768,3))) # convert RGB to RGB0 before writing output.close() A: If it's a palletted image then you can use the getcolors() method once you have loaded it into PIL. If it's a RGB or RGBA image then you'll need to do color reduction until you have 256 colors at most.
Generation of 8 bit palette from png file via Python
What would be the best python based library for generating 8-bit palette from the given .png file. As in photoshop generating under .pal format. PS: Input PNG is already in 8 bit format. (paletted) Regards
[ "I've not been able to find a spec for .PAL (Photoshop calls it \"Microsoft PAL\"), but the format is easily reverse-engineered. This works:\ndef extractPalette(infile,outfile):\n im=Image.open(infile)\n pal=im.palette.palette\n if im.palette.rawmode!='RGB':\n raise ValueError(\"Invalid mode in PNG ...
[ 3, 1 ]
[]
[]
[ "color_palette", "palette", "png", "python" ]
stackoverflow_0003184821_color_palette_palette_png_python.txt
Q: Python regular expression style Is there a Pythonic 'standard' for how regular expressions should be used? What I typically do is perform a bunch of re.compile statements at the top of my module and store the objects in global variables... then later on use them within my functions and classes. I could define the regexs within the functions I would be using them, but then they would be recompiled every time. Or, I could forgo re.compile completely, but if I am using the same regex many times it seems like recompiling would incur unnecessary overhead. A: One way that would be a lot cleaner is using a dictionary: PATTERNS = {'pattern1': re.compile('foo.*baz'), 'snake': re.compile('python'), 'knight': re.compile('[Aa]rthur|[Bb]edevere|[Ll]auncelot')} That would solve your problem of having a polluted namespace, plus it's pretty obvious to anyone looking at your code what PATTERNS is and will be used for, and it satisfies the CAPS convention for globals. In addition, you can easily call re.match(PATTERNS[pattern]), or whatever it is your logic calls for. A: I also tend to use your first approach but I've never benchmarked this. One thing to note, from the documentation, is that: The compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions. One worry is that you could have regular expressions that don't get used. If you compile all expressions at module load time you could be incurring the cost of compiling the expression but never benefiting from that "optimization". I don't suppose this would matter unless you compile lots of regular expressions that never get used. One thing I do recommend is to use the re.VERBOSE (or re.X) flag and include comments and white space to make anything beyond the most trivial regular expression more readable. A: I personally use your first approach where the expressions I'll reuse are compiled early on and available globally to the functions / methods that will need them. In my experience this is reliable, and reduces total compile time for them.
Python regular expression style
Is there a Pythonic 'standard' for how regular expressions should be used? What I typically do is perform a bunch of re.compile statements at the top of my module and store the objects in global variables... then later on use them within my functions and classes. I could define the regexs within the functions I would be using them, but then they would be recompiled every time. Or, I could forgo re.compile completely, but if I am using the same regex many times it seems like recompiling would incur unnecessary overhead.
[ "One way that would be a lot cleaner is using a dictionary:\nPATTERNS = {'pattern1': re.compile('foo.*baz'),\n 'snake': re.compile('python'),\n 'knight': re.compile('[Aa]rthur|[Bb]edevere|[Ll]auncelot')}\n\nThat would solve your problem of having a polluted namespace, plus it's pretty obvious ...
[ 6, 4, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003188024_python_regex.txt
Q: Python and JSON: using object_hook to do class hinting for multiple different classes Using the json module in python 2.6, I'm experiencing some unexpected behavior when passing a function to object_hook. I'm attempting to turn a json object into a class defined in my code. This class requires that instances of a different class as arguments. Something like this: class OuterClass: def __init__(self, arg, *InnerClass_instances): self.arg = arg self.class2 = InnerClass_instances class InnerClass: def __init__(self, name, value): self.name = name self.value = value It seems to me, that if to create a JSON object that contains all of the information for an instance of OuterClass, it would be necessary to include all of the information for each instance of InnerClass that would be passed to it. So, I thought I could write two functions to parse JSON object, one for each class, and have the function creating OuterClass, call the function that creates InnerClass instances. Something like this: def create_InnerClass(dct): if '__InnerClass__' in dct: name = dct['name'] value = dct['value'] return InnerClass(name, value) def create_OuterClass(dct): if '__OuterClass__' in dct: arg = dct['arg'] InnerClass_instances = [create_InnerClass(dct2) \ for dct2 in dct['InnerClass_instances']] return OuterClass(arg, *InnerClass_intances) Which, I assumed would work for s = #triple quotes omitted for syntax highlighting reasons { "__OuterClass__": true, "arg": 4, "InnerClass_instances": [ {"__InnerClass__": true, "name": "Joe", "value": 12}, {"__InnerClass__": true, "name": "Jimmy", "value":7} ] } outerClass = json.loads(s, object_hook = creat_OuterClass) However, calling json.loads as above returns this error: if '__InnerClass__' in dct: TypeError: argument of type 'NoneType' is not iterable However, simply calling json.loads(s), and then json.dumps(outerClass) works perfectly fine. So, it seems like something in this way of approaching the object_hook parameter is causing the dictionaries that define InnerClass instances to be turned into NoneType objects. Am I missing some understanding as to how the function object_hook is used in parsing JSON objects? Is there a way to do class hinting for multiple types of classes in a single JSON object? Nothing I've read so far has suggested that this is or is not possible. A: Not every time create_OuterClass is called will __OuterClass__ be a key in dct. Therefore, your create_OuterClass should handle this case as well. The default is to return dct: def create_OuterClass(dct): # print('create_OuterClass: {0}'.format(dct)) if '__OuterClass__' in dct: arg = dct['arg'] InnerClass_instances = [create_InnerClass(dct2) for dct2 in dct['InnerClass_instances']] return OuterClass(arg, *InnerClass_instances) return dct If you include the above print statement you get create_OuterClass: {u'__InnerClass__': True, u'name': u'Joe', u'value': 12} create_OuterClass: {u'__InnerClass__': True, u'name': u'Jimmy', u'value': 7} create_OuterClass: {u'__OuterClass__': True, u'InnerClass_instances': [{u'__InnerClass__': True, u'name': u'Joe', u'value': 12}, {u'__InnerClass__': True, u'name': u'Jimmy', u'value': 7}], u'arg': 4} This shows you how json.loads is using the object_hook callback function. It calls it first with the inner dicts, and only later with the outer dict.
Python and JSON: using object_hook to do class hinting for multiple different classes
Using the json module in python 2.6, I'm experiencing some unexpected behavior when passing a function to object_hook. I'm attempting to turn a json object into a class defined in my code. This class requires that instances of a different class as arguments. Something like this: class OuterClass: def __init__(self, arg, *InnerClass_instances): self.arg = arg self.class2 = InnerClass_instances class InnerClass: def __init__(self, name, value): self.name = name self.value = value It seems to me, that if to create a JSON object that contains all of the information for an instance of OuterClass, it would be necessary to include all of the information for each instance of InnerClass that would be passed to it. So, I thought I could write two functions to parse JSON object, one for each class, and have the function creating OuterClass, call the function that creates InnerClass instances. Something like this: def create_InnerClass(dct): if '__InnerClass__' in dct: name = dct['name'] value = dct['value'] return InnerClass(name, value) def create_OuterClass(dct): if '__OuterClass__' in dct: arg = dct['arg'] InnerClass_instances = [create_InnerClass(dct2) \ for dct2 in dct['InnerClass_instances']] return OuterClass(arg, *InnerClass_intances) Which, I assumed would work for s = #triple quotes omitted for syntax highlighting reasons { "__OuterClass__": true, "arg": 4, "InnerClass_instances": [ {"__InnerClass__": true, "name": "Joe", "value": 12}, {"__InnerClass__": true, "name": "Jimmy", "value":7} ] } outerClass = json.loads(s, object_hook = creat_OuterClass) However, calling json.loads as above returns this error: if '__InnerClass__' in dct: TypeError: argument of type 'NoneType' is not iterable However, simply calling json.loads(s), and then json.dumps(outerClass) works perfectly fine. So, it seems like something in this way of approaching the object_hook parameter is causing the dictionaries that define InnerClass instances to be turned into NoneType objects. Am I missing some understanding as to how the function object_hook is used in parsing JSON objects? Is there a way to do class hinting for multiple types of classes in a single JSON object? Nothing I've read so far has suggested that this is or is not possible.
[ "Not every time create_OuterClass is called will __OuterClass__ be a key in dct. Therefore, your create_OuterClass should handle this case as well. The default is to return dct:\ndef create_OuterClass(dct):\n # print('create_OuterClass: {0}'.format(dct)) \n if '__OuterClass__' in dct:\n arg = dct['...
[ 2 ]
[]
[]
[ "json", "python" ]
stackoverflow_0003188416_json_python.txt
Q: Python MySQL Performance: Runs fast in mysql command line, but slow with cursor.execute I'm writing a script for exporting some data. Some details about the environment: The project is Django based I'm using raw/custom SQL for the export The database engine is MySQL. The database and code are on the same box.- Details about the SQL: A bunch of inner joins A bunch of columns selected, some with a basic multiplication calculation. The sql result has about 55K rows When I run the SQL statement in the mysql command line, it takes 3-4 seconds When I run the SQL in my python script the line cursor.execute(sql, [id]) takes over 60 seconds. Any ideas on what might be causing this? A: Two ideas: MySQL may have query caching enabled, which makes it difficult to get accurate timing when you run the same query repeatedly. Try changing the ID in your query to make sure that it really does run in 3-4 seconds consistently. Try using strace on the python process to see what it is doing during this time.
Python MySQL Performance: Runs fast in mysql command line, but slow with cursor.execute
I'm writing a script for exporting some data. Some details about the environment: The project is Django based I'm using raw/custom SQL for the export The database engine is MySQL. The database and code are on the same box.- Details about the SQL: A bunch of inner joins A bunch of columns selected, some with a basic multiplication calculation. The sql result has about 55K rows When I run the SQL statement in the mysql command line, it takes 3-4 seconds When I run the SQL in my python script the line cursor.execute(sql, [id]) takes over 60 seconds. Any ideas on what might be causing this?
[ "Two ideas: \n\nMySQL may have query caching enabled, which makes it difficult to get accurate timing when you run the same query repeatedly. Try changing the ID in your query to make sure that it really does run in 3-4 seconds consistently.\nTry using strace on the python process to see what it is doing during th...
[ 0 ]
[]
[]
[ "mysql", "performance", "python" ]
stackoverflow_0003188289_mysql_performance_python.txt
Q: Python Google App Engine: A better way of saying, "If an object does not exist in the datastore, do something"? I am asking because the way I have it right now seems really strange. Basically, I am saying, "If there is an exception thrown, do something. Else, do nothing." Here is some sample code: try: db.get(db.Key(uid)) except: newUser = User(key_name=str(uid)) newUser.first_name = self.request.get("first") newUser.last_name = self.request.get("last") newUser.email = self.request.get("email") newUser.phone = self.request.get("phone") db.put(newUser) Thanks! A: Use User.get_by_key_name(str(uid)) instead. It will return None if the entity doesn't exist. See http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_by_key_name for details. User.get_or_insert(str(uid)) might also be a good fit for what you're trying to do. A: Does db.Key return None if there is no user with the given uid? If so, you could just do: if db.Key(uid) == None: newUser = User(key_name=str(uid)) newUser.first_name = self.request.get("first") newUser.last_name = self.request.get("last") newUser.email = self.request.get("email") newUser.phone = self.request.get("phone") db.put(newUser) EDIT: going by your comment, you get an exception anyway, so unless you have some other way of checking for nonexistence of a User, you may as well stick with what you have. You could always do it the other way around and put the bulk of the code in the try block, though, assuming that an exception will be thrown when trying to add a User with a Key that already exists in the database, like so: try: newUser = User(key_name=str(uid)) newUser.first_name = self.request.get("first") newUser.last_name = self.request.get("last") newUser.email = self.request.get("email") newUser.phone = self.request.get("phone") db.put(newUser) except: pass Or something like that.
Python Google App Engine: A better way of saying, "If an object does not exist in the datastore, do something"?
I am asking because the way I have it right now seems really strange. Basically, I am saying, "If there is an exception thrown, do something. Else, do nothing." Here is some sample code: try: db.get(db.Key(uid)) except: newUser = User(key_name=str(uid)) newUser.first_name = self.request.get("first") newUser.last_name = self.request.get("last") newUser.email = self.request.get("email") newUser.phone = self.request.get("phone") db.put(newUser) Thanks!
[ "Use User.get_by_key_name(str(uid)) instead. It will return None if the entity doesn't exist. \nSee http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_by_key_name for details.\nUser.get_or_insert(str(uid)) might also be a good fit for what you're trying to do.\n", "Does db.Key return...
[ 6, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003188436_google_app_engine_python.txt
Q: Picking a front-end/interpreter for a scientific code The simulation tool I have developed over the past couple of years, is written in C++ and currently has a tcl interpreted front-end. It was written such that it can be run either in an interactive shell, or by passing an input file. Either way, the input file is written in tcl (with many additional simulation-specific commands I have added). This allows for quite powerful input files (e.g.- when running monte-carlo sims, random distributions can be programmed as tcl procedures directly in the input file). Unfortunately, I am finding that the tcl interpreter is becoming somewhat limited compared to what more modern interpreted languages have to offer, and its syntax seems a bit arcane. Since the computational engine was written as a library with a c-compatible API, it should be straightforward to write alternative front-ends, and I am thinking of moving to a new interpreter, however I am having a bit of a time choosing (mostly because I don't have significant experience with many interpreted languages). The options I have begun to explore are as follows: Remaining with tcl: Pros: - No need to change the existing code. - Existing input files stay the same. (though I'd probably keep the tcl front end as an option) - Mature language with lots of community support. Cons: - Feeling limited by the language syntax. - Getting complaints from users as to the difficulty of learning tcl. Python: Pros: - Modern interpreter, known to be quite efficient. - Large, active community. - Well known scientific and mathematical modules, such as scipy. - Commonly used in the academic Scientific/engineering community (typical users of my code) Cons: - I've never used it and thus would take time to learn the language (this is also a pro, as I've been meaning to learn python for quite some time) - Strict formatting of the input files (indentation, etc..) Matlab: Pros: - Very power and widely used mathematical tool - Powerful built-in visualization/plotting. - Extensible, through community submitted code, as well as commercial toolboxes. - Many in science/engineering academia is familiar with and comfortable with matlab. Cons: - Can not distribute as an executable- would need to be an add-on/toolbox. - Would require (?) the matlab compiler (which is pricy). - Requires Matlab, which is also pricy. These pros and cons are what I've been able to come up with, though I have very little experience with interpreted languages in general. I'd love to hear any thoughts on both the interpreters I've proposed here, if these pros/cons listed are legitimate, and any other interpreters I haven't thought of (e.g.- would php be appropriate for something like this? lua?). First hand experience with embedding an interpreter in your code is definitely a plus! A: I was a strong Tcl/Tk proponent from pre-release, until I did a largish project with it and found how unmaintainable it is. Unfortunately, since prototypes are so easy in Tcl, you wind up with "one-off" scripts taking on lives of their own. Having adopted Python in the last few months, I'm finding it to be all that Tcl promised and a whole lot more. As many a Python veteran can tell you, source indentation is a bother for the first hour at most and then it seems not a hindrance but affirmatively helpful. Incidentally Tcl's author, John Ousterhout was alternately praised and panned for writing a language that forced the One True Brace Style on Tcl coders (I was 1TBS so it was fine by me). The only Tcl constructs that aren't handled well by Python are arbitrary eval "${prefix}${command} arg" constructs that shouldn't be used in Tcl anyway but are and the uplevel type statements (which were a nice idea but made for some hairy code). Indeed, Python feels a little antagonistic to dynamic eval but I think that is a Good Thing. Unfortunately, I've yet to come along with a language that embraced its GUI as well as Tcl/Tk; Tkinter does the job in Python but it hurts. I cannot speak to Matlab at all. With a few months of Python under my belt, I'd almost certainly port any Tcl program that is in ongoing development to Python for purposes of sanity. A: Have you considered using Octave? From what I gather, it is nearly a drop-in replacement for much of matlab. This might allow you to support matlab for those who have it, and a free alternative for those who don't. Since the "meat" of your program appears to be written in another language, the performance considerations seem to be not as important as providing an environment that has: plotting and visualization capabilities, is cross-platform, has a big user base, and in a language that nearly everyone in academia and/or involved with modelling fluid flow probably already knows. Matlab/Octave can potentially have all of those. A: Well, unless there are any other suggestions, the final answer I have arrived at is to go with Python. I seriously considered matlab/octave, but when reading the octave API and matlab API, they are different enough that I'd need to build separate interfaces for each (or get very creative with macros). With python I end up with a single, easier to maintain codebase for the front end, and it is used by just about everyone we know. Thanks for the tips/feedback everyone!
Picking a front-end/interpreter for a scientific code
The simulation tool I have developed over the past couple of years, is written in C++ and currently has a tcl interpreted front-end. It was written such that it can be run either in an interactive shell, or by passing an input file. Either way, the input file is written in tcl (with many additional simulation-specific commands I have added). This allows for quite powerful input files (e.g.- when running monte-carlo sims, random distributions can be programmed as tcl procedures directly in the input file). Unfortunately, I am finding that the tcl interpreter is becoming somewhat limited compared to what more modern interpreted languages have to offer, and its syntax seems a bit arcane. Since the computational engine was written as a library with a c-compatible API, it should be straightforward to write alternative front-ends, and I am thinking of moving to a new interpreter, however I am having a bit of a time choosing (mostly because I don't have significant experience with many interpreted languages). The options I have begun to explore are as follows: Remaining with tcl: Pros: - No need to change the existing code. - Existing input files stay the same. (though I'd probably keep the tcl front end as an option) - Mature language with lots of community support. Cons: - Feeling limited by the language syntax. - Getting complaints from users as to the difficulty of learning tcl. Python: Pros: - Modern interpreter, known to be quite efficient. - Large, active community. - Well known scientific and mathematical modules, such as scipy. - Commonly used in the academic Scientific/engineering community (typical users of my code) Cons: - I've never used it and thus would take time to learn the language (this is also a pro, as I've been meaning to learn python for quite some time) - Strict formatting of the input files (indentation, etc..) Matlab: Pros: - Very power and widely used mathematical tool - Powerful built-in visualization/plotting. - Extensible, through community submitted code, as well as commercial toolboxes. - Many in science/engineering academia is familiar with and comfortable with matlab. Cons: - Can not distribute as an executable- would need to be an add-on/toolbox. - Would require (?) the matlab compiler (which is pricy). - Requires Matlab, which is also pricy. These pros and cons are what I've been able to come up with, though I have very little experience with interpreted languages in general. I'd love to hear any thoughts on both the interpreters I've proposed here, if these pros/cons listed are legitimate, and any other interpreters I haven't thought of (e.g.- would php be appropriate for something like this? lua?). First hand experience with embedding an interpreter in your code is definitely a plus!
[ "I was a strong Tcl/Tk proponent from pre-release, until I did a largish project with it and found how unmaintainable it is. Unfortunately, since prototypes are so easy in Tcl, you wind up with \"one-off\" scripts taking on lives of their own.\nHaving adopted Python in the last few months, I'm finding it to be all ...
[ 5, 3, 0 ]
[]
[]
[ "c++", "interpreter", "matlab", "python", "tcl" ]
stackoverflow_0003167661_c++_interpreter_matlab_python_tcl.txt
Q: Using Env.js with Python I am having a bit of difficulty getting Env.js working with my Python application. The documentation on the website states: develop bridges for running Envjs in Ruby, Python, and other host languages with the SpiderMonkey and V8 javascript engines However, I have been unable to find any bridges to Python in either the main branch from github, or from Google. Has anyone had any success getting Env.js working with Python? A: Yeah, not sure where that text came from. I'm a committer on env.js and haven't heard of any integration efforts with python against V8 or SpiderMonkey. Looks like NoseJS has some integration, but it doesn't look too general. Looks to be against the Rhino port of env.js with some tentative comments about using Python-Spidermonkey. There is a port that uses SpiderMonkey via Ruby: http://github.com/smparkes/env-js.
Using Env.js with Python
I am having a bit of difficulty getting Env.js working with my Python application. The documentation on the website states: develop bridges for running Envjs in Ruby, Python, and other host languages with the SpiderMonkey and V8 javascript engines However, I have been unable to find any bridges to Python in either the main branch from github, or from Google. Has anyone had any success getting Env.js working with Python?
[ "Yeah, not sure where that text came from. I'm a committer on env.js and haven't heard of any integration efforts with python against V8 or SpiderMonkey.\nLooks like NoseJS has some integration, but it doesn't look too general. Looks to be against the Rhino port of env.js with some tentative comments about using Py...
[ 1 ]
[]
[]
[ "envjs", "javascript", "python" ]
stackoverflow_0003188541_envjs_javascript_python.txt
Q: Compress XML column in Sqlite with Python is SLOW! I'm new to Python and Sqlite, so I'm sure there's a better way to do this. I have a DB with 6000 rows, where 1 column is a 14K XML string. I wanted to compress all those XML strings to make the DB smaller. Unfortunately, the script below is much, much slower than this simple command line (which takes a few seconds). sqlite3 weather.db .dump | gzip -c > backup.gz I know it's not the same thing, but it does read/convert the DB to text and run gzip. So I was hoping this script would be within 10X performance, but it is more like 1000X slower. Is there a way to make the following script more efficient? Thanks. import zlib, sqlite3 conn = sqlite3.connect(r"weather.db") r = conn.cursor() w = conn.cursor() rows = r.execute("select date,location,xml_data from forecasts") for row in rows: data = zlib.compress(row[2]) w.execute("update forecasts set xml_data=? where date=? and location=?", (data, row[0], row[1])) conn.commit() conn.close() A: Not sure you can increase the performance by doing an update after the fact. there's too much overhead between doing the compress and updating the record. you won't gain any space savings unless you do a vacuum after you're done with the updates. the best solution would probably be to do the compress when the records are first inserted. then you get the space savings and the performance hit won't likely be as noticeable. if you can't do it on the insert, then i think you've explored the two possibilities and seen the results. A: You are comparing apples to oranges here. The big difference between the sqlite3|gzip and python version is that the later writes the changes back to the DB! What sqlite3|gzip does is: read the db gzip the text in addition to the above the python version writes the gzipped text back into the db with one UPDATE per read record. A: Sorry, but are you implicitly starting a transaction in your code? If you're autocommitting after each UPDATE that will slow you down substantially. Do you have an appropriate index on date and/or location? What kind of variation do you have in those columns? Can you use an autonumbered integer primary key in this table? Finally, can you profile how much time you're spending in the zlib calls and how much in the UPDATEs? In addition to the database writes that will slow this process down, your database version involves 6000 calls (with 6000 initializations) of the zip algorithm.
Compress XML column in Sqlite with Python is SLOW!
I'm new to Python and Sqlite, so I'm sure there's a better way to do this. I have a DB with 6000 rows, where 1 column is a 14K XML string. I wanted to compress all those XML strings to make the DB smaller. Unfortunately, the script below is much, much slower than this simple command line (which takes a few seconds). sqlite3 weather.db .dump | gzip -c > backup.gz I know it's not the same thing, but it does read/convert the DB to text and run gzip. So I was hoping this script would be within 10X performance, but it is more like 1000X slower. Is there a way to make the following script more efficient? Thanks. import zlib, sqlite3 conn = sqlite3.connect(r"weather.db") r = conn.cursor() w = conn.cursor() rows = r.execute("select date,location,xml_data from forecasts") for row in rows: data = zlib.compress(row[2]) w.execute("update forecasts set xml_data=? where date=? and location=?", (data, row[0], row[1])) conn.commit() conn.close()
[ "Not sure you can increase the performance by doing an update after the fact. there's too much overhead between doing the compress and updating the record. you won't gain any space savings unless you do a vacuum after you're done with the updates. the best solution would probably be to do the compress when the reco...
[ 2, 2, 1 ]
[]
[]
[ "compression", "performance", "python", "sqlite", "xml" ]
stackoverflow_0003187755_compression_performance_python_sqlite_xml.txt
Q: How to make two directory-entries refer always to the same float-value Consider this: >>> foo = {} >>> foo[1] = 1.0 >>> foo[2] = foo[1] >>> foo {1: 0.0, 2: 0.0} >>> foo[1] += 1.0 {1: 1.0, 2: 0.0} This is what happens. However, what I want would be that the last line reads: {1: 1.0, 2: 1.0} Meaning that both refer to the same value, even when that value changes. I know that the above works the way it does because numbers are immutable in Python. Is there any way easier than creating a custom class to store the value? A: The easier way to have a kind of pointer in python is pack you value in a list. >>> foo = {} >>> foo[1] = [1.0] >>> foo[2] = foo[1] >>> foo {1: [1.0], 2: [1.0]} >>> foo[1][0]+=100 # note the [0] to write in the list >>> foo {1: [101.0], 2: [101.0]} Works ! A: It is possible only with mutable objects, so you have to wrap your immutable value with some mutable object. In fact any mutable object will do, for example built-in list: >>> n = [0] >>> d = { 1 : n, 2 : n } >>> d {1: [0], 2: [0]} >>> d[1][0] = 3 >>> d {1: [3], 2: [3]} but what's hard in creating your own class or object? >>> n = type( "number", ( object, ), { "val" : 0, "__repr__" : lambda self: str(self.val) } )() >>> d = { 1 : n, 2 : n } >>> d {1: 0, 2: 0} >>> d[1].val = 9 >>> d {1: 9, 2: 9} Works just as fine ;)
How to make two directory-entries refer always to the same float-value
Consider this: >>> foo = {} >>> foo[1] = 1.0 >>> foo[2] = foo[1] >>> foo {1: 0.0, 2: 0.0} >>> foo[1] += 1.0 {1: 1.0, 2: 0.0} This is what happens. However, what I want would be that the last line reads: {1: 1.0, 2: 1.0} Meaning that both refer to the same value, even when that value changes. I know that the above works the way it does because numbers are immutable in Python. Is there any way easier than creating a custom class to store the value?
[ "The easier way to have a kind of pointer in python is pack you value in a list.\n>>> foo = {}\n>>> foo[1] = [1.0]\n>>> foo[2] = foo[1]\n\n>>> foo\n{1: [1.0], 2: [1.0]}\n\n>>> foo[1][0]+=100 # note the [0] to write in the list\n\n>>> foo\n{1: [101.0], 2: [101.0]}\n\nWorks !\n", "It is possible only with mutable o...
[ 1, 1 ]
[]
[]
[ "dictionary", "immutability", "python", "reference" ]
stackoverflow_0003188925_dictionary_immutability_python_reference.txt
Q: Why import when you need to use the full name? In python, if you need a module from a different package you have to import it. Coming from a Java background, that makes sense. import foo.bar What doesn't make sense though, is why do I need to use the full name whenever I want to use bar? If I wanted to use the full name, why do I need to import? Doesn't using the full name immediately describe which module I'm addressing? It just seems a little redundant to have from foo import bar when that's what import foo.bar should be doing. Also a little vague why I had to import when I was going to use the full name. A: The thing is, even though Python's import statement is designed to look similar to Java's, they do completely different things under the hood. As you know, in Java an import statement is really little more than a hint to the compiler. It basically sets up an alias for a fully qualified class name. For example, when you write import java.util.Set; it tells the compiler that throughout that file, when you write Set, you mean java.util.Set. And if you write s.add(o) where s is an object of type Set, the compiler (or rather, linker) goes out and finds the add method in Set.class and puts in a reference to it. But in Python, import util.set (that is a made-up module, by the way) does something completely different. See, in Python, packages and modules are not just names, they're actual objects, and when you write util.set in your code, that instructs Python to access an object named util and look for an attribute on it named set. The job of Python's import statement is to create that object and attribute. The way it works is that the interpreter looks for a file named util/__init__.py, uses the code in it to define properties of an object, and binds that object to the name util. Similarly, the code in util/set.py is used to initialize an object which is bound to util.set. There's a function called __import__ which takes care of all of this, and in fact the statement import util.set is basically equivalent to util = __import__('util.set') The point is, when you import a Python module, what you get is an object corresponding to the top-level package, util. In order to get access to util.set you need to go through that, and that's why it seems like you need to use fully qualified names in Python. There are ways to get around this, of course. Since all these things are objects, one simple approach is to just bind util.set to a simpler name, i.e. after the import statement, you can have set = util.set and from that point on you can just use set where you otherwise would have written util.set. (Of course this obscures the built-in set class, so I don't recommend actually using the name set.) Or, as mentioned in at least one other answer, you could write from util import set or import util.set as set This still imports the package util with the module set in it, but instead of creating a variable util in the current scope, it creates a variable set that refers to util.set. Behind the scenes, this works kind of like _util = __import__('util', fromlist='set') set = _util.set del _util in the former case, or _util = __import__('util.set') set = _util.set del _util in the latter (although both ways do essentially the same thing). This form is semantically more like what Java's import statement does: it defines an alias (set) to something that would ordinarily only be accessible by a fully qualified name (util.set). A: You can shorten it, if you would like: import foo.bar as whateveriwant Using the full name prevents two packages with the same-named submodules from clobbering each other. A: There is a module in the standard library called io: In [84]: import io In [85]: io Out[85]: <module 'io' from '/usr/lib/python2.6/io.pyc'> There is also a module in scipy called io: In [95]: import scipy.io In [96]: scipy.io Out[96]: <module 'scipy.io' from '/usr/lib/python2.6/dist-packages/scipy/io/__init__.pyc'> If you wanted to use both modules in the same script, then namespaces are a convenient way to distinguish the two. In [97]: import this The Zen of Python, by Tim Peters ... Namespaces are one honking great idea -- let's do more of those! A: You're a bit confused about how Python imports work. (I was too when I first started.) In Python, you can't simply refer to something within a module by the full name, unlike in Java; you HAVE to import the module first, regardless of how you plan on referring to the imported item. Try typing math.sqrt(5) in the interpreter without importing math or math.sqrt first and see what happens. Anyway... the reason import foo.bar has you required to use foo.bar instead of just bar is to prevent accidental namespace conflicts. For example, what if you do import foo.bar, and then import baz.bar? You could, of course, choose to do import foo.bar as bar (i.e. aliasing), but if you're doing that you may as well just use from foo import bar. (EDIT: except when you want to import methods and variables. Then you have to use the from ... import ... syntax. This includes instances where you want to import a method or variable without aliasing, i.e. you can't simply do import foo.bar if bar is a method or variable.) A: in Python, importing doesn't just indicate you might use something. The import actually executes code at the module level. You can think of the import as being the moment where the functions are 'interpreted' and created. Any code that is in the _____init_____.py level or not inside a function or class definition happens then. The import also makes an inexpensive copy of the whole module's namespace and puts it inside the namespace of the file / module / whatever where it is imported. An IDE then has a list of the functions you might be starting to type for command completion. A: Part of the Python philosophy is explicit is better than implicit. Python could automatically import the first time you try to access something from a package, but that's not explicit. I'm also guessing that package initialization would be much more difficult if the imports were automatic, as it wouldn't be done consistently in the code. A: Other than in Java, in Python import foo.bar declares, that you are going to use the thing referred to by foo.bar. This matches with Python's philosophy that explicit is better than implicit. There are more programming languages that make inter-module dependencies more explicit than Java, for example Ada. Using the full name makes it possible to disambiguate definitions with the same name coming from different modules. A: You don't have to use the full name. Try one of these from foo import bar import foo.bar as bar import foo.bar bar = foo.bar from foo import * A few reasons why explicit imports are good: They help signal to humans and tools what packages your module depends on. They avoid the overhead of dynamically determining which packages have to be loaded (and possibly compiled) at run time. They (along with sys.path) unambiguously distinguish symbols with conflicting names from different namespaces. They give the programmer some control of what enters the namespace within which he is working.
Why import when you need to use the full name?
In python, if you need a module from a different package you have to import it. Coming from a Java background, that makes sense. import foo.bar What doesn't make sense though, is why do I need to use the full name whenever I want to use bar? If I wanted to use the full name, why do I need to import? Doesn't using the full name immediately describe which module I'm addressing? It just seems a little redundant to have from foo import bar when that's what import foo.bar should be doing. Also a little vague why I had to import when I was going to use the full name.
[ "The thing is, even though Python's import statement is designed to look similar to Java's, they do completely different things under the hood. As you know, in Java an import statement is really little more than a hint to the compiler. It basically sets up an alias for a fully qualified class name. For example, whe...
[ 25, 6, 4, 3, 3, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003188929_python.txt
Q: Duplicate Google Spreadsheet on Demand I've created a pretty complex Google spreadsheet. I would like a user to be able to click a button or follow a link, and get a copy of this spreadsheet where they can fill in data. I would later check process this data manually. Is there anyway I can do this via a complicated link, or some Javascript, or possibly even using a server side language (e.g. Python, Java). Thank you, A: You have a few options: Rather than force a user to create a spreadsheet that you verify, you can email them a form to fill out with Google forms, and the answers get aggregated back on your spreadsheet. Use the docs API to copy documents. Use Google Apps Script to automate the process (it's essentially javascript). A: Copying the document from the client side: http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#CopyingDocs Using the Java API, it would seem you'd have to export the document and then upload it: http://code.google.com/apis/documents/docs/3.0/developers_guide_java.html
Duplicate Google Spreadsheet on Demand
I've created a pretty complex Google spreadsheet. I would like a user to be able to click a button or follow a link, and get a copy of this spreadsheet where they can fill in data. I would later check process this data manually. Is there anyway I can do this via a complicated link, or some Javascript, or possibly even using a server side language (e.g. Python, Java). Thank you,
[ "You have a few options:\n\nRather than force a user to create a spreadsheet that you verify, you can email them a form to fill out with Google forms, and the answers get aggregated back on your spreadsheet.\nUse the docs API to copy documents.\nUse Google Apps Script to automate the process (it's essentially javas...
[ 4, 0 ]
[]
[]
[ "google_apps_script", "google_sheets", "java", "javascript", "python" ]
stackoverflow_0003189012_google_apps_script_google_sheets_java_javascript_python.txt
Q: twisted: one client, many servers I'm trying to use twisted to create a cluster of computers that run one program on a piece of a larger dataset. My "servers" receive a chunk of data from the client and run command x on it. My "client" connects to multiple servers giving them each a chunk of data and telling them what parameters to run command x with. My question is: is there a way to set up the reactor loop to connect to many servers: reactor.connectTCP('localhost', PORT, BlastFactory()) reactor.run() or do I have to swap client and server in my paradigm? A: Just call connectTCP multiple times. The trick, of course, is that reactor.run() blocks "forever" (the entire run-time of your program) so you don't want to call that multiple times. You have several options; you can set up a timed call to make future connections, or you can start new connections from events on your connection (like connectionLost or clientConnectionFailed). Or, at the simplest, you can just set up multiple connection attempts before reactor.run() kicks off the whole show, like this: for host in hosts: reactor.connectTCP(host, PORT, BlastFactory()) reactor.run()
twisted: one client, many servers
I'm trying to use twisted to create a cluster of computers that run one program on a piece of a larger dataset. My "servers" receive a chunk of data from the client and run command x on it. My "client" connects to multiple servers giving them each a chunk of data and telling them what parameters to run command x with. My question is: is there a way to set up the reactor loop to connect to many servers: reactor.connectTCP('localhost', PORT, BlastFactory()) reactor.run() or do I have to swap client and server in my paradigm?
[ "Just call connectTCP multiple times.\nThe trick, of course, is that reactor.run() blocks \"forever\" (the entire run-time of your program) so you don't want to call that multiple times.\nYou have several options; you can set up a timed call to make future connections, or you can start new connections from events o...
[ 9 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003189222_python_twisted.txt
Q: Python: cannot print (execution flow ?) I am interested in a small python application, which can be downloaded here: https://launchpad.net/treemap If you run it, like this: python treemap-basic.py examle-world-population.txt It works just fine. The problem is that even if I type a print command in the "treemap-basic.py" file: print "Hello World !" @ treemap-basic.py I cannot see the message "Hello World !" at the Terminal. Why? A: I downloaded this script, and inserted print "Hello World" on line 64. When simply trying ./treemap-basic.py on the terminal, you get an IndexError since treemap-basic.py expects a command line argument. When you specify a file to work on: ./treemap-basic examle-world-population.txt You see a bunch of output in stout. If you scroll up to the top (right below where you first entered the command in the terminal) you should see "Hello World" as the first line of output.
Python: cannot print (execution flow ?)
I am interested in a small python application, which can be downloaded here: https://launchpad.net/treemap If you run it, like this: python treemap-basic.py examle-world-population.txt It works just fine. The problem is that even if I type a print command in the "treemap-basic.py" file: print "Hello World !" @ treemap-basic.py I cannot see the message "Hello World !" at the Terminal. Why?
[ "I downloaded this script, and inserted\nprint \"Hello World\"\n\non line 64. When simply trying ./treemap-basic.py on the terminal, you get an IndexError since treemap-basic.py expects a command line argument. When you specify a file to work on:\n./treemap-basic examle-world-population.txt\n\nYou see a bunch of ou...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003188656_python.txt
Q: python - recursive call I have a class model designed for a person class in python. where a person is a student and can have 0,1 or many advisors.A person can also have other attributes like name,school,year of graduation,classification he worked on,degree he obtained and so on. I have set and get methods for each of these attributes in the class. Ex. set_advisor(self,advisor) inserts advisor to the list of a student's advisors. set_year(self,year) sets the year of graduation of student. similarly get_advisor(self) returns the advisor of the student. and so on.. finally I populate the objects and name it as people. if I want to get list of students who graduated in some year I just write print [people[p].name for p in people if people[p].year="YEAR"] Now, I want to write a query, say..list the students who graduated in some year and whose advisor trace back to say some "abc"... eg dataset looks like this.. person a graduated in year 1990 person b graduated in year 1990 person c graduated in year 1991 person d graduated in year 1990 person a was advised by person e person e was advised by person f person f was advised by person g person g was advised by person abc person b was advised by person i person i was advised by person abc person c was advised by person abc person d was advised by person h person h was advised by person k Now, I want to write a recursive query to track only those who graduated in 1990 and whose advisor trace back to abc.in the above case it should give me only a and b as result. How do I go about this. I am having problems with the syntax and formulating the query.Like in the same terms as I formualted query above. Can anybody help on this. similarly..how do I write query for..say.. to get pairs of students who worked on some classification and graduated in same year and had their advisors also working on the same classification. Thanks. A: You could write a method on your class with something like: has_advisor(self, advisor): if not self.advisor: return False elif advisor in self.advisor: return True else return self.advisor.has_advisor(advisor) That would let you query things like: e = people['e'] e_in_advisor_tree_and_grad_in_1990 = [p for p in people if p.has_advisor(e) and p.year == 1990] This will get very expensive very quickly with large datasets, all of which are kept in memory at the same time.
python - recursive call
I have a class model designed for a person class in python. where a person is a student and can have 0,1 or many advisors.A person can also have other attributes like name,school,year of graduation,classification he worked on,degree he obtained and so on. I have set and get methods for each of these attributes in the class. Ex. set_advisor(self,advisor) inserts advisor to the list of a student's advisors. set_year(self,year) sets the year of graduation of student. similarly get_advisor(self) returns the advisor of the student. and so on.. finally I populate the objects and name it as people. if I want to get list of students who graduated in some year I just write print [people[p].name for p in people if people[p].year="YEAR"] Now, I want to write a query, say..list the students who graduated in some year and whose advisor trace back to say some "abc"... eg dataset looks like this.. person a graduated in year 1990 person b graduated in year 1990 person c graduated in year 1991 person d graduated in year 1990 person a was advised by person e person e was advised by person f person f was advised by person g person g was advised by person abc person b was advised by person i person i was advised by person abc person c was advised by person abc person d was advised by person h person h was advised by person k Now, I want to write a recursive query to track only those who graduated in 1990 and whose advisor trace back to abc.in the above case it should give me only a and b as result. How do I go about this. I am having problems with the syntax and formulating the query.Like in the same terms as I formualted query above. Can anybody help on this. similarly..how do I write query for..say.. to get pairs of students who worked on some classification and graduated in same year and had their advisors also working on the same classification. Thanks.
[ "You could write a method on your class with something like:\nhas_advisor(self, advisor):\n if not self.advisor:\n return False\n elif advisor in self.advisor:\n return True\n else\n return self.advisor.has_advisor(advisor)\n\nThat would let you query things like:\ne = people['e']\ne_i...
[ 1 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0003189759_python_scripting.txt
Q: I am attempting to use google app engine (python) to save a url with # character My class looks like this: class Post(db.Model): link = db.LinkProperty() I am getting the url parameter and populating the class like this: newpost = Post( link = cgi.escape(self.request.get('link'))) newpost.put() If I send a regular link it works fine. If I send a link like this (with a hash): http://www.url.com#paragraph2, it chokes. Has anyone dealt with this before? Any recommendations would be appreciated. A: The hash component of a URL is never sent to the server. This behavior is used in some AJAX patterns because of this property. I would recommend URL-encoding the hash in the URL to %23: http://example.com/whatever%23afterHash A: If db.LinkProperty won't work, just use db.StringProperty.
I am attempting to use google app engine (python) to save a url with # character
My class looks like this: class Post(db.Model): link = db.LinkProperty() I am getting the url parameter and populating the class like this: newpost = Post( link = cgi.escape(self.request.get('link'))) newpost.put() If I send a regular link it works fine. If I send a link like this (with a hash): http://www.url.com#paragraph2, it chokes. Has anyone dealt with this before? Any recommendations would be appreciated.
[ "The hash component of a URL is never sent to the server.\nThis behavior is used in some AJAX patterns because of this property.\nI would recommend URL-encoding the hash in the URL to %23:\nhttp://example.com/whatever%23afterHash\n", "If db.LinkProperty won't work, just use db.StringProperty.\n" ]
[ 4, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003189692_google_app_engine_python.txt
Q: parse xml file and create a list of files there is an info.xml file under every /var/packs/{many folders}/info.xml where are different directories but with the dirs's info in info.xml I need to parse through every {many folders} and create a list of the filepath which is inside the Path tags if the file type is "config" which can be found by checking if "config" is the type inside the type tags. The info.xml file wil be like this, <Files> <File> <Path>usr/share/doc/dialog/samples/form1</Path> <Type>doc</Type> <Size>1222</Size> <Uid>0</Uid> <Gid>0</Gid> <Mode>0755</Mode> <Hash>49744d73e8667d0e353923c0241891d46ebb9032</Hash> </File> <File> <Path>usr/share/doc/dialog/samples/form3</Path> <Type>config</Type> <Size>1294</Size> <Uid>0</Uid> <Gid>0</Gid> <Mode>0755</Mode> <Hash>f30277f73e468232c59a526baf3a5ce49519b959</Hash> </File> </Files> A: Here is very basic example with no errors processing and works with very strictly defined XML files, but you should take it as a start and continue with the following links: http://docs.python.org/library/xml.dom.html http://docs.python.org/library/xml.dom.minidom.html http://docs.python.org/library/os.path.html http://docs.python.org/library/os.html The code: import os import os.path from xml.dom.minidom import parse def parse_file(path): files = [] try: dom = parse(path) for filetag in dom.getElementsByTagName('File'): type = filetag.getElementsByTagName('Type')[0].firstChild.data if type == 'config': path = tag.getElementsByTagName('Path')[0].firstChild.data files.append(path) dom.unlink() except: raise return files def main(): files = [] for root, dirs, files in os.walk('/var/packs'): if 'info.xml' in files: files += parse_file(os.path.join(root, 'info.xml')) print 'The list of desired files:', files if __name__ == '__main__': main() A: Using lxml.etree and XPath: files = [] for root, dirnames, filenames in os.walk('/var/packs'): for filename in filenames: if filename != 'info.xml': continue tree = lxml.etree.parse(os.path.join(root, filename)) files.extend(tree.getroot().xpath('//File[Type[text()="config"]]/Path/text()')) If lxml is not available, you can alternatively use the etree API in the standard library: files = [] for root, dirnames, filenames in os.walk('/var/packs'): for filename in filenames: if filename != 'info.xml': continue tree = xml.etree.ElementTree.parse(os.path.join(root, filename)) for file_node in tree.findall('File'): type_node = file_node.find('Type') if type_node is not None and type_node.text == 'config': path_node = file_node.find('Path') if path_node is not None: files.append(path_node.text) A: Writing this off the top of my head, but here goes. We're going to make use of os.path.walk to recursively descend into your directories and minidom for doing the parsing. import os from xml.dom import minidom # opens a given info.xml file and prints out "Path"'s contents def parseInfoXML(filename): doc = minidom.parse(filename) for fileNode in doc.getElementsByTagName("File"): # warning: we assume the existence of a Path node, and that it contains a Text node print fileNode.getElementsByTagName("Path")[0].childNodes[0].data doc.unlink() def checkDirForInfoXML(arg, dirname, names): if "info.xml" in names: parseInfoXML(os.path.join(dirname, "info.xml")) # recursively walk the directory tree, calling our visitor function to check for info.xml in each dir # this will include packs as well, so be sure that there's no info.xml in there os.path.walk("/var/packs" , checkDirForInfoXML, None) Not the most efficient way to accomplish it I'm sure, but it'll do if you don't expect any errors/whatever.
parse xml file and create a list of files
there is an info.xml file under every /var/packs/{many folders}/info.xml where are different directories but with the dirs's info in info.xml I need to parse through every {many folders} and create a list of the filepath which is inside the Path tags if the file type is "config" which can be found by checking if "config" is the type inside the type tags. The info.xml file wil be like this, <Files> <File> <Path>usr/share/doc/dialog/samples/form1</Path> <Type>doc</Type> <Size>1222</Size> <Uid>0</Uid> <Gid>0</Gid> <Mode>0755</Mode> <Hash>49744d73e8667d0e353923c0241891d46ebb9032</Hash> </File> <File> <Path>usr/share/doc/dialog/samples/form3</Path> <Type>config</Type> <Size>1294</Size> <Uid>0</Uid> <Gid>0</Gid> <Mode>0755</Mode> <Hash>f30277f73e468232c59a526baf3a5ce49519b959</Hash> </File> </Files>
[ "Here is very basic example with no errors processing and works with very strictly defined XML files, but you should take it as a start and continue with the following links:\n\nhttp://docs.python.org/library/xml.dom.html\nhttp://docs.python.org/library/xml.dom.minidom.html\nhttp://docs.python.org/library/os.path.h...
[ 2, 1, 0 ]
[]
[]
[ "parsing", "python", "xml" ]
stackoverflow_0003189311_parsing_python_xml.txt
Q: How Ruby's authlogic is compared to Python's repoze.what/who library? I am trying to understand architecture of authlogic and repoze.what/who libraries but I could get the first level architectural definition. repoze packages seems to use the zope modules at some level.. Are there any equivalent or easier authentication framework like authlogic available in python? (I do not use Django.. I use Pylons) Anyone has more insight into these libraries? A: After a quick look at authlogic's homepage, I would say it can be compared to repoze.who because they both handle authentication. On the other hand, repoze.what handles authorization. For more information, you may want to see this: http://gustavonarea.net/blog/posts/repoze-auth/ HTH. PS: Neither repoze.who or repoze.what use Zope (it's the wider Repoze project that is related to Zope). repoze.who uses zope.interface, but that's a Zope-independent library which was born within the Zope project.
How Ruby's authlogic is compared to Python's repoze.what/who library?
I am trying to understand architecture of authlogic and repoze.what/who libraries but I could get the first level architectural definition. repoze packages seems to use the zope modules at some level.. Are there any equivalent or easier authentication framework like authlogic available in python? (I do not use Django.. I use Pylons) Anyone has more insight into these libraries?
[ "After a quick look at authlogic's homepage, I would say it can be compared to repoze.who because they both handle authentication. On the other hand, repoze.what handles authorization. For more information, you may want to see this:\nhttp://gustavonarea.net/blog/posts/repoze-auth/\nHTH.\nPS: Neither repoze.who or r...
[ 1 ]
[]
[]
[ "authentication", "authlogic", "python", "repoze.who", "ruby" ]
stackoverflow_0003188894_authentication_authlogic_python_repoze.who_ruby.txt
Q: What are the pros and cons in Python of using a c library vs a native python one Are there any downsides in Python to using a library that is just a binding to a C library? Does that hurt the portability of your application? Anything else I should look out for? A: Of course using a C library hurts portability. It also prohibites you (in general) to use Jython or IronPython. I would only use a C library if I had no other option. This could happen if direct access to hardware is necessary or if special efficiency requirements apply. A: C library is likely to have better performance, but needs to be recompiled for each platform. You can't use C libraries on Google App Engine A: Portability is one thing. There are even differences between python 2.x and 3.x that can make things difficult with C extensions, if the writer didn't update them. Another thing is that pure python code gives you a bit more possibilities to read, understand and even modify (although it is usually a bad sign if you need to do that for other peoples modules)
What are the pros and cons in Python of using a c library vs a native python one
Are there any downsides in Python to using a library that is just a binding to a C library? Does that hurt the portability of your application? Anything else I should look out for?
[ "Of course using a C library hurts portability. It also prohibites you (in general) to use Jython or IronPython. I would only use a C library if I had no other option. This could happen if direct access to hardware is necessary or if special efficiency requirements apply.\n", "C library is likely to have better p...
[ 4, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003190013_python.txt
Q: How to do this in a pythonic way? Consider this Python snippet: for a in range(10): if a == 7: pass if a == 8: pass if a == 9: pass else: print "yes" How can it be written shorter? #Like this or... if a ?????[7,8,9]: pass A: Use the in operator: if a in (7,8,9): pass A: To test if a falls within a range: if 7 <= a <= 9: pass To test if a is in a given sequence: if a in [3, 5, 42]: pass A: for a in range(10): if a > 6: continue print('yes') A: Based on your original code the direct "pythonic" replacement is: if not a in [7, 8, 9]: print 'yes' or if a not in [7, 8, 9]: print 'yes' The latter reads a little better, so I guess it's a bit more "pythonic". A: if a in [7,8,9] A: Depending on what you want to do, the map() function can also be interesting: def _print(x): print 'yes' map(_print, [a for a in range(10) if a not in (7,8,9)]) A: What about using lambda. >>> f = lambda x: x not in (7, 8, 9) and print('yes') >>> f(3) yes >>> f(7) False A: Since the question is tagged as beginner, I'm going to add some basic if-statement advice: if a == 7: pass if a == 8: pass if a == 9: ... else: ... are three independent if statements and the first two have no effect, the else refers only to if a == 9: so if a is 7 or 8, the program prints "yes". For future use of if-else statement like this, make sure to use elif: if a == 7: seven() elif a == 8: eight() elif a == 9: nine() else: print "yes" or use just one if-statement if they call for the same action: if a == 7 or a == 8 or a == 9: seven_eight_or_nine() else: print "yes"
How to do this in a pythonic way?
Consider this Python snippet: for a in range(10): if a == 7: pass if a == 8: pass if a == 9: pass else: print "yes" How can it be written shorter? #Like this or... if a ?????[7,8,9]: pass
[ "Use the in operator:\nif a in (7,8,9):\n pass\n\n", "To test if a falls within a range:\nif 7 <= a <= 9:\n pass\n\nTo test if a is in a given sequence:\nif a in [3, 5, 42]:\n pass\n\n", "for a in range(10):\n if a > 6:\n continue\n print('yes')\n\n", "Based on your original code the direct ...
[ 17, 15, 2, 2, 1, 1, 1, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002636656_python_syntax.txt
Q: Python - Call a function in a module dynamically I'm pretty new to Python and I have a situation where I have a variable representing a function inside of a module and I'm wondering how to call it dynamically. I have filters.py: def scale(image, width, height): pass And then in another script I have something like: import filters def process_images(method='scale', options): filters[method](**options) ... but that doesn't work obviously. If someone could fill me in on the proper way to do this, or let me know if there is a better way to pass around functions as parameters that would be awesome. A: you need built-in getattr: getattr(filters, method)(**options) A: To avoid the problem, you could pass the function directly, instead of "by name": def process_images(method=filters.scale, options): method(**options) If you have a special reason to use a string instead, you can use getattr as suggested by SilentGhost. A: import filters def process_images(function=filters.scale, options): function(**options) This can then be called like, for example: process_images(filters.rotate, **rotate_options) Note that having a default function arg doesn't seem like a good idea -- it's not intuitively obvious why filters.scale is the default out of several possible image-processing operations.
Python - Call a function in a module dynamically
I'm pretty new to Python and I have a situation where I have a variable representing a function inside of a module and I'm wondering how to call it dynamically. I have filters.py: def scale(image, width, height): pass And then in another script I have something like: import filters def process_images(method='scale', options): filters[method](**options) ... but that doesn't work obviously. If someone could fill me in on the proper way to do this, or let me know if there is a better way to pass around functions as parameters that would be awesome.
[ "you need built-in getattr:\ngetattr(filters, method)(**options)\n\n", "To avoid the problem, you could pass the function directly, instead of \"by name\":\ndef process_images(method=filters.scale, options):\n method(**options)\n\nIf you have a special reason to use a string instead, you can use getattr as sug...
[ 25, 9, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003190583_python.txt
Q: Python .xlsx (Office OpenXML) reader as simple as csv module? I know some Python xlsx readers are emerging, but from what I've seen they don't seem nearly as intuitive as the built-in csv module. What I want is a module that can do something like this: reader = xlsx.reader(open('/path/to/file')) for sheet in reader: print 'In %s we have the following employees:' % (sheet.name) for row in sheet: print '%s, %s years old' % (row['Employee'], row['Age']) Is there such a reader? A: xlrd has xlsx handling for basic data extraction, using the same APIs as for xls, in alpha test at the moment. Send me private e-mail if interested. A: Well, maybe not for the xlsx format, but certainly for xls. Grab xlrd from here: http://www.python-excel.org/ Here's some example code to get a feel for how easy it is to work with: import xlrd EMPLOYEE_CELL = 5 AGE_CELL = 6 reader = xlrd.open_workbook('C:\\path\\to\\excel_file.xls') for sheet in reader.sheets(): print 'In %s we have the following employees:' % (sheet.name) for r in xrange(sheet.nrows): row_cells = sheet.row(r) print '%s, %s years old' % (row_cells[EMPLOYEE_CELL].value, row_cells[AGE_CELL].value) If you can save the documents as an xls, you should be good. I didn't try out the code above, but that's pretty close if not 100% correct. Try it out and let me know. EDIT: I'm guessing you're trying to do this on a non-windows machine. You may be able to use something like PyODConverter to convert the document from xlsx to xls, and then run against the converted file. Something like this: user@server:~# python DocumentConverter.py excel_file.xlxs excel_file.xls user@server:~# python script_with_code_above.py Once again, haven't tested it out but hopefully it'll work for your needs.
Python .xlsx (Office OpenXML) reader as simple as csv module?
I know some Python xlsx readers are emerging, but from what I've seen they don't seem nearly as intuitive as the built-in csv module. What I want is a module that can do something like this: reader = xlsx.reader(open('/path/to/file')) for sheet in reader: print 'In %s we have the following employees:' % (sheet.name) for row in sheet: print '%s, %s years old' % (row['Employee'], row['Age']) Is there such a reader?
[ "xlrd has xlsx handling for basic data extraction, using the same APIs as for xls, in alpha test at the moment. Send me private e-mail if interested.\n", "Well, maybe not for the xlsx format, but certainly for xls. Grab xlrd from here:\nhttp://www.python-excel.org/\nHere's some example code to get a feel for how...
[ 4, 2 ]
[]
[]
[ "module", "openxml", "python", "xlsx", "xmlreader" ]
stackoverflow_0003189244_module_openxml_python_xlsx_xmlreader.txt
Q: Running a Python Script on a server (Does it have to be in /cgi-bin/)? Right now I have a script thats http://www.example.com/cgi-bin/foo?var1=A&var2=B Is there a way that I can have it run outside of the cgi-bin directory? Like could I have http://www.example.com/foo/?var1=A&var2=B A: In Apache you can change the directories that can contain executable scripts with the ScriptAlias directive in httpd.conf (or whatever file holds your configuration). You can also use mod_rewrite to rewrite URLs to point to the scripts you want to execute. Mod_rewrite also allows you to pass variables and stuff in the form of URLs if you like that, e.g. www.example.com/foo/A/B/ -> www.example.com/foo?var1=A&var2=B A: Short answer, yes. I'm no expert on this, but I know of a number of frameworks that do exactly what you just did (e.g. Ruby on Rails). A lot of it has to do with how your server routes URLs. Try looking up the documentation on your server.
Running a Python Script on a server (Does it have to be in /cgi-bin/)?
Right now I have a script thats http://www.example.com/cgi-bin/foo?var1=A&var2=B Is there a way that I can have it run outside of the cgi-bin directory? Like could I have http://www.example.com/foo/?var1=A&var2=B
[ "In Apache you can change the directories that can contain executable scripts with the ScriptAlias directive in httpd.conf (or whatever file holds your configuration).\nYou can also use mod_rewrite to rewrite URLs to point to the scripts you want to execute. Mod_rewrite also allows you to pass variables and stuff i...
[ 2, 0 ]
[]
[]
[ "cgi_bin", "html", "python", "scripting" ]
stackoverflow_0003190772_cgi_bin_html_python_scripting.txt
Q: __init__ method for form with additional arguments I'm calling my form, with additional parameter 'validate : form = MyForm(request.POST, request.FILES, validate=True) How should I write form's init method to have access to this parameter inside body of my form (for example in _clean method) ? This is what I came up with : def __init__(self, *args, **kwargs): try: validate = args['validate'] except: pass if not validate: self.validate = False elif: self.validate = True super(MyForm, self).__init__(*args, **kwargs) A: The validate=True argument is a keyword argument, so it will show up in the kwargsdict. (Only positional arguments show up in args.) You can use kwargs.pop to try to get the value of kwargs['validate']. If validate is a key in kwargs, then kwargs.pop('validate') will return the associated value. It also has the nice benefit of removing the 'validate' key from the kwargs dict, which makes it ready for the call to __init__. If the validate key is not in kwargs, then False is returned. def __init__(self, *args, **kwargs): self.validate = kwargs.pop('validate',False) super(MyForm, self).__init__(*args, **kwargs) If you do not wish to remove the 'validate' key from kwargs before passing it to __init__, simply change pop to get.
__init__ method for form with additional arguments
I'm calling my form, with additional parameter 'validate : form = MyForm(request.POST, request.FILES, validate=True) How should I write form's init method to have access to this parameter inside body of my form (for example in _clean method) ? This is what I came up with : def __init__(self, *args, **kwargs): try: validate = args['validate'] except: pass if not validate: self.validate = False elif: self.validate = True super(MyForm, self).__init__(*args, **kwargs)
[ "The validate=True argument is a keyword argument, so it will show up in the kwargsdict. (Only positional arguments show up in args.)\nYou can use kwargs.pop to try to get the value of kwargs['validate'].\nIf validate is a key in kwargs, then kwargs.pop('validate') will return the associated value. It also has the ...
[ 9 ]
[]
[]
[ "django", "django_forms", "initialization", "python" ]
stackoverflow_0003191443_django_django_forms_initialization_python.txt
Q: Decorating arithmetic operators | should I be using a metaclass? I'd like to implement an object, that bounds values within a given range after arithmetic operations have been applied to it. The code below works fine, but I'm pointlessly rewriting the methods. Surely there's a more elegant way of doing this. Is a metaclass the way to go? def check_range(_operator): def decorator1(instance,_val): value = _operator(instance,_val) if value > instance._upperbound: value = instance._upperbound if value < instance._lowerbound: value = instance._lowerbound instance.value = value return Range(value, instance._lowerbound, instance._upperbound) return decorator1 class Range(object): ''' however you add, multiply or divide, it will always stay within boundaries ''' def __init__(self, value, lowerbound, upperbound): ''' @param lowerbound: @param upperbound: ''' self._lowerbound = lowerbound self._upperbound = upperbound self.value = value def init(self): ''' set a random value within bounds ''' self.value = random.uniform(self._lowerbound, self._upperbound) def __str__(self): return self.__repr__() def __repr__(self): return "<Range: %s>" % (self.value) @check_range def __mul__(self, other): return self.value * other @check_range def __div__(self, other): return self.value / float(other) def __truediv__(self, other): return self.div(other) @check_range def __add__(self, other): return self.value + other @check_range def __sub__(self, other): return self.value - other A: It is possible to use a metaclass to apply a decorator to a set of function names, but I don't think that this is the way to go in your case. Applying the decorator in the class body on a function-by-function basis as you've done, with the @decorator syntax, I think is a very good option. (I think you've got a bug in your decorator, BTW: you probably do not want to set instance.value to anything; arithmetic operators usually don't mutate their operands). Another approach I might use in your situation, kind of avoiding decorators all together, is to do something like this: import operator class Range(object): def __init__(self, value, lowerbound, upperbound): self._lowerbound = lowerbound self._upperbound = upperbound self.value = value def __repr__(self): return "<Range: %s>" % (self.value) def _from_value(self, val): val = max(min(val, self._upperbound), self._lowerbound) # NOTE: it's nice to use type(self) instead of writing the class # name explicitly; it then continues to work if you change the # class name, or use a subclass return type(self)(val, rng._lowerbound, rng._upperbound) def _make_binary_method(fn): # this is NOT a method, just a helper function that is used # while the class body is being evaluated def bin_op(self, other): return self._from_value(fn(self.value, other)) return bin_op __mul__ = _make_binary_method(operator.mul) __div__ = _make_binary_method(operator.truediv) __truediv__ = __div__ __add__ = _make_binary_method(operator.add) __sub__ = _make_binary_method(operator.sub) rng = Range(7, 0, 10) print rng + 5 print rng * 50 print rng - 10 print rng / 100 printing <Range: 10> <Range: 10> <Range: 0> <Range: 0.07> I suggest that you do NOT use a metaclass in this circumstance, but here is one way you could. Metaclasses are a useful tool, and if you're interested, it's nice to understand how to use them for when you really need them. def check_range(fn): def wrapper(self, other): value = fn(self, other) value = max(min(value, self._upperbound), self._lowerbound) return type(self)(value, self._lowerbound, self._upperbound) return wrapper class ApplyDecoratorsType(type): def __init__(cls, name, bases, attrs): for decorator, names in attrs.get('_auto_decorate', ()): for name in names: fn = attrs.get(name, None) if fn is not None: setattr(cls, name, decorator(fn)) class Range(object): __metaclass__ = ApplyDecoratorsType _auto_decorate = ( (check_range, '__mul__ __div__ __truediv__ __add__ __sub__'.split()), ) def __init__(self, value, lowerbound, upperbound): self._lowerbound = lowerbound self._upperbound = upperbound self.value = value def __repr__(self): return "<Range: %s>" % (self.value) def __mul__(self, other): return self.value * other def __div__(self, other): return self.value / float(other) def __truediv__(self, other): return self / other def __add__(self, other): return self.value + other def __sub__(self, other): return self.value - other A: As it is wisely said about metaclasses: if you wonder wether you need them, then you don't. I don't fully understand your problem, but I would create a BoundedValue class, and us only instances of said class into the class you are proposing. class BoundedValue(object): default_lower = 0 default_upper = 1 def __init__(self, upper=None, lower=None): self.upper = upper or BoundedValue.default_upper self.lower = lower or BoundedValue.default_lower @property def val(self): return self._val @val.setter def val(self, value): assert self.lower <= value <= self.upper self._val = value v = BoundedValue() v.val = 0.5 # Correctly assigns the value 0.5 print v.val # prints 0.5 v.val = 10 # Throws assertion error Of course you could (and should) change the assertion for the actual behavior you are looking for; also you can change the constructor to include the initialization value. I chose to make it an assignment post-construction via the property val. Once you have this object, you can create your classes and use BoundedValue instances, instead of floats or ints.
Decorating arithmetic operators | should I be using a metaclass?
I'd like to implement an object, that bounds values within a given range after arithmetic operations have been applied to it. The code below works fine, but I'm pointlessly rewriting the methods. Surely there's a more elegant way of doing this. Is a metaclass the way to go? def check_range(_operator): def decorator1(instance,_val): value = _operator(instance,_val) if value > instance._upperbound: value = instance._upperbound if value < instance._lowerbound: value = instance._lowerbound instance.value = value return Range(value, instance._lowerbound, instance._upperbound) return decorator1 class Range(object): ''' however you add, multiply or divide, it will always stay within boundaries ''' def __init__(self, value, lowerbound, upperbound): ''' @param lowerbound: @param upperbound: ''' self._lowerbound = lowerbound self._upperbound = upperbound self.value = value def init(self): ''' set a random value within bounds ''' self.value = random.uniform(self._lowerbound, self._upperbound) def __str__(self): return self.__repr__() def __repr__(self): return "<Range: %s>" % (self.value) @check_range def __mul__(self, other): return self.value * other @check_range def __div__(self, other): return self.value / float(other) def __truediv__(self, other): return self.div(other) @check_range def __add__(self, other): return self.value + other @check_range def __sub__(self, other): return self.value - other
[ "It is possible to use a metaclass to apply a decorator to a set of function names, but I don't think that this is the way to go in your case. Applying the decorator in the class body on a function-by-function basis as you've done, with the @decorator syntax, I think is a very good option. (I think you've got a bu...
[ 2, 1 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0003191125_metaclass_python.txt
Q: Form class __init__ not working I have this form class : class MyForm(forms.Form): def __init__(self, *args, **kwargs): self.notvalidate = kwargs.pop('notvalidate',False) super(MyForm, self).__init__(*args, **kwargs) email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,maxlength=75))) (...) if not notvalidate: def clean_email(self): email = self.cleaned_data.get("email") if email and User.objects.filter(email=email).count() > 0: raise forms.ValidationError( _(u"Email already used.")) return email Although in init I set self.notvalidate value to either True(if was given) or False inside the body of MyForm I'm getting name 'notvalidate' is not defined (or if I check for self.notvalidate - name 'self' is not defined). What is wrong ? A: Move the if not notvalidate into the clean_email method, and reference it using self.notvalidate. def clean_email(self): if not self.notvalidate: email = self.cleaned_data.get("email") if email and User.objects.filter(email=email).count() > 0: raise forms.ValidationError( _(u"Email already used.")) return email Also, you may want to rename the flag to should_validate_email and lose the negation. A: What are you trying to achieve is changing the class level attribute clean_email but you want to do that using instance attribute self.notvalidate, so you are doing contradictory things here. Simplest way to not validate would be to check in clean_email and return e.g def clean_email(self): if self.notvalidate: return .... But if due to some mysterious reason you do not want clean_mail method to be existing in the class at all, you need to create a class using metaclass or simpler way would be to call a function to create class e.g. def createFormClass(validate): class MyClass(object): if validate: def clean_email(self): pass return MyClass MyClassValidated = createFormClass(True) MyClassNotValidated = createFormClass(False) Though I will strongly suggest NOT to do this. A: Change notvalidate to self.notvalidate.
Form class __init__ not working
I have this form class : class MyForm(forms.Form): def __init__(self, *args, **kwargs): self.notvalidate = kwargs.pop('notvalidate',False) super(MyForm, self).__init__(*args, **kwargs) email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,maxlength=75))) (...) if not notvalidate: def clean_email(self): email = self.cleaned_data.get("email") if email and User.objects.filter(email=email).count() > 0: raise forms.ValidationError( _(u"Email already used.")) return email Although in init I set self.notvalidate value to either True(if was given) or False inside the body of MyForm I'm getting name 'notvalidate' is not defined (or if I check for self.notvalidate - name 'self' is not defined). What is wrong ?
[ "Move the if not notvalidate into the clean_email method, and reference it using self.notvalidate.\n def clean_email(self):\n if not self.notvalidate: \n email = self.cleaned_data.get(\"email\")\n if email and User.objects.filter(email=email).count() > 0:\n raise forms....
[ 2, 1, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003191648_django_django_forms_python.txt
Q: Decorate a whole library in Python I'm new to the ideas of decorators (and still trying to wrap my head around them), but I think I've come across a problem that would be well suited for them. I'd like to have class that is decorated across all of the functions in the math library. More specifically my class has two members, x and flag. When flag is true, I'd like the original math function to be called. When flag is false, I'd like to return None. As a framework for what I'm asking here is the class: import math class num(object): def __init__(self, x, flag): self.x = x self.flag = flag def __float__(self): return float(self.x) As a result, this works fine: a = num(3, True) print math.sqrt(a) However this should (in my perfect world), return None: b = num(4, False) print math.sqrt(b) Any suggestions or tips on how this would be possible to apply over a whole library of functions? A: You can use decorators for this, although you won't need the @decorator syntax. The following code imports each function you list from the math module into the current module's namespace, wrapping it in the defined decorator. It should give you the basic idea. from functools import wraps def check_flag(func): @wraps(func) def _exec(x, *args, **kw): if getattr(x, 'flag', False): return None return func(x, *args, **kw) return _exec import sys, math _module = sys.modules[__name__] for func in ('exp', 'log', 'sqrt'): setattr(_module, func, check_flag(getattr(math, func))) You could automate the listing of functions defined in the math module, as Alex demonstrates, but I think explicitly wrapping just the functions you're interested in using is a better way to go. A: Here's the general idea...: >>> class num(object): ... def __init__(self, x, flag): ... self.x = x ... self.flag = flag ... def __float__(self): ... return float(self.x) ... from functools import wraps >>> def wrapper(f): ... @wraps(f) ... def wrapped(*a): ... if not all(getattr(x, 'flag', True) for x in a): ... return None ... return f(*(getattr(x, 'x', x) for x in a)) ... return wrapped ... >>> import inspect >>> import math >>> for n, v in inspect.getmembers(math, inspect.isroutine): ... setattr(math, n, wrapper(v)) ... >>> a = num(3, True) >>> print math.sqrt(a) 1.73205080757 >>> b = num(4, False) >>> print math.sqrt(b) None Note that this wrapper also covers non-unary functions in math (returning None if any argument has a False .flag) and allows mixed calls thereof (with some args being instances of num and others being actual floats). The key part, applicable to any "wrap all functions in a certain module" tasks, is using module inspect to get all the names and values of functions (built-in or not) in module math, and an explicit call to the wrapper (same semantics as the decorator syntax) to set that name to the wrapped value in the math module.
Decorate a whole library in Python
I'm new to the ideas of decorators (and still trying to wrap my head around them), but I think I've come across a problem that would be well suited for them. I'd like to have class that is decorated across all of the functions in the math library. More specifically my class has two members, x and flag. When flag is true, I'd like the original math function to be called. When flag is false, I'd like to return None. As a framework for what I'm asking here is the class: import math class num(object): def __init__(self, x, flag): self.x = x self.flag = flag def __float__(self): return float(self.x) As a result, this works fine: a = num(3, True) print math.sqrt(a) However this should (in my perfect world), return None: b = num(4, False) print math.sqrt(b) Any suggestions or tips on how this would be possible to apply over a whole library of functions?
[ "You can use decorators for this, although you won't need the @decorator syntax.\nThe following code imports each function you list from the math module into the current module's namespace, wrapping it in the defined decorator. It should give you the basic idea.\nfrom functools import wraps\ndef check_flag(func):\...
[ 6, 6 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0003191799_decorator_python.txt
Q: Python scipy.weave and STANN C++ Library I'm trying out scipy.weave to build a fast minimal spanning tree program in Python. Unfortunately, using scipy.weave with a C++ library that I found, STANN, is more difficult that I had assumed. Here's the link to the STANN library: http://sites.google.com/a/compgeom.com/stann/ Below is the Python with scipy.weave script that I wrote. import scipy.weave as weave from scipy.weave import inline import numpy def gmst(points): # computing GMST with STANN headers assert(type(points) == type(numpy.array([]))) # now the c++ code code = """ using namespace std; typedef reviver::dpoint<double,2> Point; typedef vector<Point>::size_type stype; vector< std::pair<stype,stype> > outputmst; PyArrayObject *py_val gmst(points,outputmst); return_val = outputmst; """ return inline(code,['points'], headers = ["<iostream>","<gmst.hpp>","<dpoint.hpp>","<test.hpp>"], include_dirs=["/home/tree/usr/STANN/include"]) So far no luck in making weave work. Any ideas why I'm running into a problem? Thanks for the help. Cheers A: Wrapping external code with weave is a fragile and hacky affair. You should take a look at Cython -- it's great at this sort of stuff.
Python scipy.weave and STANN C++ Library
I'm trying out scipy.weave to build a fast minimal spanning tree program in Python. Unfortunately, using scipy.weave with a C++ library that I found, STANN, is more difficult that I had assumed. Here's the link to the STANN library: http://sites.google.com/a/compgeom.com/stann/ Below is the Python with scipy.weave script that I wrote. import scipy.weave as weave from scipy.weave import inline import numpy def gmst(points): # computing GMST with STANN headers assert(type(points) == type(numpy.array([]))) # now the c++ code code = """ using namespace std; typedef reviver::dpoint<double,2> Point; typedef vector<Point>::size_type stype; vector< std::pair<stype,stype> > outputmst; PyArrayObject *py_val gmst(points,outputmst); return_val = outputmst; """ return inline(code,['points'], headers = ["<iostream>","<gmst.hpp>","<dpoint.hpp>","<test.hpp>"], include_dirs=["/home/tree/usr/STANN/include"]) So far no luck in making weave work. Any ideas why I'm running into a problem? Thanks for the help. Cheers
[ "Wrapping external code with weave is a fragile and hacky affair. You should take a look at Cython -- it's great at this sort of stuff.\n" ]
[ 0 ]
[]
[]
[ "c++", "numpy", "python", "scipy" ]
stackoverflow_0003146264_c++_numpy_python_scipy.txt
Q: Bash equivalent to Python's string literal for utf string conversion I'm writing a bash script that needs to parse html that includes special characters such as @!'ó. Currently I have the entire script running and it ignores or trips on these queries because they're returned from the server as decimal unicode like this: &#39;. I've figured out how to parse and convert to hexadecimal and load these into python to convert them back to their symbols and I am wondering if bash can do this final conversion natively. Simple example in python: print ur"\u0032" ur"\u0033" ur"\u0040" prints out 23@ Can I achieve the same result in Bash? I've looked into iconv but I don't think it can do what I want, or more probably I just don't know how. Here's some relevant information: Python String Literals Hex to UTF conversion in Python And here are some examples of expected input-output. Ludwig van Beethoven - 5th Symphony and 6th Symphony &#39;&#39;Pastoral&#39;&#39; - Boston Symphony Orchestra - Charles Munch Ludwig van Beethoven - 5th Symphony and 6th Symphony ''Pastoral'' - Boston Symphony Orchestra - Charles Munch &#1040;&#1083;&#1080;&#1089;&#1040; (Alisa) - &#1052;&#1099; &#1074;&#1084;&#1077;&#1089;&#1090;&#1077;. &#1061;&#1061; &#1083;&#1077;&#1090; (My vmeste XX let) АлисА (Alisa) - Мы вместе. ХХ лет (My vmeste XX let) A: The printf builtin in Bash doesn't support Unicode codes, but the external printf (at least on my GNU-based system) does: $ /usr/bin/printf "\u0410\u043b\u0438\u0441\u0410" АлисА or this, which selects printf from your path in case it's not in /usr/bin: $ $(type -P printf) "\u0410\u043b\u0438\u0441\u0410" АлисА or $ env printf "\u0410\u043b\u0438\u0441\u0410" АлисА A: possible solution, e.g.: $ function conv() { echo $* | python -c 'import re, sys; print re.sub(r"&#(\d+);", lambda x: unichr(int(x.group(1))), sys.stdin.read()).rstrip()' ; } $ conv '&#1040;&#1083;&#1080;&#1089;&#1040; (Alisa)' АлисА (Alisa)
Bash equivalent to Python's string literal for utf string conversion
I'm writing a bash script that needs to parse html that includes special characters such as @!'ó. Currently I have the entire script running and it ignores or trips on these queries because they're returned from the server as decimal unicode like this: &#39;. I've figured out how to parse and convert to hexadecimal and load these into python to convert them back to their symbols and I am wondering if bash can do this final conversion natively. Simple example in python: print ur"\u0032" ur"\u0033" ur"\u0040" prints out 23@ Can I achieve the same result in Bash? I've looked into iconv but I don't think it can do what I want, or more probably I just don't know how. Here's some relevant information: Python String Literals Hex to UTF conversion in Python And here are some examples of expected input-output. Ludwig van Beethoven - 5th Symphony and 6th Symphony &#39;&#39;Pastoral&#39;&#39; - Boston Symphony Orchestra - Charles Munch Ludwig van Beethoven - 5th Symphony and 6th Symphony ''Pastoral'' - Boston Symphony Orchestra - Charles Munch &#1040;&#1083;&#1080;&#1089;&#1040; (Alisa) - &#1052;&#1099; &#1074;&#1084;&#1077;&#1089;&#1090;&#1077;. &#1061;&#1061; &#1083;&#1077;&#1090; (My vmeste XX let) АлисА (Alisa) - Мы вместе. ХХ лет (My vmeste XX let)
[ "The printf builtin in Bash doesn't support Unicode codes, but the external printf (at least on my GNU-based system) does:\n$ /usr/bin/printf \"\\u0410\\u043b\\u0438\\u0441\\u0410\"\nАлисА\n\nor this, which selects printf from your path in case it's not in /usr/bin:\n$ $(type -P printf) \"\\u0410\\u043b\\u0438\\u04...
[ 2, 1 ]
[]
[]
[ "bash", "python", "utf_8" ]
stackoverflow_0003191110_bash_python_utf_8.txt
Q: Streaming 1GB File in Python How long should it take to stream a 1GB file in python on say a 2Ghz Intel Core 2 Duo machine? fp = open('publisher_feed_8663.xml') for line in fp: a = line.split('<') I suppose I wasn't specific enough. This process takes 20+ minutes which is abnormally long. Based on empirical data, what is a reasonable time? A: Your answer: start = time.time() fp = open('publisher_feed_8663.xml') for line in fp: a = line.split('<') print time.time() - start You will require a 1GB file named publisher_feed_8663.xml, python and a 2Ghz Intel Core 2 Duo machine. For parsing of XML, you probably want to use an event based stream parser, such as SAX or lxml. I recommend reading the lxml documentation about iterparse: http://lxml.de/parsing.html#iterparse-and-iterwalk As for how long should this take, you can do trivial harddrive benchmarks on linux using tools like hdparm -tT /dev/sda. More RAM always helps with processing large files, as the OS can keep a bigger disk cache. A: Other people have talked about the time, I'll talk about the processing (XML aside). If you're doing something this massive, you should certainly look at generators. This pdf will teach you basically all you will ever need to know about generators. Any time you are either consuming or producing large amounts of data (especially serially) generators should be your very best friend. A: That will entirely depend on what's in the file. You're reading it a line at a time, which will mean a load of overhead calling the iterator again and again for the common case of lots of short lines. Use fp.read(CHUNK) with some large number for CHUNK to improve performance. However, I'm not sure what you're doing with split('<'). You can't usefully process XML with tools as basic as that, or with line-at-a-time parsing, since XML is not line-based. If you actually want to do something with the XML infoset in the file as you read it, you should consider a SAX parser. (Then again, 1GB of XML? That's already non-sensible really.)
Streaming 1GB File in Python
How long should it take to stream a 1GB file in python on say a 2Ghz Intel Core 2 Duo machine? fp = open('publisher_feed_8663.xml') for line in fp: a = line.split('<') I suppose I wasn't specific enough. This process takes 20+ minutes which is abnormally long. Based on empirical data, what is a reasonable time?
[ "Your answer:\nstart = time.time()\nfp = open('publisher_feed_8663.xml')\nfor line in fp:\n a = line.split('<')\nprint time.time() - start\n\nYou will require a 1GB file named publisher_feed_8663.xml, python and a 2Ghz Intel Core 2 Duo machine.\nFor parsing of XML, you probably want to use an event based stream p...
[ 8, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003189490_python.txt
Q: Python regex for fixing Australian/New Zealand Phone Numbers I have a Python script that we're using to parse CSV files with user-entered phone numbers in it - ergo, there are quite a few weird format/errors. We need to parse these numbers into their separate components, as well as fix some common entry errors. Our phone numbers are for Sydney or Melbourne (Australia), or Auckland (New Zealand), given in international format. Our standard Sydney number looks like: +61(2)8328-1972 We have the international prefix +61, followed by a single digit area code in brackets, 2, followed by the two halves of the local component, separated by a hyphen, 8328-1972. Melbourne numbers simply have 3 instead of 2 in the area code, e.g. +61(3)8328-1972 The Auckland numbers are similar, but they have a 7-digit local component (3 then 4 numbers), instead of the normal 8 digits. +64(9)842-1000 We also have matches for a number of common errors. I've separated the regex expressions into their own class. class PhoneNumberFormats(): """Provides compiled regex objects for different phone number formats. We put these in their own class for performance reasons - there's no point recompiling the same pattern for each Employee""" standard_format = re.compile(r'^\+(?P<intl_prefix>\d{2})\((?P<area_code>\d)\)(?P<local_first_half>\d{3,4})-(?P<local_second_half>\d{4})') extra_zero = re.compile(r'^\+(?P<intl_prefix>\d{2})\(0(?P<area_code>\d)\)(?P<local_first_half>\d{3,4})-(?P<local_second_half>\d{4})') missing_hyphen = re.compile(r'^\+(?P<intl_prefix>\d{2})\(0(?P<area_code>\d)\)(?P<local_first_half>\d{3,4})(?P<local_second_half>\d{4})') space_instead_of_hyphen = re.compile(r'^\+(?P<intl_prefix>\d{2})\((?P<area_code>\d)\)(?P<local_first_half>\d{3,4}) (?P<local_second_half>\d{4})') We have one for standard_format numbers, then others for various common error cases e.g. putting an extra zero before the area code (02 instead of 2), or missing hyphens in the local component (e.g.83281972instead of8328-1972`) etc. We then call these from cascaded if/elifs: def clean_phone_number(self): """Perform some rudimentary checks and corrections, to make sure numbers are in the right format. Numbers should be in the form 0XYYYYYYYY, where X is the area code, and Y is the local number.""" if not self.telephoneNumber: self.PHFull = '' self.PHFull_message = 'Missing phone number.' else: if PhoneNumberFormats.standard_format.search(self.telephoneNumber): result = PhoneNumberFormats.standard_format.search(self.telephoneNumber) self.PHFull = '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half') self.PHFull_message = '' elif PhoneNumberFormats.extra_zero.search(self.telephoneNumber): result = PhoneNumberFormats.extra_zero.search(self.telephoneNumber) self.PHFull = '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half') self.PHFull_message = 'Extra zero in area code - ask user to remediate.' elif PhoneNumberFormats.missing_hyphen.search(self.telephoneNumber): result = PhoneNumberFormats.missing_hyphen.search(self.telephoneNumber) self.PHFull = '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half') self.PHFull_message = 'Missing hyphen in local component - ask user to remediate.' elif PhoneNumberFormats.space_instead_of_hyphen.search(self.telephoneNumber): result = PhoneNumberFormats.missing_hyphen.search(self.telephoneNumber) self.PHFull = '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half') self.PHFull_message = 'Space instead of hyphen in local component - ask user to remediate.' else: self.PHFull = '' self.PHFull_message = 'Number didn\'t match recognised format. Original text is: ' + self.telephoneNumber My aim is to make the matching as tight as possible, yet still at least catch the common errors. There are number of problems with what I've done above though: I'm using \d{3,4} to match the first half of the local component. Ideally, however, we only really want to catch a 3-digit first half if if it's a New Zealand number (i.e. starts with +64(9)). That way, we can flag Sydney/Melbourne numbers that are missing a digit. I could separate out auckland_number into it's own regex pattern in PhoneNumberFormats, however, that means it wouldn't catch a New Zealand number combined with the error cases (extra_zero, missing_hyphen, space_instead_of_hyphen). So unless I recreate version of them just for Auckland, like auckland_extra_zero, which seems pointlessly repetitive, I can't see how to address this easily. We don't pickup combinations of errors - e.g. if they have a extra zero, and a missing hyphen, we won't pick this up. Is there an easy way to do this using regex, without explicitly creating permutations of the different errors? I'd like to address the above two issues, and hopefully tighten it up a bit to catch anything that I've missed. Is there a smarter way to do what I've attempted to do above? Cheers, Victor Additional Comments: The following is just to provide some context: This script is for a global company, with one office in Sydney, one in Melbourne and one in Auckland. The numbers come from an internal Active Directory listing of employees (i.e. it's not a customer listing, but our own office phones). Hence, we're not looking for a general Australian phone number matching script, rather, we're looking at a general sript to parse numbers from three specific offices. General, it's only the last 4 numbers that should differ. Mobile phones aren't required. The script is designed to parse a CSV dump of the Active Directory, and reformat the numbers into an acceptable format for another program (QuickComm) This program is from a external vendor, and requires numbers in the exact format that I've produced in the code above - that's why the numbers are spat out like 0283433422. The script I've written can't change the records, it only works on a CSV dump of them - the records are stored in Active Directory, and the only way to access them to get them fixed is to email the employee and ask them to login and change their own records. So this script is run by a PA, to produce the output required by this program. She/he will also get a list of people who have incorrectly formatted numbers - hence the messages about asking the user to remediate. In theory, there should only a be small number of these. We then email/ring these employees, asking them to fix their records - the script is run once a month (numbers may change), we also need to flag new employees that manage to enter their records in wrong as well. @John Macklin: Are you recommending I scrap regexes, and just try to pull specific-position digits out of the string? I was looking for a way to catch the common error cases, in combinations (e.g. space instead of hyphen, combined with an extra zero), but is this not easily feasible? A: Don't use complicated regexes. Delete EVERYTHING except digits -- non-digits are error-prone cruft. If the third digit is 0, delete it. Expect 61 followed by valid AUS area code ([23478] for generality NB 4 is for mobiles) then 8 digits or 64 followed by valid NZL area code (whatever that is) followed by 7 digits. Anything else is bad. In the good stuff, insert the +()- at the appropriate places. By the way (1) area code 2 is for the whole of NSW+ACT, not just Sydney, 3 is for VIC+TAS (2) lots of people these days don't have landlines, just mobiles, and people tend to retain the same mobile phone number longer than they maintain the same landline phone number or the same postal address, so mobile phone number is great for fuzzy matching customer records -- so I'm more than a little curious why you don't include them. The following tell you all you ever wanted to know, plus a whole lot more, about the Australian and New Zealand phone numbering schemes. Comment on the regexes: (1) You are using the search method with a "^" prefix. Using the match method with no prefix is somewhat less inelegant. (2) You don't seem to be checking for trailing rubbish in your phone number field: >>> import re >>> standard_format = re.compile(r'^\+(?P<intl_prefix>\d{2})\((?P<area_code>\d)\ )(?P<local_first_half>\d{3,4})-(?P<local_second_half>\d{4})') >>> m =standard_format.search("+61(3)1234-567890whoopsie") >>> m.groups() ('61', '3', '1234', '5678') >>> You may like to (a) end some of your regexes with \Z (NOT $) so that they don't match OK when there is trailing rubbish or (b) introduce another group to catch trailing rubbish. and a social engineering comment: Have you yet tested the user reaction to a staff member carrying out this directive: "Space instead of hyphen in local component - ask user to remediate"? Can't the script just fix it and carry on? and some comments on the code: the self.PHFull code (a) is terribly repetitive (if you must have regexes put them in a list with corresponding action codes and error messages and iterate over the list) (b) is the same for "error" cases as for standard cases (so why are you asking the users to "remediate"???) (c) throws away the country code and substitutes a 0 i.e. your standard +61(2)1234-5678 is being kept as 0212345678 aarrgghhh ... even if you have the country stored with the address that's no good if an NZer migrates to Aus and the address gets updated but not the phone number and please don't say that you are relying on the current (no NZ customers outside the Auckland area???) non-overlap of area codes ... Update after full story revealed Keep it SIMPLE for both you and the staff. Instructions to staff using Active Directory should be (depending on which office) "Fill in +61(2)9876-7 followed by your 3-digit extension number". If they can't get that right after a couple of attempts, it's time they got the DCM. So you use one regex per office, filling in the constant part, so that say the SYD offices have numbers of the form +61(2)9876-7ddd you use the regex r"\+61\(2\)9876-7\d{3,3}\Z". If a regex matches, then you remove all non-digits and use "0" + the_digits[2:] for the next app. If no regexes match, send a rocket. A: +1 for @John Machin's recommendations. The World Telephone Number Guide is quite useful for national numbering plans, especially the exceptions. The ITU has freely available standards for lots of stuff too. A: Phone numbers are formatted that way to make them easier to remember for people-- there's no reason that I can see for storing them like that. Why not split by commas and parse each number by simply ignoring anything that's not a digit? >>> import string >>> def parse_number(number): n = '' for x in number: if x in string.digits: n += x return n Once you've got it like that you can do verification based on the itl prefix and area code. (if the 3rd digit is 3 then there should be 7 more digits, etc) After it's verified, splitting into components is easy. The first two digits are the prefix, the next is the area code, etc. You can do a check for all the common mistakes without using regex. Outputting is also pretty easy in this case.
Python regex for fixing Australian/New Zealand Phone Numbers
I have a Python script that we're using to parse CSV files with user-entered phone numbers in it - ergo, there are quite a few weird format/errors. We need to parse these numbers into their separate components, as well as fix some common entry errors. Our phone numbers are for Sydney or Melbourne (Australia), or Auckland (New Zealand), given in international format. Our standard Sydney number looks like: +61(2)8328-1972 We have the international prefix +61, followed by a single digit area code in brackets, 2, followed by the two halves of the local component, separated by a hyphen, 8328-1972. Melbourne numbers simply have 3 instead of 2 in the area code, e.g. +61(3)8328-1972 The Auckland numbers are similar, but they have a 7-digit local component (3 then 4 numbers), instead of the normal 8 digits. +64(9)842-1000 We also have matches for a number of common errors. I've separated the regex expressions into their own class. class PhoneNumberFormats(): """Provides compiled regex objects for different phone number formats. We put these in their own class for performance reasons - there's no point recompiling the same pattern for each Employee""" standard_format = re.compile(r'^\+(?P<intl_prefix>\d{2})\((?P<area_code>\d)\)(?P<local_first_half>\d{3,4})-(?P<local_second_half>\d{4})') extra_zero = re.compile(r'^\+(?P<intl_prefix>\d{2})\(0(?P<area_code>\d)\)(?P<local_first_half>\d{3,4})-(?P<local_second_half>\d{4})') missing_hyphen = re.compile(r'^\+(?P<intl_prefix>\d{2})\(0(?P<area_code>\d)\)(?P<local_first_half>\d{3,4})(?P<local_second_half>\d{4})') space_instead_of_hyphen = re.compile(r'^\+(?P<intl_prefix>\d{2})\((?P<area_code>\d)\)(?P<local_first_half>\d{3,4}) (?P<local_second_half>\d{4})') We have one for standard_format numbers, then others for various common error cases e.g. putting an extra zero before the area code (02 instead of 2), or missing hyphens in the local component (e.g.83281972instead of8328-1972`) etc. We then call these from cascaded if/elifs: def clean_phone_number(self): """Perform some rudimentary checks and corrections, to make sure numbers are in the right format. Numbers should be in the form 0XYYYYYYYY, where X is the area code, and Y is the local number.""" if not self.telephoneNumber: self.PHFull = '' self.PHFull_message = 'Missing phone number.' else: if PhoneNumberFormats.standard_format.search(self.telephoneNumber): result = PhoneNumberFormats.standard_format.search(self.telephoneNumber) self.PHFull = '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half') self.PHFull_message = '' elif PhoneNumberFormats.extra_zero.search(self.telephoneNumber): result = PhoneNumberFormats.extra_zero.search(self.telephoneNumber) self.PHFull = '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half') self.PHFull_message = 'Extra zero in area code - ask user to remediate.' elif PhoneNumberFormats.missing_hyphen.search(self.telephoneNumber): result = PhoneNumberFormats.missing_hyphen.search(self.telephoneNumber) self.PHFull = '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half') self.PHFull_message = 'Missing hyphen in local component - ask user to remediate.' elif PhoneNumberFormats.space_instead_of_hyphen.search(self.telephoneNumber): result = PhoneNumberFormats.missing_hyphen.search(self.telephoneNumber) self.PHFull = '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half') self.PHFull_message = 'Space instead of hyphen in local component - ask user to remediate.' else: self.PHFull = '' self.PHFull_message = 'Number didn\'t match recognised format. Original text is: ' + self.telephoneNumber My aim is to make the matching as tight as possible, yet still at least catch the common errors. There are number of problems with what I've done above though: I'm using \d{3,4} to match the first half of the local component. Ideally, however, we only really want to catch a 3-digit first half if if it's a New Zealand number (i.e. starts with +64(9)). That way, we can flag Sydney/Melbourne numbers that are missing a digit. I could separate out auckland_number into it's own regex pattern in PhoneNumberFormats, however, that means it wouldn't catch a New Zealand number combined with the error cases (extra_zero, missing_hyphen, space_instead_of_hyphen). So unless I recreate version of them just for Auckland, like auckland_extra_zero, which seems pointlessly repetitive, I can't see how to address this easily. We don't pickup combinations of errors - e.g. if they have a extra zero, and a missing hyphen, we won't pick this up. Is there an easy way to do this using regex, without explicitly creating permutations of the different errors? I'd like to address the above two issues, and hopefully tighten it up a bit to catch anything that I've missed. Is there a smarter way to do what I've attempted to do above? Cheers, Victor Additional Comments: The following is just to provide some context: This script is for a global company, with one office in Sydney, one in Melbourne and one in Auckland. The numbers come from an internal Active Directory listing of employees (i.e. it's not a customer listing, but our own office phones). Hence, we're not looking for a general Australian phone number matching script, rather, we're looking at a general sript to parse numbers from three specific offices. General, it's only the last 4 numbers that should differ. Mobile phones aren't required. The script is designed to parse a CSV dump of the Active Directory, and reformat the numbers into an acceptable format for another program (QuickComm) This program is from a external vendor, and requires numbers in the exact format that I've produced in the code above - that's why the numbers are spat out like 0283433422. The script I've written can't change the records, it only works on a CSV dump of them - the records are stored in Active Directory, and the only way to access them to get them fixed is to email the employee and ask them to login and change their own records. So this script is run by a PA, to produce the output required by this program. She/he will also get a list of people who have incorrectly formatted numbers - hence the messages about asking the user to remediate. In theory, there should only a be small number of these. We then email/ring these employees, asking them to fix their records - the script is run once a month (numbers may change), we also need to flag new employees that manage to enter their records in wrong as well. @John Macklin: Are you recommending I scrap regexes, and just try to pull specific-position digits out of the string? I was looking for a way to catch the common error cases, in combinations (e.g. space instead of hyphen, combined with an extra zero), but is this not easily feasible?
[ "Don't use complicated regexes. Delete EVERYTHING except digits -- non-digits are error-prone cruft. If the third digit is 0, delete it.\nExpect 61 followed by valid AUS area code ([23478] for generality NB 4 is for mobiles) then 8 digits\nor 64 followed by valid NZL area code (whatever that is) followed by 7 digit...
[ 5, 3, 0 ]
[]
[]
[ "phone_number", "python", "regex" ]
stackoverflow_0003191936_phone_number_python_regex.txt
Q: Get the key of logged-in user with no DB access in Django on Google App Engine? I'm using Django on GAE. When I say user = request.user, I believe it hits the datastore to fetch the User entity. I would like to just get the key for the currently logged in user, because that will allow me to get the user-related data I need from the memcache. A: You probably are still going to hit the DB once to get the session record, which is where the user_id field is stored. Then you may need to side-step the lazy evaluation done in the django.contrib.auth.middleware code. It's not difficult, but you need to read the code and find exactly the info you want and then get at it without triggering any of the magic. Oh, and if you want to mumble your way through the Session objects directly you will have to call session.get_decoded() to get a dict. The field you want (if it exists) is _auth_user_id.
Get the key of logged-in user with no DB access in Django on Google App Engine?
I'm using Django on GAE. When I say user = request.user, I believe it hits the datastore to fetch the User entity. I would like to just get the key for the currently logged in user, because that will allow me to get the user-related data I need from the memcache.
[ "You probably are still going to hit the DB once to get the session record, which is where the user_id field is stored. Then you may need to side-step the lazy evaluation done in the django.contrib.auth.middleware code. It's not difficult, but you need to read the code and find exactly the info you want and then ge...
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003188274_django_google_app_engine_python.txt
Q: Uninstantiated class attribute Hello I need an uninstantiated class attribute and I am doing this: >>> class X: ... def __init__(self, y=None): ... self.y = list() Is this ok? If no, is there another way of doing it. I can't instantiate this attribute in __init__ cause I would be appending to this later. A: Define the y var on the class-level attribute. You will need to initialize it to something, even it's an empty list (as you were doing before). >>> class X: ... y = [] ... def __init__(self): ... pass Update based on your comments: You mentioned that you were mixed on the terminology (I'm assuming between class and instance variables), so here's what'll happen if you use this class (and is probably not what you want). >>> class X: ... y = [] # Class level attribute ... def __init__(self): ... pass ... >>> x = X() >>> x.y.append(1) >>> x.y [1] >>> x.y.append(2) >>> z = X() >>> z.y.append(3) >>> z.y [1, 2, 3] >>> X.y.append(4) >>> [1, 2, 3, 4] Notice that when you add a variable to the class it sticks around between constructions. In the previous code we instantiated the variable x and the variable z as an instance of X. While we added to the y variable in the z instance, we still appended to the class variable y. Note on the very last line (X.y.append(4)) I append an item using a reference to the class X. What you probably want is based off of your original post: >>> class X: ... def __init__(self, y=None): ... self.y = y or list() # Instance level attribute. Default to empty list if y is not passed in. ... >>> x = X() >>> x.y.append(1) >>> x.y [1] >>> z = X() >>> z.y.append(2) >>> z.y [2] >>> >>> s = X() >>> s.y [] >>> t = X(y=[10]) >>> t.y [10] Notice how a new list is created with each instance. When we create a new instance z and try to append to the y variable we only get the value that was appended, rather than keeping all of the existing additions to the list. In the last instantiation (t) example the constructor passes in the y parameter in it's construction, and thus has the list [10] as it's y instance variable. Hopefully that helps. Feel free to ask any more uncertainties as comments. Also, I would suggest reading up on the Python class documentation here. A: If you need a initial empty attribute, to which you will later add items, just do this class X(object): def __init__(self): self.y = [] Few things to note here (differences from your version) Derive class from object y = list() is same as y = [] and is preferred. No need of having default argument y=None, when you are not using it A: to add to the others statements: there are class variables and instance variables, they are separate and cannot be accessed the same way. ex: class foo: x=[] def __init__(self): self.y=[] foo.x.append(20) f = foo() f.y.append(30) print f.y print foo.x print f.x print foo.y #results------------------------------- [30] [20] [20] Traceback (most recent call last): File "C:\Users\adminuser\Desktop\temp.py", line 12, in <module> print foo.y AttributeError: class foo has no attribute 'y' A: Let me extent the answer of Anurag Uniyal a little bit class X(object): def __init__(self, y=None): if y is None: # y wasn't specified, create an empty list self.y = [] else: # y was specified, use it try: self.y = list(y) #create y's copy so that the original # variable is safe except TypeError: # ooops, couldn't create a list. We might warn # the user or something. Oh, nevermind self.y = []
Uninstantiated class attribute
Hello I need an uninstantiated class attribute and I am doing this: >>> class X: ... def __init__(self, y=None): ... self.y = list() Is this ok? If no, is there another way of doing it. I can't instantiate this attribute in __init__ cause I would be appending to this later.
[ "Define the y var on the class-level attribute. You will need to initialize it to something, even it's an empty list (as you were doing before).\n>>> class X:\n... y = [] \n... def __init__(self):\n... pass\n\nUpdate based on your comments:\nYou mentioned that you were mixed on the terminology (I'm...
[ 4, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003192211_python.txt
Q: How do I register a protocol to work with my program? I'd like my program to be summoned when a browser tries to open a page with the protocol "tf2emp://xxxxx". The program will then have to download content based on the 5 digit number given in said protocol. My program is written in python, and I'm using wx for the gui. A: This page from Mozilla should help you register protocols for Mozilla Firefox on WIndows and Linux. Similar info exists for other browsers/platforms, Google is your friend. :) A: Have a peek at Microsoft's page on the subject: http://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx
How do I register a protocol to work with my program?
I'd like my program to be summoned when a browser tries to open a page with the protocol "tf2emp://xxxxx". The program will then have to download content based on the 5 digit number given in said protocol. My program is written in python, and I'm using wx for the gui.
[ "This page from Mozilla should help you register protocols for Mozilla Firefox on WIndows and Linux. Similar info exists for other browsers/platforms, Google is your friend. :)\n", "Have a peek at Microsoft's page on the subject:\nhttp://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx\n" ]
[ 3, 2 ]
[]
[]
[ "protocols", "python" ]
stackoverflow_0003192530_protocols_python.txt
Q: What encoding does the unicode function in BeautifulSoup convert from? When I use the unicode function in BeautifulSoup - what encoding does it convert to Unicode from? Does it automatically use the soup.originalEncoding? from BeautifulSoup import BeautifulSoup doc = "<html><h1>Heading</h1><p>Text" soup = BeautifulSoup(doc) print unicode(soup) Thanks A: unicode() is a Python builtin, not part of BeautifulSoup. See the docs here. unicode([object[, encoding[, errors]]]) If encoding and/or errors are given, unicode() will decode the object which can either be an 8-bit string or a character buffer using the codec for encoding. The encoding parameter is a string giving the name of an encoding; if the encoding is not known, LookupError is raised. Error handling is done according to errors; this specifies the treatment of characters which are invalid in the input encoding. If errors is 'strict' (the default), a ValueError is raised on errors, while a value of 'ignore' causes errors to be silently ignored, and a value of 'replace' causes the official Unicode replacement character, U+FFFD, to be used to replace input characters which cannot be decoded. See also the codecs module. If you don't specify the encoding, sys.getdefaultencoding() will be used by default.
What encoding does the unicode function in BeautifulSoup convert from?
When I use the unicode function in BeautifulSoup - what encoding does it convert to Unicode from? Does it automatically use the soup.originalEncoding? from BeautifulSoup import BeautifulSoup doc = "<html><h1>Heading</h1><p>Text" soup = BeautifulSoup(doc) print unicode(soup) Thanks
[ "unicode() is a Python builtin, not part of BeautifulSoup. See the docs here.\n\nunicode([object[, encoding[, errors]]])\nIf encoding and/or errors are given,\n unicode() will decode the object which\n can either be an 8-bit string or a\n character buffer using the codec for\n encoding. The encoding parameter i...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003192547_beautifulsoup_python.txt
Q: An inheritance example in Python I'm not clear how to pose this question. If I did, I'd probably be a lot closer to a solution.. I need some insight into inheritance. I want to make a custom subtype of float. But I want the instance of this subtype to re-evaluate its value before performing any of the normal float methods (__add__,__mul__, etc..). In this example it should multiply its value by the global FACTOR: class FactorFloat(float): # I don't think I want to do this: ## def __new__(self, value): ## return float.__new__(self, value) def __init__(self, value): float.__init__(self, value) # Something important is missing.. # I want to do something with global FACTOR # when any float method is called. f = FactorFloat(3.) FACTOR = 10. print f # 30.0 print f-1 # 29.0 FACTOR = 2. print f # 6.0 print f-1 # 5.0 This is a just a sanitized example that I think gets my point across. I'll post a more complex "real" problem if necessary. A: class FactorFloat(float): def _factor_scale(f): def wrapper(self, *args, **kwargs): scaled = float.__mul__(self, FACTOR) result = f(scaled, *args, **kwargs) # if you want to return FactorFloats when possible: if isinstance(result, float): result = type(self)(result/FACTOR) return result return wrapper def __repr__(self): return '%s(%s)' % (type(self).__name__, float.__repr__(self)) __str__ = _factor_scale(float.__str__) __mul__ = _factor_scale(float.__mul__) __div__ = _factor_scale(float.__div__) __add__ = _factor_scale(float.__add__) __sub__ = _factor_scale(float.__sub__) f = FactorFloat(3.) FACTOR = 10. print f # 30.0 print f-1 # 29.0 FACTOR = 2. print f # 6.0 print f-1 # 5.0 print repr(f) for: 30.0 29.0 6.0 5.0 FactorFloat(3.0) EDIT: In response to the question in the comment; making things slightly more general and automated, using a class decorator. I would not loop over dir(baseclass), but instead would explicitly list the methods I wished to wrap. In the example below, I list them in the class variable _scale_methods. def wrap_scale_methods(cls): Base = cls.__base__ def factor_scale(f): def wrapper(self, *args, **kwargs): scaled = Base.__mul__(self, FACTOR) result = f(scaled, *args, **kwargs) if isinstance(result, Base): result = type(self)(result/FACTOR) return result return wrapper for methodname in cls._scale_methods: setattr(cls, methodname, factor_scale(getattr(Base, methodname))) return cls @wrap_scale_methods class FactorComplex(complex): _scale_methods = '__str__ __mul__ __div__ __add__ __sub__'.split() def __repr__(self): return '%s(%s)' % (type(self).__name__, complex.__repr__(self)[1:-1]) A: What you're wanting to do is actually very hard. I do not know of any python software that subclasses a type such as float or int and then does mathematics with it. I think that perhaps there is a better way to accomplish what you're trying to achieve without using a subclass of float. You should investigate alternatives. A: Here are a couple of methods to get your testcases passing def __str__(self): return str(FACTOR*self) def __sub__(self, other): return self*FACTOR-other obviously you have to also implement __add__, __mul__, etc... Having said that - what is your use case? This seems like a weird thing to want to do
An inheritance example in Python
I'm not clear how to pose this question. If I did, I'd probably be a lot closer to a solution.. I need some insight into inheritance. I want to make a custom subtype of float. But I want the instance of this subtype to re-evaluate its value before performing any of the normal float methods (__add__,__mul__, etc..). In this example it should multiply its value by the global FACTOR: class FactorFloat(float): # I don't think I want to do this: ## def __new__(self, value): ## return float.__new__(self, value) def __init__(self, value): float.__init__(self, value) # Something important is missing.. # I want to do something with global FACTOR # when any float method is called. f = FactorFloat(3.) FACTOR = 10. print f # 30.0 print f-1 # 29.0 FACTOR = 2. print f # 6.0 print f-1 # 5.0 This is a just a sanitized example that I think gets my point across. I'll post a more complex "real" problem if necessary.
[ "class FactorFloat(float):\n def _factor_scale(f):\n def wrapper(self, *args, **kwargs):\n scaled = float.__mul__(self, FACTOR)\n result = f(scaled, *args, **kwargs)\n # if you want to return FactorFloats when possible:\n if isinstance(result, float):\n ...
[ 5, 1, 1 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0003192032_inheritance_python.txt
Q: How do I protect my Python codebase so that guests can't see certain modules but so it still works? We're starting a new project in Python with a few proprietary algorithms and sensitive bits of logic that we'd like to keep private. We also will have a few outsiders (select members of the public) working on the code. We cannot grant the outsiders access to the small, private bits of code, but we'd like a public version to work well enough for them. Say that our project, Foo, has a module, bar, with one function, get_sauce(). What really happens in get_sauce() is secret, but we want a public version of get_sauce() to return an acceptable, albeit incorrect, result. We also run our own Subversion server so we have total control over who can access what. Symlinks My first thought was symlinking — Instead of bar.py, provide bar_public.py to everybody and bar_private.py to internal developers only. Unfortunately, creating symlinks is tedious, manual work — especially when there are really going to be about two dozen of these private modules. More importantly, it makes management of the Subversion authz file difficult, since for each module we want to protect an exception must be added on the server. Someone might forget to do this and accidentally check in secrets... Then the module is in the repo and we have to rebuild the repository without it and hope that an outsider didn't download it in the meantime. Multiple repositories The next thought was to have two repositories: private └── trunk/ ├── __init__.py └── foo/ ├── __init__.py └── bar.py public └── trunk/ ├── __init__.py └── foo/ ├── __init__.py ├── bar.py ├── baz.py └── quux.py The idea is that only internal developers will be able to checkout both private/ and public/. Internal developers will set their PYTHONPATH=private/trunk:public/trunk, but everyone else will just set PYTHONPATH=public/trunk. Then, both insiders and outsiders can from foo import bar and get the right module, right? Let's try this: % PYTHONPATH=private/trunk:public/trunk python Python 2.5.1 Type "help", "copyright", "credits" or "license" for more information. >>> import foo.bar >>> foo.bar.sauce() 'a private bar' >>> import foo.quux Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named quux I'm not a Python expert, but it seems that Python has already made up its mind about module foo and searches relative to that: >>> foo <module 'foo' from '/path/to/private/trunk/foo/__init__.py'> Not even deleting foo helps: >>> import sys >>> del foo >>> del sys.modules['foo'] >>> import foo.quux Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named quux Can you provide me with a better solution or suggestion? A: In the __init__ method of the foo package you can change __path__ to make it look for its modules in other directories. So create a directory called secret and put it in your private Subversion repository. In secret put your proprietary bar.py. In the __init__.py of the public foo package put in something like: __path__.insert(0,'secret') This will mean for users who have the private repository and so the secret directory they will get the proprietary bar.py as foo.bar as secret is the first directory in the search path. For other users, Python won't find secret and will look as the next directory in __path__ and so will load the normal bar.py from foo. So it will look something like this: private └── trunk/ └── secret/ └── bar.py public └── trunk/ ├── __init__.py └── foo/ ├── __init__.py ├── bar.py ├── baz.py └── quux.py A: Use some sort of plugin system, and keep your plugins to your self, but also have publically available plugins that gets shipped with the open code. Plugin systems abound. You can easily make dead simple ones yourself. If you want something more advanced I prefer the Zope Component Architecture, but there are also options like setuptools entry_points, etc. Which one to use in your case would be a good second question. A: Here's an alternate solution I noticed when reading the docs for Flask: flaskext/__init__.py The only purpose of this file is to mark the package as namespace package. This is required so that multiple modules from different PyPI packages can reside in the same Python package: __import__('pkg_resources').declare_namespace(__name__) If you want to know exactly what is happening there, checkout the distribute or setuptools docs which explain how this works.
How do I protect my Python codebase so that guests can't see certain modules but so it still works?
We're starting a new project in Python with a few proprietary algorithms and sensitive bits of logic that we'd like to keep private. We also will have a few outsiders (select members of the public) working on the code. We cannot grant the outsiders access to the small, private bits of code, but we'd like a public version to work well enough for them. Say that our project, Foo, has a module, bar, with one function, get_sauce(). What really happens in get_sauce() is secret, but we want a public version of get_sauce() to return an acceptable, albeit incorrect, result. We also run our own Subversion server so we have total control over who can access what. Symlinks My first thought was symlinking — Instead of bar.py, provide bar_public.py to everybody and bar_private.py to internal developers only. Unfortunately, creating symlinks is tedious, manual work — especially when there are really going to be about two dozen of these private modules. More importantly, it makes management of the Subversion authz file difficult, since for each module we want to protect an exception must be added on the server. Someone might forget to do this and accidentally check in secrets... Then the module is in the repo and we have to rebuild the repository without it and hope that an outsider didn't download it in the meantime. Multiple repositories The next thought was to have two repositories: private └── trunk/ ├── __init__.py └── foo/ ├── __init__.py └── bar.py public └── trunk/ ├── __init__.py └── foo/ ├── __init__.py ├── bar.py ├── baz.py └── quux.py The idea is that only internal developers will be able to checkout both private/ and public/. Internal developers will set their PYTHONPATH=private/trunk:public/trunk, but everyone else will just set PYTHONPATH=public/trunk. Then, both insiders and outsiders can from foo import bar and get the right module, right? Let's try this: % PYTHONPATH=private/trunk:public/trunk python Python 2.5.1 Type "help", "copyright", "credits" or "license" for more information. >>> import foo.bar >>> foo.bar.sauce() 'a private bar' >>> import foo.quux Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named quux I'm not a Python expert, but it seems that Python has already made up its mind about module foo and searches relative to that: >>> foo <module 'foo' from '/path/to/private/trunk/foo/__init__.py'> Not even deleting foo helps: >>> import sys >>> del foo >>> del sys.modules['foo'] >>> import foo.quux Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named quux Can you provide me with a better solution or suggestion?
[ "In the __init__ method of the foo package you can change __path__ to make it look for its modules in other directories.\nSo create a directory called secret and put it in your private Subversion repository. In secret put your proprietary bar.py. In the __init__.py of the public foo package put in something like:...
[ 3, 2, 0 ]
[]
[]
[ "modularity", "project_management", "python", "repository", "svn" ]
stackoverflow_0001443146_modularity_project_management_python_repository_svn.txt
Q: ctypes calling function with windows datatypes arguments Could someone help me how should I call the following function using ctypes python library: DWORD myfunc(LPCSTR a,BYTE b, LPBYTE c, LPDWORD d, LPCBYTE *e,DWORD LEN) How should I declare and initialize the arguments of the mentioned functions? Could someone provide an example? A: Try: from ctypes.wintypes import * It has most of the types you want.
ctypes calling function with windows datatypes arguments
Could someone help me how should I call the following function using ctypes python library: DWORD myfunc(LPCSTR a,BYTE b, LPBYTE c, LPDWORD d, LPCBYTE *e,DWORD LEN) How should I declare and initialize the arguments of the mentioned functions? Could someone provide an example?
[ "Try:\nfrom ctypes.wintypes import *\n\nIt has most of the types you want.\n" ]
[ 3 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0002913076_ctypes_python.txt
Q: Python newbie - help needed in choosing modules/libraries i am learning python.. i want to do certain kind of scripting in python.. like, i want to communicate 'wmic' commands through dos promt.. store the result a file.. access some sqlite database, take the data it has and compare with the result i stored.. now, what i dont get is that, how should i proceed? is there any specific frameworks or modules/libraries? like, win32api / com or what else? pls guide me what things i should follow/learn to accomplish what i intend to do.. thanks A: One of the particularly attractive features of Python is the "batteries included" philosophy: The standard library is huge, and extremely well thought out in 90% of the modules I've ever used. Conversely, this means that a good approach is to learn it first before branching out and installing third-party libraries that may be much less well supported and, ultimately, have no advantage. In practice, this means I'd recommend keeping https://docs.python.org/release/2.6.5/library/index.html close to your heart, and delve into the documentation for the sqlite3 and probably the subprocess modules. You may or may not want win32api later (I've never worked with wmic, so I'm not sure what you'd need), or come back here when you have concrete questions and already explored the standard library offering. A: for your project look here http://tgolden.sc.sabren.com/python/wmi/index.html http://docs.python.org/library/sqlite3.html here is list of generic python modules http://docs.python.org/modindex.html http://docs.python.org/ - here you can find all information you need with examples.
Python newbie - help needed in choosing modules/libraries
i am learning python.. i want to do certain kind of scripting in python.. like, i want to communicate 'wmic' commands through dos promt.. store the result a file.. access some sqlite database, take the data it has and compare with the result i stored.. now, what i dont get is that, how should i proceed? is there any specific frameworks or modules/libraries? like, win32api / com or what else? pls guide me what things i should follow/learn to accomplish what i intend to do.. thanks
[ "One of the particularly attractive features of Python is the \"batteries included\" philosophy: The standard library is huge, and extremely well thought out in 90% of the modules I've ever used. Conversely, this means that a good approach is to learn it first before branching out and installing third-party librari...
[ 0, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0003192815_module_python.txt
Q: unknown array length in python ctypes I'm calling a C function using ctypes from Python. It returns a pointer to a struct, in memory allocated by the library (the application calls another function to free it later). I'm having trouble figuring out how to massage the function call to fit with ctypes. The struct looks like: struct WLAN_INTERFACE_INFO_LIST { DWORD dwNumberOfItems; [...] WLAN_INTERFACE_INFO InterfaceInfo[]; } I've been using a Structure subclass that looks like this: class WLAN_INTERFACE_INFO_LIST(Structure): _fields_ = [ ("NumberOfItems", DWORD), [...] ("InterfaceInfo", WLAN_INTERFACE_INFO * 1) ] How can I tell ctypes to let me access the nth item of the InterfaceInfo array? I cannot use Scott's excellent customresize() function because I don't own the memory (Memory cannot be resized because this object doesn't own it). A: Modifying Scott's answer to remove the resize() call worked: def customresize(array, new_size): return (array._type_*new_size).from_address(addressof(array))
unknown array length in python ctypes
I'm calling a C function using ctypes from Python. It returns a pointer to a struct, in memory allocated by the library (the application calls another function to free it later). I'm having trouble figuring out how to massage the function call to fit with ctypes. The struct looks like: struct WLAN_INTERFACE_INFO_LIST { DWORD dwNumberOfItems; [...] WLAN_INTERFACE_INFO InterfaceInfo[]; } I've been using a Structure subclass that looks like this: class WLAN_INTERFACE_INFO_LIST(Structure): _fields_ = [ ("NumberOfItems", DWORD), [...] ("InterfaceInfo", WLAN_INTERFACE_INFO * 1) ] How can I tell ctypes to let me access the nth item of the InterfaceInfo array? I cannot use Scott's excellent customresize() function because I don't own the memory (Memory cannot be resized because this object doesn't own it).
[ "Modifying Scott's answer to remove the resize() call worked:\ndef customresize(array, new_size):\n return (array._type_*new_size).from_address(addressof(array))\n\n" ]
[ 4 ]
[]
[]
[ "arrays", "ctypes", "pointers", "python", "winapi" ]
stackoverflow_0003192638_arrays_ctypes_pointers_python_winapi.txt
Q: Python: How to find path to the script running a python script Lets say i have a python script at homedir/codes/py/run.py I also have a bash script at homedir/codes/run.sh This bash script runs run.py by python py/run.py. The thing is that i need to be able to find out, in run.py, the path to the calling script run.sh. If run.sh is run from its own directory, i can just use os.getcwd(). But run.sh can in principle be run from anywhere, and then os.getcwd() will return the path to where run.sh is run FROM, and not the actual location of run.sh. ex: At homedir/codes: ./run.sh -> os.getcwd() returns homedir/codes At homedir: ./codes/run.sh -> os.getcwd() returns homedir But i want homedir/codes no matter how run.sh is called. Is this possible? A: To get the absolute path of the current script in bash, do: SCRIPT=$(readlink -f "$0") Now, pass that variable as the last argument to the python script. You can get the argument from python as: sys.argv[-1] A: you can get the absolute qualified path with: os.path.join(os.path.abspath(os.curdir))
Python: How to find path to the script running a python script
Lets say i have a python script at homedir/codes/py/run.py I also have a bash script at homedir/codes/run.sh This bash script runs run.py by python py/run.py. The thing is that i need to be able to find out, in run.py, the path to the calling script run.sh. If run.sh is run from its own directory, i can just use os.getcwd(). But run.sh can in principle be run from anywhere, and then os.getcwd() will return the path to where run.sh is run FROM, and not the actual location of run.sh. ex: At homedir/codes: ./run.sh -> os.getcwd() returns homedir/codes At homedir: ./codes/run.sh -> os.getcwd() returns homedir But i want homedir/codes no matter how run.sh is called. Is this possible?
[ "To get the absolute path of the current script in bash, do:\nSCRIPT=$(readlink -f \"$0\")\n\nNow, pass that variable as the last argument to the python script. You can get the argument from python as:\nsys.argv[-1]\n\n", "you can get the absolute qualified path with:\nos.path.join(os.path.abspath(os.curdir))\n\...
[ 3, 3 ]
[]
[]
[ "path", "python" ]
stackoverflow_0003192853_path_python.txt
Q: Python - use of 'self' - noob here going crazy trying to understand it I have a simple socket class: MySocketLib.py .. import socket class socklib(): def create_tcp_serversocket(self,port): serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind((socket.gethostname(), port)) serversocket.listen(5) return serversocket def send_msg(self, sock, msg, msglen): ... blah blah ... def recv_msg(self, sock, msglen): ... blah blah .... My main file is Server.py as follows: import MySocketLib class serverclass(): def __init__(self,port): self.servsock = 0 self.port = port def run(self): self.servsock = self.create_tcp_serversocket(self.port) (clientsock, address) = self.servsock.accept() # ERROR: 'SELF' not defined ... blah blah ... ############################# ### Main startup code if __name__ == '__main__': server = serverclass(2000) # server is on port 2000 server.run() I keep getting the below error: File "D:\CodeLearn\Server.py", line 14, in serverclass (clientsock, address) = self.servsock.accept() NameError: name 'self' is not defined I can't seem to get a handle on the concept of "self". Some times, it seems to be needed and sometimes not. Why would i need to define 'self' here when it is a python keyword? Thanks everyone ... it was indeed the tabs and spacing issues. I use eclipse and in preferences I have set "Editor" preferences to use spaces when tabbing. A: Don't use tabs in Python source code. Configure your editor to always use spaces. self is not a Python keyword, it's a convention. It's the usual name for the "instance" of a class you're using. Example: class X: def __init__(self, v): self.v = v a = X(1) b = X(2) print a.v, b.v When this code runs, the Python runtime will eventually allocate memory for two instances of X which it will assign to a and b respectively. If there wasn't something like self, you would have to write: a = X() a.v = 1 b = X() b.b = 2 print a.v, b.v And you would get an error because you wrote b.b instead of b.v. Moreover, calling methods would be outright ugly: class X: def set(v): ???.v = v How would you say "access the reference v which was allocated in __init__ of X"? One solution would be to pass the instance reference (the pointer to the memory which was allocated for X) as a parameter: class X: def set(a, v): a.v = v a.set(a, 1) # Holy ugly! Everyone would use different names and we would all violate DRY and it would be a mess. So what Python did is: class X: def set(self, v): self.v = v a.set(1) # while "set" runs, "self" == "a" b.set(2) # while "set" runs, "self" == "b" That said, I have no idea why the code above fails. self is obviously defined or the error would already happen in the first line of your run() method. So my guess is that you mixed spaces and tabs for indentation and that confuses Python and it sees: def run(self): self.servsock = self.create_tcp_serversocket(self.port) (clientsock, address) = self.servsock.accept() # ERROR: 'SELF' not defined Then it would try to evaluate self.servsock.accept() while it parses the class definition. At that time, there is no instance yet (the class doesn't exist!) so self is not available either. Conclusion: Never mix tabs and spaces. A: It maybe indentation error. File "D:\CodeLearn\Server.py", line 14, in serverclass This meen that (clientsock, address) = self.servsock.accept() is not inside run function, but in serverclass itself A: Your indentation is wrong, so __init__() and run() are being interpreted as top-level functions -- with no automatic self parameter. What you need is: class serverclass: def __init__(self,port): self.servsock = 0 self.port = port def run(self): self.servsock = self.create_tcp_serversocket(self.port) (clientsock, address) = self.servsock.accept() # ERROR: 'SELF' not defined ... blah blah ...
Python - use of 'self' - noob here going crazy trying to understand it
I have a simple socket class: MySocketLib.py .. import socket class socklib(): def create_tcp_serversocket(self,port): serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind((socket.gethostname(), port)) serversocket.listen(5) return serversocket def send_msg(self, sock, msg, msglen): ... blah blah ... def recv_msg(self, sock, msglen): ... blah blah .... My main file is Server.py as follows: import MySocketLib class serverclass(): def __init__(self,port): self.servsock = 0 self.port = port def run(self): self.servsock = self.create_tcp_serversocket(self.port) (clientsock, address) = self.servsock.accept() # ERROR: 'SELF' not defined ... blah blah ... ############################# ### Main startup code if __name__ == '__main__': server = serverclass(2000) # server is on port 2000 server.run() I keep getting the below error: File "D:\CodeLearn\Server.py", line 14, in serverclass (clientsock, address) = self.servsock.accept() NameError: name 'self' is not defined I can't seem to get a handle on the concept of "self". Some times, it seems to be needed and sometimes not. Why would i need to define 'self' here when it is a python keyword? Thanks everyone ... it was indeed the tabs and spacing issues. I use eclipse and in preferences I have set "Editor" preferences to use spaces when tabbing.
[ "Don't use tabs in Python source code. Configure your editor to always use spaces.\nself is not a Python keyword, it's a convention. It's the usual name for the \"instance\" of a class you're using. Example:\nclass X:\n def __init__(self, v): self.v = v\n\na = X(1)\nb = X(2)\nprint a.v, b.v\n\nWhen this code run...
[ 4, 2, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0003193411_class_python.txt
Q: Python Case Insensitive Replace without hurting re cache related question: Case insensitive replace What's the best way to do a case insensitive replace WITHOUT HURTING THE CACHE in the re module? I'm monitoring carefully the cache to make sure my favorite regexes stay there (speed, of course). I just notice that my code: ner_token_result = re.sub('(?i)'+leftover, corrected_word, ner_token_result) is re.compiling every time it is run. leftover is dynamic (based on user input). I like regular expressions (fast, I can read them) but I don't want to hurt my cache. I don't want to use a caseless string class... I don't want the ugliness of converting to lowercase, replacing and restoring case... Please help? A: If your other expressions are pre-compiled it means you did something like this: regex = re.compile(leftover, re.I) Which means you will be able to refer to regex regardless of cache overloading. If you didn't do this, do it for those regexes that need to be re-used throughout your code. A: Obviously the dynamic regex needs to be compiled each time leftover changes. Are you worried that this is pushing your other regexs out of the cache? If so, simply compile the other regexs you are using with re.compile
Python Case Insensitive Replace without hurting re cache
related question: Case insensitive replace What's the best way to do a case insensitive replace WITHOUT HURTING THE CACHE in the re module? I'm monitoring carefully the cache to make sure my favorite regexes stay there (speed, of course). I just notice that my code: ner_token_result = re.sub('(?i)'+leftover, corrected_word, ner_token_result) is re.compiling every time it is run. leftover is dynamic (based on user input). I like regular expressions (fast, I can read them) but I don't want to hurt my cache. I don't want to use a caseless string class... I don't want the ugliness of converting to lowercase, replacing and restoring case... Please help?
[ "If your other expressions are pre-compiled it means you did something like this:\nregex = re.compile(leftover, re.I)\n\nWhich means you will be able to refer to regex regardless of cache overloading. If you didn't do this, do it for those regexes that need to be re-used throughout your code.\n", "Obviously the d...
[ 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003193605_python_regex.txt
Q: Multiple text nodes in Python's ElementTree? HTML generation I'm using ElementTree to generate some HTML, but I've run into the problem that ElementTree doesn't store text as a Node, but as the text and tail properties of Element. This is a problem if I want to generate something that would require multiple text nodes, for example: <a>text1 <b>text2</b> text3 <b>text4</b> text5</a> As far as I can tell there is no way to generate this- am I missing something? Or, is there a better solution for quick and simple HTML generation in Python? A: To generate the above string with ElementTree you can use the following code. The trick to this is that the text is the very first lot of text before the next element and the tail is all the text after the element up to the next element. import xml.etree.ElementTree as ET root = ET.Element("a") root.text = 'text1 ' #First Text in the Element a b = ET.SubElement(root, "b") b.text = 'text2' #Text in the first b b.tail = ' text3 ' #Text immediately after the first b but before the second b = ET.SubElement(root, "b") b.text = 'text4' b.tail = ' text5' print ET.tostring(root) #This prints <a>text1 <b>text2</b> text3 <b>text4</b> text5</a>
Multiple text nodes in Python's ElementTree? HTML generation
I'm using ElementTree to generate some HTML, but I've run into the problem that ElementTree doesn't store text as a Node, but as the text and tail properties of Element. This is a problem if I want to generate something that would require multiple text nodes, for example: <a>text1 <b>text2</b> text3 <b>text4</b> text5</a> As far as I can tell there is no way to generate this- am I missing something? Or, is there a better solution for quick and simple HTML generation in Python?
[ "To generate the above string with ElementTree you can use the following code. The trick to this is that the text is the very first lot of text before the next element and the tail is all the text after the element up to the next element.\nimport xml.etree.ElementTree as ET\nroot = ET.Element(\"a\")\nroot.text = '...
[ 14 ]
[]
[]
[ "elementtree", "html_generation", "python" ]
stackoverflow_0003145015_elementtree_html_generation_python.txt
Q: Python+Scipy+Integration: dealing with precision errors in functions with spikes I am trying to use scipy.integrate.quad to integrate a function over a very large range (0..10,000). The function is zero over most of its range but has a spike in a very small range (e.g. 1,602..1,618). When integrating, I would expect the output to be positive, but I guess that somehow quad's guessing algorithm is getting confused and outputting zero. What I would like to know is, is there a way to overcome this (e.g. by using a different algorithm, some other parameter, etc.)? I don't usually know where the spike is going to be, so I can't just split the integration range and sum the parts (unless somebody has a good idea on how to do that). Thanks! Sample output: >>>scipy.integrate.quad(weighted_ftag_2, 0, 10000) (0.0, 0.0) >>>scipy.integrate.quad(weighted_ftag_2, 0, 1602) (0.0, 0.0) >>>scipy.integrate.quad(weighted_ftag_2, 1602, 1618) (3.2710994652983256, 3.6297354011338712e-014) >>>scipy.integrate.quad(weighted_ftag_2, 1618, 10000) (0.0, 0.0) A: You might want to try other integration methods, such as the integrate.romberg() method. Alternatively, you can get the location of the point where your function is large, with weighted_ftag_2(x_samples).argmax(), and then use some heuristics to cut the integration interval around the maximum of your function (which is located at x_samples[….argmax()]. You must taylor the list of sampled abscissas (x_samples) to your problem: it must always contain points that are in the region where your function is maximum. More generally, any specific information about the function to be integrated can help you get a good value for its integral. I would combine a method that works well for your function (one of the many methods offered by Scipy) with a reasonable splitting of the integration interval (for instance along the lines suggested above). A: How about evaluating your function f() over each integer range [x, x+1), and adding up e.g. romb(), as EOL suggests, where it's > 0: from __future__ import division import numpy as np from scipy.integrate import romb def romb_non0( f, a=0, b=10000, nromb=2**6+1, verbose=1 ): """ sum romb() over the [x, x+1) where f != 0 """ sum_romb = 0 for x in xrange( a, b ): y = f( np.arange( x, x+1, 1./nromb )) if y.any(): r = romb( y, 1./nromb ) sum_romb += r if verbose: print "info romb_non0: %d %.3g" % (x, r) # , y return sum_romb #........................................................................... if __name__ == "__main__": np.set_printoptions( 2, threshold=100, suppress=True ) # .2f def f(x): return x if (10 <= x).all() and (x <= 12).all() \ else np.zeros_like(x) romb_non0( f, verbose=1 )
Python+Scipy+Integration: dealing with precision errors in functions with spikes
I am trying to use scipy.integrate.quad to integrate a function over a very large range (0..10,000). The function is zero over most of its range but has a spike in a very small range (e.g. 1,602..1,618). When integrating, I would expect the output to be positive, but I guess that somehow quad's guessing algorithm is getting confused and outputting zero. What I would like to know is, is there a way to overcome this (e.g. by using a different algorithm, some other parameter, etc.)? I don't usually know where the spike is going to be, so I can't just split the integration range and sum the parts (unless somebody has a good idea on how to do that). Thanks! Sample output: >>>scipy.integrate.quad(weighted_ftag_2, 0, 10000) (0.0, 0.0) >>>scipy.integrate.quad(weighted_ftag_2, 0, 1602) (0.0, 0.0) >>>scipy.integrate.quad(weighted_ftag_2, 1602, 1618) (3.2710994652983256, 3.6297354011338712e-014) >>>scipy.integrate.quad(weighted_ftag_2, 1618, 10000) (0.0, 0.0)
[ "You might want to try other integration methods, such as the integrate.romberg() method.\nAlternatively, you can get the location of the point where your function is large, with weighted_ftag_2(x_samples).argmax(), and then use some heuristics to cut the integration interval around the maximum of your function (wh...
[ 3, 1 ]
[]
[]
[ "integrate", "numerical_methods", "precision", "python", "scipy" ]
stackoverflow_0003186196_integrate_numerical_methods_precision_python_scipy.txt
Q: Date calculations in Python I am relatively new to Python, and I am experimenting with writing the following date calc functions find the date that is/was Monday for a specified datetime find the first non-weekend day of the month in a specified datetime find the first non-weekend day of the year in a specified datetime find the Nth [day of week] for a month in a specified datetime Here are my attempts so far - if the logic can be improved (or corrected) to be more 'Pythonic', please let me know import datetime def find_month_first_monday(tstamp = datetime.today()): day_of_month = datetime.date.today().timetuple()[2] day_of_week = datetime.weekday(tstamp) # now I have the dow, and dom, I can index into a 2D array of # dates for the month - IF I knew how to get to that array ... def find_first_gbd_in_month(tstamp = datetime.today()): # naive way would be to find the month and year from the passed in arg, # calculate the first day for that month/year and iterate until a non-weekend day # is found. Not elegant, there must be a better way pass def find_first_gbd_in_year(tstamp = datetime.today()): # Ditto, as above. pass def find_ndow_in_month(tstamp = datetime.today()): # again, I can get the month and the year from the passed in argument # what I need is a 2D array of dates for the month/year, so I can get # the nth dow (similar to reading off a calendar) pass A: find_month_first_monday I'd use a different algorithm. First, find the first day of the month. first_day_of_month = datetime.date.today().replace(day=1) and find the week day of first_day_of_month, week_day = first_day_of_month.weekday() and add days if necessary. if week_day: first_day_of_month += datetime.timedelta(days=7-week_day) find_first_gbd_in_month Similar to find_month_first_monday, but add the day only if week_day is 5 or 6 (Saturday and Sunday). find_first_gbd_in_year Supply the month=1 argument in .replace as well. find_ndow_in_month Find the first day of week, then add n-1 weeks. A: Use the excellent dateutil module. It is very easy to do that and other date calculations with it. Some examples: import datetime from dateutil import rrule today = datetime.date.today() First friday of the month, for 10 months: print list(rrule.rrule(rrule.MONTHLY, count=10, byweekday=rrule.FR(1), dtstart=today))) results: [datetime.datetime(2010, 8, 2, 0, 0), datetime.datetime(2010, 9, 6, 0, 0), datetime.datetime(2010, 10, 4, 0, 0), datetime.datetime(2010, 11, 1, 0, 0), datetime.datetime(2010, 12, 6, 0, 0), datetime.datetime(2011, 1, 3, 0, 0), datetime.datetime(2011, 2, 7, 0, 0), datetime.datetime(2011, 3, 7, 0, 0), datetime.datetime(2011, 4, 4, 0, 0), datetime.datetime(2011, 5, 2, 0, 0)] First monday of the year, for 3 years: print list(rrule.rrule(rrule.YEARLY, count=3, byweekday=rrule.MO(1), dtstart=datetime.date.today())) Results: [datetime.datetime(2011, 1, 3, 0, 0), datetime.datetime(2012, 1, 2, 0, 0), datetime.datetime(2013, 1, 7, 0, 0)]
Date calculations in Python
I am relatively new to Python, and I am experimenting with writing the following date calc functions find the date that is/was Monday for a specified datetime find the first non-weekend day of the month in a specified datetime find the first non-weekend day of the year in a specified datetime find the Nth [day of week] for a month in a specified datetime Here are my attempts so far - if the logic can be improved (or corrected) to be more 'Pythonic', please let me know import datetime def find_month_first_monday(tstamp = datetime.today()): day_of_month = datetime.date.today().timetuple()[2] day_of_week = datetime.weekday(tstamp) # now I have the dow, and dom, I can index into a 2D array of # dates for the month - IF I knew how to get to that array ... def find_first_gbd_in_month(tstamp = datetime.today()): # naive way would be to find the month and year from the passed in arg, # calculate the first day for that month/year and iterate until a non-weekend day # is found. Not elegant, there must be a better way pass def find_first_gbd_in_year(tstamp = datetime.today()): # Ditto, as above. pass def find_ndow_in_month(tstamp = datetime.today()): # again, I can get the month and the year from the passed in argument # what I need is a 2D array of dates for the month/year, so I can get # the nth dow (similar to reading off a calendar) pass
[ "find_month_first_monday\nI'd use a different algorithm. First, find the first day of the month.\nfirst_day_of_month = datetime.date.today().replace(day=1)\n\nand find the week day of first_day_of_month, \nweek_day = first_day_of_month.weekday()\n\nand add days if necessary.\nif week_day:\n first_day_of_month += d...
[ 4, 4 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0003194036_datetime_python.txt
Q: How to create a pop window using pygtk? Todo: On button click in main window, open a popup dialog Framework: pygtk Experience: Beginner A: import gtk d = gtk.Dialog() d.add_buttons(gtk.STOCK_YES, 1, gtk.STOCK_NO, 2) label = gtk.Label('Do you like GTK?') label.show() d.vbox.pack_start(label) answer = d.run() d.destroy() print answer
How to create a pop window using pygtk?
Todo: On button click in main window, open a popup dialog Framework: pygtk Experience: Beginner
[ "import gtk\n\nd = gtk.Dialog()\nd.add_buttons(gtk.STOCK_YES, 1, gtk.STOCK_NO, 2)\n\nlabel = gtk.Label('Do you like GTK?')\nlabel.show()\nd.vbox.pack_start(label)\n\nanswer = d.run()\nd.destroy()\n\nprint answer\n\n\n" ]
[ 6 ]
[]
[]
[ "linux", "pygtk", "python" ]
stackoverflow_0003194436_linux_pygtk_python.txt
Q: django django_authopenid.openid_store error in apache I am getting the following error on my website: Error importing openid store django_authopenid.openid_store: "No ElementTree library found. You may need to install one. Tried importing ['lxml.etree', 'xml.etree.cElementTree', 'xml.etree.ElementTree', 'cElementTree', 'elementtree.ElementTree']" I have commented all the django openid code and all the imports, still its giving the error. When I run the project in django development server by doing: python manage.py runserver It works fine. But in apache its giving the the above error. I have even installed all the required packages and checked by running import and the module name, in the python shell on the server, its importing fine, still its giving the error. Please help A: this one is fixed, there was an url in the urls.py file and i commented that and now everything is working fine.
django django_authopenid.openid_store error in apache
I am getting the following error on my website: Error importing openid store django_authopenid.openid_store: "No ElementTree library found. You may need to install one. Tried importing ['lxml.etree', 'xml.etree.cElementTree', 'xml.etree.ElementTree', 'cElementTree', 'elementtree.ElementTree']" I have commented all the django openid code and all the imports, still its giving the error. When I run the project in django development server by doing: python manage.py runserver It works fine. But in apache its giving the the above error. I have even installed all the required packages and checked by running import and the module name, in the python shell on the server, its importing fine, still its giving the error. Please help
[ "this one is fixed, there was an url in the urls.py file and i commented that and now everything is working fine.\n" ]
[ 0 ]
[]
[]
[ "apache", "django", "openid", "python" ]
stackoverflow_0003194261_apache_django_openid_python.txt
Q: Code based unique constraint Django Model I have a Django model that looks like this: class Categories(models.Model): """ Model for storing the categories """ name = models.CharField(max_length=8) keywords = models.TextField() spamwords = models.TextField() translations = models.TextField() def save(self, force_insert=False, force_update=False): """ Custom save method that converts the name to uppercase """ self.name = self.name.upper() super(Categories, self).save(force_insert, force_update) Whenever the data is inserted or updated. I'd like to check that that a record with same name doesn't exists. It's a unique constraint that I'd like to implement via code and not the DB. The amount of data in this table is minuscule so the the performance hit is not an issue. If there is an constraint violation, I'd like to raise one of Django's inbuilt constraint exceptions instead of creating a custom one. Could someone how me the best/fastest way to accomplish this? Thanks. A: In your model definition you can tell Django that 'name' should be unique: name = models.CharField(max_length=8, unique=True) A django.db.IntegrityError will be raised if you attempt to save two records with the same name.
Code based unique constraint Django Model
I have a Django model that looks like this: class Categories(models.Model): """ Model for storing the categories """ name = models.CharField(max_length=8) keywords = models.TextField() spamwords = models.TextField() translations = models.TextField() def save(self, force_insert=False, force_update=False): """ Custom save method that converts the name to uppercase """ self.name = self.name.upper() super(Categories, self).save(force_insert, force_update) Whenever the data is inserted or updated. I'd like to check that that a record with same name doesn't exists. It's a unique constraint that I'd like to implement via code and not the DB. The amount of data in this table is minuscule so the the performance hit is not an issue. If there is an constraint violation, I'd like to raise one of Django's inbuilt constraint exceptions instead of creating a custom one. Could someone how me the best/fastest way to accomplish this? Thanks.
[ "In your model definition you can tell Django that 'name' should be unique:\nname = models.CharField(max_length=8, unique=True)\n\nA django.db.IntegrityError will be raised if you attempt to save two records with the same name.\n" ]
[ 8 ]
[ "in the view\ntry:\n Category.objects.get(name='name')\nexcept Category.DoesNotExist:\n # call the save method of model\n\n" ]
[ -1 ]
[ "django", "django_models", "python" ]
stackoverflow_0003194650_django_django_models_python.txt
Q: Building a list of months by iterating between two dates in a list (Python) I have an ordered (i.e. sorted) list that contains dates sorted (as datetime objects) in ascending order. I want to write a function that iterates through this list and generates another list of the first available dates for each month. For example, suppose my sorted list contains the following data: A = [ '2001/01/01', '2001/01/03', '2001/01/05', '2001/02/04', '2001/02/05', '2001/03/01', '2001/03/02', '2001/04/10', '2001/04/11', '2001/04/15', '2001/05/07', '2001/05/12', '2001/07/01', '2001/07/10', '2002/03/01', '2002/04/01', ] The returned list would be B = [ '2001/01/01', '2001/02/04', '2001/03/01', '2001/04/10', '2001/05/07', '2001/07/01', '2002/03/01', '2002/04/01', ] The logic I propose would be something like this: def extract_month_first_dates(input_list, start_date, end_date): #note: start_date and end_date DEFINITELY exist in the passed in list prev_dates, output = [],[] # <- is this even legal? for (curr_date in input_list): if ((curr_date < start_date) or (curr_date > end_date)): continue curr_month = curr_date.date.month curr_year = curr_date.date.year date_key = "{0}-{1}".format(curr_year, curr_month) if (date_key in prev_dates): continue else: output.append(curr_date) prev_dates.append(date_key) return output Any comments, suggestions? - can this be improved to be more 'Pythonic' ? A: >>> import itertools >>> [min(j) for i, j in itertools.groupby(A, key=lambda x: x[:7])] ['2001/01/01', '2001/02/04', '2001/03/01', '2001/04/10', '2001/05/07', '2001/07/01', '2002/03/01', '2002/04/01'] A: Searching lists is a O(n) operation. I think you can simply check whether the key is new: def extract_month_first_dates(input_list): output = [] last_key = None for curr_date in input_list: date_key = curr_date.date.month, curr_date.date.year # no string key required if date_key != last_key: output.append(curr_date) last_key = date_key return output A: Here is a simple solution in classic python i.e. no itertools ;) and self explanatory visited = {} B = [] for a in A: month = a[:7] if month not in visited: B.append(a) visited[month] = 1 print B Ouput: ['2001/01/01', '2001/02/04', '2001/03/01', '2001/04/10', '2001/05/07', '2001/07/01', '2002/03/01', '2002/04/01']
Building a list of months by iterating between two dates in a list (Python)
I have an ordered (i.e. sorted) list that contains dates sorted (as datetime objects) in ascending order. I want to write a function that iterates through this list and generates another list of the first available dates for each month. For example, suppose my sorted list contains the following data: A = [ '2001/01/01', '2001/01/03', '2001/01/05', '2001/02/04', '2001/02/05', '2001/03/01', '2001/03/02', '2001/04/10', '2001/04/11', '2001/04/15', '2001/05/07', '2001/05/12', '2001/07/01', '2001/07/10', '2002/03/01', '2002/04/01', ] The returned list would be B = [ '2001/01/01', '2001/02/04', '2001/03/01', '2001/04/10', '2001/05/07', '2001/07/01', '2002/03/01', '2002/04/01', ] The logic I propose would be something like this: def extract_month_first_dates(input_list, start_date, end_date): #note: start_date and end_date DEFINITELY exist in the passed in list prev_dates, output = [],[] # <- is this even legal? for (curr_date in input_list): if ((curr_date < start_date) or (curr_date > end_date)): continue curr_month = curr_date.date.month curr_year = curr_date.date.year date_key = "{0}-{1}".format(curr_year, curr_month) if (date_key in prev_dates): continue else: output.append(curr_date) prev_dates.append(date_key) return output Any comments, suggestions? - can this be improved to be more 'Pythonic' ?
[ ">>> import itertools\n>>> [min(j) for i, j in itertools.groupby(A, key=lambda x: x[:7])]\n['2001/01/01', '2001/02/04', '2001/03/01', '2001/04/10', '2001/05/07', '2001/07/01', '2002/03/01', '2002/04/01']\n\n", "Searching lists is a O(n) operation. I think you can simply check whether the key is new:\ndef extract_...
[ 7, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003194682_python.txt
Q: Python Encoding issue Why am I getting this issue? and how do I resolve it? UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 24: unexpected code byte Thank you A: Somewhere, perhaps subtly, you are asking Python to turn a stream of bytes into a "string" of characters. Don't think of a string as "bytes". A string is a list of numbers, each number having an agreed meaning in Unicode. (#65 = Latin Capital A. #19968 = Chinese Character "One"/"First") . There are many methods of encoding a list of Unicode entities into a stream of bytes. Python is assuming your stream of bytes is the result of a particular such method, called "UTF-8". However, your stream of bytes has data that does not correspond to that method. Thus the error is raised. You need to figure out the encoding of the stream of bytes, and tell Python that encoding. It's important to know if you're using Python 2 or 3, and the code leading up to this exception to see where your bytes came from and what the appropriate way to deal with them is. If it's from reading a file, you can explicity deal with the bytes read. But you must be sure of the file encoding. If it's from a string that is part of your source code, then Python is assuming the "wrong thing" about your source files... perhaps $LC_ALL or $LANG needs to be set. This is a good time to firmly understand the concept of encoding, and how text editors choose an encoding to write, and what is standard for your language and operating system. A: In addition to what Joe said, chardet is a useful tool to detect encoding of the source data. A: Somewhere you have a plain string encoded as "Windows-1252" (or "cp1252") containing a "RIGHT SINGLE QUOTATION MARK" (’) instead of an APOSTROPHE ('). This could come from a file you read, or even in a Python source file of yours; you could be running Python 2.x and have a # -*- coding: utf8 -*- line somewhere near the script's beginning, or you could be running Python 3.x. You don't give enough data; however, somewhere you have a cp1252-encoded string, which you try (explicitly or implicitly) to decode to unicode as utf-8. This won't work. Give us more info, and we'll try again to help you. Joe Koberg's answer reminded me of an older answer of mine, which some people have found helpful: Python UnicodeDecodeError - Am I misunderstanding encode?
Python Encoding issue
Why am I getting this issue? and how do I resolve it? UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 24: unexpected code byte Thank you
[ "Somewhere, perhaps subtly, you are asking Python to turn a stream of bytes into a \"string\" of characters.\nDon't think of a string as \"bytes\". A string is a list of numbers, each number having an agreed meaning in Unicode. (#65 = Latin Capital A. #19968 = Chinese Character \"One\"/\"First\") .\nThere are ma...
[ 1, 0, 0 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0003188895_encoding_python.txt
Q: Django \u characters in my UTF8 strings I am adding UTF-8 data to a database in Django. As the data goes into the database, everything looks fine - the characters (for example): “Hello” are UTF-8 encoded. My MySQL database is UTF-8 encoded. When I examine the data from the DB by doing a select, my example string looks like this: ?Hello?. I assume this is showing the characters as UTF-8 encoded. When I select the data from the database in the terminal or for export as a web-service, however - my string looks like this: \u201cHello World\u201d. Does anyone know how I can display my characters correctly? Do I need to perform some additional UTF-8 encoding somewhere? Thanks, Nick. A: u'\u201cHello World\u201d' Is the correct Python representation of the Unicode text “Hello World”. The smartquote characters are being displayed using a \uXXXX hex escape rather than verbatim because there are often problems with writing Unicode characters to the terminal, particularly on Windows. (It looks like MySQL tried to write them to the terminal but failed, resulting in the ? placeholders.) On a terminal that does manage to correctly input and output Unicode characters, you can confirm that they're the same thing: 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. >>> u'\u201cHello World\u201d'==u'“Hello World”' True just as for byte strings, \x sequences are just the same as characters: >>> '\x61'=='a' True Now if you've got \u or \x sequences escaping Python and making their way into an exported file, then you've done something wrong with the export. Perhaps you used repr() somewhere by mistake.
Django \u characters in my UTF8 strings
I am adding UTF-8 data to a database in Django. As the data goes into the database, everything looks fine - the characters (for example): “Hello” are UTF-8 encoded. My MySQL database is UTF-8 encoded. When I examine the data from the DB by doing a select, my example string looks like this: ?Hello?. I assume this is showing the characters as UTF-8 encoded. When I select the data from the database in the terminal or for export as a web-service, however - my string looks like this: \u201cHello World\u201d. Does anyone know how I can display my characters correctly? Do I need to perform some additional UTF-8 encoding somewhere? Thanks, Nick.
[ "u'\\u201cHello World\\u201d'\n\nIs the correct Python representation of the Unicode text “Hello World”. The smartquote characters are being displayed using a \\uXXXX hex escape rather than verbatim because there are often problems with writing Unicode characters to the terminal, particularly on Windows. (It looks ...
[ 6 ]
[]
[]
[ "django", "python", "utf_8" ]
stackoverflow_0003194801_django_python_utf_8.txt
Q: AttributeError: 'datetime.date' object has no attribute 'date' I have a script like this: import datetime # variable cal_start_of_week_date has type <type 'datetime.date'> # variable period has type <type 'datetime.timedelta'> cal_prev_monday = (cal_start_of_week_date - period).date() When the above statement is executed, I get the error: AttributeError: 'datetime.date' object has no attribute 'date' How to fix this? A: Stop trying to call the date() method of a date object. It's already a date. A: .date() method exists only on datetime.datetime objects. You have object of datetime.date type. Remove method call and be happy.
AttributeError: 'datetime.date' object has no attribute 'date'
I have a script like this: import datetime # variable cal_start_of_week_date has type <type 'datetime.date'> # variable period has type <type 'datetime.timedelta'> cal_prev_monday = (cal_start_of_week_date - period).date() When the above statement is executed, I get the error: AttributeError: 'datetime.date' object has no attribute 'date' How to fix this?
[ "Stop trying to call the date() method of a date object. It's already a date.\n", ".date() method exists only on datetime.datetime objects. You have object of datetime.date type.\nRemove method call and be happy.\n" ]
[ 31, 7 ]
[]
[]
[ "python" ]
stackoverflow_0003195405_python.txt
Q: External use of Django DB module failed because of settings module loading I am facing a problem with using Django DB module in an external gateway script. I have the following python file under myproject/myapplication/lib.py #<path>/myproject/myapplication/lib.py from django.db import connection from django.db import settings #SOME METHODS ARE HERE which is using django db module. I need to import lib in another python script under the same directory myproject/myapplication/gateway.py #<path>/myproject/myapplication/gateway.py import sys, os os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings" sys.path.append('../') import lib #SOME LOGIC HERE but it is failing with the following error : Fisbrok:myproject firas$ python myapplication/gateway.py Traceback (most recent call last): File "myapplication/gateway.py", line 7, in ? import lib File ".... lib.py", line 1, in ? from django.db import connection File "/opt/local/lib/python2.4/site-packages/django/db/__init__.py", line 14, in ? if not settings.DATABASES: File "/opt/local/lib/python2.4/site-packages/django/utils/functional.py", line 276, in __getattr__ self._setup() File "/opt/local/lib/python2.4/site-packages/django/conf/__init__.py", line 40, in _setup self._wrapped = Settings(settings_module) File "/opt/local/lib/python2.4/site-packages/django/conf/__init__.py", line 75, in __init__ raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'myproject.settings' (Is it on sys.path? Does it have syntax errors?): No module named myproject.settings Am I missing something ? A: your project directory, myproject has to be in python path to set the settings module as myproject.settings you can set the project directory on python in the gateway.py file by import sys sys.path.insert(0, 'absolute/path/to/project') before the line os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"
External use of Django DB module failed because of settings module loading
I am facing a problem with using Django DB module in an external gateway script. I have the following python file under myproject/myapplication/lib.py #<path>/myproject/myapplication/lib.py from django.db import connection from django.db import settings #SOME METHODS ARE HERE which is using django db module. I need to import lib in another python script under the same directory myproject/myapplication/gateway.py #<path>/myproject/myapplication/gateway.py import sys, os os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings" sys.path.append('../') import lib #SOME LOGIC HERE but it is failing with the following error : Fisbrok:myproject firas$ python myapplication/gateway.py Traceback (most recent call last): File "myapplication/gateway.py", line 7, in ? import lib File ".... lib.py", line 1, in ? from django.db import connection File "/opt/local/lib/python2.4/site-packages/django/db/__init__.py", line 14, in ? if not settings.DATABASES: File "/opt/local/lib/python2.4/site-packages/django/utils/functional.py", line 276, in __getattr__ self._setup() File "/opt/local/lib/python2.4/site-packages/django/conf/__init__.py", line 40, in _setup self._wrapped = Settings(settings_module) File "/opt/local/lib/python2.4/site-packages/django/conf/__init__.py", line 75, in __init__ raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'myproject.settings' (Is it on sys.path? Does it have syntax errors?): No module named myproject.settings Am I missing something ?
[ "your project directory, myproject has to be in python path to set the settings module as myproject.settings\nyou can set the project directory on python in the gateway.py file by\nimport sys\nsys.path.insert(0, 'absolute/path/to/project')\n\nbefore the line \nos.environ['DJANGO_SETTINGS_MODULE'] = \"myproject.sett...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003195738_django_python.txt
Q: How to get checkbox data using python on gae This is my HTML: <div id='automail'> <form action = "/admin/mail" method = "get"> auto mail when user :<br/><br/> <div> <input type="checkbox" name="automail" value ="signup">signUp</input><br/> <input type="checkbox" name="automail" value ="login">login</input><br/> </div> <div style="text-align:right"> <input type="submit" value="save"></input> </div> </form> </div> And this is my python handle: class mail(BaseRequestHandler): def get(self): all=self.request.get('automail') if not all: self.response.out.write('sss') return self.response.out.write(all) when I choosee 'signup' and 'login', it only show 'signup'. So how to get all data from checkbox using python on gae? updated: it is ok now ,two ways : 1. all=self.request.get_all('automail') 2. all=self.request.get('automail',allow_multiple=True) A: If multiple arguments have the same name, self.request.get returns the first one. You want get_all.
How to get checkbox data using python on gae
This is my HTML: <div id='automail'> <form action = "/admin/mail" method = "get"> auto mail when user :<br/><br/> <div> <input type="checkbox" name="automail" value ="signup">signUp</input><br/> <input type="checkbox" name="automail" value ="login">login</input><br/> </div> <div style="text-align:right"> <input type="submit" value="save"></input> </div> </form> </div> And this is my python handle: class mail(BaseRequestHandler): def get(self): all=self.request.get('automail') if not all: self.response.out.write('sss') return self.response.out.write(all) when I choosee 'signup' and 'login', it only show 'signup'. So how to get all data from checkbox using python on gae? updated: it is ok now ,two ways : 1. all=self.request.get_all('automail') 2. all=self.request.get('automail',allow_multiple=True)
[ "If multiple arguments have the same name, self.request.get returns the first one.\nYou want get_all.\n" ]
[ 6 ]
[]
[]
[ "checkbox", "google_app_engine", "python" ]
stackoverflow_0003195647_checkbox_google_app_engine_python.txt
Q: To send Chat Invitation, to GTalk using Google App Engine(Python)? How can i send Chat invitation over GTalk using Google App Engine(Python), i was searching for code in documentation of GAE, but i didnt get it. As i am new to Python, please post me the code too... A: http://code.google.com/appengine/docs/python/xmpp/overview.html from google.appengine.api import xmpp from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class FooHandler(webapp.RequestHandler): def get(self): xmpp.send_invite('example@gmail.com') application = webapp.WSGIApplication([('.*', FooHandler)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
To send Chat Invitation, to GTalk using Google App Engine(Python)?
How can i send Chat invitation over GTalk using Google App Engine(Python), i was searching for code in documentation of GAE, but i didnt get it. As i am new to Python, please post me the code too...
[ "http://code.google.com/appengine/docs/python/xmpp/overview.html\nfrom google.appengine.api import xmpp\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass FooHandler(webapp.RequestHandler):\n def get(self):\n xmpp.send_invite('example@gmail.com')\n...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003192792_google_app_engine_python.txt