title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
How to define a class in Python
1,495,666
<p>Quite simple, I'm learning python and I can't find a reference that tells me how to write the following:</p> <pre><code>public class Team { private String name; private String logo; private int members; public Team(){} // getters/setters } </code></pre> <p>Later:</p> <pre><code>Team team = new Team(); team.setName( "Oscar" ); team.setLogo( "http://...." ); team.setMembers( 10 ); </code></pre> <p>That is a class Team with the properties: name/logo/members </p> <p><strong>Edit</strong> After a few attempt I got this:</p> <pre><code>class Team: pass </code></pre> <p>Later</p> <pre><code>team = Team() team.name="Oscar" team.logo="http://..." team.members=10 </code></pre> <p>Is this the python way?? Feels odd ( coming from a strongly typed language of course ) </p>
40
2009-09-30T01:02:16Z
1,495,740
<p>Here is what I would recommend:</p> <pre class="lang-py prettyprint-override"><code>class Team(object): def __init__(self, name=None, logo=None, members=0): self.name = name self.logo = logo self.members = members team = Team("Oscar", "http://...", 10) team2 = Team() team2.name = "Fred" team3 = Team(name="Joe", members=10) </code></pre> <p>Some notes on this.</p> <p>0) I declared that Team inherits from <code>object</code>. This makes Team a "new-style class"; this has been recommended practice in Python since it was introduced in Python 2.2. (In Python 3.0 and above, classes are always "new-style" even if you leave out the <code>(object)</code> notation; but having that notation does no harm and makes the inheritance explicit.) Here's a StackOverflow <a href="http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python">discussion</a> of new-style classes.</p> <p>1) It's not required, but I made the initializer take optional arguments so that you can initialize the instance on one line, as I did with <code>team</code> and <code>team3</code>. These arguments are named, so you can either provide values as positional parameters (as with <code>team</code>) or you can use the <code>argument=</code> form as I did with <code>team3</code>. When you explicitly specify the name of the arguments, you can specify arguments in any order.</p> <p>2) If you needed to have getter and setter functions, perhaps to check something, in Python you can declare special method functions. This is what Martin v. Löwis meant when he said "property descriptors". In Python, it is generally considered good practice to simply assign to member variables, and simply reference them to fetch them, because you can always add in the property descriptors later should you need them. (And if you never need them, then your code is less cluttered and took you less time to write. Bonus!)</p> <p>Here's a good link about property descriptors: <a href="http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/"><a href="http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/">http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/</a></a></p> <p>3) It doesn't really matter if you specify values as part of the call to <code>Team()</code> or if you poke them into your class instance later. The final class instance you end up with will be identical.</p> <pre><code>team = Team("Joe", "http://example.com", 1) team2 = Team() team2.name = "Joe" team2.logo = "http://example.com" team2.members = 1 print team.__dict__ == team2.__dict__ </code></pre> <p>The above will print <code>True</code>. (You can easily overload the <code>==</code> operator for <code>Team</code> instances, and make Python do the right thing when you say <code>team == team2</code> but this doesn't happen by default.)</p> <hr> <p>EDIT: I left out one thing in the above answer, and I'd like to add it now. If you do the optional argument thing on the <code>__init__()</code> function, you need to be careful if you want to provide a "mutable" as an optional argument.</p> <p>Integers and strings are "immutable". You can never change them in place; what happens instead is Python creates a new object and replaces the one you had before.</p> <p>Lists and dictionaries are "mutable". You can keep the same object around forever, adding to it and deleting from it.</p> <pre class="lang-py prettyprint-override"><code>x = 3 # the name "x" is bound to an integer object with value 3 x += 1 # the name "x" is rebound to a different integer object with value 4 x = [] # the name "x" is bound to an empty list object x.append(1) # the 1 is appended to the same list x already had </code></pre> <p>The key thing you need to know: optional arguments are evaluated only once, when the function is compiled. So if you pass a mutable as an optional argument in the <code>__init__()</code> for your class, then each instance of your class shares one mutable object. This is almost never what you want.</p> <pre class="lang-py prettyprint-override"><code>class K(object): def __init__(self, lst=[]): self.lst = lst k0 = K() k1 = K() k0.lst.append(1) print k0.lst # prints "[1]" print k1.lst # also prints "[1]" k1.lst.append(2) print k0.lst # prints "[1, 2]" </code></pre> <p>The solution is very simple:</p> <pre class="lang-py prettyprint-override"><code>class K(object): def __init__(self, lst=None): if lst is None: self.lst = [] # bind lst with a new, empty list else: self.lst = lst # bind lst with provided list k0 = K() k1 = K() k0.lst.append(1) print k0.lst # prints "[1]" print k1.lst # print "[]" </code></pre> <p>This business of using a default argument value of <code>None</code>, then testing that the argument passed <code>is None</code>, qualifies as a Python design pattern, or at least an idiom you should master.</p>
87
2009-09-30T01:35:29Z
[ "python" ]
How close is Python to being able to wrap it in a workbook type skin?
1,496,039
<p>With my luck this question will be closed too quickly. I see a tremendous possibility for a python application that basically is like a workbook. Imagine if you will that instead of writing code you select from a menu of choices. For example, the File menu would have an open command that lets the user navigate to a file or directory of file or a webpage, even a list of web pages and specify those as the things that will be the base for the next actions.</p> <p>Then you have a find menu. The menu would allow easy access to the various parsing tools, regular expression and string tools so you can specify the thing you want to find within the files.</p> <p>Another menu item could allow you to create queries to interact with database objects.</p> <p>I could go on and on. As the language becomes more higher level then these types of features become easier to implement. There is a tremendous advantage to developing something like this. How much time is spent reinventing the wheel for mundane tasks? Programmers have functions that they have built to do many mundane tasks but what about democratizing the power offered by a tool like Python.</p> <p>I have people in my office all of the time asking how to solve problems that seem intractable to them, but when I show them how with a few lines of code their problem is solvable except for the edge cases they become amazed. I deflect their gratitude with the observation that it is not really that hard except for being able to construct the right google search to identify the right package or library to solve the problem. There is nothing amazing about my ability to use lxml and sets to pull all bolded sections from a collection of say 12,000 documents and compare across time and across unique identifiers in the collection how those bolded sections have evolved/changed or converged. The amazing piece is that someone wrote the libraries to do these things.</p> <p>What is the advantage to the community for something like this. Imagine if you would an interface that looks like a workbook but interacts with an app-store. So if you want to pull something from html file you go to the app store and buy a plug-in that handles the work. If the workbook is built robustly enough it could be licensed to a machine, the 'apps' would be tied to a particular workbook.</p> <p>Just imagine the creativity that could be unleashed by users if they could get over the feeling that access to this power is difficult. You guys may not see this but I see Python being so close to being able to port to something like a workbook framework. Weren't the early spreadsheet programs nothing more than a frame around some Fortran libraries that had been ported to C? </p> <p>Comments or is there such an application and I have not found it.</p>
1
2009-09-30T03:51:01Z
1,496,055
<p>There are Python application that are based on generating code -- the most amazing one probably <a href="http://www.resolversystems.com/products/" rel="nofollow">Resolver One</a>, which focuses on spreadsheets (and hinges on IronPython). With that exception, however, interacting based on the UI paradigm you have in mind (pick one of this, one of that, etc) tends to be pretty limited in the gamut of choices it offers to let the user generate the exact application they need -- there's just <strong>so</strong> much more you can say by writing even a little script, than what you can say by point-and-grunt.</p> <p>That being said, Python would surely be a great choice both to implement such an app and as the language to generate... if and when you have a UI sketch that looks like it can actually allow non-programmers to specify a large-enough spectrum of apps in a broad-enough domain!-). Spreadsheets have proven themselves in this sense, but I don't know of other niches or approaches that have actually done so -- do you?</p>
3
2009-09-30T03:58:23Z
[ "python", "wrapper", "openaccess" ]
How close is Python to being able to wrap it in a workbook type skin?
1,496,039
<p>With my luck this question will be closed too quickly. I see a tremendous possibility for a python application that basically is like a workbook. Imagine if you will that instead of writing code you select from a menu of choices. For example, the File menu would have an open command that lets the user navigate to a file or directory of file or a webpage, even a list of web pages and specify those as the things that will be the base for the next actions.</p> <p>Then you have a find menu. The menu would allow easy access to the various parsing tools, regular expression and string tools so you can specify the thing you want to find within the files.</p> <p>Another menu item could allow you to create queries to interact with database objects.</p> <p>I could go on and on. As the language becomes more higher level then these types of features become easier to implement. There is a tremendous advantage to developing something like this. How much time is spent reinventing the wheel for mundane tasks? Programmers have functions that they have built to do many mundane tasks but what about democratizing the power offered by a tool like Python.</p> <p>I have people in my office all of the time asking how to solve problems that seem intractable to them, but when I show them how with a few lines of code their problem is solvable except for the edge cases they become amazed. I deflect their gratitude with the observation that it is not really that hard except for being able to construct the right google search to identify the right package or library to solve the problem. There is nothing amazing about my ability to use lxml and sets to pull all bolded sections from a collection of say 12,000 documents and compare across time and across unique identifiers in the collection how those bolded sections have evolved/changed or converged. The amazing piece is that someone wrote the libraries to do these things.</p> <p>What is the advantage to the community for something like this. Imagine if you would an interface that looks like a workbook but interacts with an app-store. So if you want to pull something from html file you go to the app store and buy a plug-in that handles the work. If the workbook is built robustly enough it could be licensed to a machine, the 'apps' would be tied to a particular workbook.</p> <p>Just imagine the creativity that could be unleashed by users if they could get over the feeling that access to this power is difficult. You guys may not see this but I see Python being so close to being able to port to something like a workbook framework. Weren't the early spreadsheet programs nothing more than a frame around some Fortran libraries that had been ported to C? </p> <p>Comments or is there such an application and I have not found it.</p>
1
2009-09-30T03:51:01Z
1,496,078
<p>Your idea kinda reminded me of something I stumbled across months ago: <a href="http://www.ailab.si/orange/" rel="nofollow">http://www.ailab.si/orange/</a></p>
1
2009-09-30T04:10:42Z
[ "python", "wrapper", "openaccess" ]
How close is Python to being able to wrap it in a workbook type skin?
1,496,039
<p>With my luck this question will be closed too quickly. I see a tremendous possibility for a python application that basically is like a workbook. Imagine if you will that instead of writing code you select from a menu of choices. For example, the File menu would have an open command that lets the user navigate to a file or directory of file or a webpage, even a list of web pages and specify those as the things that will be the base for the next actions.</p> <p>Then you have a find menu. The menu would allow easy access to the various parsing tools, regular expression and string tools so you can specify the thing you want to find within the files.</p> <p>Another menu item could allow you to create queries to interact with database objects.</p> <p>I could go on and on. As the language becomes more higher level then these types of features become easier to implement. There is a tremendous advantage to developing something like this. How much time is spent reinventing the wheel for mundane tasks? Programmers have functions that they have built to do many mundane tasks but what about democratizing the power offered by a tool like Python.</p> <p>I have people in my office all of the time asking how to solve problems that seem intractable to them, but when I show them how with a few lines of code their problem is solvable except for the edge cases they become amazed. I deflect their gratitude with the observation that it is not really that hard except for being able to construct the right google search to identify the right package or library to solve the problem. There is nothing amazing about my ability to use lxml and sets to pull all bolded sections from a collection of say 12,000 documents and compare across time and across unique identifiers in the collection how those bolded sections have evolved/changed or converged. The amazing piece is that someone wrote the libraries to do these things.</p> <p>What is the advantage to the community for something like this. Imagine if you would an interface that looks like a workbook but interacts with an app-store. So if you want to pull something from html file you go to the app store and buy a plug-in that handles the work. If the workbook is built robustly enough it could be licensed to a machine, the 'apps' would be tied to a particular workbook.</p> <p>Just imagine the creativity that could be unleashed by users if they could get over the feeling that access to this power is difficult. You guys may not see this but I see Python being so close to being able to port to something like a workbook framework. Weren't the early spreadsheet programs nothing more than a frame around some Fortran libraries that had been ported to C? </p> <p>Comments or is there such an application and I have not found it.</p>
1
2009-09-30T03:51:01Z
1,496,242
<p>Is your concept very similar to Microsoft Access? Generally programmers tend not to write such programs because they produce such horrible code that the authors themselves would never want to use their program.</p>
0
2009-09-30T05:22:43Z
[ "python", "wrapper", "openaccess" ]
Aggregating multiple feeds with Universal Feed Parser
1,496,067
<p>Having great luck working with single-source feed parsing in Universal Feed Parser, but now I need to run multiple feeds through it and generate chronologically interleaved output (not RSS). Seems like I'll need to iterate through URLs and stuff every entry into a list of dictionaries, then sort that by the entry timestamps and take a slice off the top. That seems do-able, but pretty expensive resource-wise (I'll cache it aggressively for that reason). </p> <p>Just wondering if there's an easier way - an existing library that works with feedparser to do simple aggregation, for example. Sample code? Gotchas or warnings? Thanks.</p>
0
2009-09-30T04:04:18Z
1,496,285
<p>You could throw the feeds into a database and then generate a new feed from this database.</p> <p>Consider looking into two feedparser-based RSS aggregators: <a href="http://www.planetplanet.org/" rel="nofollow">Planet Feed Aggregator</a> and <a href="http://www.feedjack.org/" rel="nofollow">FeedJack</a> (Django based), or at least how they solve this problem.</p>
2
2009-09-30T05:48:24Z
[ "python", "django" ]
Aggregating multiple feeds with Universal Feed Parser
1,496,067
<p>Having great luck working with single-source feed parsing in Universal Feed Parser, but now I need to run multiple feeds through it and generate chronologically interleaved output (not RSS). Seems like I'll need to iterate through URLs and stuff every entry into a list of dictionaries, then sort that by the entry timestamps and take a slice off the top. That seems do-able, but pretty expensive resource-wise (I'll cache it aggressively for that reason). </p> <p>Just wondering if there's an easier way - an existing library that works with feedparser to do simple aggregation, for example. Sample code? Gotchas or warnings? Thanks.</p>
0
2009-09-30T04:04:18Z
1,496,616
<p>Here is already suggestion to store data in the database, e.g. <code>bsddb.btopen()</code> or any RDBMS.</p> <p>Take a look at <code>heapq.merge()</code> and <code>bisect.insort()</code> or use one of B-tree implementations if you'd like to merge data in memory.</p>
1
2009-09-30T07:40:27Z
[ "python", "django" ]
wxpython -- threads and window events
1,496,092
<p>I have a wxPython application (<a href="http://www.OpenSTV.org" rel="nofollow">http://www.OpenSTV.org</a>) that counts ballots using methods that have multiple rounds. I'd like to do two things:</p> <p>(1) For a large number of ballots, this can be a bit slow, so I'd like to show the user a progress dialog so he doesn't think the application is frozen.</p> <p>(2) I'd like to allow the user to break ties manually, and this requires the counting code to show a dialog window.</p> <p>To achieve (1), I create a thread to run the counting code, and this allows me to present a nice progress dialog to the user. </p> <p>The problem with this, however, is that the counting code is not the main thread, and only the main thread in wxPython can process window events.</p> <p>I suppose I could create a thread to run the progress dialog instead, but this seems awkward. Is there a better way of accomplishing both (1) and (2)?</p>
4
2009-09-30T04:16:26Z
1,496,118
<p>There are several ways to call the main thread wxPython thread from a process thread. The simplest is <strong>wx.CallAfter()</strong> which will always execute the functional passed to it in the main thread. You can also use <strong>wx.PostEvent()</strong> and there's an example of this in the demo (labeled: Threads), and there are several more complicated but more customizable ways which are discussed in the last chapter of <em>wxPython in Action</em>.</p>
3
2009-09-30T04:32:09Z
[ "python", "events", "multithreading", "wxpython", "window" ]
wxpython -- threads and window events
1,496,092
<p>I have a wxPython application (<a href="http://www.OpenSTV.org" rel="nofollow">http://www.OpenSTV.org</a>) that counts ballots using methods that have multiple rounds. I'd like to do two things:</p> <p>(1) For a large number of ballots, this can be a bit slow, so I'd like to show the user a progress dialog so he doesn't think the application is frozen.</p> <p>(2) I'd like to allow the user to break ties manually, and this requires the counting code to show a dialog window.</p> <p>To achieve (1), I create a thread to run the counting code, and this allows me to present a nice progress dialog to the user. </p> <p>The problem with this, however, is that the counting code is not the main thread, and only the main thread in wxPython can process window events.</p> <p>I suppose I could create a thread to run the progress dialog instead, but this seems awkward. Is there a better way of accomplishing both (1) and (2)?</p>
4
2009-09-30T04:16:26Z
1,496,127
<p>Use <a href="http://docs.python.org/library/queue.html">Queue</a> to communicate and synchronize among threads, with each thread "owning" and exclusively interacting with a resource that's not handy to share.</p> <p>In GUI toolkits where only the main thread can really handle the GUI, the main thread should play along -- set up and start the threads doing the actual work, then do nothing but GUI work, using Queues to communicate to and from the other threads.</p> <p>For (1), when your counting thread has an update, it should <code>put</code> it to the Queue where the main thread is waiting; when your main thread gets a suitable message on that Queue, it updates the progress dialog.</p> <p>For (2), the counting thread sends the "have the user break a tie" request, main thread gets it and responds appropriately, and sends back the resolution on a separate Queue.</p> <p>So in general, there are two kinds of communications: one that don't require a response, and others that do. For the former kind, just put the notification on the appropriate queue and simply proceed -- it will be acted on in due course. For the latter kind, my favorite idiom is to put on the appropriate queue a pair (request, response_queue). If otherwise identical requests differ in that some need a response and others don't, queueing (request, None) when no response is needed (and (request, q) where q's a Queue when a response IS needed) is a nice, easy, and general idiom, too.</p>
5
2009-09-30T04:38:29Z
[ "python", "events", "multithreading", "wxpython", "window" ]
Problem loading transparent background sprites in pygame
1,496,106
<p>I'm trying to load a transparent image into pygame using the following code:</p> <pre><code>def load_image(name, colorkey=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect() </code></pre> <p>For some reason, everytime I load the image the background is automatically changed to black? I'm not using the colorkey in this case as my image(s) will end up with a white border around them which is quite visible given that my game's background is constantly changing. </p> <p>Any ideas?</p> <p>Thanks,Regards</p>
1
2009-09-30T04:25:56Z
1,497,001
<p>You call image.convert(). From the <a href="http://www.pygame.org/docs/ref/surface.html#Surface.convert" rel="nofollow">docs for Surface.convert</a>:</p> <blockquote> <p>"The converted Surface will have no pixel alphas. They will be stripped if the original had them. See *Surface.convert_alpha* - change the pixel format of an image including per pixel alphas for preserving or creating per-pixel alphas."</p> </blockquote>
3
2009-09-30T09:22:54Z
[ "python", "pygame" ]
In Python in GAE, what is the best way to limit the risk of executing untrusted code?
1,496,115
<p>I would like to enable students to submit python code solutions to a few simple python problems. My applicatoin will be running in GAE. How can I limit the risk from malicios code that is sumitted? I realize that this is a hard problem and I have read related Stackoverflow and other posts on the subject. I am curious if the restrictions aleady in place in the GAE environment make it simpler to limit damage that untrusted code could inflict. Is it possible to simply scan the submitted code for a few restricted keywords (exec, import, etc.) and then ensure the code only runs for less than a fixed amount of time, or is it still difficult to sandbox untrusted code even in the resticted GAE environment? For example:</p> <pre><code># Import and execute untrusted code in GAE untrustedCode = """#Untrusted code from students.""" class TestSpace(object):pass testspace = TestSpace() try: #Check the untrusted code somehow and throw and exception. except: print "Code attempted to import or access network" try: # exec code in a new namespace (Thanks Alex Martelli) # limit runtime somehow exec untrustedCode in vars(testspace) except: print "Code took more than x seconds to run" </code></pre>
3
2009-09-30T04:30:46Z
1,496,145
<p>@mjv's smiley comment is actually spot-on: make sure the submitter IS identified and associated with the code in question (which presumably is going to be sent to a task queue), and log any diagnostics caused by an individual's submissions.</p> <p>Beyond that, you can indeed prepare a test-space that's more restrictive (thanks for the acknowledgment;-) including a special '<strong>builtin</strong>' that has all you want the students to be able to use and redefines <code>__import__</code> &amp;c. That, plus a token pass to forbid exec, eval, import, <code>__subclasses__</code>, <code>__bases__</code>, <code>__mro__</code>, ..., gets you closer. A totally secure sandbox in a GAE environment however is a real challenge, unless you can whitelist a tiny subset of the language that the students are allowed.</p> <p>So I would suggest a layered approach: the sandbox GAE app in which the students upload and execute their code has essentially no persistent layer to worry about; rather, it "persists" by sending urlfetch requests to ANOTHER app, which never runs any untrusted code and is able to vet each request very critically. Default-denial with whitelisting is still the holy grail, but with such an extra layer for security you may be able to afford a default-acceptance with blacklisting...</p>
5
2009-09-30T04:47:15Z
[ "python", "google-app-engine" ]
In Python in GAE, what is the best way to limit the risk of executing untrusted code?
1,496,115
<p>I would like to enable students to submit python code solutions to a few simple python problems. My applicatoin will be running in GAE. How can I limit the risk from malicios code that is sumitted? I realize that this is a hard problem and I have read related Stackoverflow and other posts on the subject. I am curious if the restrictions aleady in place in the GAE environment make it simpler to limit damage that untrusted code could inflict. Is it possible to simply scan the submitted code for a few restricted keywords (exec, import, etc.) and then ensure the code only runs for less than a fixed amount of time, or is it still difficult to sandbox untrusted code even in the resticted GAE environment? For example:</p> <pre><code># Import and execute untrusted code in GAE untrustedCode = """#Untrusted code from students.""" class TestSpace(object):pass testspace = TestSpace() try: #Check the untrusted code somehow and throw and exception. except: print "Code attempted to import or access network" try: # exec code in a new namespace (Thanks Alex Martelli) # limit runtime somehow exec untrustedCode in vars(testspace) except: print "Code took more than x seconds to run" </code></pre>
3
2009-09-30T04:30:46Z
1,496,953
<p>You really can't sandbox Python code inside App Engine with any degree of certainty. Alex's idea of logging who's running what is a good one, but if the user manages to break out of the sandbox, they can erase the event logs. The only place this information would be safe is in the per-request logging, since users can't erase that.</p> <p>For a good example of what a rathole trying to sandbox Python turns into, see <a href="http://tav.espians.com/a-challenge-to-break-python-security.html" rel="nofollow">this post</a>. For Guido's take on securing Python, see <a href="http://neopythonic.blogspot.com/2009/03/capabilities-for-python.html" rel="nofollow">this post</a>.</p> <p>There are another couple of options: If you're free to choose the language, you could run Rhino (a Javascript interpreter) on the Java runtime; Rhino is nicely sandboxed. You may also be able to use Jython; I don't know if it's practical to sandbox it, but it seems likely.</p> <p>Alex's suggestion of using a separate app is also a good one. This is pretty much the approach that <a href="http://shell.appspot.com/" rel="nofollow">shell.appspot.com</a> takes: It can't prevent you from doing malicious things, but the app itself stores nothing of value, so there's no harm if you do.</p>
2
2009-09-30T09:12:03Z
[ "python", "google-app-engine" ]
In Python in GAE, what is the best way to limit the risk of executing untrusted code?
1,496,115
<p>I would like to enable students to submit python code solutions to a few simple python problems. My applicatoin will be running in GAE. How can I limit the risk from malicios code that is sumitted? I realize that this is a hard problem and I have read related Stackoverflow and other posts on the subject. I am curious if the restrictions aleady in place in the GAE environment make it simpler to limit damage that untrusted code could inflict. Is it possible to simply scan the submitted code for a few restricted keywords (exec, import, etc.) and then ensure the code only runs for less than a fixed amount of time, or is it still difficult to sandbox untrusted code even in the resticted GAE environment? For example:</p> <pre><code># Import and execute untrusted code in GAE untrustedCode = """#Untrusted code from students.""" class TestSpace(object):pass testspace = TestSpace() try: #Check the untrusted code somehow and throw and exception. except: print "Code attempted to import or access network" try: # exec code in a new namespace (Thanks Alex Martelli) # limit runtime somehow exec untrustedCode in vars(testspace) except: print "Code took more than x seconds to run" </code></pre>
3
2009-09-30T04:30:46Z
5,614,660
<p>Here's an idea. Instead of running the code server-side, run it client-side with Skuplt:</p> <p><a href="http://www.skulpt.org/" rel="nofollow">http://www.skulpt.org/</a></p> <p>This is both safer, and easier to implement.</p>
0
2011-04-10T20:53:40Z
[ "python", "google-app-engine" ]
Passing a list of kwargs?
1,496,346
<p>Can I pass a list of kwargs to a method for brevity? This is what i'm attempting to do:</p> <pre><code>def method(**kwargs): #do something keywords = (keyword1 = 'foo', keyword2 = 'bar') method(keywords) </code></pre>
43
2009-09-30T06:08:33Z
1,496,355
<p>Yes. You do it like this:</p> <pre><code>def method(**kwargs): print kwargs keywords = {'keyword1': 'foo', 'keyword2': 'bar'} method(keyword1='foo', keyword2='bar') method(**keywords) </code></pre> <p>Running this in Python confirms these produce identical results:</p> <pre><code>{'keyword2': 'bar', 'keyword1': 'foo'} {'keyword2': 'bar', 'keyword1': 'foo'} </code></pre>
75
2009-09-30T06:11:41Z
[ "python", "kwargs" ]
Passing a list of kwargs?
1,496,346
<p>Can I pass a list of kwargs to a method for brevity? This is what i'm attempting to do:</p> <pre><code>def method(**kwargs): #do something keywords = (keyword1 = 'foo', keyword2 = 'bar') method(keywords) </code></pre>
43
2009-09-30T06:08:33Z
1,496,356
<p>Do you mean a dict? Sure you can:</p> <pre><code>def method(**kwargs): #do something keywords = {keyword1: 'foo', keyword2: 'bar'} method(**keywords) </code></pre>
1
2009-09-30T06:12:09Z
[ "python", "kwargs" ]
Passing a list of kwargs?
1,496,346
<p>Can I pass a list of kwargs to a method for brevity? This is what i'm attempting to do:</p> <pre><code>def method(**kwargs): #do something keywords = (keyword1 = 'foo', keyword2 = 'bar') method(keywords) </code></pre>
43
2009-09-30T06:08:33Z
1,496,424
<p>As others have pointed out, you can do what you want by passing a dict. There are various ways to construct a dict. One that preserves the <code>keyword=value</code> style you attempted is to use the <a href="http://docs.python.org/library/stdtypes.html#mapping-types-dict">dict</a> built-in:</p> <pre><code>keywords = dict(keyword1 = 'foo', keyword2 = 'bar') </code></pre> <p>Note the versatility of <code>dict</code>; all of these produce the same result:</p> <pre><code>&gt;&gt;&gt; kw1 = dict(keyword1 = 'foo', keyword2 = 'bar') &gt;&gt;&gt; kw2 = dict({'keyword1':'foo', 'keyword2':'bar'}) &gt;&gt;&gt; kw3 = dict([['keyword1', 'foo'], ['keyword2', 'bar']]) &gt;&gt;&gt; kw4 = dict(zip(('keyword1', 'keyword2'), ('foo', 'bar'))) &gt;&gt;&gt; assert kw1 == kw2 == kw3 == kw4 &gt;&gt;&gt; </code></pre>
6
2009-09-30T06:35:18Z
[ "python", "kwargs" ]
Passing a list of kwargs?
1,496,346
<p>Can I pass a list of kwargs to a method for brevity? This is what i'm attempting to do:</p> <pre><code>def method(**kwargs): #do something keywords = (keyword1 = 'foo', keyword2 = 'bar') method(keywords) </code></pre>
43
2009-09-30T06:08:33Z
29,567,960
<p>So when I've come here I was looking for a way to pass several **kwargs in one function - for later use in further functions. Because this, not that surprisingly, doesn't work:</p> <pre><code>def func1(**f2_x, **f3_x): ... </code></pre> <p>With some own 'experimental' coding I came to the obviously way how to do it:</p> <pre><code>def func3(f3_a, f3_b): print "--func3--" print f3_a print f3_b def func2(f2_a, f2_b): print "--func2--" print f2_a print f2_b def func1(f1_a, f1_b, f2_x={},f3_x={}): print "--func1--" print f1_a print f1_b func2(**f2_x) func3(**f3_x) func1('aaaa', 'bbbb', {'f2_a':1, 'f2_b':2}, {'f3_a':37, 'f3_b':69}) </code></pre> <p>This prints as expected:</p> <pre><code>--func1-- aaaa bbbb --func2-- 1 2 --func3-- 37 69 </code></pre>
3
2015-04-10T18:03:07Z
[ "python", "kwargs" ]
SQLAlchemy - MapperExtension.before_delete not called
1,496,429
<p>I have question regarding the SQLAlchemy. I have database which contains Items, every Item has assigned more Records (1:n). And the Record is partially stored in the database, but it also has an assigned file (1:1) on the filesystem.</p> <p>What I want to do is to delete the assigned file when the Record is removed from the database. So I wrote the following MapperExtension:</p> <pre><code>class _StoredRecordEraser(MapperExtension): def before_delete(self, mapper, connection, instance): instance.erase() </code></pre> <p>The following code creates an experimental setup (full code is here: <a href="http://home.zcu.cz/~honzas/test.py" rel="nofollow">test.py</a>):</p> <pre><code>session = Session() i1 = Item(id='item1') r11 = Record(id='record11', attr='1') i1.records.append(r11) r12 = Record(id='record12', attr='2') i1.records.append(r12) session.add(i1) session.commit() </code></pre> <p>And finally, my problem... The following code works O.k. and the <code>old.erase()</code> method is called:</p> <pre><code>session = Session() i1 = session.query(Item).get('item1') old = i1.records[0] new = Record(id='record13', attr='3') i1.records.remove(old) i1.records.append(new) session.commit() </code></pre> <p>But when I change the <code>id</code> of a new Record to <code>record11</code>, which is already in the database, but it is not the same item (<code>attr=3</code>), <b>the <code>old.erase()</code> is not called.</b> Does anybody know why?</p> <p>Thanks</p>
0
2009-09-30T06:38:34Z
1,506,587
<p>A delete + insert of two records that ultimately have the same primary key within a single flush are converted into a single update right now. this is not the best behavior - it really should delete then insert, so that the various events assigned to those activities are triggered as expected (not just mapper extension methods, but database level defaults too). But the flush() process is hardwired to perform inserts/updates first, then deletes. As a workaround, you can issue a flush() after the remove/delete operation, then a second for the add/insert.</p> <p>As far as flushes' current behavior, I've looked into trying to break this out but it gets very complicated - inserts which depend on deletes would have to execute after the deletes, but updates which depend on inserts would have to execute beforehand. Ultimately, the unitofwork module would be rewritten (big time) to consider all insert/update/deletes in a single stream of dependent actions that would be topologically sorted against each other. This would simplify the methods used to execute statements in the correct order, although all new systems for synchronizing data between rows based on server-level defaults would have to be devised, and its possible that complexity would be re-introduced if it turned out the "simpler" method spent too much time naively sorting insert statements that are known at the ORM level to not require any sorting against each other. The topological sort works at a more coarse grained level than that right now.</p>
3
2009-10-01T21:22:54Z
[ "python", "sqlalchemy" ]
How to treat the first line of a file differently in Python?
1,496,456
<p>I often need to process large text files containing headers in the first line. The headers are often treated differently to the body of the file, or my processing of the body is dependent on the headers. Either way I need to treat the first line as a special case. I could use simple line iteration and set a flag:</p> <pre><code>headerProcessed = false for line in f: if headerProcessed: processBody(line) else: processHeader(line) headerProcessed = true </code></pre> <p>but I dislike a test in the loop that is redundant for all but one of the millions of times it executes. Is there a better way? Could I treat the first line differently then get the iteration to start on the second line? Should I be bothered?</p>
7
2009-09-30T06:46:59Z
1,496,477
<p>You could:</p> <pre><code>processHeader(f.readline()) for line in f: processBody(line) </code></pre>
12
2009-09-30T06:52:33Z
[ "python", "file", "iteration" ]
How to treat the first line of a file differently in Python?
1,496,456
<p>I often need to process large text files containing headers in the first line. The headers are often treated differently to the body of the file, or my processing of the body is dependent on the headers. Either way I need to treat the first line as a special case. I could use simple line iteration and set a flag:</p> <pre><code>headerProcessed = false for line in f: if headerProcessed: processBody(line) else: processHeader(line) headerProcessed = true </code></pre> <p>but I dislike a test in the loop that is redundant for all but one of the millions of times it executes. Is there a better way? Could I treat the first line differently then get the iteration to start on the second line? Should I be bothered?</p>
7
2009-09-30T06:46:59Z
1,496,489
<p>Use iter()</p> <pre><code>it_f = iter(f) header = it_f.next() processHeader(header) for line in it_f: processBody(line) </code></pre> <p>It works with any iterable object.</p>
3
2009-09-30T06:56:22Z
[ "python", "file", "iteration" ]
How to treat the first line of a file differently in Python?
1,496,456
<p>I often need to process large text files containing headers in the first line. The headers are often treated differently to the body of the file, or my processing of the body is dependent on the headers. Either way I need to treat the first line as a special case. I could use simple line iteration and set a flag:</p> <pre><code>headerProcessed = false for line in f: if headerProcessed: processBody(line) else: processHeader(line) headerProcessed = true </code></pre> <p>but I dislike a test in the loop that is redundant for all but one of the millions of times it executes. Is there a better way? Could I treat the first line differently then get the iteration to start on the second line? Should I be bothered?</p>
7
2009-09-30T06:46:59Z
1,496,491
<pre><code>f = file("test") processHeader(f.next()) #or next(f) for py3 for line in f: processBody(line) </code></pre> <p>This works.</p> <p>Edit:</p> <p>Changed <code>.__next__</code> to <code>next</code> (they <em>are</em> equivalent, but I suppose next is more concise).</p> <p>Regaring <code>file</code> vs <code>open</code>, <code>file</code> just seems more clear to me, therefore I will continue to prefer it over <code>open</code>.</p>
8
2009-09-30T06:56:41Z
[ "python", "file", "iteration" ]
How to treat the first line of a file differently in Python?
1,496,456
<p>I often need to process large text files containing headers in the first line. The headers are often treated differently to the body of the file, or my processing of the body is dependent on the headers. Either way I need to treat the first line as a special case. I could use simple line iteration and set a flag:</p> <pre><code>headerProcessed = false for line in f: if headerProcessed: processBody(line) else: processHeader(line) headerProcessed = true </code></pre> <p>but I dislike a test in the loop that is redundant for all but one of the millions of times it executes. Is there a better way? Could I treat the first line differently then get the iteration to start on the second line? Should I be bothered?</p>
7
2009-09-30T06:46:59Z
1,496,514
<p>Large text files with headers in the first line? So it's tabular data. </p> <p>Just to make sure: Have you looked at the <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv</a> module? It should handle all tabular data except such where the fields are not delimited but defined by position. And it does the header stuff too.</p>
2
2009-09-30T07:05:58Z
[ "python", "file", "iteration" ]
Guidance on optimising Python runtime for embedded systems with low system resources
1,496,761
<p>My team is incorporating the Python 2.4.4 runtime into our project in order to leverage some externally developed functionality. </p> <p>Our platform has a 450Mhz SH4 application core and limited memory for use by the Python runtime and application. </p> <p>We have ported Python, but initial testing has highlighted the following hurdles: </p> <p>a) start-up times for the Python runtime can be as bad as 25 seconds (when importing the libraries concerned, and in turn their dependencies)</p> <p>b) Python never seems to release memory to the OS during garbage collection - the only recourse is to close the runtime and restart (incurring start-up delays noted above, which often times is impractical) </p> <p>If we can mitigate these issues our use of Python would be substantially improved. Any guidance from the SO community would be very valuable. Especially from anyone who has knowledge of the intrinsics of how the Python execution engine operates. </p>
9
2009-09-30T08:25:53Z
1,497,008
<p>Perhaps it is hard to believe, but CPython version 2.4 <a href="http://evanjones.ca/python-memory.html" rel="nofollow">never releases memory to the OS</a>. This is allegedly fixed in verion Python 2.5.</p> <p>In addition, performance (processor-wise) was improved in Python 2.5 and Python 2.6 on top of that.</p> <p>See the <a href="http://docs.python.org/whatsnew/2.5.html#build-and-c-api-changes" rel="nofollow">C API section in What's new in Python 2.5</a>, look for the item called <em>Evan Jones’s patch to obmalloc</em></p> <p>Alex Martelli (whose advice should always be at least considered), <a href="http://stackoverflow.com/questions/1316767/how-can-i-explicitly-free-memory-in-python/1316799#1316799">says multiprocess is the only way to go to free memory.</a> If you cannot use <code>multiprocessing</code> (module in Python 2.6), <code>os.fork</code> is at least available. Using os.fork in the most primitive manner (fork one work process at the beginning, wait for it to finish, fork a new..) is still better than relauching the interpreter paying 25 seconds for that.</p>
5
2009-09-30T09:25:39Z
[ "python", "performance", "memory", "embedded", "garbage-collection" ]
how to obtain physical drives in Windows
1,496,842
<p>I'm programming in Python with a wrapper of the kernel32 dll, so I can use any functions of this dll, like GetLogicalDrives(), for instance. I'm trying to obtain the information of the physical drives, <strong>even if they are not mounted</strong>. I've seen a question similar to this, but I need the information of the not mounted drives. All methods I've seen need a directory or a file in the device, but if it's not mounted, I can't have one, so the question is:</p> <p>Is there a method which can provide me a list of the physical drives in the system, even if they are not mounted?</p> <p>I have to say that using the Windows Registry, I've obtained the number of physical drives in "*HKEY_LOCAL_MACHINE\Hardware\Devicemap\Scsi\Scsi Port x*", because inside of this key, you can see the number of drives, including cd-rom devices or floppy devices. But I need size of the not mounted devices also, so...</p>
1
2009-09-30T08:47:55Z
1,497,004
<p>FindFirstVolume and FindNextVolume <em>may</em> be what you need.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa364425%28VS.85%29.aspx" rel="nofollow">MSDN FindFirstVolume page</a></p> <p>There's an example that searches for volumes and list all paths for each volume, and at first sight, it seems to allow the possibility that there is no such path for some volumes. That said, I've never used this.</p>
1
2009-09-30T09:23:46Z
[ "python", "windows" ]
how to obtain physical drives in Windows
1,496,842
<p>I'm programming in Python with a wrapper of the kernel32 dll, so I can use any functions of this dll, like GetLogicalDrives(), for instance. I'm trying to obtain the information of the physical drives, <strong>even if they are not mounted</strong>. I've seen a question similar to this, but I need the information of the not mounted drives. All methods I've seen need a directory or a file in the device, but if it's not mounted, I can't have one, so the question is:</p> <p>Is there a method which can provide me a list of the physical drives in the system, even if they are not mounted?</p> <p>I have to say that using the Windows Registry, I've obtained the number of physical drives in "*HKEY_LOCAL_MACHINE\Hardware\Devicemap\Scsi\Scsi Port x*", because inside of this key, you can see the number of drives, including cd-rom devices or floppy devices. But I need size of the not mounted devices also, so...</p>
1
2009-09-30T08:47:55Z
1,497,529
<p>Use Tim Golden's wmi module. Here's the <a href="http://timgolden.me.uk/python/wmi%5Fcookbook.html#find-drive-types" rel="nofollow">cookbook</a> entry:</p> <pre><code>import wmi w = wmi.WMI() for drive in w.Win32_LogicalDisk(): print drive.Caption, drive.Size, drive.FreeSpace </code></pre> <p>prints</p> <pre> C: 99928924160 14214135808 D: None None E: 499983122432 3380903936 S: 737329123328 362274299904 T: 737329123328 9654988800 </pre> <p>However, note that no information is available for my D: drive (DVD drive, not mounted). I don't think you can get size info for removable media which isn't mounted.</p>
3
2009-09-30T11:21:11Z
[ "python", "windows" ]
how to obtain physical drives in Windows
1,496,842
<p>I'm programming in Python with a wrapper of the kernel32 dll, so I can use any functions of this dll, like GetLogicalDrives(), for instance. I'm trying to obtain the information of the physical drives, <strong>even if they are not mounted</strong>. I've seen a question similar to this, but I need the information of the not mounted drives. All methods I've seen need a directory or a file in the device, but if it's not mounted, I can't have one, so the question is:</p> <p>Is there a method which can provide me a list of the physical drives in the system, even if they are not mounted?</p> <p>I have to say that using the Windows Registry, I've obtained the number of physical drives in "*HKEY_LOCAL_MACHINE\Hardware\Devicemap\Scsi\Scsi Port x*", because inside of this key, you can see the number of drives, including cd-rom devices or floppy devices. But I need size of the not mounted devices also, so...</p>
1
2009-09-30T08:47:55Z
1,497,789
<p>Also you can try win32 module for Python.</p>
1
2009-09-30T12:24:08Z
[ "python", "windows" ]
how to obtain physical drives in Windows
1,496,842
<p>I'm programming in Python with a wrapper of the kernel32 dll, so I can use any functions of this dll, like GetLogicalDrives(), for instance. I'm trying to obtain the information of the physical drives, <strong>even if they are not mounted</strong>. I've seen a question similar to this, but I need the information of the not mounted drives. All methods I've seen need a directory or a file in the device, but if it's not mounted, I can't have one, so the question is:</p> <p>Is there a method which can provide me a list of the physical drives in the system, even if they are not mounted?</p> <p>I have to say that using the Windows Registry, I've obtained the number of physical drives in "*HKEY_LOCAL_MACHINE\Hardware\Devicemap\Scsi\Scsi Port x*", because inside of this key, you can see the number of drives, including cd-rom devices or floppy devices. But I need size of the not mounted devices also, so...</p>
1
2009-09-30T08:47:55Z
1,497,814
<p><a href="http://msdn.microsoft.com/en-us/library/aa365730%28VS.85%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa365730%28VS.85%29.aspx</a></p> <p>GetLogicalDrives() GetLogicalDriveStrings()</p> <p>Look like what you want. But they work off A:, B: C: etc, rather than \?\HardDisk or whatever</p>
-2
2009-09-30T12:31:15Z
[ "python", "windows" ]
how to obtain physical drives in Windows
1,496,842
<p>I'm programming in Python with a wrapper of the kernel32 dll, so I can use any functions of this dll, like GetLogicalDrives(), for instance. I'm trying to obtain the information of the physical drives, <strong>even if they are not mounted</strong>. I've seen a question similar to this, but I need the information of the not mounted drives. All methods I've seen need a directory or a file in the device, but if it's not mounted, I can't have one, so the question is:</p> <p>Is there a method which can provide me a list of the physical drives in the system, even if they are not mounted?</p> <p>I have to say that using the Windows Registry, I've obtained the number of physical drives in "*HKEY_LOCAL_MACHINE\Hardware\Devicemap\Scsi\Scsi Port x*", because inside of this key, you can see the number of drives, including cd-rom devices or floppy devices. But I need size of the not mounted devices also, so...</p>
1
2009-09-30T08:47:55Z
11,803,238
<p>How about <code>Win32_DiskDrive</code> wmi class?</p> <pre><code>c = wmi.WMI() dd = c.Win32_DiskDrive()[0] print.dd </code></pre> <p>More about Win32_DiskDrive <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa394132%28v=vs.85%29.aspx" rel="nofollow">on the msdn</a></p>
0
2012-08-03T21:00:28Z
[ "python", "windows" ]
Web Service client in Python using ZSI - "Classless struct didn't get dictionary"
1,496,910
<p>I am trying to write a sample client in Python using ZSI for a simple Web Service. The Web Service WSDL is following:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.example.org/test/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="test" targetNamespace="http://www.example.org/test/"&gt; &lt;wsdl:message name="NewOperationRequest"&gt; &lt;wsdl:part name="NewOperationRequest" type="xsd:string"/&gt; &lt;/wsdl:message&gt; &lt;wsdl:message name="NewOperationResponse"&gt; &lt;wsdl:part name="NewOperationResponse" type="xsd:string"/&gt; &lt;/wsdl:message&gt; &lt;wsdl:portType name="test"&gt; &lt;wsdl:operation name="NewOperation"&gt; &lt;wsdl:input message="tns:NewOperationRequest"/&gt; &lt;wsdl:output message="tns:NewOperationResponse"/&gt; &lt;/wsdl:operation&gt; &lt;/wsdl:portType&gt; &lt;wsdl:binding name="testSOAP" type="tns:test"&gt; &lt;soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/&gt; &lt;wsdl:operation name="NewOperation"&gt; &lt;soap:operation soapAction="http://www.example.org/test/NewOperation"/&gt; &lt;wsdl:input&gt; &lt;soap:body namespace="http://www.example.org/test/" use="literal"/&gt; &lt;/wsdl:input&gt; &lt;wsdl:output&gt; &lt;soap:body namespace="http://www.example.org/test/" use="literal"/&gt; &lt;/wsdl:output&gt; &lt;/wsdl:operation&gt; &lt;/wsdl:binding&gt; &lt;wsdl:service name="test"&gt; &lt;wsdl:port binding="tns:testSOAP" name="testSOAP"&gt; &lt;soap:address location="http://localhost/test"/&gt; &lt;/wsdl:port&gt; &lt;/wsdl:service&gt; &lt;/wsdl:definitions&gt; </code></pre> <p>Every time I run following code:</p> <pre><code>from ZSI.ServiceProxy import ServiceProxy service = ServiceProxy('test.wsdl') service.NewOperation('test') </code></pre> <p>I receive:</p> <pre><code>(...) /var/lib/python-support/python2.5/ZSI/TCcompound.pyc in cb(self, elt, sw, pyobj, name, **kw) 345 f = lambda attr: pyobj.get(attr) 346 if TypeCode.typechecks and type(d) != types.DictType: --&gt; 347 raise TypeError("Classless struct didn't get dictionary") 348 349 indx, lenofwhat = 0, len(self.ofwhat) TypeError: Classless struct didn't get dictionary </code></pre> <p>I have searched Google for this error and I found couple posts describing similar problem but with no answer. Do you know was is wrong here? Is there an error in the WSDL, do I miss something in the code or there is a bug in ZSI?</p> <p>Thank you in advance for you help :-)</p>
1
2009-09-30T09:00:31Z
1,553,177
<p>Finally, I have found the solution. </p> <p>I should run like this:</p> <pre><code>from ZSI.ServiceProxy import ServiceProxy service = ServiceProxy('test.wsdl') service.NewOperation(NewOperationRequest='test') </code></pre> <p>The reason of the problem was that the name of the parameter was missing (sic!) - silly error ;-)</p>
3
2009-10-12T07:27:15Z
[ "python", "wsdl", "zsi" ]
Python 2.5 and 2.6 and Numpy compatibility problem
1,496,942
<p>In the computers of our laboratory, which have Python 2.6.2 installed in them, my program, which is an animation of the 2D random walk and diffusion, works perfectly. </p> <p>However, I can't get the exact same program to work on my laptop, which has Python 2.5. By that not working, I mean the animation is screwed; the axis always changes every time the pylab.draw() and pylab.clf() commands are called in a for loop. </p> <p>I call a pylab.axis([specified axis]) command before <em>and</em> after draw() and clf() to fix the "field-of-view", but it's still the same - what I get is a flickering series of image instead of the smooth animation I get when I run the exact same program in our laboratory.</p> <p>I tried to install Python 2.6 in my laptop, but I discovered that there is no Numpy for Py2.6. So it is a mystery to me that my program, which imports Numpy and uses many of its functions, works in our laboratory computer. What can be done with my compatibility problem?</p>
1
2009-09-30T09:09:19Z
1,497,061
<p>Numpy for python 2.6 appears to be downloadable from <a href="http://sourceforge.net/projects/numpy/files/" rel="nofollow">numpy sourceforge</a> or can be compiled from source</p>
1
2009-09-30T09:38:26Z
[ "python", "numpy", "compatibility" ]
Python 2.5 and 2.6 and Numpy compatibility problem
1,496,942
<p>In the computers of our laboratory, which have Python 2.6.2 installed in them, my program, which is an animation of the 2D random walk and diffusion, works perfectly. </p> <p>However, I can't get the exact same program to work on my laptop, which has Python 2.5. By that not working, I mean the animation is screwed; the axis always changes every time the pylab.draw() and pylab.clf() commands are called in a for loop. </p> <p>I call a pylab.axis([specified axis]) command before <em>and</em> after draw() and clf() to fix the "field-of-view", but it's still the same - what I get is a flickering series of image instead of the smooth animation I get when I run the exact same program in our laboratory.</p> <p>I tried to install Python 2.6 in my laptop, but I discovered that there is no Numpy for Py2.6. So it is a mystery to me that my program, which imports Numpy and uses many of its functions, works in our laboratory computer. What can be done with my compatibility problem?</p>
1
2009-09-30T09:09:19Z
1,497,175
<p>The various (<code>matplotlib.pyplot</code>) graphical backends do not behave in exactly the same way.</p> <p>You could try setting the backend so that it is the same on both machines:</p> <pre><code>matplotlib.use('GTKagg') # Right after importing matplotlib </code></pre> <p>For a list of possible backends, you can do <code>matplotlib.use('...')</code>.</p>
2
2009-09-30T10:03:38Z
[ "python", "numpy", "compatibility" ]
How to display outcoming and incoming SOAP message for ZSI.ServiceProxy in Python?
1,497,038
<p>How to display a SOAP message generated by ZSI.ServiceProxy and a respond from a Web Service when a Web Service method is invoked?</p>
1
2009-09-30T09:33:13Z
1,501,943
<p>Here is some <a href="http://pywebsvcs.sourceforge.net/zsi.html#SECTION0012200000000000000000" rel="nofollow">documentation</a> on the ServiceProxy class. The constructor accepts a <code>tracefile</code> argument which can be any object with a <code>write</code> method, so this looks like what you are after. Modifying the example from the documentation:</p> <pre><code>from ZSI import ServiceProxy import BabelTypes import sys dbgfile = open('dbgfile', 'w') # to log trace to a file, or dbgfile = sys.stdout # to log trace to stdout service = ServiceProxy('http://www.xmethods.net/sd/BabelFishService.wsdl', tracefile=dbgfile, typesmodule=BabelTypes) value = service.BabelFish('en_de', 'This is a test!') dbgfile.close() </code></pre>
2
2009-10-01T04:50:22Z
[ "python", "web-services", "zsi" ]
question related to reverse function and kwargs
1,497,258
<p>To reverse lookup an url by means of name or View_name we will use reverse function in the views like below</p> <pre><code>reverse("calendarviewurl2", kwargs={"year":theyear,"month":themonth}) </code></pre> <p>and reverse function signature is as follows </p> <p><a href="http://code.djangoproject.com/browser/django/trunk/django/core/urlresolvers.py" rel="nofollow">http://code.djangoproject.com/browser/django/trunk/django/core/urlresolvers.py</a></p> <pre><code>def reverse(self, lookup_view, *args, **kwargs) </code></pre> <p>My question is related to kwargs </p> <p>when we want to send a dictionary as keyword arguments we should use the below syntax <strong><em>snippet 1</em></strong></p> <pre><code> kwargs={"year":2009,"month":9} reverse("name",**kwargs) </code></pre> <p>as opposed to below code<br /> <strong><em>snippet 2</em></strong></p> <pre><code> reverse("name",kwargs={"year":2009,"month":9}) </code></pre> <p>So my question is </p> <ol> <li>Do the snippet1 and snippet2 are same? ( i feel they are not same)</li> <li>In case of reverse function only snippet 2 is working where as snippet 1 is not properly working.Why is it so? (Even though the proper way to send a dictionary is by using syntax mentioned in snippet1.)</li> </ol>
4
2009-09-30T10:27:07Z
1,497,331
<p>Didn't you look at the <a href="http://code.djangoproject.com/browser/django/trunk/django/core/urlresolvers.py#L305">signature</a>,</p> <pre><code>def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): </code></pre> <p>takes no <code>**kwargs</code> at all.</p> <pre><code>kwargs={"year":2009,"month":9} reverse("name",**kwargs) </code></pre> <p>means </p> <pre><code>reverse("name", year=2009, month=9) </code></pre> <p>which is completely different from </p> <pre><code>reverse("name",kwargs={"year":2009,"month":9}) </code></pre> <p>When a function actually does take <code>**kwargs</code>, both ways to call it are the same. But that's not the case here. Reverse would have look like this to take <code>**kwargs</code>:</p> <pre><code>def reverse(viewname, urlconf=None, prefix=None, current_app=None, *args, **kwargs): </code></pre>
9
2009-09-30T10:41:25Z
[ "python", "django" ]
How to make unique short URL with Python?
1,497,504
<p>How can I make unique URL in Python a la <a href="http://imgur.com/gM19g">http://imgur.com/gM19g</a> or <a href="http://tumblr.com/xzh3bi25y">http://tumblr.com/xzh3bi25y</a> When using uuid from python I get a very large one. I want something shorter for URLs.</p>
26
2009-09-30T11:16:10Z
1,497,517
<p>The reason UUIDs are long is because they contain lots of information so that they can be guaranteed to be globally unique.</p> <p>If you want something shorter, then you'll need to do something like generate a random string, checking whether it is in the universe of already generated strings, and repeating until you get an unused string. You'll also need to watch out for concurrency here (what if the same string gets generated by a separate process before you inserted into the set of strings?).</p> <p>If you need some help generating random strings in Python, this <a href="http://stackoverflow.com/questions/367586/generating-random-text-strings-of-a-given-pattern">other question</a> might help.</p>
2
2009-09-30T11:18:33Z
[ "python", "url", "uuid", "tinyurl", "short-url" ]
How to make unique short URL with Python?
1,497,504
<p>How can I make unique URL in Python a la <a href="http://imgur.com/gM19g">http://imgur.com/gM19g</a> or <a href="http://tumblr.com/xzh3bi25y">http://tumblr.com/xzh3bi25y</a> When using uuid from python I get a very large one. I want something shorter for URLs.</p>
26
2009-09-30T11:16:10Z
1,497,533
<p>It doesn't really matter that this is Python, but you just need a hash function that maps to the length you want. For example, maybe use MD5 and then take just the first <code>n</code> characters. You'll have to watch out for collisions in that case, though, so you might want to pick something a little more robust in terms of collision detection (like using primes to cycle through the space of hash strings).</p>
1
2009-09-30T11:21:54Z
[ "python", "url", "uuid", "tinyurl", "short-url" ]
How to make unique short URL with Python?
1,497,504
<p>How can I make unique URL in Python a la <a href="http://imgur.com/gM19g">http://imgur.com/gM19g</a> or <a href="http://tumblr.com/xzh3bi25y">http://tumblr.com/xzh3bi25y</a> When using uuid from python I get a very large one. I want something shorter for URLs.</p>
26
2009-09-30T11:16:10Z
1,497,541
<p>I'm not sure most URL shorteners use a random string. My impression is they write the URL to a database, then use the integer ID of the new record as the short URL, encoded base 36 or 62 (letters+digits).</p> <p>Python code to convert an int to a string in arbitrary bases is <a href="http://code.activestate.com/recipes/65212/">here</a>.</p>
14
2009-09-30T11:24:40Z
[ "python", "url", "uuid", "tinyurl", "short-url" ]
How to make unique short URL with Python?
1,497,504
<p>How can I make unique URL in Python a la <a href="http://imgur.com/gM19g">http://imgur.com/gM19g</a> or <a href="http://tumblr.com/xzh3bi25y">http://tumblr.com/xzh3bi25y</a> When using uuid from python I get a very large one. I want something shorter for URLs.</p>
26
2009-09-30T11:16:10Z
1,497,573
<p><strong>Edit</strong>: Here, I wrote a module for you. Use it. <a href="http://code.activestate.com/recipes/576918/">http://code.activestate.com/recipes/576918/</a></p> <p><hr /></p> <p>Counting up from 1 will guarantee short, unique URLS. /1, /2, /3 ... etc.</p> <p>Adding uppercase and lowercase letters to your alphabet will give URLs like those in your question. And you're just counting in base-62 instead of base-10.</p> <p>Now the only problem is that the URLs come consecutively. To fix that, read my answer to this question here:</p> <p><a href="http://stackoverflow.com/questions/1051949/map-incrementing-integer-range-to-six-digit-base-26-max-but-unpredictably/1052896#1052896">http://stackoverflow.com/questions/1051949/map-incrementing-integer-range-to-six-digit-base-26-max-but-unpredictably/1052896#1052896</a></p> <p>Basically the approach is to simply swap bits around in the incrementing value to give the appearance of randomness while maintaining determinism and guaranteeing that you don't have any collisions.</p>
22
2009-09-30T11:32:51Z
[ "python", "url", "uuid", "tinyurl", "short-url" ]
How to make unique short URL with Python?
1,497,504
<p>How can I make unique URL in Python a la <a href="http://imgur.com/gM19g">http://imgur.com/gM19g</a> or <a href="http://tumblr.com/xzh3bi25y">http://tumblr.com/xzh3bi25y</a> When using uuid from python I get a very large one. I want something shorter for URLs.</p>
26
2009-09-30T11:16:10Z
1,497,728
<p>I don't know if you can use this, but we generate content objects in Zope that get unique numeric ids based on current time strings, in millis (eg, 1254298969501)</p> <p>Maybe you can guess the rest. Using the recipe described here: <a href="http://stackoverflow.com/questions/561486/how-to-convert-an-integer-to-the-shortest-url-safe-string-in-python">http://stackoverflow.com/questions/561486/how-to-convert-an-integer-to-the-shortest-url-safe-string-in-python</a>, we encode and decode the real id on the fly, with no need for storage. A 13-digit integer is reduced to 7 alphanumeric chars in base 62, for example.</p> <p>To complete the implementation, we registered a short (xxx.yy) domain name, that decodes and does a 301 redirect for "not found" URLs, </p> <p>If I was starting over, I would subtract the "starting-over" time (in millis) from the numeric id prior to encoding, then re-add it when decoding. Or else when generating the objects. Whatever. That would be way shorter..</p>
1
2009-09-30T12:09:42Z
[ "python", "url", "uuid", "tinyurl", "short-url" ]
How to make unique short URL with Python?
1,497,504
<p>How can I make unique URL in Python a la <a href="http://imgur.com/gM19g">http://imgur.com/gM19g</a> or <a href="http://tumblr.com/xzh3bi25y">http://tumblr.com/xzh3bi25y</a> When using uuid from python I get a very large one. I want something shorter for URLs.</p>
26
2009-09-30T11:16:10Z
4,640,654
<p>This module will do what you want, guaranteeing that the string is globally unique (it is a UUID):</p> <p><a href="http://pypi.python.org/pypi/shortuuid/0.1" rel="nofollow">http://pypi.python.org/pypi/shortuuid/0.1</a></p> <p>If you need something shorter, you should be able to truncate it to the desired length and still get something that will reasonably probably avoid clashes.</p>
3
2011-01-09T17:41:46Z
[ "python", "url", "uuid", "tinyurl", "short-url" ]
How to make unique short URL with Python?
1,497,504
<p>How can I make unique URL in Python a la <a href="http://imgur.com/gM19g">http://imgur.com/gM19g</a> or <a href="http://tumblr.com/xzh3bi25y">http://tumblr.com/xzh3bi25y</a> When using uuid from python I get a very large one. I want something shorter for URLs.</p>
26
2009-09-30T11:16:10Z
5,494,143
<p>Try this <a href="http://code.google.com/p/tiny4py/" rel="nofollow">http://code.google.com/p/tiny4py/</a> ... It's still under development, but very useful!!</p>
0
2011-03-31T00:43:03Z
[ "python", "url", "uuid", "tinyurl", "short-url" ]
How to make unique short URL with Python?
1,497,504
<p>How can I make unique URL in Python a la <a href="http://imgur.com/gM19g">http://imgur.com/gM19g</a> or <a href="http://tumblr.com/xzh3bi25y">http://tumblr.com/xzh3bi25y</a> When using uuid from python I get a very large one. I want something shorter for URLs.</p>
26
2009-09-30T11:16:10Z
28,075,828
<p><strong>My Goal:</strong> Generate a unique identifier of a specified fixed length consisting of the characters <code>0-9</code> and <code>a-z</code>. For example:</p> <pre class="lang-none prettyprint-override"><code>zcgst5od 9x2zgn0l qa44sp0z 61vv1nl5 umpprkbt ylg4lmcy dec0lu1t 38mhd8i5 rx00yf0e kc2qdc07 </code></pre> <p>Here's my solution. <em>(Adapted from <a href="http://stackoverflow.com/a/561809/1497596">this answer</a> by <a href="http://stackoverflow.com/users/50902/kmkaplan">kmkaplan</a>.)</em></p> <pre><code>import random class IDGenerator(object): ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz" def __init__(self, length=8): self._alphabet_length = len(self.ALPHABET) self._id_length = length def _encode_int(self, n): # Adapted from: # Source: http://stackoverflow.com/a/561809/1497596 # Author: http://stackoverflow.com/users/50902/kmkaplan encoded = '' while n &gt; 0: n, r = divmod(n, self._alphabet_length) encoded = self.ALPHABET[r] + encoded return encoded def generate_id(self): """Generate an ID without leading zeros. For example, for an ID that is eight characters in length, the returned values will range from '10000000' to 'zzzzzzzz'. """ start = self._alphabet_length**(self._id_length - 1) end = self._alphabet_length**self._id_length - 1 return self._encode_int(random.randint(start, end)) if __name__ == "__main__": # Sample usage: Generate ten IDs each eight characters in length. idgen = IDGenerator(8) for i in range(10): print idgen.generate_id() </code></pre>
0
2015-01-21T20:00:54Z
[ "python", "url", "uuid", "tinyurl", "short-url" ]
How to make unique short URL with Python?
1,497,504
<p>How can I make unique URL in Python a la <a href="http://imgur.com/gM19g">http://imgur.com/gM19g</a> or <a href="http://tumblr.com/xzh3bi25y">http://tumblr.com/xzh3bi25y</a> When using uuid from python I get a very large one. I want something shorter for URLs.</p>
26
2009-09-30T11:16:10Z
31,250,977
<p><a href="http://hashids.org/python/" rel="nofollow">Hashids</a> is an awesome tool for this.</p> <p>Edit:</p> <p>Here's how to use Hashids to generate a unique short URL with Python:</p> <pre><code>from hashids import Hashids pk = 123 # Your object's id domain = 'imgur.com' # Your domain hashids = Hashids(salt='this is my salt', min_length=6) link_id = hashids.encode(pk) url = 'http://{domain}/{link_id}'.format(domain=domain, link_id=link_id) </code></pre>
0
2015-07-06T16:27:40Z
[ "python", "url", "uuid", "tinyurl", "short-url" ]
Can Python determine the class of a object accessing a method
1,497,683
<p>Is there anyway to do something like this:</p> <pre><code>class A: def foo(self): if isinstance(caller, B): print "B can't call methods in A" else: print "Foobar" class B: def foo(self, ref): ref.foo() class C: def foo(self, ref): ref.foo() a = A(); B().foo(a) # Outputs "B can't call methods in A" C().foo(a) # Outputs "Foobar" </code></pre> <p>Where <em>caller</em> in <code>A</code> uses some form of introspection to determine the class of the calling method's object?</p> <p>In the end, I put this together based on some of the suggestions (not sure if it's appropriate or good etiquette to add this):</p> <pre><code>import inspect ... def check_caller(self, klass): frame = inspect.currentframe() current = lambda : frame.f_locals.get('self') while not current() is None: if isinstance(current(), klass): return True frame = frame.f_back return False </code></pre> <p>It's not perfect for all the reasons supplied, but thanks for the responses: they were a big help.</p>
1
2009-09-30T11:58:36Z
1,497,696
<p>The caller is always an instance of A. The fact that you're calling it inside a B method doesn't change that. In other words: Insiode <code>B.foo</code>, <code>ref</code> is an instance of <code>A</code>, so calling <code>ref.foo()</code> is a call on <code>A</code>, <code>B</code> is not involved on that call (it could happen top-level).</p> <p>The only sane way is to pass a reference to <code>self</code> so A can check if it is B or not.</p> <pre><code>class A(object): def foo(self, caller=None): if isinstance(caller, B): print "B can't call methods in A" else: print "Foobar" class B(object): def foo(self, ref): ref.foo(self) class C(object): def foo(self, ref): ref.foo(self) a = A(); B().foo(a) # Outputs "B can't call methods in A" C().foo(a) # Outputs "Foobar" a.foo() # Outputs "Foobar" </code></pre>
4
2009-09-30T12:02:03Z
[ "python", "introspection" ]
Can Python determine the class of a object accessing a method
1,497,683
<p>Is there anyway to do something like this:</p> <pre><code>class A: def foo(self): if isinstance(caller, B): print "B can't call methods in A" else: print "Foobar" class B: def foo(self, ref): ref.foo() class C: def foo(self, ref): ref.foo() a = A(); B().foo(a) # Outputs "B can't call methods in A" C().foo(a) # Outputs "Foobar" </code></pre> <p>Where <em>caller</em> in <code>A</code> uses some form of introspection to determine the class of the calling method's object?</p> <p>In the end, I put this together based on some of the suggestions (not sure if it's appropriate or good etiquette to add this):</p> <pre><code>import inspect ... def check_caller(self, klass): frame = inspect.currentframe() current = lambda : frame.f_locals.get('self') while not current() is None: if isinstance(current(), klass): return True frame = frame.f_back return False </code></pre> <p>It's not perfect for all the reasons supplied, but thanks for the responses: they were a big help.</p>
1
2009-09-30T11:58:36Z
1,497,768
<p>Assuming the caller is a method, then yes you can, by looking in the previous frame, and picking out <code>self</code> from the locals.</p> <pre><code>class Reciever: def themethod(self): frame = sys._getframe(1) arguments = frame.f_code.co_argcount if arguments == 0: print "Not called from a method" return caller_calls_self = frame.f_code.co_varnames[0] thecaller = frame.f_locals[caller_calls_self] print "Called from a", thecaller.__class__.__name__, "instance" </code></pre> <p>Üglŷ as heck, but it works. Now why you would want to do this is another question altogether, I suspect that there is a better way. The whole concept of A isn't allowed to call B is likely to be a mistake.</p>
5
2009-09-30T12:20:31Z
[ "python", "introspection" ]
Can Python determine the class of a object accessing a method
1,497,683
<p>Is there anyway to do something like this:</p> <pre><code>class A: def foo(self): if isinstance(caller, B): print "B can't call methods in A" else: print "Foobar" class B: def foo(self, ref): ref.foo() class C: def foo(self, ref): ref.foo() a = A(); B().foo(a) # Outputs "B can't call methods in A" C().foo(a) # Outputs "Foobar" </code></pre> <p>Where <em>caller</em> in <code>A</code> uses some form of introspection to determine the class of the calling method's object?</p> <p>In the end, I put this together based on some of the suggestions (not sure if it's appropriate or good etiquette to add this):</p> <pre><code>import inspect ... def check_caller(self, klass): frame = inspect.currentframe() current = lambda : frame.f_locals.get('self') while not current() is None: if isinstance(current(), klass): return True frame = frame.f_back return False </code></pre> <p>It's not perfect for all the reasons supplied, but thanks for the responses: they were a big help.</p>
1
2009-09-30T11:58:36Z
1,498,298
<p>Something like this may meet your needs better:</p> <pre><code>class A(object): def foo(self): # do stuff class B(A): def foo(self): raise NotImplementedError class C(A): pass </code></pre> <p>...but it's difficult to say without knowing exactly what you're trying to do.</p>
0
2009-09-30T13:58:58Z
[ "python", "introspection" ]
Is it OK if objects from different classes interact with each other?
1,498,009
<p>I just started to use the object oriented programming in Python. I wander if it is OK if I create a method of a class which use objects from another class. In other words, when I call a method of the first class I give an object from the second class as one of the arguments. And then, the considered methods (of the first class) can manipulate by the object from the second class (to get its attributes or use its methods). Is it allowed in Python? Is it not considered as a bad programming style?</p> <p>Is it OK if I instantiate objects from the second class withing a method of the first class. In other words, if I call a method from the first class it instantiate objects fro the second class. </p> <p>Thank you in advance for any help.</p>
4
2009-09-30T13:11:04Z
1,498,030
<p>If you're talking about passing an instance of one object to the method of a another one, then yes of course it's allowed! And it's considered fine practice.</p> <p>If you want to know more about good object oriented coding, may I offer some suggested readings:</p> <p><em>Design Patterns: Elements of Reusable Object-Oriented Software</em> by Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides</p> <p>Known as the Gang Of Four book, this lays out a number of design patterns that seem to show up in object oriented code time and time again. This is a good place to go for ideas on how to handle certain problems in a good object oriented way. </p> <p>Another good one:</p> <p><em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler, Kent Beck, John Brant , William Opdyke, Don Roberts</p> <p>This is a great book for learning what NOT to do when writing object oriented code, and how to fix it to make it better when you do encounter it. It offers a list of code smells that suggest bad object oriented code and a reference section of refactorings that provide instructions on how to fix those smells and make them more object oriented. </p>
7
2009-09-30T13:13:29Z
[ "python", "oop" ]
Is it OK if objects from different classes interact with each other?
1,498,009
<p>I just started to use the object oriented programming in Python. I wander if it is OK if I create a method of a class which use objects from another class. In other words, when I call a method of the first class I give an object from the second class as one of the arguments. And then, the considered methods (of the first class) can manipulate by the object from the second class (to get its attributes or use its methods). Is it allowed in Python? Is it not considered as a bad programming style?</p> <p>Is it OK if I instantiate objects from the second class withing a method of the first class. In other words, if I call a method from the first class it instantiate objects fro the second class. </p> <p>Thank you in advance for any help.</p>
4
2009-09-30T13:11:04Z
1,498,033
<p>I see no problem with that, it happens all the time. Do you have a specific problem you're trying to solve or just asking a general question without a context?</p>
0
2009-09-30T13:13:35Z
[ "python", "oop" ]
Is it OK if objects from different classes interact with each other?
1,498,009
<p>I just started to use the object oriented programming in Python. I wander if it is OK if I create a method of a class which use objects from another class. In other words, when I call a method of the first class I give an object from the second class as one of the arguments. And then, the considered methods (of the first class) can manipulate by the object from the second class (to get its attributes or use its methods). Is it allowed in Python? Is it not considered as a bad programming style?</p> <p>Is it OK if I instantiate objects from the second class withing a method of the first class. In other words, if I call a method from the first class it instantiate objects fro the second class. </p> <p>Thank you in advance for any help.</p>
4
2009-09-30T13:11:04Z
1,498,085
<p>What you're talking about is fine. In fact most data types (string, int, boolean, etc.) in Python are objects, so pretty much every method works in the way you described.</p>
1
2009-09-30T13:22:11Z
[ "python", "oop" ]
Is it OK if objects from different classes interact with each other?
1,498,009
<p>I just started to use the object oriented programming in Python. I wander if it is OK if I create a method of a class which use objects from another class. In other words, when I call a method of the first class I give an object from the second class as one of the arguments. And then, the considered methods (of the first class) can manipulate by the object from the second class (to get its attributes or use its methods). Is it allowed in Python? Is it not considered as a bad programming style?</p> <p>Is it OK if I instantiate objects from the second class withing a method of the first class. In other words, if I call a method from the first class it instantiate objects fro the second class. </p> <p>Thank you in advance for any help.</p>
4
2009-09-30T13:11:04Z
1,498,152
<p>The answer is that it os MORE than OK, it's in fact the whole point.</p> <p>What is not "OK" is when objects start fiddling with the internals of each other. You can prevent this from happening accidentally, by calling things that are meant to be internal with a leading underscore (or two, which makes it internal also for subclasses). This works as a little marker for other programmers that you aren't supposed to use it, and that it's not official API and can change.</p>
1
2009-09-30T13:32:39Z
[ "python", "oop" ]
Is it OK if objects from different classes interact with each other?
1,498,009
<p>I just started to use the object oriented programming in Python. I wander if it is OK if I create a method of a class which use objects from another class. In other words, when I call a method of the first class I give an object from the second class as one of the arguments. And then, the considered methods (of the first class) can manipulate by the object from the second class (to get its attributes or use its methods). Is it allowed in Python? Is it not considered as a bad programming style?</p> <p>Is it OK if I instantiate objects from the second class withing a method of the first class. In other words, if I call a method from the first class it instantiate objects fro the second class. </p> <p>Thank you in advance for any help.</p>
4
2009-09-30T13:11:04Z
1,498,499
<p>The Law of Demeter is general guidance on which methods and objects you can interact with in good faith. </p> <p>It is guidance. You <em>can</em> make code that works that doesn't follow the LoD, but it is a good guide and helps you build "structure shy systems" -- something you will appreciate later when you try to make big changes.</p> <p><a href="http://en.wikipedia.org/wiki/Law%5Fof%5FDemeter" rel="nofollow">http://en.wikipedia.org/wiki/Law%5Fof%5FDemeter</a></p> <p>I recommend reading up on good OO practices and principles when you're not coding. Maybe a few papers or a chapter of a book each evening or every other day. Try the SOLID principles. You can find a quick reference to them here:</p> <p><a href="http://agileinaflash.blogspot.com/2009/03/solid.html" rel="nofollow">http://agileinaflash.blogspot.com/2009/03/solid.html</a></p>
0
2009-09-30T14:32:13Z
[ "python", "oop" ]
Performance of Python worth the cost?
1,498,155
<p>I'm looking at implementing a fuzzy logic controller based on either PyFuzzy (Python) or FFLL (C++) libraries.</p> <p>I'd prefer to work with python but am unsure if the performance will be acceptable in the embedded environment it will work in (either ARM or embedded x86 proc both ~64Mbs of RAM). </p> <p>The main concern is that response times are as fast as possible (an update rate of 5hz+ would be ideal >2Hz is required). The system would be reading from multiple (probably 5) sensors from an RS232 port and provide 2/3 outputs based on the results of the fuzzy evaluation.</p> <p>Should I be concerned that Python will be too slow for this task?</p>
5
2009-09-30T13:32:45Z
1,498,176
<p>Python is very slow at handling large amounts of non-string data. For some operations, you may see that it is 1000 times slower than C/C++, so yes, you should investigate into this and do necessary benchmarks before you make time-critical algorithms in Python.</p> <p>However, you can extend python with modules in C/C++ code, so that time-critical things are fast, while still being able to use python for the main code.</p>
11
2009-09-30T13:36:28Z
[ "python", "c", "embedded", "fuzzy-logic" ]
Performance of Python worth the cost?
1,498,155
<p>I'm looking at implementing a fuzzy logic controller based on either PyFuzzy (Python) or FFLL (C++) libraries.</p> <p>I'd prefer to work with python but am unsure if the performance will be acceptable in the embedded environment it will work in (either ARM or embedded x86 proc both ~64Mbs of RAM). </p> <p>The main concern is that response times are as fast as possible (an update rate of 5hz+ would be ideal >2Hz is required). The system would be reading from multiple (probably 5) sensors from an RS232 port and provide 2/3 outputs based on the results of the fuzzy evaluation.</p> <p>Should I be concerned that Python will be too slow for this task?</p>
5
2009-09-30T13:32:45Z
1,498,214
<p>In general, you shouldn't obsess over performance until you've actually seen it become a problem. Since we don't know the details of your app, we can't say how it'd perform if implemented in Python. And since you haven't implemented it yet, neither can you.</p> <p>Implement the version you're most comfortable with, and can implement fastest, first. Then benchmark it. And <em>if</em> it is too slow, you have three options which should be done in order:</p> <ul> <li>First, optimize your Python code</li> <li>If that's not enough, write the most performance-critical functions in C/C++, and call that from your Python code</li> <li>And finally, if you <em>really</em> need top performance, you might have to rewrite the whole thing in C++. But then at least you'll have a working prototype in Python, and you'll have a much clearer idea of how it should be implemented. You'll know what pitfalls to avoid, and you'll have an already correct implementation to test against and compare results to.</li> </ul>
35
2009-09-30T13:44:01Z
[ "python", "c", "embedded", "fuzzy-logic" ]
Performance of Python worth the cost?
1,498,155
<p>I'm looking at implementing a fuzzy logic controller based on either PyFuzzy (Python) or FFLL (C++) libraries.</p> <p>I'd prefer to work with python but am unsure if the performance will be acceptable in the embedded environment it will work in (either ARM or embedded x86 proc both ~64Mbs of RAM). </p> <p>The main concern is that response times are as fast as possible (an update rate of 5hz+ would be ideal >2Hz is required). The system would be reading from multiple (probably 5) sensors from an RS232 port and provide 2/3 outputs based on the results of the fuzzy evaluation.</p> <p>Should I be concerned that Python will be too slow for this task?</p>
5
2009-09-30T13:32:45Z
1,498,739
<p>Make it work, then make it work fast.</p>
5
2009-09-30T15:09:50Z
[ "python", "c", "embedded", "fuzzy-logic" ]
Performance of Python worth the cost?
1,498,155
<p>I'm looking at implementing a fuzzy logic controller based on either PyFuzzy (Python) or FFLL (C++) libraries.</p> <p>I'd prefer to work with python but am unsure if the performance will be acceptable in the embedded environment it will work in (either ARM or embedded x86 proc both ~64Mbs of RAM). </p> <p>The main concern is that response times are as fast as possible (an update rate of 5hz+ would be ideal >2Hz is required). The system would be reading from multiple (probably 5) sensors from an RS232 port and provide 2/3 outputs based on the results of the fuzzy evaluation.</p> <p>Should I be concerned that Python will be too slow for this task?</p>
5
2009-09-30T13:32:45Z
1,499,253
<p>If most of your runtime is spent in C libraries, the language you use to call these libraries isn't important. What language are your time-eating libraries written in ?</p>
1
2009-09-30T16:28:37Z
[ "python", "c", "embedded", "fuzzy-logic" ]
Performance of Python worth the cost?
1,498,155
<p>I'm looking at implementing a fuzzy logic controller based on either PyFuzzy (Python) or FFLL (C++) libraries.</p> <p>I'd prefer to work with python but am unsure if the performance will be acceptable in the embedded environment it will work in (either ARM or embedded x86 proc both ~64Mbs of RAM). </p> <p>The main concern is that response times are as fast as possible (an update rate of 5hz+ would be ideal >2Hz is required). The system would be reading from multiple (probably 5) sensors from an RS232 port and provide 2/3 outputs based on the results of the fuzzy evaluation.</p> <p>Should I be concerned that Python will be too slow for this task?</p>
5
2009-09-30T13:32:45Z
1,502,231
<p>From your description, speed should not be much of a concern (and you can use C, cython, whatever you want to make it faster), but memory would be. For environments with 64 Mb max (where the OS and all should fit as well, right ?), I think there is a good chance that python may not be the right tool for target deployment.</p> <p>If you have non trivial logic to handle, I would still prototype in python, though.</p>
0
2009-10-01T06:33:58Z
[ "python", "c", "embedded", "fuzzy-logic" ]
Performance of Python worth the cost?
1,498,155
<p>I'm looking at implementing a fuzzy logic controller based on either PyFuzzy (Python) or FFLL (C++) libraries.</p> <p>I'd prefer to work with python but am unsure if the performance will be acceptable in the embedded environment it will work in (either ARM or embedded x86 proc both ~64Mbs of RAM). </p> <p>The main concern is that response times are as fast as possible (an update rate of 5hz+ would be ideal >2Hz is required). The system would be reading from multiple (probably 5) sensors from an RS232 port and provide 2/3 outputs based on the results of the fuzzy evaluation.</p> <p>Should I be concerned that Python will be too slow for this task?</p>
5
2009-09-30T13:32:45Z
1,612,690
<p>I never really measured the performance of pyfuzzy's examples, but as the new version 0.1.0 can read FCL files as FFLL does. Just describe your fuzzy system in this format, write some wrappers, and check the performance of both variants.</p> <p>For reading FCL with pyfuzzy you need the antlr python runtime, but after reading you should be able to pickle the read object, so you don't need the antlr overhead on the target.</p>
0
2009-10-23T10:55:21Z
[ "python", "c", "embedded", "fuzzy-logic" ]
Pymsn/Papyon contact memberships
1,498,634
<p>Dear Stackoverflow, I'm having the following problem:</p> <p>I'm programming a bot for MSN Messenger in python with the pymsn/papyon library. I have everything running, except that I don't know how to accept new contacts already pending or new requests. Sadly the documentation of the library is very bad. I've achieved to retrieve all pending contacts in the contact list.</p> <p>My precise question is:<br /> - Is there a handler that accept incoming requests (new and old) and how can I implement it.<br /> or<br /> - If I have the email of the pending contact, what is the function to accept the request or how can I change the membership from Pending to Allow.</p> <p>I appreciate all your help and/or all the information you can provide.</p>
0
2009-09-30T14:55:13Z
1,872,443
<p>if you want check there is any contact, just list all you contact and check if the contact status is pending. Short code like:</p> <pre><code>for contact in self.client._address_book.contacts: if contact.is_pending: self.client._address_book.accept_contact_invitation(contact) </code></pre> <p>is_pending is my implement but you are easily to write it your own. And you just have a thread monitor this all will be fine.</p>
0
2009-12-09T08:37:57Z
[ "python", "bots", "msn-messenger" ]
Django: form values not updating when model updates
1,498,763
<p>I am creating a form that uses MultipleChoiceField. The values for this field are derived from another model. This method works fine, however, I am noticing (on the production server) that when I add a new item to the model in question (NoticeType), the form does not dynamically update. I have to restart the server for the new item to show up on my MultipleChoiceField.</p> <p>Any changes to the NoticeType model (editing items or creating new ones) do not propagate to the form. After I restart the production server, the updates appear. </p> <p>Any ideas why this might be ? The relevant portion of the form is below. Thanks.</p> <pre><code>from django import forms from django.contrib.auth.models import User from notification.models import NoticeType class EditUserProfileForm(forms.Form): CHOICES = [] for notice in NoticeType.objects.all(): CHOICES.append( (notice.label,notice.display) ) notifications = forms.MultipleChoiceField( label="Email Notifications", required=False, choices=( CHOICES ), widget=forms.CheckboxSelectMultiple,) </code></pre>
4
2009-09-30T15:14:17Z
1,498,918
<p>My hunch is that the class definition is only being processed once on load rather than for each instantiation. Try adding the CHOICES computation to the <strong>init</strong> method like so:</p> <pre><code>def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) CHOICES = [] for notice in NoticeType.objects.all(): CHOICES.append( (notice.label, notice.display) ) self.fields['notifications'].choices = CHOICES </code></pre>
6
2009-09-30T15:32:57Z
[ "python", "django", "django-forms" ]
Django: form values not updating when model updates
1,498,763
<p>I am creating a form that uses MultipleChoiceField. The values for this field are derived from another model. This method works fine, however, I am noticing (on the production server) that when I add a new item to the model in question (NoticeType), the form does not dynamically update. I have to restart the server for the new item to show up on my MultipleChoiceField.</p> <p>Any changes to the NoticeType model (editing items or creating new ones) do not propagate to the form. After I restart the production server, the updates appear. </p> <p>Any ideas why this might be ? The relevant portion of the form is below. Thanks.</p> <pre><code>from django import forms from django.contrib.auth.models import User from notification.models import NoticeType class EditUserProfileForm(forms.Form): CHOICES = [] for notice in NoticeType.objects.all(): CHOICES.append( (notice.label,notice.display) ) notifications = forms.MultipleChoiceField( label="Email Notifications", required=False, choices=( CHOICES ), widget=forms.CheckboxSelectMultiple,) </code></pre>
4
2009-09-30T15:14:17Z
1,499,297
<p>Although mherren is right that you can fix this problem by defining your choices in the <code>__init__</code> method, there is an easier way: use the <code>ModelMultipleChoiceField</code> which is specifically designed to take a queryset, and updates dynamically.</p> <pre><code>class EditUserProfileForm(forms.Form): notifications = forms. ModelMultipleChoiceField( label="Email Notifications", required=False, queryset = NoticeType.objects.all(), widget=forms.CheckboxSelectMultiple) </code></pre>
8
2009-09-30T16:37:14Z
[ "python", "django", "django-forms" ]
How to get the PATH separator in Python?
1,499,019
<p>When multiple directories need to be concatenated, as in an executable search path, there is an os-dependent separator character. For Windows it's <code>';'</code>, for Linux it's <code>':'</code>. Is there a way in Python to get which character to split on?</p> <p>In the discussions to this question <a href="http://stackoverflow.com/questions/1489599/how-do-i-find-out-my-python-path-using-python">http://stackoverflow.com/questions/1489599/how-do-i-find-out-my-python-path-using-python</a> , it is suggested that <code>os.sep</code> will do it. That answer is wrong, since it is the separator for components of a directory or filename and equates to <code>'\\'</code> or <code>'/'</code>.</p>
106
2009-09-30T15:51:47Z
1,499,033
<p><a href="http://docs.python.org/library/os.html#os.pathsep"><code>os.pathsep</code></a></p>
163
2009-09-30T15:53:44Z
[ "python", "operating-system" ]
How to get the PATH separator in Python?
1,499,019
<p>When multiple directories need to be concatenated, as in an executable search path, there is an os-dependent separator character. For Windows it's <code>';'</code>, for Linux it's <code>':'</code>. Is there a way in Python to get which character to split on?</p> <p>In the discussions to this question <a href="http://stackoverflow.com/questions/1489599/how-do-i-find-out-my-python-path-using-python">http://stackoverflow.com/questions/1489599/how-do-i-find-out-my-python-path-using-python</a> , it is suggested that <code>os.sep</code> will do it. That answer is wrong, since it is the separator for components of a directory or filename and equates to <code>'\\'</code> or <code>'/'</code>.</p>
106
2009-09-30T15:51:47Z
1,499,034
<p>It is os.pathsep</p>
25
2009-09-30T15:53:53Z
[ "python", "operating-system" ]
How to get the PATH separator in Python?
1,499,019
<p>When multiple directories need to be concatenated, as in an executable search path, there is an os-dependent separator character. For Windows it's <code>';'</code>, for Linux it's <code>':'</code>. Is there a way in Python to get which character to split on?</p> <p>In the discussions to this question <a href="http://stackoverflow.com/questions/1489599/how-do-i-find-out-my-python-path-using-python">http://stackoverflow.com/questions/1489599/how-do-i-find-out-my-python-path-using-python</a> , it is suggested that <code>os.sep</code> will do it. That answer is wrong, since it is the separator for components of a directory or filename and equates to <code>'\\'</code> or <code>'/'</code>.</p>
106
2009-09-30T15:51:47Z
35,413,644
<p>Making it a little more explicit (For python newbies like me)</p> <pre><code>import os print(os.pathsep) </code></pre>
6
2016-02-15T15:53:55Z
[ "python", "operating-system" ]
Python - importing package classes into console global namespace
1,499,119
<p>I'm having a spot of trouble getting my python classes to work within the python console. I want to automatically import all of my classes into the global namespace so I can use them without any prefix.module.names.</p> <p>Here's what I've got so far...</p> <pre><code>projectname/ |-__init__.py | |-main_stuff/ |-__init__.py |-main1.py |-main2.py | |-other_stuff/ |-__init__.py |-other1.py |-other2.py </code></pre> <p>Each file defines a class of the same name, e.g. main1.py will define a class called Main1.</p> <p>My <code>PYTHONPATH</code> is the absolute path to projectname/.</p> <p>I've got a python startup file that contains this:</p> <pre><code>from projectname import * </code></pre> <p>But this doesn't let me use my classes at all. Upon starting a python console I would like to be able to write:</p> <pre><code>ob=Main1() </code></pre> <p>but Main1 isn't within the current namespace, so it doesn't work.</p> <p>I tried adding things to the <code>__init__.py</code> files...</p> <p>In <code>projectname/__init__.py</code>:</p> <pre><code>import main_stuff </code></pre> <p>In <code>projectname/main_stuff/__init__.py</code>:</p> <pre><code>import other_stuff __all__ = ["main1", "main2", "main3"] </code></pre> <p>And so on. And in my startup file I added:</p> <pre><code>from projectname.main_stuff import * from projectname.main_stuff/other_stuff import * </code></pre> <p>But to use the classes within the python console I still have to write:</p> <pre><code>ob=main1.Main1() </code></pre> <p>I'd prefer not to need the <code>main1.</code> part. Does anyone know how I can automatically put my classes in the global namespace when using the python console?</p> <p>Thanks. </p> <p>==== EDIT ====</p> <p>What I need is to import a package at the class level, but <code>from package import *</code> gives me everything at the module level. I'm after an easy way of doing something like this:</p> <pre><code>for module in package do: from package.module import * </code></pre> <p>==== ANOTHER EDIT ====</p> <p>I ended up adding the class imports to my python startup file individually. It's not ideal because of the overhead of maintaining it, but it does what I want.</p> <pre><code>from class1.py import Class1 from class2.py import Class2 from class3.py import Class3 </code></pre>
8
2009-09-30T16:04:52Z
1,499,164
<p>You want to use a different form of import.</p> <p>In <code>projectname/main_stuff/__init__.py</code>:</p> <pre><code>from other_stuff import * __all__ = ["main1", "main2", "main3"] </code></pre> <p>When you use a statement like this:</p> <pre><code>import foo </code></pre> <p>You are defining the name foo in the current module. Then you can use <code>foo.something</code> to get at the stuff in foo.</p> <p>When you use this:</p> <pre><code>from foo import * </code></pre> <p>You are taking all of the names defined in foo and defining them in this module (like pouring a bucket of names from foo into your module).</p>
14
2009-09-30T16:13:14Z
[ "python", "import", "console", "namespaces", "global" ]
Running python script as another user
1,499,268
<p>On a Linux box I want to run a Python script as another user.</p> <p>I've already made a wrapper program in C++ that calls the script, since I've realized that the ownership of running the script is decided by the ownership of the python interpreter. After that I change the C++ program to a different user and run the C++ program.</p> <p>This setup doesn't seem to be working. Any ideas?</p>
8
2009-09-30T16:31:05Z
1,499,282
<p>Use the command <code>sudo</code>.</p> <p>In order to run a program as a user, the system must "authenticate" that user.</p> <p>Obviously, <code>root</code> can run any program as any user, and any user can <code>su</code> to another user with a password.</p> <p>The program <code>sudo</code> can be configured to allow a group of users to <code>sudo</code> a particular command as a particular user.</p> <p>For example, you could create a group <code>scriptUsers</code> and a user <code>scriptRun</code>. Then, configure <code>sudo</code> to let any user in <code>scriptUsers</code> become <code>scriptRun</code> ONLY to run your script.</p>
0
2009-09-30T16:33:49Z
[ "python", "linux" ]
Running python script as another user
1,499,268
<p>On a Linux box I want to run a Python script as another user.</p> <p>I've already made a wrapper program in C++ that calls the script, since I've realized that the ownership of running the script is decided by the ownership of the python interpreter. After that I change the C++ program to a different user and run the C++ program.</p> <p>This setup doesn't seem to be working. Any ideas?</p>
8
2009-09-30T16:31:05Z
1,499,313
<p>Give those users the ability to <code>sudo su $dedicated_username</code> and tailor the permissions on your system so that <code>$dedicated_user</code> has sufficient, but not excessive, access.</p>
1
2009-09-30T16:39:46Z
[ "python", "linux" ]
Running python script as another user
1,499,268
<p>On a Linux box I want to run a Python script as another user.</p> <p>I've already made a wrapper program in C++ that calls the script, since I've realized that the ownership of running the script is decided by the ownership of the python interpreter. After that I change the C++ program to a different user and run the C++ program.</p> <p>This setup doesn't seem to be working. Any ideas?</p>
8
2009-09-30T16:31:05Z
1,499,317
<p>It sounds like you want to use the <a href="http://en.wikipedia.org/wiki/Setuid" rel="nofollow">setuid</a> bit</p>
4
2009-09-30T16:40:19Z
[ "python", "linux" ]
Running python script as another user
1,499,268
<p>On a Linux box I want to run a Python script as another user.</p> <p>I've already made a wrapper program in C++ that calls the script, since I've realized that the ownership of running the script is decided by the ownership of the python interpreter. After that I change the C++ program to a different user and run the C++ program.</p> <p>This setup doesn't seem to be working. Any ideas?</p>
8
2009-09-30T16:31:05Z
1,499,386
<p>You can set the user with os.setuid(), and you can get the uid with pwd. Like so:</p> <pre><code>&gt;&gt;&gt; import pwd, os &gt;&gt;&gt; uid = pwd.getpwnam('root')[2] &gt;&gt;&gt; os.setuid(uid) </code></pre> <p>Obviously this only works if the user or executable has the permission to do so. Exactly how to set that up I don't know. Obviously it works if you are root. I think you may need to the the setuid flag on the Python executable, and that would leave a WHOPPING security hole. possible that's permittable if the user you setuid too is a dedicated restricted user that can't do anything except whatever you need to do.</p> <p>Unix security, based on users and setuiding and stuff, is not very good or practical, and it's easy to leave big security holes. A more secure option is actually to do this client-server typish, so you have a demon that does everything, and the client talks to it. The demon can then run with a higher security than the users, but the users would have to give a name and password when they run the script, or identify themselves with some public/private key or somesuch.</p>
11
2009-09-30T16:53:11Z
[ "python", "linux" ]
App Engine Python how to handle urls?
1,499,485
<p>I just want to ask a simple question, as I don't imagine how to do it.</p> <p>In the app.yaml, when I want to declare query string parameter, how do I do it?</p> <p>For example, to make a multi language site, I create the url in this format:</p> <pre><code>mysite.com/english/aboutus mysite.com/italiano/aboutus </code></pre> <p>and in app.yaml the script to handle them are</p> <pre><code>- url: /english/aboutus script: index.py - url: /italiano/aboutus script: index.py </code></pre> <p>In which way can I determine the difference between these two urls, and how to handle them in index.py? </p> <p>I know this is simple question, I could look around for references, but it might help for others in stackoverflow.com as well.</p>
0
2009-09-30T17:11:41Z
1,499,554
<p>Instead you could use the webapp framework to handle the URL's.</p> <p>For example, in index.py</p> <pre><code>application = webapp.WSGIApplication( [('/english', EnglishHandler)], [('/italiano', ItalianHandler)], debug=True) </code></pre> <p>More information can be found here. <a href="http://code.google.com/appengine/docs/python/gettingstarted/usingwebapp.html" rel="nofollow">http://code.google.com/appengine/docs/python/gettingstarted/usingwebapp.html</a></p>
2
2009-09-30T17:28:09Z
[ "python", "google-app-engine" ]
App Engine Python how to handle urls?
1,499,485
<p>I just want to ask a simple question, as I don't imagine how to do it.</p> <p>In the app.yaml, when I want to declare query string parameter, how do I do it?</p> <p>For example, to make a multi language site, I create the url in this format:</p> <pre><code>mysite.com/english/aboutus mysite.com/italiano/aboutus </code></pre> <p>and in app.yaml the script to handle them are</p> <pre><code>- url: /english/aboutus script: index.py - url: /italiano/aboutus script: index.py </code></pre> <p>In which way can I determine the difference between these two urls, and how to handle them in index.py? </p> <p>I know this is simple question, I could look around for references, but it might help for others in stackoverflow.com as well.</p>
0
2009-09-30T17:11:41Z
1,499,770
<p>The <code>SCRIPT_NAME</code> environ entry contains the path under which your script was invoked. Haven't tested this in GAE specifically, but it's something WSGI inherited from <a href="http://hoohoo.ncsa.illinois.edu/cgi/env.html#protocol" rel="nofollow">CGI</a>.</p> <pre><code>language= environ['SCRIPT_NAME'][1:].split('/', 1)[0] if language not in ('english', 'italiano'): language= 'english' </code></pre>
1
2009-09-30T18:10:34Z
[ "python", "google-app-engine" ]
App Engine Python how to handle urls?
1,499,485
<p>I just want to ask a simple question, as I don't imagine how to do it.</p> <p>In the app.yaml, when I want to declare query string parameter, how do I do it?</p> <p>For example, to make a multi language site, I create the url in this format:</p> <pre><code>mysite.com/english/aboutus mysite.com/italiano/aboutus </code></pre> <p>and in app.yaml the script to handle them are</p> <pre><code>- url: /english/aboutus script: index.py - url: /italiano/aboutus script: index.py </code></pre> <p>In which way can I determine the difference between these two urls, and how to handle them in index.py? </p> <p>I know this is simple question, I could look around for references, but it might help for others in stackoverflow.com as well.</p>
0
2009-09-30T17:11:41Z
1,503,689
<p>I remember doing something like this:</p> <p>in app.yaml put</p> <pre><code>- url: /(.*)/(.*)/? script: main.py </code></pre> <p>and in main.py</p> <pre><code>class MainHandler(webapp.RequestHandler): def get(self, Urlpart1, Urlpart2): def main(): application = webapp.WSGIApplication([('/(.*)/(.*)/', MainHandler), ('/(.*)/(.*)', MainHandler)], debug=True) </code></pre> <p>where Urlparts are words between slashes </p>
4
2009-10-01T12:33:20Z
[ "python", "google-app-engine" ]
App Engine Python how to handle urls?
1,499,485
<p>I just want to ask a simple question, as I don't imagine how to do it.</p> <p>In the app.yaml, when I want to declare query string parameter, how do I do it?</p> <p>For example, to make a multi language site, I create the url in this format:</p> <pre><code>mysite.com/english/aboutus mysite.com/italiano/aboutus </code></pre> <p>and in app.yaml the script to handle them are</p> <pre><code>- url: /english/aboutus script: index.py - url: /italiano/aboutus script: index.py </code></pre> <p>In which way can I determine the difference between these two urls, and how to handle them in index.py? </p> <p>I know this is simple question, I could look around for references, but it might help for others in stackoverflow.com as well.</p>
0
2009-09-30T17:11:41Z
1,569,489
<p>There're 39 human languages supported. Best way seems comply via lib/django/django/conf/locale/ <a href="http://classifiedsmarket.appspot.com?hl=kn" rel="nofollow">Here's</a> an app that translates all engines messages via parameter hl=[languageCode] [code disposable][2]</p>
0
2009-10-14T23:05:12Z
[ "python", "google-app-engine" ]
How do I define a SWIG typemap for a reference to pointer?
1,499,569
<p>I have a Publisher class written in C++ with the following two methods:</p> <pre><code>PublishField(char* name, double* address); GetFieldReference(char* name, double*&amp; address); </code></pre> <p>Python bindings for this class are being generated using SWIG. In my swig .i file I have the following:</p> <pre><code> %pointer_class(double*, ptrDouble); </code></pre> <p>This lets me publish a field that is defined in a Python variable:</p> <pre><code>value = ptrDouble() value.assign(10.0) PublishField("value", value.cast()) </code></pre> <p>Trying to using the GetFieldReference method results in a TypeError however:</p> <pre><code>GetFieldReference("value", newValue) </code></pre> <p>I think I need to create a typemap for the double*&amp; that returns a ptrDouble, but I am not quite sure what that would look like.</p>
1
2009-09-30T17:31:01Z
1,510,406
<p>Here is a working solution that I came up with.</p> <p>Add a wrapper function to the swig.i file:</p> <pre><code>%inline %{ double * GetReference(char* name, Publisher* publisher) { double* ptr = new double; publisher-&gt;GetFieldReference(name, ptr); return ptr; } %} </code></pre> <p>Now from Python I can use the following:</p> <pre><code>value = ptrDouble.frompointer(GetFieldReference("value", publisher) </code></pre>
1
2009-10-02T15:55:05Z
[ "c++", "python", "swig" ]
How do I define a SWIG typemap for a reference to pointer?
1,499,569
<p>I have a Publisher class written in C++ with the following two methods:</p> <pre><code>PublishField(char* name, double* address); GetFieldReference(char* name, double*&amp; address); </code></pre> <p>Python bindings for this class are being generated using SWIG. In my swig .i file I have the following:</p> <pre><code> %pointer_class(double*, ptrDouble); </code></pre> <p>This lets me publish a field that is defined in a Python variable:</p> <pre><code>value = ptrDouble() value.assign(10.0) PublishField("value", value.cast()) </code></pre> <p>Trying to using the GetFieldReference method results in a TypeError however:</p> <pre><code>GetFieldReference("value", newValue) </code></pre> <p>I think I need to create a typemap for the double*&amp; that returns a ptrDouble, but I am not quite sure what that would look like.</p>
1
2009-09-30T17:31:01Z
2,561,620
<p>This typemap should solve the problem - </p> <pre><code>// Typemaps for double *&amp; %typemap(in) double *&amp; (double *ppDouble = NULL) %{ $1 = &amp;ppDouble ; %} %typemap(argout) double *&amp; { *(double **)&amp;jarg2 = *$1; } %typemap(javain) double *&amp; "$javainput" </code></pre> <p>You may need to check if assigning jarg2 (in 'argout' typemap) with required double value is correct or jarg1 should be assigned rather.</p>
0
2010-04-01T15:38:14Z
[ "c++", "python", "swig" ]
With multiple Python installs, how does MacPorts know which one to install MySQLdb for?
1,499,572
<p>I just upgraded the default Python 2.5 on Leopard to 2.6 via the installer on www.python.org. Upon doing so, the MySQLdb I had installed was no longer found. So I tried reinstalling it via <code>port install py-mysql</code>, and it succeeded, but MySQLdb was still not <code>import</code>able. So then I tried to <code>python install python26</code> with <code>python_select python26</code> and it succeeded, but it doesn't appear that it is getting precedence over the python.org install:</p> <p><code>$ which python<br /> /Library/Frameworks/Python.framework/Versions/2.6/bin/python</code></p> <p>When I would expect it to be something like <code>/opt/local/bin/python</code></p> <p>My <code>path</code> environment is: <code>/Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/local/mysql/bin/:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/mysql/bin:/Users/bsr/bin</code></p> <p>Anyway, when I try <code>port install py-mysql</code> but how does it know where to install the Python MySQL library?</p>
0
2009-09-30T17:32:09Z
1,500,063
<p>The <code>MacPorts</code> python ports generally follow a pattern: if the port name starts with just <code>py-</code>, it is configured to install into MacPorts python2.4. Likewise <code>py25-</code> requires python2.5. For the MacPorts python2.6, you want <a href="http://www.macports.org/ports.php?by=name&amp;substr=py26-mysql" rel="nofollow">this port</a>:</p> <pre><code>sudo port install py26-mysql </code></pre>
2
2009-09-30T19:04:55Z
[ "python", "mysql", "osx" ]
With multiple Python installs, how does MacPorts know which one to install MySQLdb for?
1,499,572
<p>I just upgraded the default Python 2.5 on Leopard to 2.6 via the installer on www.python.org. Upon doing so, the MySQLdb I had installed was no longer found. So I tried reinstalling it via <code>port install py-mysql</code>, and it succeeded, but MySQLdb was still not <code>import</code>able. So then I tried to <code>python install python26</code> with <code>python_select python26</code> and it succeeded, but it doesn't appear that it is getting precedence over the python.org install:</p> <p><code>$ which python<br /> /Library/Frameworks/Python.framework/Versions/2.6/bin/python</code></p> <p>When I would expect it to be something like <code>/opt/local/bin/python</code></p> <p>My <code>path</code> environment is: <code>/Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/local/mysql/bin/:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/mysql/bin:/Users/bsr/bin</code></p> <p>Anyway, when I try <code>port install py-mysql</code> but how does it know where to install the Python MySQL library?</p>
0
2009-09-30T17:32:09Z
2,302,542
<p>You also need python_select (or is it select_python?) to change the default python used.</p>
1
2010-02-20T14:47:59Z
[ "python", "mysql", "osx" ]
How to programmatically get SVN revision number?
1,499,811
<p><a href="http://stackoverflow.com/questions/681770/how-to-programmatically-get-svn-revision-description-and-author-in-c">Like this question</a>, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the <code>.svn</code> folder somewhere, but where, and how do I parse it? I want to do something like what SO does, having the revision in the bottom-right corner.</p> <p>Code in Python or PHP appreciated if you have it on hand, or just a point in the right direction.</p>
7
2009-09-30T18:17:47Z
1,499,847
<p>You can get the current revision number of a checkout using, on the command line, "<code>svn info</code>".</p> <p>For instance :</p> <pre><code>$ svn info Chemin : . URL : http://.../trunk Racine du dépôt : http://... UUID du dépôt : 128b9c1a-...-612a326c9977 Révision : 185 Type de nœud : répertoire Tâche programmée : normale Auteur de la dernière modification : ... Révision de la dernière modification : 185 Date de la dernière modification: 2009-09-28 20:12:29 +0200 (lun. 28 sept. 2009) </code></pre> <p>Note it's localized ; if you're on Linux, you could try using :</p> <pre><code>$ LANG=en svn info svn: warning: cannot set LC_CTYPE locale svn: warning: environment variable LANG is en svn: warning: please check that your locale name is correct Path: . URL: http://.../trunk Repository Root: http://... Repository UUID: 128b9c1a-...-612a326c9977 Revision: 185 Node Kind: directory Schedule: normal Last Changed Author: mzeis Last Changed Rev: 185 Last Changed Date: 2009-09-28 20:12:29 +0200 (Mon, 28 Sep 2009) </code></pre> <p>If using this from PHP, though, getting it as XML might be more helpful <em>(easier to parse, and not locale-aware)</em> :</p> <pre><code>$ svn info --xml &lt;?xml version="1.0"?&gt; &lt;info&gt; &lt;entry kind="dir" path="." revision="185"&gt; &lt;url&gt;http://.../trunk&lt;/url&gt; &lt;repository&gt; &lt;root&gt;http://...&lt;/root&gt; &lt;uuid&gt;128b9c1a-...-612a326c9977&lt;/uuid&gt; &lt;/repository&gt; &lt;wc-info&gt; &lt;schedule&gt;normal&lt;/schedule&gt; &lt;depth&gt;infinity&lt;/depth&gt; &lt;/wc-info&gt; &lt;commit revision="185"&gt; &lt;author&gt;...&lt;/author&gt; &lt;date&gt;2009-09-28T18:12:29.130307Z&lt;/date&gt; &lt;/commit&gt; &lt;/entry&gt; &lt;/info&gt; </code></pre> <p>Just use <a href="http://php.net/simplexml%5Fload%5Fstring" rel="nofollow"><code>simplexml_load_string</code></a> on that, and fetch the <code>revision</code> attribute of the <code>entry</code> tag.</p> <p><br> Note that I would not do that on each page view : not quite as fast as one would hope for your application.</p> <p>Instead, I would get that revision number when creating the archive I will, later, send to the production server -- and store it in some kind of configuration file.</p> <p>This way, you don't need to use the <code>svn</code> command on your production server, and you don't need to do your checkout on that server either.</p>
3
2009-09-30T18:21:48Z
[ "php", "python", "svn" ]
How to programmatically get SVN revision number?
1,499,811
<p><a href="http://stackoverflow.com/questions/681770/how-to-programmatically-get-svn-revision-description-and-author-in-c">Like this question</a>, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the <code>.svn</code> folder somewhere, but where, and how do I parse it? I want to do something like what SO does, having the revision in the bottom-right corner.</p> <p>Code in Python or PHP appreciated if you have it on hand, or just a point in the right direction.</p>
7
2009-09-30T18:17:47Z
1,499,851
<p>I would probably write out the version number to a text file somewhere within the website using the post-commit hook and then just read that file when loading your page.</p> <p><a href="http://svnbook.red-bean.com/en/1.1/ch05s02.html" rel="nofollow">More on using hooks here</a></p>
4
2009-09-30T18:22:44Z
[ "php", "python", "svn" ]
How to programmatically get SVN revision number?
1,499,811
<p><a href="http://stackoverflow.com/questions/681770/how-to-programmatically-get-svn-revision-description-and-author-in-c">Like this question</a>, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the <code>.svn</code> folder somewhere, but where, and how do I parse it? I want to do something like what SO does, having the revision in the bottom-right corner.</p> <p>Code in Python or PHP appreciated if you have it on hand, or just a point in the right direction.</p>
7
2009-09-30T18:17:47Z
1,499,859
<p>You could just shell out to the command line and run svn info. Just keep in mind this could be a mixed revision. You could also run an svn up and the last line of STDOUT will give you the revision number. </p> <p>Or, are you wanting to use the svn API? You might also want to look at the TortoiseSVN code from SubWCRev which is used to replace a token in a file with the current revisions of the WC. </p>
0
2009-09-30T18:24:15Z
[ "php", "python", "svn" ]
How to programmatically get SVN revision number?
1,499,811
<p><a href="http://stackoverflow.com/questions/681770/how-to-programmatically-get-svn-revision-description-and-author-in-c">Like this question</a>, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the <code>.svn</code> folder somewhere, but where, and how do I parse it? I want to do something like what SO does, having the revision in the bottom-right corner.</p> <p>Code in Python or PHP appreciated if you have it on hand, or just a point in the right direction.</p>
7
2009-09-30T18:17:47Z
1,499,894
<p>I like the solution used by MediaWiki, reading the contents of <code>.svn/entities</code>. Check the first answer on this question: <a href="http://stackoverflow.com/questions/16248/getting-the-subversion-repository-number-into-code">http://stackoverflow.com/questions/16248/getting-the-subversion-repository-number-into-code</a></p>
2
2009-09-30T18:32:05Z
[ "php", "python", "svn" ]
How to programmatically get SVN revision number?
1,499,811
<p><a href="http://stackoverflow.com/questions/681770/how-to-programmatically-get-svn-revision-description-and-author-in-c">Like this question</a>, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the <code>.svn</code> folder somewhere, but where, and how do I parse it? I want to do something like what SO does, having the revision in the bottom-right corner.</p> <p>Code in Python or PHP appreciated if you have it on hand, or just a point in the right direction.</p>
7
2009-09-30T18:17:47Z
1,499,895
<p>If you're looking for a Python implementation, check out <a href="http://pysvn.tigris.org/" rel="nofollow">pysvn</a>, you can invoke the <a href="http://pysvn.tigris.org/docs/pysvn%5Fprog%5Fref.html#pysvn%5Fclient%5Finfo" rel="nofollow">info command</a> to get details including the current revision:</p> <pre><code>entry = info( path ) </code></pre>
2
2009-09-30T18:32:05Z
[ "php", "python", "svn" ]
How to programmatically get SVN revision number?
1,499,811
<p><a href="http://stackoverflow.com/questions/681770/how-to-programmatically-get-svn-revision-description-and-author-in-c">Like this question</a>, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the <code>.svn</code> folder somewhere, but where, and how do I parse it? I want to do something like what SO does, having the revision in the bottom-right corner.</p> <p>Code in Python or PHP appreciated if you have it on hand, or just a point in the right direction.</p>
7
2009-09-30T18:17:47Z
1,499,911
<p>This works for svn version 1.6.2. But be warned, different SVN versions use different formats of the .svn folder.</p> <pre><code>&lt;?php $contents = file_get_contents(dirname(__FILE__) . '/.svn/entries'); preg_match("/dir\n(.+)/", $contents, $matches); $svnRevision = $matches[1]; print "This Directory's SVN Revsion = $svnRevision\n"; </code></pre>
3
2009-09-30T18:35:38Z
[ "php", "python", "svn" ]
How to programmatically get SVN revision number?
1,499,811
<p><a href="http://stackoverflow.com/questions/681770/how-to-programmatically-get-svn-revision-description-and-author-in-c">Like this question</a>, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the <code>.svn</code> folder somewhere, but where, and how do I parse it? I want to do something like what SO does, having the revision in the bottom-right corner.</p> <p>Code in Python or PHP appreciated if you have it on hand, or just a point in the right direction.</p>
7
2009-09-30T18:17:47Z
1,500,651
<p>Following Lance, here's a command line one-liner.</p> <pre><code>svn log -q --limit 1 http://svnbox/path/to/repo/trunk \ | php -r 'fgets(STDIN); preg_match("/(\d+)/", fgets(STDIN), $m); echo $m[0];' </code></pre>
3
2009-09-30T21:02:36Z
[ "php", "python", "svn" ]
How to programmatically get SVN revision number?
1,499,811
<p><a href="http://stackoverflow.com/questions/681770/how-to-programmatically-get-svn-revision-description-and-author-in-c">Like this question</a>, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the <code>.svn</code> folder somewhere, but where, and how do I parse it? I want to do something like what SO does, having the revision in the bottom-right corner.</p> <p>Code in Python or PHP appreciated if you have it on hand, or just a point in the right direction.</p>
7
2009-09-30T18:17:47Z
1,501,219
<p>Subversion includes the <a href="http://svnbook.red-bean.com/en/1.7/svn.ref.svnversion.re.html" rel="nofollow">svnversion</a> tool for exactly this purpose. A working copy may actually have local modifications, or may consist of a mix of revisions. <code>svnversion</code> knows how to handle that; see the examples in the linked documentation.</p> <p>You can invoke <code>svnversion</code> from python like this:</p> <pre><code>import subprocess def svnversion(): p = subprocess.Popen("svnversion", stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() return stdout </code></pre>
13
2009-09-30T23:37:06Z
[ "php", "python", "svn" ]
How to programmatically get SVN revision number?
1,499,811
<p><a href="http://stackoverflow.com/questions/681770/how-to-programmatically-get-svn-revision-description-and-author-in-c">Like this question</a>, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the <code>.svn</code> folder somewhere, but where, and how do I parse it? I want to do something like what SO does, having the revision in the bottom-right corner.</p> <p>Code in Python or PHP appreciated if you have it on hand, or just a point in the right direction.</p>
7
2009-09-30T18:17:47Z
4,346,943
<p>I know this is pretty old, but I thought I'd offer up how I do this in PHP for my web apps:</p> <p>Put this in a PHP file in your app, and set the SVN Keywords property for "Date Revision Author HeadURL Id" (keyword substitution in the file).</p> <pre><code>$SVN_rev = "\$LastChangedRevision$"; $SVN_headURL = "\$HeadURL$"; function stripSVNstuff($s) { $s = substr($s, strpos($s, ":")+1); $s = str_replace("$", "", $s); return trim($s); } </code></pre> <p>So after svn does keyword replacement on the source file, the $SVN_rev line will look like:</p> <pre><code>$SVN_rev = "\$LastChangedRevision: 6 $"; </code></pre> <p>so the output of stripSVNstuff($SVN_rev) would be "6" (without quotes).</p>
1
2010-12-03T15:21:45Z
[ "php", "python", "svn" ]
Python/WebApp Google App Engine - testing for user/pass in the headers
1,499,832
<p>When you call a web service like this:</p> <pre><code> username = 'test12' password = 'test34' client = httplib2.Http(".cache") client.add_credentials(username,password) URL = "http://localhost:8080/wyWebServiceTest" response, content = client.request(URL) </code></pre> <p>How do you get the username/password into variables on the server side (i.e. in the web-service that I'm writing). I checked the self.request.headers and self.request.environ and couldn't find them. </p> <p>(I'm not using Google Login, need to bounce this userid/pass against my own database to verify security.) </p> <p>I was trying to ideas from this page: <a href="http://pythonpaste.org/webob/reference.html#headers" rel="nofollow">http://pythonpaste.org/webob/reference.html#headers</a> </p> <p>Thanks,</p> <p>Neal Walters </p> <p>Slight enhancement to Peter's code below: </p> <pre><code> auth = None if 'Authorization' in self.request.headers: auth = self.request.headers['Authorization'] if not auth: </code></pre>
4
2009-09-30T18:20:00Z
1,500,047
<p>httplib2 will only pass the credentials after a 401 response from the web server, after which the credentials should be sent in an Authorization: header.</p>
1
2009-09-30T19:01:08Z
[ "python", "google-app-engine", "web-applications" ]
Python/WebApp Google App Engine - testing for user/pass in the headers
1,499,832
<p>When you call a web service like this:</p> <pre><code> username = 'test12' password = 'test34' client = httplib2.Http(".cache") client.add_credentials(username,password) URL = "http://localhost:8080/wyWebServiceTest" response, content = client.request(URL) </code></pre> <p>How do you get the username/password into variables on the server side (i.e. in the web-service that I'm writing). I checked the self.request.headers and self.request.environ and couldn't find them. </p> <p>(I'm not using Google Login, need to bounce this userid/pass against my own database to verify security.) </p> <p>I was trying to ideas from this page: <a href="http://pythonpaste.org/webob/reference.html#headers" rel="nofollow">http://pythonpaste.org/webob/reference.html#headers</a> </p> <p>Thanks,</p> <p>Neal Walters </p> <p>Slight enhancement to Peter's code below: </p> <pre><code> auth = None if 'Authorization' in self.request.headers: auth = self.request.headers['Authorization'] if not auth: </code></pre>
4
2009-09-30T18:20:00Z
1,500,356
<p>The credentials will appear in the Authorization header. The steps work like this:</p> <ol> <li>Client makes a request to your app with no attempt at authorization</li> <li>Server responds with a "401 Authorization Required" response, and the "WWW-Authenticate" header set to 'Basic realm="something"' (for basic auth).</li> <li>Client responds with an Authorization header set appropriately (see below).</li> </ol> <p>The exact content of the client's Authorization header in step 3 depends on the authorization method used. For HTTP Basic auth, it's the base64-encoded user credentials - see <a href="http://en.wikipedia.org/wiki/Basic%5Faccess%5Fauthentication" rel="nofollow">here</a>. For HTTP digest auth, both the server's header and the response from the client are a bit more complicated - see <a href="http://en.wikipedia.org/wiki/Digest%5Faccess%5Fauthentication" rel="nofollow">here</a>.</p>
3
2009-09-30T20:04:28Z
[ "python", "google-app-engine", "web-applications" ]
Python/WebApp Google App Engine - testing for user/pass in the headers
1,499,832
<p>When you call a web service like this:</p> <pre><code> username = 'test12' password = 'test34' client = httplib2.Http(".cache") client.add_credentials(username,password) URL = "http://localhost:8080/wyWebServiceTest" response, content = client.request(URL) </code></pre> <p>How do you get the username/password into variables on the server side (i.e. in the web-service that I'm writing). I checked the self.request.headers and self.request.environ and couldn't find them. </p> <p>(I'm not using Google Login, need to bounce this userid/pass against my own database to verify security.) </p> <p>I was trying to ideas from this page: <a href="http://pythonpaste.org/webob/reference.html#headers" rel="nofollow">http://pythonpaste.org/webob/reference.html#headers</a> </p> <p>Thanks,</p> <p>Neal Walters </p> <p>Slight enhancement to Peter's code below: </p> <pre><code> auth = None if 'Authorization' in self.request.headers: auth = self.request.headers['Authorization'] if not auth: </code></pre>
4
2009-09-30T18:20:00Z
1,500,515
<p>I haven't tested this code (insert smiley) but I think this is the sort of thing you need. Basically your credentials won't be in the header if your server hasn't bounced a 401 back to your client (the client needs to know the realm to know what credentials to provide).</p> <pre><code>class MYREALM_securepage(webapp.RequestHandler): def get(self): if not 'Authorization' in self.request.headers: self.response.headers['WWW-Authenticate'] = 'Basic realm="MYREALM"' self.response.set_status(401) self.response.out.write("Authorization required") else: auth = self.request.headers['Authorization'] (username, password) = base64.b64decode(auth.split(' ')[1]).split(':') # Check the username and password, and proceed ... </code></pre>
7
2009-09-30T20:36:30Z
[ "python", "google-app-engine", "web-applications" ]
Django: How to set initial values for a field in an inline model formset?
1,500,121
<p>I have what I think should be a simple problem. I have an inline model formset, and I'd like to make a select field have a default selected value of the currently logged in user. In the view, I'm using Django's Authentication middleware, so getting the user is a simple matter of accessing <code>request.user</code>. </p> <p>What I haven't been able to figure out, though, is how to set that user as the default selected value in a select box (ModelChoiceField) containing a list of users. Can anyone help me with this? </p>
7
2009-09-30T19:15:53Z
1,500,771
<p>I'm not sure how to handle this in inline formsets, but the following approach will work for normal Forms and ModelForms:</p> <p>You can't set this as part of the model definition, but you can set it during the form initialization:</p> <pre><code>def __init__(self, logged_in_user, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) self.fields['my_user_field'].initial = logged_in_user ... form = MyForm(request.user) </code></pre>
4
2009-09-30T21:32:18Z
[ "python", "django", "default-value", "django-forms" ]
Django: How to set initial values for a field in an inline model formset?
1,500,121
<p>I have what I think should be a simple problem. I have an inline model formset, and I'd like to make a select field have a default selected value of the currently logged in user. In the view, I'm using Django's Authentication middleware, so getting the user is a simple matter of accessing <code>request.user</code>. </p> <p>What I haven't been able to figure out, though, is how to set that user as the default selected value in a select box (ModelChoiceField) containing a list of users. Can anyone help me with this? </p>
7
2009-09-30T19:15:53Z
8,223,856
<p>This does the trick. It works by setting the initial values of all "extra" forms.</p> <pre><code>formset = MyFormset(instance=myinstance) user = request.user for form in formset.forms: if 'user' not in form.initial: form.initial['user'] = user.pk </code></pre>
3
2011-11-22T08:25:00Z
[ "python", "django", "default-value", "django-forms" ]
Django: How to set initial values for a field in an inline model formset?
1,500,121
<p>I have what I think should be a simple problem. I have an inline model formset, and I'd like to make a select field have a default selected value of the currently logged in user. In the view, I'm using Django's Authentication middleware, so getting the user is a simple matter of accessing <code>request.user</code>. </p> <p>What I haven't been able to figure out, though, is how to set that user as the default selected value in a select box (ModelChoiceField) containing a list of users. Can anyone help me with this? </p>
7
2009-09-30T19:15:53Z
31,100,197
<p>I'm using Rune Kaagaard's idea above, except I noticed that formsets provide an extra_forms property: <a href="https://docs.djangoproject.com/en/1.8/_modules/django/forms/formsets/" rel="nofollow">django.forms.formsets code</a></p> <pre><code>@property def extra_forms(self): """Return a list of all the extra forms in this formset.""" return self.forms[self.initial_form_count():] </code></pre> <p>So, sticking with the example above:</p> <pre><code>formset = MyFormset(instance=myinstance) user = request.user for form in formset.extra_forms: form.initial['user'] = user.pk </code></pre> <p>Saves having to test any initial forms, just provide default for extra forms.</p>
0
2015-06-28T13:11:48Z
[ "python", "django", "default-value", "django-forms" ]
How to tell when nosetest is running programmatically
1,500,214
<p><strong>nosetest</strong> is the default test framework in Turbogeras 2.0. The application has a websetup.py module that initialise the database. I use mysql for my development and production environment and websetup works fine, but <strong>nosetest</strong> uses sqlite on memory and when it tries to initialise the DB sends an error:</p> <blockquote> <p>TypeError: SQLite Date, Time, and DateTime types only accept Python datetime objects as input.</p> </blockquote> <p>I've detected when this happens and is in the import fase:</p> <pre><code>csvreader = csv.reader(open('res/products.csv'), delimiter=",", quotechar="'") for row in csvreader: p = model.Product(row[1], row[2], row[3], row[4] + ".jpg") # Even tried to convert the date to a sqlalchemy type # need to put a conditional here, when testing I don't care this date import sqlalchemy dateadded = sqlalchemy.types.DateTime(row[5]) p.dateAdded = dateadded p.brand_id = row[6] p.code = row[3] ccat = model.DBSession.query(model.Category)\ .filter(model.Category.id==int(row[8]) + 3).one() p.categories.append(ccat) p.normalPrice = row[9] p.specialPrice = row[10] p.discountPrice = row[11] model.DBSession.add(p) </code></pre> <p>How can I tell when nosetest is running? I've try:</p> <pre><code>if globals().has_key('ModelTest'): </code></pre> <p>and</p> <pre><code>if vars().has_key('ModelTest'): </code></pre> <p>The first one with no results and the second one with error</p>
0
2009-09-30T19:34:50Z
1,500,318
<p>I don't use TurboGears, but is there not a setting or global somewhere that indicates that the tests are running? In large systems, there are often small changes that need to be made when running tests. Switching between SQLite and MySQL is just one example.</p>
0
2009-09-30T19:55:57Z
[ "python", "sqlalchemy", "nosetests" ]
How to tell when nosetest is running programmatically
1,500,214
<p><strong>nosetest</strong> is the default test framework in Turbogeras 2.0. The application has a websetup.py module that initialise the database. I use mysql for my development and production environment and websetup works fine, but <strong>nosetest</strong> uses sqlite on memory and when it tries to initialise the DB sends an error:</p> <blockquote> <p>TypeError: SQLite Date, Time, and DateTime types only accept Python datetime objects as input.</p> </blockquote> <p>I've detected when this happens and is in the import fase:</p> <pre><code>csvreader = csv.reader(open('res/products.csv'), delimiter=",", quotechar="'") for row in csvreader: p = model.Product(row[1], row[2], row[3], row[4] + ".jpg") # Even tried to convert the date to a sqlalchemy type # need to put a conditional here, when testing I don't care this date import sqlalchemy dateadded = sqlalchemy.types.DateTime(row[5]) p.dateAdded = dateadded p.brand_id = row[6] p.code = row[3] ccat = model.DBSession.query(model.Category)\ .filter(model.Category.id==int(row[8]) + 3).one() p.categories.append(ccat) p.normalPrice = row[9] p.specialPrice = row[10] p.discountPrice = row[11] model.DBSession.add(p) </code></pre> <p>How can I tell when nosetest is running? I've try:</p> <pre><code>if globals().has_key('ModelTest'): </code></pre> <p>and</p> <pre><code>if vars().has_key('ModelTest'): </code></pre> <p>The first one with no results and the second one with error</p>
0
2009-09-30T19:34:50Z
1,509,700
<p>Presumably if nose is running, the 'nose' top-level module will have been imported. You should be able to test that with</p> <pre><code>if 'nose' in sys.modules: print "Nose is running, or at least has been imported!" #or whatever you need to do if nose is running </code></pre> <p>Of course this is not a foolproof test, which assumes that there's no other reason why nose would be imported.</p>
0
2009-10-02T14:01:57Z
[ "python", "sqlalchemy", "nosetests" ]
Programmatically determine maximum command line length with Python
1,500,542
<p>Does anyone know a portable way for Python to determine a system's maximum command line length? The program I'm working on builds a command and feeds it to subprocess. For systems with smaller command line length maximums, it is possible that the command will be too long. If I can detect that, the command can be broken up to avoid exceeding the maximum length, but I've not found a (portable) way to determine the maximum.</p>
0
2009-09-30T20:41:50Z
1,500,652
<p>Just ask sysconf:</p> <p><code></p> <pre> os.sysconf(os.sysconf_names['SC_ARG_MAX']) </pre> <p></code></p>
4
2009-09-30T21:02:42Z
[ "python", "command-line", "subprocess" ]
cProfile and Python: Finding the specific line number that code spends most time on
1,500,564
<p>I'm using cProfile, pstats and Gprof2dot to profile a rather long python script.</p> <p>The results tell me that the most time is spent calling a method in an object I've defined. However, what I would really like is to know exactly what line number within that function is eating up the time. </p> <p>Any idea's how to get this additional information?</p> <p>(By the way, I'm using Python 2.6 on OSX snow leopard if that helps...)</p>
5
2009-09-30T20:46:34Z
1,500,791
<p>Suppose the amount of time being "eaten up" is some number, like 40%. Then if you just interrupt the program or pause it at a random time, the probability is 40% that you will see it, precisely exposed on the call stack. Do this 10 times, and on 4 samples, +/-, you will see it.</p> <p><a href="http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024">This tells why it works.</a> <a href="http://stackoverflow.com/questions/1469679/understanding-python-profile-output/1472429#1472429">This is an example.</a></p>
0
2009-09-30T21:36:48Z
[ "python", "scripting", "numbers", "profiler", "line" ]
cProfile and Python: Finding the specific line number that code spends most time on
1,500,564
<p>I'm using cProfile, pstats and Gprof2dot to profile a rather long python script.</p> <p>The results tell me that the most time is spent calling a method in an object I've defined. However, what I would really like is to know exactly what line number within that function is eating up the time. </p> <p>Any idea's how to get this additional information?</p> <p>(By the way, I'm using Python 2.6 on OSX snow leopard if that helps...)</p>
5
2009-09-30T20:46:34Z
1,500,818
<p><code>cProfile</code> does not track line numbers within a function; it only tracks the line number of where the function was defined. </p> <p><code>cProfile</code> attempts to duplicate the behavior of <code>profile</code> (which is pure Python). <code>profile</code> uses <code>pstats</code> to store the data from running, and <code>pstats</code> only stores line numbers for function definitions, not for individual Python statements.</p> <p>If you need to figure out with finer granularity what is eating all your time, then you need to refactor your big function into several, smaller functions.</p>
2
2009-09-30T21:42:54Z
[ "python", "scripting", "numbers", "profiler", "line" ]
cProfile and Python: Finding the specific line number that code spends most time on
1,500,564
<p>I'm using cProfile, pstats and Gprof2dot to profile a rather long python script.</p> <p>The results tell me that the most time is spent calling a method in an object I've defined. However, what I would really like is to know exactly what line number within that function is eating up the time. </p> <p>Any idea's how to get this additional information?</p> <p>(By the way, I'm using Python 2.6 on OSX snow leopard if that helps...)</p>
5
2009-09-30T20:46:34Z
1,502,200
<p>There is a <a href="http://pypi.python.org/pypi/line%5Fprofiler/1.0b2" rel="nofollow">line profiler</a> in python written by Robert Kern.</p>
3
2009-10-01T06:25:22Z
[ "python", "scripting", "numbers", "profiler", "line" ]
Python XML Serializers
1,500,575
<p>Can some recommend an XML serializer that is element or attribute centric, and that doesn't use key-value pairs. </p> <p>For example, GAE db.model has a to_xml() function but it writes out like this: </p> <pre><code> &lt;property name="firstname" type="string"&gt;John&lt;/property&gt; &lt;property name="lastname" type="string"&gt;Doe&lt;/property&gt; &lt;property name="city" type="string"&gt;Dallas&lt;/property&gt; &lt;property name="dateTimeCreated" type="gd:when"&gt;2009-09-30 19:45:45.975270&lt;/property&gt; </code></pre> <p>From what I remember, these are much harder to map in XSLT tools than simple elements/attributes like this:</p> <p>DESIRED OUTPUT</p> <pre><code> &lt;firstname&gt;John&lt;/firstname&gt; &lt;lastname&gt;Doe&lt;/lastname&gt; &lt;city&gt;Dallas&lt;/city&gt; &lt;dateTimeCreated type="gd:when"&gt;2009-09-30 19:45:45.975270&lt;/dateTimeCreated&gt; </code></pre> <p>I just tried the GNOSIS lib, and my first attempt worked, but also created name value pairs something like this: </p> <pre><code> &lt;attr name="__coredata__" type="dict" id="4760164835402068688" &gt; &lt;entry&gt; &lt;key type="string"&gt;firstname&lt;/key&gt; &lt;val type="string"&gt;John&lt;/val&gt; &lt;/entry&gt; &lt;entry&gt; &lt;key type="string"&gt;lastname&lt;/key&gt; &lt;val type="string"&gt;Doe&lt;/val&gt; &lt;/entry&gt; etc... </code></pre> <p>Thanks,</p> <p>Neal Walters </p>
0
2009-09-30T20:47:56Z
1,501,536
<p><a href="http://www.strangegizmo.com/products/pyxslt/doc/pyxslt.serialize-module.html" rel="nofollow">pyxslt.serialize</a> looks closest to your specs but not a 100% map (for example, it doesn't record the type -- just turns everything into strings). Could still be a good basis from where to customize (maybe by copy / paste / edit, if it doesn't offer all the hooks you need for a cleaner customization).</p>
2
2009-10-01T01:56:24Z
[ "python", "xml-serialization" ]
What is the right way to override the copy/deepcopy operations on an object in Python?
1,500,718
<p>So just to establish, I feel like I understand the difference between copy vs. deepcopy in the copy module and I've used copy.copy and copy.deepcopy before successfully, but this is the first time I've actually gone about overloading the __copy__ and __deepcopy__ methods. I've already Googled around and looked through the built-in Python modules to look for instances of the __copy__ and __deepcopy__ functions (e.g. sets.py, decimal.py, and fractions.py), but I'm still not 100% sure I've got it right.</p> <p>Here's my scenario: </p> <p>I have a configuration object that mostly just consists of simple properties (though it will potentially have lists of other non-primitive objects in it). Initially I'm going to instantiate one configuration object with a default set of values. This configuration will be handed off to multiple other objects (to ensure all objects start with the same configuration). Once user interaction starts, however, each object will need to be able to tweak the configurations independently without affecting each other's configurations (which says to me I'll need to make deepcopys of my initial configuration to hand around).</p> <p>Here's a sample object:</p> <pre><code>class ChartConfig(object): def __init__(self): #Drawing properties (Booleans/strings) self.antialiased = None self.plot_style = None self.plot_title = None self.autoscale = None #X axis properties (strings/ints) self.xaxis_title = None self.xaxis_tick_rotation = None self.xaxis_tick_align = None #Y axis properties (strings/ints) self.yaxis_title = None self.yaxis_tick_rotation = None self.yaxis_tick_align = None #A list of non-primitive objects self.trace_configs = [] def __copy__(self): pass def __deepcopy__(self, memo): pass </code></pre> <p>What is the right way to implement the copy and deepcopy methods on this object to ensure copy.copy and copy.deepcopy give me the proper behavior? I'm currently using Python 2.6.2. </p> <p>Thanks in advance!</p>
32
2009-09-30T21:18:45Z
1,500,788
<p>I might be a bit off on the specifics, but here goes;</p> <p>From the <a href="http://docs.python.org/library/copy.html" rel="nofollow"><code>copy</code> docs</a>;</p> <blockquote> <ul> <li>A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.</li> <li>A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.</li> </ul> </blockquote> <p>In other words: <code>copy()</code> will copy only the top element and leave the rest as pointers into the original structure. <code>deepcopy()</code> will recursively copy over everything.</p> <p>That is, <code>deepcopy()</code> is what you need.</p> <p>If you need to do something really specific, you can override <code>__copy__()</code> or <code>__deepcopy__()</code>, as described in the manual. Personally, I'd probably implement a plain function (e.g. <code>config.copy_config()</code> or such) to make it plain that it isn't Python standard behaviour.</p>
2
2009-09-30T21:35:54Z
[ "python" ]
What is the right way to override the copy/deepcopy operations on an object in Python?
1,500,718
<p>So just to establish, I feel like I understand the difference between copy vs. deepcopy in the copy module and I've used copy.copy and copy.deepcopy before successfully, but this is the first time I've actually gone about overloading the __copy__ and __deepcopy__ methods. I've already Googled around and looked through the built-in Python modules to look for instances of the __copy__ and __deepcopy__ functions (e.g. sets.py, decimal.py, and fractions.py), but I'm still not 100% sure I've got it right.</p> <p>Here's my scenario: </p> <p>I have a configuration object that mostly just consists of simple properties (though it will potentially have lists of other non-primitive objects in it). Initially I'm going to instantiate one configuration object with a default set of values. This configuration will be handed off to multiple other objects (to ensure all objects start with the same configuration). Once user interaction starts, however, each object will need to be able to tweak the configurations independently without affecting each other's configurations (which says to me I'll need to make deepcopys of my initial configuration to hand around).</p> <p>Here's a sample object:</p> <pre><code>class ChartConfig(object): def __init__(self): #Drawing properties (Booleans/strings) self.antialiased = None self.plot_style = None self.plot_title = None self.autoscale = None #X axis properties (strings/ints) self.xaxis_title = None self.xaxis_tick_rotation = None self.xaxis_tick_align = None #Y axis properties (strings/ints) self.yaxis_title = None self.yaxis_tick_rotation = None self.yaxis_tick_align = None #A list of non-primitive objects self.trace_configs = [] def __copy__(self): pass def __deepcopy__(self, memo): pass </code></pre> <p>What is the right way to implement the copy and deepcopy methods on this object to ensure copy.copy and copy.deepcopy give me the proper behavior? I'm currently using Python 2.6.2. </p> <p>Thanks in advance!</p>
32
2009-09-30T21:18:45Z
1,500,887
<p>The recommendations for customizing are at the very end of the <a href="http://docs.python.org/library/copy.html">docs page</a>:</p> <blockquote> <p>Classes can use the same interfaces to control copying that they use to control pickling. See the description of module pickle for information on these methods. The copy module does not use the copy_reg registration module.</p> <p>In order for a class to define its own copy implementation, it can define special methods <code>__copy__()</code> and <code>__deepcopy__()</code>. The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the <code>__deepcopy__()</code> implementation needs to make a deep copy of a component, it should call the <code>deepcopy()</code> function with the component as first argument and the memo dictionary as second argument.</p> </blockquote> <p>Since you appear not to care about pickling customization, defining <code>__copy__</code> and <code>__deepcopy__</code> definitely seems like the right way to go for you.</p> <p>Specifically, <code>__copy__</code> (the shallow copy) is pretty easy in your case...:</p> <pre><code>def __copy__(self): newone = type(self)() newone.__dict__.update(self.__dict__) return newone </code></pre> <p><code>__deepcopy__</code> would be similar (accepting a <code>memo</code> arg too) but before the return it would have to call <code>self.foo = deepcopy(self.foo, memo)</code> for any attribute <code>self.foo</code> that needs deep copying (essentially attributes that are containers -- lists, dicts, non-primitive objects which hold other stuff through their <code>__dict__</code>s).</p>
26
2009-09-30T21:58:58Z
[ "python" ]
What is the right way to override the copy/deepcopy operations on an object in Python?
1,500,718
<p>So just to establish, I feel like I understand the difference between copy vs. deepcopy in the copy module and I've used copy.copy and copy.deepcopy before successfully, but this is the first time I've actually gone about overloading the __copy__ and __deepcopy__ methods. I've already Googled around and looked through the built-in Python modules to look for instances of the __copy__ and __deepcopy__ functions (e.g. sets.py, decimal.py, and fractions.py), but I'm still not 100% sure I've got it right.</p> <p>Here's my scenario: </p> <p>I have a configuration object that mostly just consists of simple properties (though it will potentially have lists of other non-primitive objects in it). Initially I'm going to instantiate one configuration object with a default set of values. This configuration will be handed off to multiple other objects (to ensure all objects start with the same configuration). Once user interaction starts, however, each object will need to be able to tweak the configurations independently without affecting each other's configurations (which says to me I'll need to make deepcopys of my initial configuration to hand around).</p> <p>Here's a sample object:</p> <pre><code>class ChartConfig(object): def __init__(self): #Drawing properties (Booleans/strings) self.antialiased = None self.plot_style = None self.plot_title = None self.autoscale = None #X axis properties (strings/ints) self.xaxis_title = None self.xaxis_tick_rotation = None self.xaxis_tick_align = None #Y axis properties (strings/ints) self.yaxis_title = None self.yaxis_tick_rotation = None self.yaxis_tick_align = None #A list of non-primitive objects self.trace_configs = [] def __copy__(self): pass def __deepcopy__(self, memo): pass </code></pre> <p>What is the right way to implement the copy and deepcopy methods on this object to ensure copy.copy and copy.deepcopy give me the proper behavior? I'm currently using Python 2.6.2. </p> <p>Thanks in advance!</p>
32
2009-09-30T21:18:45Z
15,774,013
<p>Putting together Alex Martelli's answer and Rob Young's comment you get the following code:</p> <pre><code>from copy import copy, deepcopy class A(object): def __init__(self): print 'init' self.v = 10 self.z = [2,3,4] def __copy__(self): cls = self.__class__ result = cls.__new__(cls) result.__dict__.update(self.__dict__) return result def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result for k, v in self.__dict__.items(): setattr(result, k, deepcopy(v, memo)) return result a = A() a.v = 11 b1, b2 = copy(a), deepcopy(a) a.v = 12 a.z.append(5) print b1.v, b1.z print b2.v, b2.z </code></pre> <p>prints</p> <pre><code>init 11 [2, 3, 4, 5] 11 [2, 3, 4] </code></pre> <p>here <code>__deepcopy__</code> fills in the <code>memo</code> dict to avoid excess copying in case the object itself is referenced from its member.</p>
24
2013-04-02T20:46:44Z
[ "python" ]
What is the right way to override the copy/deepcopy operations on an object in Python?
1,500,718
<p>So just to establish, I feel like I understand the difference between copy vs. deepcopy in the copy module and I've used copy.copy and copy.deepcopy before successfully, but this is the first time I've actually gone about overloading the __copy__ and __deepcopy__ methods. I've already Googled around and looked through the built-in Python modules to look for instances of the __copy__ and __deepcopy__ functions (e.g. sets.py, decimal.py, and fractions.py), but I'm still not 100% sure I've got it right.</p> <p>Here's my scenario: </p> <p>I have a configuration object that mostly just consists of simple properties (though it will potentially have lists of other non-primitive objects in it). Initially I'm going to instantiate one configuration object with a default set of values. This configuration will be handed off to multiple other objects (to ensure all objects start with the same configuration). Once user interaction starts, however, each object will need to be able to tweak the configurations independently without affecting each other's configurations (which says to me I'll need to make deepcopys of my initial configuration to hand around).</p> <p>Here's a sample object:</p> <pre><code>class ChartConfig(object): def __init__(self): #Drawing properties (Booleans/strings) self.antialiased = None self.plot_style = None self.plot_title = None self.autoscale = None #X axis properties (strings/ints) self.xaxis_title = None self.xaxis_tick_rotation = None self.xaxis_tick_align = None #Y axis properties (strings/ints) self.yaxis_title = None self.yaxis_tick_rotation = None self.yaxis_tick_align = None #A list of non-primitive objects self.trace_configs = [] def __copy__(self): pass def __deepcopy__(self, memo): pass </code></pre> <p>What is the right way to implement the copy and deepcopy methods on this object to ensure copy.copy and copy.deepcopy give me the proper behavior? I'm currently using Python 2.6.2. </p> <p>Thanks in advance!</p>
32
2009-09-30T21:18:45Z
24,621,200
<p>Its not clear from your problem why you need to override these methods, since you don't want to do any customization to the copying methods.</p> <p>Anyhow, if you do want to customize the deep copy (e.g. by sharing some attributes and copying others), here is a solution:</p> <pre><code>from copy import deepcopy def deepcopy_with_sharing(obj, shared_attribute_names, memo=None): ''' Deepcopy an object, except for a given list of attributes, which should be shared between the original object and its copy. obj is some object shared_attribute_names: A list of strings identifying the attributes that should be shared between the original and its copy. memo is the dictionary passed into __deepcopy__. Ignore this argument if not calling from within __deepcopy__. ''' assert isinstance(shared_attribute_names, (list, tuple)) shared_attributes = {k: getattr(obj, k) for k in shared_attribute_names} if hasattr(obj, '__deepcopy__'): # Do hack to prevent infinite recursion in call to deepcopy deepcopy_method = obj.__deepcopy__ obj.__deepcopy__ = None for attr in shared_attribute_names: del obj.__dict__[attr] clone = deepcopy(obj, memo) for attr, val in shared_attributes.iteritems(): setattr(obj, attr, val) setattr(clone, attr, val) if hasattr(obj, '__deepcopy__'): # Undo hack obj.__deepcopy__ = deepcopy_method return clone class A(object): def __init__(self): self.copy_me = [] self.share_me = [] def __deepcopy__(self, memo): return deepcopy_with_sharing(self, shared_attribute_names = ['share_me'], memo=memo) a = A() b = deepcopy(a) assert a.copy_me is not b.copy_me assert a.share_me is b.share_me </code></pre>
1
2014-07-07T22:53:32Z
[ "python" ]