content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to get list index and element simultaneously in Python? I find myself frequently writing code like this: k = 0 for i in mylist: # y[k] = some function of i k += 1 Instead, I could do for k in range(K): # y[k] = some function of mylist[k] but that doesn't seem "pythonic". (You know... indexing. Ick!) Is there some syntax that allows me to extract both the index (k) and the element (i) simultaneously using either a loop, list comprehension, or generator? The task is in scientific computing, so there is a lot of stuff in the loop body, making a list comprehension probably not powerful enough on its own, I think. I welcome tips on related concepts, too, that I might not have even though of. Thank you. A: You can use enumerate: for k,i in enumerate(mylist): #do something with index k #do something with element i More information about looping techniques. Edit: As pointed out in the comments, using other variable names like for i, item in enumerate(mylist): makes it easier to read and understand your code in the long run. Normally you should use i, j, k for numbers and meaningful variable names to describe elements of a list. I.e. if you have e.g. a list of books and iterate over it, then you should name the variable book. A: enumerate is the answer: for index, element in enumerate(iterable): #work with index and element
How to get list index and element simultaneously in Python?
I find myself frequently writing code like this: k = 0 for i in mylist: # y[k] = some function of i k += 1 Instead, I could do for k in range(K): # y[k] = some function of mylist[k] but that doesn't seem "pythonic". (You know... indexing. Ick!) Is there some syntax that allows me to extract both the index (k) and the element (i) simultaneously using either a loop, list comprehension, or generator? The task is in scientific computing, so there is a lot of stuff in the loop body, making a list comprehension probably not powerful enough on its own, I think. I welcome tips on related concepts, too, that I might not have even though of. Thank you.
[ "You can use enumerate:\nfor k,i in enumerate(mylist):\n #do something with index k\n #do something with element i\n\nMore information about looping techniques.\nEdit:\nAs pointed out in the comments, using other variable names like\nfor i, item in enumerate(mylist):\n\nmakes it easier to read and understand your code in the long run. Normally you should use i, j, k for numbers and meaningful variable names to describe elements of a list.\nI.e. if you have e.g. a list of books and iterate over it, then you should name the variable book.\n", "enumerate is the answer:\nfor index, element in enumerate(iterable):\n #work with index and element\n\n" ]
[ 62, 19 ]
[]
[]
[ "python" ]
stackoverflow_0002072407_python.txt
Q: "Real" and non-embedded use of Ruby, Python and their friends So I'm aware of the big ammount of general-purpose scripting languages like Ruby, Python, Perl, maybe even PHP, etc. that actually claim being usable for creating desktop applications too. I think my question can be answered clearly Are there actually companies using a special scripting language only to create their applications? Are there any real advantages on creating a product in a language like Python only? I'm not talking about the viability of those languages for web-development! Should I stick with C(++) for desktop apps? best regards, lamas A: The company I work for uses Perl and Tk with PerlApp to build executable packages to produce or major software application. Perl beats C and C++ for simplicity of code. You can do things in one line of Perl that take 20 lines of C. We've used WxPerl for a few smaller projects. We'd like to move fully to WxPerl, but existing code works, so the move has a low priority until Wx can give us something we need that Tk can't. Python is popular for building GUI apps, too. You may have heard about Chandler. That's a big Python app. There are many others as well. Ruby is also a suitable choice. PHP is breaking into the world of command line apps. I am not sure about the power or flexibility of its GUI toolkits. A: The languages you list aren't really scripting languages, as that tends to describe languages designed to work inside of a larger framework (like javascript) that provides its interface to the world. While you can certainly write scripts in those languages, each is a proper programming language (referred to as a dynamic or interpreted language, in contrast to compiled languages like C or C++). There are many mature gui toolkits for creating desktop apps with interpreted languages. A search for any of those languages with "gui" on SO will yield many results. The advantage of the languages you list are rapid development and concise code. The advantage of compiled languages is mainly speed, and deeper ties with the internals of the operating system. But for most desktop apps, the ease of development in an interpreted language outweighs any small performance gains (unless you are writing a cpu intensive app, in which case, write the cpu heavy bits in C, and then call them from the interpreted language, which can handle the gui) Many interpreted languages offer easy escapes to C or other languages (often with a nice inline syntax). I would encourage you to take a look at some examples on http://rosettacode.org to see the fundamental differences between how programs come together with the languages you are interested in. A: Python (combined with PyQt) is a very solid combination for GUI desktop applications (note that while QT is LGPL, PyQt (the Python bindings) is dual licensed: GPL or commercial). It offers the same (GUI library-wise) as Qt on C++ but with Python's specific strenghts. I'll list some of the more obvious ones: rapid prototyping extremely readable (hence maintainable) code Should I stick with C(++) for desktop apps? In general: no, unless you want to / need to (for a specific reason). A: I would recommend you not try to look for a language that is best for GUI apps but instead look for the language that you like the most and then use that to write your app. Ruby, Python, Perl all have GUI tool kits available to them. Most of them have access to the same often used tool kits like TK, GTK, and Wx. The look and feel of a an app will be dependent more on the GUI tool kit than on the language, and performance wise your likely to see more impact for how you write your app than language choice. If your comfortable with C++ then you should also look at C# or Java as options. While not scripting languages they have many of the same benefits like memory management and more sane string implementations. A: I have used a number of programs that were developed using scripted languages. Several embedded device vendors ship my group Windows-based configuration and debugging utilities written in TCL. Google's drawing program SketchUp has a lot of Ruby inside it (and users can create add-ons using Ruby). I have seen many Linux applications written in Python. There are many more examples out there, but often times finished applications are bundled up to the point where you can't really tell what's powering it on the inside. Yes, there can be advantages to working with scripted languages. Some scripted languages make it easier to do specific tasks; for example, text processing is much easier (IMO) in a language like Ruby that has regular expression support and a robust String class than it is in plain old C. Generating a UI using a scripted language may make it easier to support multiple platforms, as all the platform-specific code is taken care of inside the language interpreter or pre-compiled libraries. For example, our suppliers who build TCL-based apps claim they can build the UI for an app using TCL in a fraction of the time it would take them to build it in C++ or VB, and then they can port it to Linux almost effortlessly. On the other hand there are a few things that scripted languages typically aren't suited for, such as writing drivers or doing anything that requires low-level hardware access. Most importantly, however, is this: modern languages have become quite powerful to the point where choice of language doesn't make as big of a difference as it used to be. Use the language you are most comfortable with. The learning curve associated with learning a new language will usually have a much larger impact on your project. A: http://www.pygtk.org/applications.html Seems like a really long list of GUI applications in Python using just one of the frameworks. A: Some part of MPICH2 is written in Python. I didn't check everything, but many parts of it used for running mpi applications are written it Python. Maybe MPICH2 is not used by everyone, but for sure it is good piece of software.
"Real" and non-embedded use of Ruby, Python and their friends
So I'm aware of the big ammount of general-purpose scripting languages like Ruby, Python, Perl, maybe even PHP, etc. that actually claim being usable for creating desktop applications too. I think my question can be answered clearly Are there actually companies using a special scripting language only to create their applications? Are there any real advantages on creating a product in a language like Python only? I'm not talking about the viability of those languages for web-development! Should I stick with C(++) for desktop apps? best regards, lamas
[ "The company I work for uses Perl and Tk with PerlApp to build executable packages to produce or major software application.\nPerl beats C and C++ for simplicity of code. You can do things in one line of Perl that take 20 lines of C.\nWe've used WxPerl for a few smaller projects. We'd like to move fully to WxPerl, but existing code works, so the move has a low priority until Wx can give us something we need that Tk can't.\nPython is popular for building GUI apps, too. You may have heard about Chandler. That's a big Python app. There are many others as well.\nRuby is also a suitable choice.\nPHP is breaking into the world of command line apps. I am not sure about the power or flexibility of its GUI toolkits.\n", "The languages you list aren't really scripting languages, as that tends to describe languages designed to work inside of a larger framework (like javascript) that provides its interface to the world. While you can certainly write scripts in those languages, each is a proper programming language (referred to as a dynamic or interpreted language, in contrast to compiled languages like C or C++).\nThere are many mature gui toolkits for creating desktop apps with interpreted languages. A search for any of those languages with \"gui\" on SO will yield many results.\nThe advantage of the languages you list are rapid development and concise code.\nThe advantage of compiled languages is mainly speed, and deeper ties with the internals of the operating system. But for most desktop apps, the ease of development in an interpreted language outweighs any small performance gains (unless you are writing a cpu intensive app, in which case, write the cpu heavy bits in C, and then call them from the interpreted language, which can handle the gui)\nMany interpreted languages offer easy escapes to C or other languages (often with a nice inline syntax).\nI would encourage you to take a look at some examples on http://rosettacode.org to see the fundamental differences between how programs come together with the languages you are interested in.\n", "Python (combined with PyQt) is a very solid combination for GUI desktop applications (note that while QT is LGPL, PyQt (the Python bindings) is dual licensed: GPL or commercial).\nIt offers the same (GUI library-wise) as Qt on C++ but with Python's specific strenghts. I'll list some of the more obvious ones:\n\nrapid prototyping\nextremely readable (hence maintainable) code\n\nShould I stick with C(++) for desktop apps? \nIn general: no, unless you want to / need to (for a specific reason).\n", "I would recommend you not try to look for a language that is best for GUI apps but instead look for the language that you like the most and then use that to write your app.\nRuby, Python, Perl all have GUI tool kits available to them. Most of them have access to the same often used tool kits like TK, GTK, and Wx. The look and feel of a an app will be dependent more on the GUI tool kit than on the language, and performance wise your likely to see more impact for how you write your app than language choice.\nIf your comfortable with C++ then you should also look at C# or Java as options. While not scripting languages they have many of the same benefits like memory management and more sane string implementations.\n", "I have used a number of programs that were developed using scripted languages. Several embedded device vendors ship my group Windows-based configuration and debugging utilities written in TCL. Google's drawing program SketchUp has a lot of Ruby inside it (and users can create add-ons using Ruby). I have seen many Linux applications written in Python. There are many more examples out there, but often times finished applications are bundled up to the point where you can't really tell what's powering it on the inside.\nYes, there can be advantages to working with scripted languages. Some scripted languages make it easier to do specific tasks; for example, text processing is much easier (IMO) in a language like Ruby that has regular expression support and a robust String class than it is in plain old C. Generating a UI using a scripted language may make it easier to support multiple platforms, as all the platform-specific code is taken care of inside the language interpreter or pre-compiled libraries. For example, our suppliers who build TCL-based apps claim they can build the UI for an app using TCL in a fraction of the time it would take them to build it in C++ or VB, and then they can port it to Linux almost effortlessly.\nOn the other hand there are a few things that scripted languages typically aren't suited for, such as writing drivers or doing anything that requires low-level hardware access.\nMost importantly, however, is this: modern languages have become quite powerful to the point where choice of language doesn't make as big of a difference as it used to be. Use the language you are most comfortable with. The learning curve associated with learning a new language will usually have a much larger impact on your project.\n", "http://www.pygtk.org/applications.html\nSeems like a really long list of GUI applications in Python using just one of the frameworks.\n", "Some part of MPICH2 is written in Python. I didn't check everything, but many parts of it used for running mpi applications are written it Python. Maybe MPICH2 is not used by everyone, but for sure it is good piece of software. \n" ]
[ 6, 4, 3, 2, 1, 0, 0 ]
[]
[]
[ "perl", "python", "ruby", "scripting" ]
stackoverflow_0002067907_perl_python_ruby_scripting.txt
Q: Python thread for pre-importing modules I am writing a Python application in the field of scientific computing. Currently, when the user works with the GUI and starts a new physics simulation, the interpreter immediately imports several necessary modules for this simulation, such as Traits and Mayavi. These modules are heavy and take too long to import, and the user has to wait ~10 seconds before he can continue, which is bad. I thought of something that might remedy this. I'll describe it and perhaps someone else has already implemented it, if so please give me a link. If not I might do it myself. What I want is a separate thread that will import modules asynchronously. It will probably be a subclass of threading.Thread. Here's a usage example: importer_thread = ImporterThread() importer_thread.start() # ... importer_thread.import('Mayavi') importer_thread.import('Traits') # A thread-safe method that will put the module name # into a queue which the thread in an inifine loop # ... # When the user actually needs the modules: import Mayavi, Traits # If they were already loaded by importer_thread, we're good. # If not, we'll just have to wait as usual. So do you know of anything like this? If not, do you have any suggestions about the design? A: The problem with this is that the imports must still complete before they are usable. Depending on when they're first used, the application could still have to block for 10 seconds before it could start up anyway. Much more productive would be to profile the modules and figure out why they take so long to import. A: Why not just do this when the app starts? def background_imports(): import Traits import Mayavi thread = threading.Thread(target=background_imports) thread.setDaemon(True) thread.start() A: The general idea is good, but the Python/GUI session might not be all that responsive while the background thread is importing away; unfortunately, import inherently and inevitably "locks up" Python substantially (it's not just the GIL, there's specific extra locking for imports). Still worth trying, as it might make things a bit better -- it's also very easy, since Queues are intrinsically thread-safe and, besides a Queue's put and get, all you need is basically an __import__. Still, don't be surprised if this doesn't help enough and you still need extra oomph. If you have some drive that's intrinsically very fast, but with limited space, such as a "RAM drive" or a particularly snippy solid-state one, it may be worth keeping the needed packages in a .tar.bz2 (or other form of archive) and unpacking it onto the fast drive at program start (that's essentially just I/O and so it won't lock things up badly -- I/O operations rapidly release the GIL -- and also it's especially easy to delegate to a subprocess running tar xjf or the like). If some of the import slowness is due to a huge number of .py/.pyc/.pyo files, it's worth a try to keep those (in .pyc form only, not as .py) in a zipfile and importing from there (but that only helps with the I/O overhead, depending on your OS, filesystem, and drive: doesn't help with delays due to loading huge DLLs or executing initialization code in packages at load time, which I suspect are likelier culprits for the slowness). You could also consider splitting the application up with multiprocessing -- again using Queues (but of the multiprocessing kind) to communicate -- so that both imports and some heavy computations are delegated to a few auxiliary processes and thus made asynchronous (this may also help fully exploiting multiple cores at once). I suspect this may unfortunately be hard to arrange properly for visualization tasks (such as those you're presumably doing with mayavi) but it might help if you also have some "pure heavy computation" packages and tasks.
Python thread for pre-importing modules
I am writing a Python application in the field of scientific computing. Currently, when the user works with the GUI and starts a new physics simulation, the interpreter immediately imports several necessary modules for this simulation, such as Traits and Mayavi. These modules are heavy and take too long to import, and the user has to wait ~10 seconds before he can continue, which is bad. I thought of something that might remedy this. I'll describe it and perhaps someone else has already implemented it, if so please give me a link. If not I might do it myself. What I want is a separate thread that will import modules asynchronously. It will probably be a subclass of threading.Thread. Here's a usage example: importer_thread = ImporterThread() importer_thread.start() # ... importer_thread.import('Mayavi') importer_thread.import('Traits') # A thread-safe method that will put the module name # into a queue which the thread in an inifine loop # ... # When the user actually needs the modules: import Mayavi, Traits # If they were already loaded by importer_thread, we're good. # If not, we'll just have to wait as usual. So do you know of anything like this? If not, do you have any suggestions about the design?
[ "The problem with this is that the imports must still complete before they are usable. Depending on when they're first used, the application could still have to block for 10 seconds before it could start up anyway. Much more productive would be to profile the modules and figure out why they take so long to import.\n", "Why not just do this when the app starts?\ndef background_imports():\n import Traits\n import Mayavi\n\nthread = threading.Thread(target=background_imports)\nthread.setDaemon(True)\nthread.start()\n\n", "The general idea is good, but the Python/GUI session might not be all that responsive while the background thread is importing away; unfortunately, import inherently and inevitably \"locks up\" Python substantially (it's not just the GIL, there's specific extra locking for imports).\nStill worth trying, as it might make things a bit better -- it's also very easy, since Queues are intrinsically thread-safe and, besides a Queue's put and get, all you need is basically an __import__. Still, don't be surprised if this doesn't help enough and you still need extra oomph.\nIf you have some drive that's intrinsically very fast, but with limited space, such as a \"RAM drive\" or a particularly snippy solid-state one, it may be worth keeping the needed packages in a .tar.bz2 (or other form of archive) and unpacking it onto the fast drive at program start (that's essentially just I/O and so it won't lock things up badly -- I/O operations rapidly release the GIL -- and also it's especially easy to delegate to a subprocess running tar xjf or the like).\nIf some of the import slowness is due to a huge number of .py/.pyc/.pyo files, it's worth a try to keep those (in .pyc form only, not as .py) in a zipfile and importing from there (but that only helps with the I/O overhead, depending on your OS, filesystem, and drive: doesn't help with delays due to loading huge DLLs or executing initialization code in packages at load time, which I suspect are likelier culprits for the slowness).\nYou could also consider splitting the application up with multiprocessing -- again using Queues (but of the multiprocessing kind) to communicate -- so that both imports and some heavy computations are delegated to a few auxiliary processes and thus made asynchronous (this may also help fully exploiting multiple cores at once). I suspect this may unfortunately be hard to arrange properly for visualization tasks (such as those you're presumably doing with mayavi) but it might help if you also have some \"pure heavy computation\" packages and tasks.\n" ]
[ 2, 2, 1 ]
[ "\"the user works with the GUI and starts a new physics simulation\"\nNot really clear. Does \"works with the GUI\" means double click? Double click what? Some wxWidgets GUI application? Or IDLE? \nIf so, what does \"starts a new physics simulation\" mean? Click a button somewhere else? A GUI button to bring up a panel where they write code? Or do they import a script they wrote off line?\nWhy is the import happening before the simulation starts? How long does a simulation take? What does the GUI show?\nI suspect that there's a way to be much, much lazier in doing the big imports. But from the description, it's hard to determine if there's a point in time where the import doesn't matter as much to the user.\nThreads don't help much. What helps is rethinking the UI experience.\n" ]
[ -1 ]
[ "import", "multithreading", "python" ]
stackoverflow_0002071786_import_multithreading_python.txt
Q: '%s' % 'somestring' Here are a couple of examples taken from django-basic-apps: # self.title is a unicode string already def __unicode__(self): return u'%s' % self.title # 'q' is a string search_term = '%s' % request.GET['q'] What's the point of this string formatting? A: It's just a habit of mine. In these cases it's not necessary. A: At first glance, it doesn't look sensible, but it does have the benefit of forcing the result to be a string (or unicode string), rather than whatever it might have been from before. Another way to do the same thing might be to call str on the format argument (or unicode). A: You're probably better off asking Nathan Borror, the author. It may just be a personal style. Django does use proxy objects for strings in some cases though, so it may be to force them to "actual" strings. I believe these proxies are for i18n/l10n purposes (don't quote me on that, could also be to avoid db lookups until needed, or a number of other reasons). A: Maybe the author is used to strictly typed languages and he misses it in python and this is his way to make python more strictly typed than it is. Here - to make the types of input/output parameters clear only for the reader because provided all is working as expected it is just useless for the python itself. A: Another idea: Maybe this is done with possible future implementations in mind? self.title and request.GET[…] are currently already of the desired type, but implementation details might change in the future, and they might stop being a unicode string or a string. Now, I would have used str() and unicode(), though…
'%s' % 'somestring'
Here are a couple of examples taken from django-basic-apps: # self.title is a unicode string already def __unicode__(self): return u'%s' % self.title # 'q' is a string search_term = '%s' % request.GET['q'] What's the point of this string formatting?
[ "It's just a habit of mine. In these cases it's not necessary.\n", "At first glance, it doesn't look sensible, but it does have the benefit of forcing the result to be a string (or unicode string), rather than whatever it might have been from before. Another way to do the same thing might be to call str on the format argument (or unicode).\n", "You're probably better off asking Nathan Borror, the author. It may just be a personal style.\nDjango does use proxy objects for strings in some cases though, so it may be to force them to \"actual\" strings. I believe these proxies are for i18n/l10n purposes (don't quote me on that, could also be to avoid db lookups until needed, or a number of other reasons).\n", "Maybe the author is used to strictly typed languages and he misses it in python and this is his way to make python more strictly typed than it is. \nHere - to make the types of input/output parameters clear only for the reader because provided all is working as expected it is just useless for the python itself.\n", "Another idea: Maybe this is done with possible future implementations in mind? self.title and request.GET[…] are currently already of the desired type, but implementation details might change in the future, and they might stop being a unicode string or a string.\nNow, I would have used str() and unicode(), though…\n" ]
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002069362_django_python.txt
Q: Django Views Join Models Using Foreign Key I have the following models defined: class Player(models.Model): Team = models.ForeignKey(Team) Name = models.CharField(max_length=200) Position = models.CharField(max_length=3) ... snip ... What I would like to output in a view is a list of players who are in the team with id = 1. I have tried things such as: {% for player in userTeam.userTeamSquad %} <tr><td>{{ player.Name }}</td><td> {{ player.Position }}</td></tr> {% endfor %} But can't get it right. A: You need a view that looks something like this: def players(request): players_in_team_one = Player.objects.filter(Team__pk = 1) return render_to_response('players.html', {'players': players_in_team_one}) and you can loop through it like this in players.html: {% for player in players %} <tr><td>{{ player.Name }}</td><td> {{ player.Position }}</td></tr> {% endfor %} p.s. As a matter of style, it's more standard to use all_lowercase_names_with_underscores as field names.
Django Views Join Models Using Foreign Key
I have the following models defined: class Player(models.Model): Team = models.ForeignKey(Team) Name = models.CharField(max_length=200) Position = models.CharField(max_length=3) ... snip ... What I would like to output in a view is a list of players who are in the team with id = 1. I have tried things such as: {% for player in userTeam.userTeamSquad %} <tr><td>{{ player.Name }}</td><td> {{ player.Position }}</td></tr> {% endfor %} But can't get it right.
[ "You need a view that looks something like this:\ndef players(request):\n players_in_team_one = Player.objects.filter(Team__pk = 1)\n return render_to_response('players.html', {'players': players_in_team_one})\n\nand you can loop through it like this in players.html:\n{% for player in players %}\n <tr><td>{{ player.Name }}</td><td> {{ player.Position }}</td></tr>\n{% endfor %}\n\np.s. As a matter of style, it's more standard to use all_lowercase_names_with_underscores as field names.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002072966_django_python.txt
Q: Need help with python list manipulation i have two seperate lists list1 = ["Infantry","Tanks","Jets"] list2 = [ 10, 20, 30] so in reality, I have 10 Infantry, 20 Tanks and 30 Jets I want to create a class so that in the end, I can call this: for unit in units: print unit.amount print unit.name #and it will produce: # 10 Infantry # 20 Tanks # 30 Jets so the goal is to sort of combine list1 and list2 into a class that can be easily called. been trying many combinations for the past 3 hrs, nothing good turned out :( A: class Unit(object): def __init__(self, amount, name): self.amount = amount self.name = name units = [Unit(a, n) for (a, n) in zip(list2, list1)] A: from collections import namedtuple Unit = namedtuple("Unit", "name, amount") units = [Unit(*v) for v in zip(list1, list2)] for unit in units: print "%4d %s" % (unit.amount, unit.name) Alex pointed out a few details before I could. A: This should do it: class Unit: """Very simple class to track a unit name, and an associated count.""" def __init__(self, name, amount): self.name = name self.amount = amount # Pre-existing lists of types and amounts. list1 = ["Infantry", "Tanks", "Jets"] list2 = [ 10, 20, 30] # Create a list of Unit objects, and initialize using # pairs from the above lists. units = [] for a, b in zip(list1, list2): units.append(Unit(a, b)) A: In Python 2.6, I'd recommend a named tuple -- less code than writing the simple class out and very frugal in memory use too: import collections Unit = collections.namedtuple('Unit', 'amount name') units = [Unit(a, n) for a, n in zip(list2, list1)] When a class has a fixed set of fields (doesn't need its instances to be "expandable" with new arbitrary fields per-instance) and no specific "behavior" (i.e., no specific methods necessary), consider using a named tuple type instead (alas, not available in Python 2.5 or earlier, if you're stuck with that;-). A: How about a dictionary: units = dict(zip(list1,list2)) for type,amount in units.iteritems(): print amount,type Endlessly expandable for additional information, and easily manipulated. If a basic type will do the job, think carefully about not using it.
Need help with python list manipulation
i have two seperate lists list1 = ["Infantry","Tanks","Jets"] list2 = [ 10, 20, 30] so in reality, I have 10 Infantry, 20 Tanks and 30 Jets I want to create a class so that in the end, I can call this: for unit in units: print unit.amount print unit.name #and it will produce: # 10 Infantry # 20 Tanks # 30 Jets so the goal is to sort of combine list1 and list2 into a class that can be easily called. been trying many combinations for the past 3 hrs, nothing good turned out :(
[ "class Unit(object):\n def __init__(self, amount, name):\n self.amount = amount\n self.name = name\n\nunits = [Unit(a, n) for (a, n) in zip(list2, list1)]\n\n", "from collections import namedtuple\n\nUnit = namedtuple(\"Unit\", \"name, amount\")\nunits = [Unit(*v) for v in zip(list1, list2)]\n\nfor unit in units:\n print \"%4d %s\" % (unit.amount, unit.name)\n\nAlex pointed out a few details before I could.\n", "This should do it:\nclass Unit:\n \"\"\"Very simple class to track a unit name, and an associated count.\"\"\"\n def __init__(self, name, amount):\n self.name = name\n self.amount = amount\n\n# Pre-existing lists of types and amounts. \nlist1 = [\"Infantry\", \"Tanks\", \"Jets\"]\nlist2 = [ 10, 20, 30]\n\n# Create a list of Unit objects, and initialize using\n# pairs from the above lists. \nunits = []\nfor a, b in zip(list1, list2):\n units.append(Unit(a, b))\n\n", "In Python 2.6, I'd recommend a named tuple -- less code than writing the simple class out and very frugal in memory use too:\nimport collections\n\nUnit = collections.namedtuple('Unit', 'amount name')\n\nunits = [Unit(a, n) for a, n in zip(list2, list1)]\n\nWhen a class has a fixed set of fields (doesn't need its instances to be \"expandable\" with new arbitrary fields per-instance) and no specific \"behavior\" (i.e., no specific methods necessary), consider using a named tuple type instead (alas, not available in Python 2.5 or earlier, if you're stuck with that;-).\n", "How about a dictionary:\nunits = dict(zip(list1,list2))\n\nfor type,amount in units.iteritems():\n print amount,type\n\nEndlessly expandable for additional information, and easily manipulated. If a basic type will do the job, think carefully about not using it.\n" ]
[ 18, 8, 5, 5, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002072936_list_python.txt
Q: Python class methods I have a class as follows: class X: def __init__(self): self.sum_x =0.0 self.sum_x_squared=0.0 self.var_x =0.0 self.sum_y =0.0 self.sum_y_squared=0.0 self.var_y =0.0 def update(self,data): [x,y,vx,vy]=data self.update_sums(self.sum_x,self.sum_x_squared,x) self.update_sums(self.sum_y,self.sum_y_squared,y) . def update_sums(self,sums,squares,val): sums += val squares += val*val . I would like to pass the member variables sum_x, sum_x_squared etc to the update_sums function for update how do I do this, I am confused. Thanks A: First, note that your question has nothing to do with classmethod (which makes class methods in Python) -- it's entirely about normal instance methods (you should edit your title... or your question, if you do mean it to be about class methods). For the Q as it stands, the only way to do what you want is to pass the names of the attributes that the method needs to set (or enough data to let the method reconstruct the names), e.g.: def update(self,data): x, y, vx, vy = data self.update_sums('x' , x) self.update_sums('y' , y) def update_sums(self, attname, val): sums = 'sum_' + attname setattr(self, sums, getattr(self, sums, 0) + val) sums = 'sum_' + attname + '_squared' setattr(self, sums, getattr(self, sums, 0) + val * val) I would not recommend this approach, in general, as it makes code bulkier, less readable, and marginally less efficient than the elementary approach of just hard-coding the attribute names. If the auxiliary method (here update_sums) encapsulates a lot of tricky logic that you're really very keen to avoid duplicating, maybe; but while eliminating repetition is a very worthwhile task, it takes taste and balance to avoid going overboard with it;-). A: you don't need to pass nothing but the self, which you're mandated to do anyway: def update_sums(self, val): self.sum += val self.sum_squared += val * val ... the call will be the following: self.update_sums(x) The way you designed the class so far is not very useful or flexible, I'd suggest something along these lines: class X: def __init__(self): self.sums = [0] * 4 self.sums_squared = [0] * 4 def update(self, data): self.update_sums(data) def update_sums(self, vals): self.sums = [i + j for i, j in zip(self.sums, vals)] self.sums_squared = [i + j*j for i, j in zip(self.sums, vals)] It's still no ideal, because I don't know what the purpose of this whole thing is, but it's better then to have all those values. A: No need. You have direct access to self.sumx, etc. Are you sure that the functions do belong to the class X? You seem to be missing semicolon and whitespace formatting. A: You don't have to pass them, update_sums can access them just like update can. A: It looks to me like there is another class in there wanting to be let out. I would remove duplication by refactoring the code like this: class SumOfSquares(object): def __init__(self): self.sum = 0.0 self.squares = 0.0 def update(self, val): self.sum += val self.squares += val * val class X(object): def __init__(self): self.x = SumOfSquares() self.y = SumOfSquares() def update(self,data): [x,y,vx,vy]=data self.x.update(x) self.y.update(y) A: self.sumx, self.sum_x_squared?
Python class methods
I have a class as follows: class X: def __init__(self): self.sum_x =0.0 self.sum_x_squared=0.0 self.var_x =0.0 self.sum_y =0.0 self.sum_y_squared=0.0 self.var_y =0.0 def update(self,data): [x,y,vx,vy]=data self.update_sums(self.sum_x,self.sum_x_squared,x) self.update_sums(self.sum_y,self.sum_y_squared,y) . def update_sums(self,sums,squares,val): sums += val squares += val*val . I would like to pass the member variables sum_x, sum_x_squared etc to the update_sums function for update how do I do this, I am confused. Thanks
[ "First, note that your question has nothing to do with classmethod (which makes class methods in Python) -- it's entirely about normal instance methods (you should edit your title... or your question, if you do mean it to be about class methods).\nFor the Q as it stands, the only way to do what you want is to pass the names of the attributes that the method needs to set (or enough data to let the method reconstruct the names), e.g.:\ndef update(self,data):\n x, y, vx, vy = data\n self.update_sums('x' , x)\n self.update_sums('y' , y)\n\ndef update_sums(self, attname, val):\n sums = 'sum_' + attname\n setattr(self, sums, getattr(self, sums, 0) + val)\n sums = 'sum_' + attname + '_squared'\n setattr(self, sums, getattr(self, sums, 0) + val * val)\n\nI would not recommend this approach, in general, as it makes code bulkier, less readable, and marginally less efficient than the elementary approach of just hard-coding the attribute names. If the auxiliary method (here update_sums) encapsulates a lot of tricky logic that you're really very keen to avoid duplicating, maybe; but while eliminating repetition is a very worthwhile task, it takes taste and balance to avoid going overboard with it;-).\n", "you don't need to pass nothing but the self, which you're mandated to do anyway:\ndef update_sums(self, val):\n self.sum += val\n self.sum_squared += val * val\n ...\n\nthe call will be the following: self.update_sums(x)\nThe way you designed the class so far is not very useful or flexible, I'd suggest something along these lines:\nclass X:\n def __init__(self):\n self.sums = [0] * 4\n self.sums_squared = [0] * 4\n\n def update(self, data):\n self.update_sums(data)\n\n def update_sums(self, vals):\n self.sums = [i + j for i, j in zip(self.sums, vals)]\n self.sums_squared = [i + j*j for i, j in zip(self.sums, vals)]\n\nIt's still no ideal, because I don't know what the purpose of this whole thing is, but it's better then to have all those values.\n", "No need. You have direct access to self.sumx, etc.\nAre you sure that the functions do belong to the class X? You seem to be missing semicolon and whitespace formatting.\n", "You don't have to pass them, update_sums can access them just like update can.\n", "It looks to me like there is another class in there wanting to be let out. I would remove duplication by refactoring the code like this:\nclass SumOfSquares(object):\n def __init__(self):\n self.sum = 0.0\n self.squares = 0.0\n\n def update(self, val):\n self.sum += val\n self.squares += val * val\n\nclass X(object):\n def __init__(self):\n self.x = SumOfSquares()\n self.y = SumOfSquares()\n\n def update(self,data):\n [x,y,vx,vy]=data\n self.x.update(x)\n self.y.update(y)\n\n", "self.sumx, self.sum_x_squared?\n" ]
[ 5, 2, 1, 1, 1, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002072875_oop_python.txt
Q: Django error opening SQLite3 db file on when running off Apache I got this error: OperationalError at / unable to open database file Things I've tried so far are setting the absolute path of my dev.db file in the settings.py. I've tried adding www-data to my admin group and setting the group of my project folder to the admin, and setting the group to www-data, none of which solved the problem. I'm completely stuck here, if anyone has a solution it would be MUCH appreciated! Shawn A: Just passed the last 30 minutes banging my head on this problem .. Solution In your settings.py: DATABASE_NAME = '/absolute/path/to/your/database.db' Setting rights: chown www-data /absolute/path/to/your/ chown www-data /absolute/path/to/your/database.db
Django error opening SQLite3 db file on when running off Apache
I got this error: OperationalError at / unable to open database file Things I've tried so far are setting the absolute path of my dev.db file in the settings.py. I've tried adding www-data to my admin group and setting the group of my project folder to the admin, and setting the group to www-data, none of which solved the problem. I'm completely stuck here, if anyone has a solution it would be MUCH appreciated! Shawn
[ "Just passed the last 30 minutes banging my head on this problem ..\nSolution\nIn your settings.py:\nDATABASE_NAME = '/absolute/path/to/your/database.db'\n\nSetting rights:\nchown www-data /absolute/path/to/your/\nchown www-data /absolute/path/to/your/database.db\n\n" ]
[ 8 ]
[]
[]
[ "django", "python", "sqlite", "ubuntu" ]
stackoverflow_0001733050_django_python_sqlite_ubuntu.txt
Q: Access to widget in GTK+ Building a GTK+ widget dynamically from code allows for easy access to the child widgets directly. Now, how do I access to the child widgets when building a GTK+ Dialog (as example) from a .glade file? class ConfigDialog(object): def __init__(self, glade_file, testing=False): self.testing=testing builder = gtk.Builder() builder.add_from_file(glade_file) self.dialog = builder.get_object("config_dialog") self.dialog._testing=testing self.dialog._builder=builder I've tinkering a bit with .get_internal_child without success. Q: let's say I want to access the widget named "name_entry", how would I go about it? A: Already you are making the call self.dialog = builder.get_object("config_dialog") You should also be able to do self.nameEntry = builder.get_object("name_entry") This is at least how python-glade works and I assume GtkBuilder is the same. A: In addition, if you want to search for a named widget and the Builder instance isn't available, you could try using the following utility function: def get_child_by_name(parent, name): """ Iterate through a gtk container, `parent`, and return the widget with the name `name`. """ def iterate_children(widget, name): if widget.get_name() == name: return widget try: for w in widget.get_children(): result = iterate_children(w, name) if result is not None: return result else: continue except AttributeError: pass return iterate_children(parent, name)
Access to widget in GTK+
Building a GTK+ widget dynamically from code allows for easy access to the child widgets directly. Now, how do I access to the child widgets when building a GTK+ Dialog (as example) from a .glade file? class ConfigDialog(object): def __init__(self, glade_file, testing=False): self.testing=testing builder = gtk.Builder() builder.add_from_file(glade_file) self.dialog = builder.get_object("config_dialog") self.dialog._testing=testing self.dialog._builder=builder I've tinkering a bit with .get_internal_child without success. Q: let's say I want to access the widget named "name_entry", how would I go about it?
[ "Already you are making the call\nself.dialog = builder.get_object(\"config_dialog\")\n\nYou should also be able to do\nself.nameEntry = builder.get_object(\"name_entry\")\n\nThis is at least how python-glade works and I assume GtkBuilder is the same.\n", "In addition, if you want to search for a named widget and the Builder instance isn't available, you could try using the following utility function:\ndef get_child_by_name(parent, name):\n \"\"\"\n Iterate through a gtk container, `parent`, \n and return the widget with the name `name`.\n \"\"\"\n def iterate_children(widget, name):\n if widget.get_name() == name:\n return widget\n try:\n for w in widget.get_children():\n result = iterate_children(w, name)\n if result is not None:\n return result\n else:\n continue\n except AttributeError:\n pass\n return iterate_children(parent, name)\n\n" ]
[ 7, 4 ]
[]
[]
[ "gtk", "python" ]
stackoverflow_0002072976_gtk_python.txt
Q: How to draw complement of a network graph? Any function in that Graphviz which can do that? If not, any other free software that can do that? A: Given that you want to render your graphs in graphviz, i suggest using the python library, networkx, to calculate graph complement. Networkx is an excellent library for graph theoretic analysis; it also has a seamless interface with graphviz. (Rough definition of a graph complement: imagine a graph A', which has the identical nodes as A but that has all possible edges, i.e., every node is connected to every other node; now remove from A' the edges in A; what's left is the complement of A, A') import networkx as NX G = NX.gnm_random_graph(10, 10) # create a random graph w/ 10 nodes, 10 edges G_cmpl = NX.complement(G) # get the complement of graph 'G' # to render it in graphviz: NX.write_dot(G_cmpl, "somefilename.dot") A: Compute the complement yourself, then plot it.
How to draw complement of a network graph?
Any function in that Graphviz which can do that? If not, any other free software that can do that?
[ "Given that you want to render your graphs in graphviz, i suggest using the python library, networkx, to calculate graph complement. Networkx is an excellent library for graph theoretic analysis; it also has a seamless interface with graphviz.\n(Rough definition of a graph complement: imagine a graph A', which has the identical nodes as A but that has all possible edges, i.e., every node is connected to every other node; now remove from A' the edges in A; what's left is the complement of A, A')\nimport networkx as NX\nG = NX.gnm_random_graph(10, 10) # create a random graph w/ 10 nodes, 10 edges\nG_cmpl = NX.complement(G) # get the complement of graph 'G'\n\n# to render it in graphviz:\nNX.write_dot(G_cmpl, \"somefilename.dot\")\n\n", "Compute the complement yourself, then plot it.\n" ]
[ 5, 0 ]
[]
[]
[ "complement", "graph", "graphviz", "plot", "python" ]
stackoverflow_0002066259_complement_graph_graphviz_plot_python.txt
Q: Use function from Python script in OS path I have a third-party Python script (foo.py) in a folder that is in my system path (but not the Python sys.path). foo.py is not part of any Python module. I am writing another script (bar.py) in which I'd like to call a function located in foo.py. Is this possible? Can it be done without explicitly naming the folder of foo.py? Thanks. A: You can include the path of foo.py in the PYTHONPATH environment variable. The interpreter will look also the directories contained there, so you can make the import just like it was on the same directory. A: If Python does not find the module, I don't think there's another way then to specify where it can be found, with one easy way being: import sys sys.path.append('/myfolder/itsinthisfolder/') import foo
Use function from Python script in OS path
I have a third-party Python script (foo.py) in a folder that is in my system path (but not the Python sys.path). foo.py is not part of any Python module. I am writing another script (bar.py) in which I'd like to call a function located in foo.py. Is this possible? Can it be done without explicitly naming the folder of foo.py? Thanks.
[ "You can include the path of foo.py in the PYTHONPATH environment variable. The interpreter will look also the directories contained there, so you can make the import just like it was on the same directory.\n", "If Python does not find the module, I don't think there's another way then to specify where it can be found, with one easy way being:\nimport sys\nsys.path.append('/myfolder/itsinthisfolder/')\n\nimport foo\n\n" ]
[ 2, 2 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002074071_import_python.txt
Q: Finding python.exe programmatically in python Possible Duplicate: Getting python.exe path at run time I have a python app that launches other apps with explicit calls to C:\python25\python.exe, but this doesn't work if the user has 2.6 installed or if they have it installed to another location. There is a %PYTHON% variable for the exe, but this is only available to the user who installed Python (other users don't have this envvar set). Is there another way to look up this location? A: import sys print sys.executable A: >>> import sys >>> sys.executable 'C:\\Program Files\\Python31\\pythonw.exe' A: Consider using execfile. This executes the script you want using the same python instance that's already running.
Finding python.exe programmatically in python
Possible Duplicate: Getting python.exe path at run time I have a python app that launches other apps with explicit calls to C:\python25\python.exe, but this doesn't work if the user has 2.6 installed or if they have it installed to another location. There is a %PYTHON% variable for the exe, but this is only available to the user who installed Python (other users don't have this envvar set). Is there another way to look up this location?
[ "import sys\nprint sys.executable\n\n", ">>> import sys\n>>> sys.executable\n'C:\\\\Program Files\\\\Python31\\\\pythonw.exe'\n\n", "Consider using execfile. This executes the script you want using the same python instance that's already running.\n" ]
[ 9, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002074212_python.txt
Q: max size in BlobProperty (appengine) What is the maximum size of one BlobProperty in appengine? I'm not talking about of the Blobstore API, i'm referring to the property class BlobProperty Please add a link who support your answers A: The limit is 1 megabyte. Docs here. Like db.Text, a db.Blob value can be as large as 1 megabyte, but is not indexed, and cannot be used in query filters or sort orders. The db.Blob class takes a str value as an argument to its constructor. Blobs are modeled using the BlobProperty class.
max size in BlobProperty (appengine)
What is the maximum size of one BlobProperty in appengine? I'm not talking about of the Blobstore API, i'm referring to the property class BlobProperty Please add a link who support your answers
[ "The limit is 1 megabyte. Docs here.\n\nLike db.Text, a db.Blob value can be\n as large as 1 megabyte, but is not\n indexed, and cannot be used in query\n filters or sort orders. The db.Blob\n class takes a str value as an argument\n to its constructor. Blobs are modeled\n using the BlobProperty class.\n\n" ]
[ 11 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002074154_google_app_engine_python.txt
Q: mysql-python static linking on Linux 64-bit Has anyone tried to statically link mysql-python with mysql client library on 64-bit Linux? gcc -pthread -shared build/temp.linux-x86_64-2.6/_mysql.o /home/apy/MySQL- python-1.2.3c1/mysql-5.1.42/i/lib/mysql/libmysqlclient_r.a -L/home/apy/MyS QL-python-1.2.3c1/mysql-5.1.42/i/lib/mysql -lmysqlclient_r -lz -lpthread -lcrypt -lnsl - lm -lpthread -o build/lib.linux-x86_64-2.6/_mysql.so /usr/lib64/gcc-lib/x86_64-suse-linux/3.3.4/../../../../x86_64-suse-linux/bin/ld: /home/a py/MySQL-python-1.2.3c1/mysql-5.1.42/i/lib/mysql/libmysqlclient_r.a(libmys ql.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a sha red object; recompile with -fPIC /home/apy/MySQL-python-1.2.3c1/mysql-5.1.42/i/lib/mysql/libmysqlclient_r.a: could not read symbols: Bad value See also: mysql-python: building a completely standalone _mysql.so on Mac OS X? A: Set CFLAGS="-fPIC" environment variable. (reason) Pass --disable-shared to ./configure (besides --enable-static, that is) when building mysql.
mysql-python static linking on Linux 64-bit
Has anyone tried to statically link mysql-python with mysql client library on 64-bit Linux? gcc -pthread -shared build/temp.linux-x86_64-2.6/_mysql.o /home/apy/MySQL- python-1.2.3c1/mysql-5.1.42/i/lib/mysql/libmysqlclient_r.a -L/home/apy/MyS QL-python-1.2.3c1/mysql-5.1.42/i/lib/mysql -lmysqlclient_r -lz -lpthread -lcrypt -lnsl - lm -lpthread -o build/lib.linux-x86_64-2.6/_mysql.so /usr/lib64/gcc-lib/x86_64-suse-linux/3.3.4/../../../../x86_64-suse-linux/bin/ld: /home/a py/MySQL-python-1.2.3c1/mysql-5.1.42/i/lib/mysql/libmysqlclient_r.a(libmys ql.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a sha red object; recompile with -fPIC /home/apy/MySQL-python-1.2.3c1/mysql-5.1.42/i/lib/mysql/libmysqlclient_r.a: could not read symbols: Bad value See also: mysql-python: building a completely standalone _mysql.so on Mac OS X?
[ "\nSet CFLAGS=\"-fPIC\" environment variable. (reason)\nPass --disable-shared to ./configure (besides --enable-static, that is) when building mysql.\n\n" ]
[ 1 ]
[]
[]
[ "64_bit", "linux", "mysql", "python", "static_libraries" ]
stackoverflow_0002052791_64_bit_linux_mysql_python_static_libraries.txt
Q: Scrapy SgmlLinkExtractor is ignoring allowed links Please take a look at this spider example in Scrapy documentation. The explanation is: This spider would start crawling example.com’s home page, collecting category links, and item links, parsing the latter with the parse_item method. For each item response, some data will be extracted from the HTML using XPath, and a Item will be filled with it. I copied the same spider exactly, and replaced "example.com" with another initial url. from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from stb.items import StbItem class StbSpider(CrawlSpider): domain_name = "stb" start_urls = ['http://www.stblaw.com/bios/MAlpuche.htm'] rules = (Rule(SgmlLinkExtractor(allow=(r'/bios/.\w+\.htm', )), callback='parse', follow=True), ) def parse(self, response): hxs = HtmlXPathSelector(response) item = StbItem() item['JD'] = hxs.select('//td[@class="bodycopysmall"]').re('\d\d\d\d\sJ.D.') return item SPIDER = StbSpider() But my spider "stb" does not collect links from "/bios/" as it is supposed to do. It runs the initial url, scrapes the item['JD'] and writes it on a file and then quits. Why is it that SgmlLinkExtractor is ignored? The Rule is read because it catches syntax errors inside the Rule line. Is this a bug? is there something wrong in my code? There are no errors except a bunch unhandled errors that I see with every run. It would be nice to know what I am doing wrong here. Thanks for any clues. Am I misunderstanding what SgmlLinkExtractor is supposed to do? A: The parse function is actually implemented and used in the CrawlSpider class, and you're unintentionally overriding it. If you change the name to something else, like parse_item, then the Rule should work.
Scrapy SgmlLinkExtractor is ignoring allowed links
Please take a look at this spider example in Scrapy documentation. The explanation is: This spider would start crawling example.com’s home page, collecting category links, and item links, parsing the latter with the parse_item method. For each item response, some data will be extracted from the HTML using XPath, and a Item will be filled with it. I copied the same spider exactly, and replaced "example.com" with another initial url. from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from stb.items import StbItem class StbSpider(CrawlSpider): domain_name = "stb" start_urls = ['http://www.stblaw.com/bios/MAlpuche.htm'] rules = (Rule(SgmlLinkExtractor(allow=(r'/bios/.\w+\.htm', )), callback='parse', follow=True), ) def parse(self, response): hxs = HtmlXPathSelector(response) item = StbItem() item['JD'] = hxs.select('//td[@class="bodycopysmall"]').re('\d\d\d\d\sJ.D.') return item SPIDER = StbSpider() But my spider "stb" does not collect links from "/bios/" as it is supposed to do. It runs the initial url, scrapes the item['JD'] and writes it on a file and then quits. Why is it that SgmlLinkExtractor is ignored? The Rule is read because it catches syntax errors inside the Rule line. Is this a bug? is there something wrong in my code? There are no errors except a bunch unhandled errors that I see with every run. It would be nice to know what I am doing wrong here. Thanks for any clues. Am I misunderstanding what SgmlLinkExtractor is supposed to do?
[ "The parse function is actually implemented and used in the CrawlSpider class, and you're unintentionally overriding it. If you change the name to something else, like parse_item, then the Rule should work.\n" ]
[ 11 ]
[]
[]
[ "python", "scrapy", "web_crawler" ]
stackoverflow_0001811132_python_scrapy_web_crawler.txt
Q: Uploading files to App Engine using webapp and Django forms My basic question is this: Is there an equivalent of form = MyForm(request.POST, request.FILES) when handling file uploads using the webapp framework on Google App Engine? I know that I can pull out specific uploaded file data using self.request.get('field_name') or a FieldStorage object using self.request.params['field_name'], but in my case I do not know the field names in advance. I would like to let the form object take care of pulling the data it needs out of the request (especially since the forms, and thus the incoming field names, have prefixes). I'm porting a sort of generic CMS system from Django (already running on App Engine) to Google's webapp framework, and this is the last major stumbling block. When a new item is created, I'd like to be able to just pass the POSTed parameters and files straight to the Django form object for that item, so that I don't have to know ahead of time what fields are in the form and which of those fields are file uploads. This was possible using Django, but I can't see any easy way to do it in the webapp framework. A: Here's the solution I came up with. I added the following method to my custom webapp.RequestHandler subclass: # Required imports import cgi from django.core.files.uploadedfile import SimpleUploadedFile def get_uploaded_files(self): """Gets a dictionary mapping field names to SimpleUploadedFile objects for each uploaded file in the given params. Suitable for passing to a Django form as the `files` argument.""" return dict((k, SimpleUploadedFile(v.filename, v.file.read())) for k, v in self.request.params.items() if isinstance(v, cgi.FieldStorage) and v.file) Now, when handling uploaded files, I can do something like the following: form = MyForm(self.request.params, self.get_uploaded_files()) This works well for me so far. (I don't know if it's bad form to answer my own question. I'm sorry if it is.) A: Have a look at app-engine-patch. request.FILES is supposed to work if you use it. There is also a little snippet here, but I have not tested it: if request.method == 'POST': form = MyImageUploadForm( request.POST, request.FILES) if form.is_valid(): themodel = MyImageModel() themodel.data = form.cleaned_data['file'].read() themodel.content_type = form.cleaned_data['file'].content_type themodel.put() else: form = MyImageUploadForm() A: self.request.arguments() contains all the elements that you could retrieve separately using self.request.get('field_name') if you knew 'field_name'. Since you don't know the name of your fields in advance, you might want to loop on all of it's elements. This would work just fine if the names of your fields have a fixed prepend, such as photo_cat and photo_dog.
Uploading files to App Engine using webapp and Django forms
My basic question is this: Is there an equivalent of form = MyForm(request.POST, request.FILES) when handling file uploads using the webapp framework on Google App Engine? I know that I can pull out specific uploaded file data using self.request.get('field_name') or a FieldStorage object using self.request.params['field_name'], but in my case I do not know the field names in advance. I would like to let the form object take care of pulling the data it needs out of the request (especially since the forms, and thus the incoming field names, have prefixes). I'm porting a sort of generic CMS system from Django (already running on App Engine) to Google's webapp framework, and this is the last major stumbling block. When a new item is created, I'd like to be able to just pass the POSTed parameters and files straight to the Django form object for that item, so that I don't have to know ahead of time what fields are in the form and which of those fields are file uploads. This was possible using Django, but I can't see any easy way to do it in the webapp framework.
[ "Here's the solution I came up with. I added the following method to my custom webapp.RequestHandler subclass:\n# Required imports\nimport cgi\nfrom django.core.files.uploadedfile import SimpleUploadedFile\n\ndef get_uploaded_files(self):\n \"\"\"Gets a dictionary mapping field names to SimpleUploadedFile objects\n for each uploaded file in the given params. Suitable for passing to a\n Django form as the `files` argument.\"\"\"\n return dict((k, SimpleUploadedFile(v.filename, v.file.read()))\n for k, v in self.request.params.items()\n if isinstance(v, cgi.FieldStorage) and v.file)\n\nNow, when handling uploaded files, I can do something like the following:\nform = MyForm(self.request.params, self.get_uploaded_files())\n\nThis works well for me so far.\n(I don't know if it's bad form to answer my own question. I'm sorry if it is.)\n", "Have a look at app-engine-patch. request.FILES is supposed to work if you use it.\nThere is also a little snippet here, but I have not tested it:\nif request.method == 'POST':\n form = MyImageUploadForm( request.POST, request.FILES)\n if form.is_valid():\n themodel = MyImageModel()\n themodel.data = form.cleaned_data['file'].read()\n themodel.content_type = form.cleaned_data['file'].content_type\n themodel.put()\n else:\n form = MyImageUploadForm()\n\n", "self.request.arguments() contains all the elements that you could retrieve separately using self.request.get('field_name') if you knew 'field_name'.\nSince you don't know the name of your fields in advance, you might want to loop on all of it's elements. This would work just fine if the names of your fields have a fixed prepend, such as photo_cat and photo_dog.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "django", "file_upload", "forms", "google_app_engine", "python" ]
stackoverflow_0002052673_django_file_upload_forms_google_app_engine_python.txt
Q: Django ManyToManyField Creation Problems I currently have these models: class Category(models.Model): name = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, related_name='child') description = models.TextField(blank=True,null=True) class Item(models.Model): name = models.CharField(max_length=500) ... tag = models.ManyToManyField(Category, null=True, blank=True, related_name='tag_item') My issue is, I can't add tags to any Items that I've already created. If I attempt to do something like: >>> cat = Category.objects.get(pk=1) >>> cat.tag_item.create(item_id = 1) I get TypeError: 'item_id' is an invalid keyword argument for this function However, if I do: >>> cat.tag_item.create() I end up with a newly created empty item. I also don't understand how I would perform a query to get all tags for a particular item? There is no Tag class because I don't have to specify a through attribute on the ManyToManyField since there is no extra data, so I can't use a Tag manager to do something like Tag.objects.filter(item_id=3) A: Have a look at some examples here. Basically, you should do: class Item(models.Model): name = models.CharField(max_length=500) ... tags = models.ManyToManyField(Category, blank=True) To create an item, a tag and associate them, do the following: item = Item(name='test') item.save() tag = Category(name='foo') item.tags.add(tag) and to query all tags: item.tags.all()
Django ManyToManyField Creation Problems
I currently have these models: class Category(models.Model): name = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, related_name='child') description = models.TextField(blank=True,null=True) class Item(models.Model): name = models.CharField(max_length=500) ... tag = models.ManyToManyField(Category, null=True, blank=True, related_name='tag_item') My issue is, I can't add tags to any Items that I've already created. If I attempt to do something like: >>> cat = Category.objects.get(pk=1) >>> cat.tag_item.create(item_id = 1) I get TypeError: 'item_id' is an invalid keyword argument for this function However, if I do: >>> cat.tag_item.create() I end up with a newly created empty item. I also don't understand how I would perform a query to get all tags for a particular item? There is no Tag class because I don't have to specify a through attribute on the ManyToManyField since there is no extra data, so I can't use a Tag manager to do something like Tag.objects.filter(item_id=3)
[ "Have a look at some examples here.\nBasically, you should do:\nclass Item(models.Model):\n name = models.CharField(max_length=500)\n ...\n tags = models.ManyToManyField(Category, blank=True)\n\nTo create an item, a tag and associate them, do the following:\nitem = Item(name='test')\nitem.save()\ntag = Category(name='foo')\nitem.tags.add(tag)\n\nand to query all tags:\nitem.tags.all()\n\n" ]
[ 4 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0002074900_django_django_models_many_to_many_python.txt
Q: Random weighted choice I have data like this: d = ( (701, 1, 0.2), (701, 2, 0.3), (701, 3, 0.5), (702, 1, 0.2), (702, 2, 0.3), (703, 3, 0.5) ) Where (701, 1, 0.2) = (id1, id2, priority) Is there a pretty way to choose id2 if I know id1, using priority? Func(701) should return:   1 - in 20% cases   2 - 30%   3 - 50% Percent will be rough of course A: Generate a Cumulative Distribution Function for each ID1 thus: cdfs = defaultdict() for id1,id2,val in d: prevtotal = cdfs[id1][-1][0] newtotal = prevtotal + val cdfs[id1].append( (newtotal,id2) ) So you will have cdfs = { 701 : [ (0.2,1), (0.5,2), (1.0,3) ], 702 : [ (0.2,1), (0.5,2) ], 703 : [ (0.5,3) ] } Then generate a random number and search for it in the list. def func(id1): max = cdfs[id1][-1][0] rand = random.random()*max for upper,id2 in cdfs[id1]: if upper>rand: return id2 return None A: Realizing that my first answer was quite buggy in its math, I have produced a new idea. I believe the algorithm here is similar to that of several of the other answers, but this implementation seems to qualify for the "pretty" (if that equals simple) requirement of the question: def func(id): rnd = random() sum = 0 for row in d: if row[0] == id: sum = sum + row[2] if rnd < sum: return row[1] With the example data from the OP it goes like this: Pick a random number between 0 and 1.0 If the number is < 0.2 return the first element Else if the number is < 0.5 return the second element Else (if the number is < 1.0) return the third element A: Use a discrete uniform distribution from the random module over a sufficient number of values, then partition it: For example, for case 701 use a distribution over 10 values, for 2 values return 1, for another 3, return 2, and for the other 5, return 3. You can build any distribution using enough uniform distributions :) A: If your percent values will not be more precise than whole percent values, use a random number generator to generate a number 0-99. Then in your function, use (programmatic) cases to choose the correct number. For example (clean this up): if 701 if random_num < 20 return 1 else if random number < 50 // ( 20 + 30 ) return 2 else if random number < 100 // ( 20 + 30 + 50 ) return 3 else // error A: A very quick hack: import random d = { 701: [(1,0.2),(2,0.3),(3,0.5)], 702: [(1,0.2),(2,0.3),(3,0.5)] } def func(value): possible_values=d[value] total=sum(p[-1] for p in possible_values) random_value=random.random() prob=possible_values[0][-1]/total index=1 while index<len(possible_values) and prob<random_value: prob+=possible_values[index][-1]/total index+=1 return possible_values[index-1][0] if __name__=='__main__': testcases=1000 cnt=[0,0,0] for case in xrange(testcases): answer=func(701) cnt[answer-1]+=1 for i in xrange(3): print "Got %d %f%% of the time"%(i+1,float(cnt[i])/testcases*100) It isn't pretty, but it is the first thing that came to mind, and appears to work as expected. What this does is to get a random value in the interval [0,1) (using random.random()). It then uses whether the random value falls in the intervals [0,0.2),[0.2,0.5) or [0.5,1), to figure out which value to return. A: Two ideas (allow me to illustrate it with separated options and ratios for the sake of clarity in the argument names, if they're packed in a tuple you can save the "zip"): a) Denormalize the weights to get integer ratios, then put in a list as many copies as the ratio and use random.choice. def choice_with_ratios(options, ratios): tmp = sum([[v]*n for v, n in zip(options, ratios)], []) return random.choice(tmp) b) Use the normalized weights and start summing up until you reach a random generated uniform value def choice_with_weights(options, weights): s = 0 r = random.random() for v, w in zip(options, weights): s += w if s >= r: break return v By the way, if the first field is used as a key, you should have it in a dictionary, like: d = { 701: ((1, 0.2), (2, 0.3), (3, 0.5), 702: ((1, 0.3), (2, 0.2), (3, 0.5) } A: You can also create a 100-element list for each value, and then let random.choice do the selecting from a seeded list whose members are loaded in the weighting that you want: import random from collections import defaultdict d = ( (701, 1, 0.2), (701, 2, 0.3), (701, 3, 0.5), (702, 1, 0.2), (702, 2, 0.3), (702, 3, 0.5) ) class WeightedLookup(object): def __init__(self, valueTupleList): self.valdict = defaultdict(list) for key, val, prob in valueTupleList: self.valdict[key] += [val]*(int)(prob*100) def __getitem__(self,key): return random.choice(self.valdict[key]) lookup = WeightedLookup(d) # test out our lookup distribution, sample it 100000 times res = { 1:0, 2:0, 3:0 } for i in range(100000): res[lookup[701]] += 1 # print how many times each value was returned for k in (1,2,3): print k, res[k] Prints: 1 20059 2 30084 3 49857
Random weighted choice
I have data like this: d = ( (701, 1, 0.2), (701, 2, 0.3), (701, 3, 0.5), (702, 1, 0.2), (702, 2, 0.3), (703, 3, 0.5) ) Where (701, 1, 0.2) = (id1, id2, priority) Is there a pretty way to choose id2 if I know id1, using priority? Func(701) should return:   1 - in 20% cases   2 - 30%   3 - 50% Percent will be rough of course
[ "Generate a Cumulative Distribution Function for each ID1 thus:\ncdfs = defaultdict()\nfor id1,id2,val in d:\n prevtotal = cdfs[id1][-1][0]\n newtotal = prevtotal + val\n cdfs[id1].append( (newtotal,id2) )\n\nSo you will have\ncdfs = { 701 : [ (0.2,1), (0.5,2), (1.0,3) ], \n 702 : [ (0.2,1), (0.5,2) ],\n 703 : [ (0.5,3) ] }\n\nThen generate a random number and search for it in the list.\ndef func(id1):\n max = cdfs[id1][-1][0]\n rand = random.random()*max\n for upper,id2 in cdfs[id1]:\n if upper>rand:\n return id2\n return None\n\n", "Realizing that my first answer was quite buggy in its math, I have produced a new idea. I believe the algorithm here is similar to that of several of the other answers, but this implementation seems to qualify for the \"pretty\" (if that equals simple) requirement of the question:\ndef func(id):\n rnd = random()\n sum = 0\n for row in d:\n if row[0] == id:\n sum = sum + row[2]\n if rnd < sum:\n return row[1]\n\nWith the example data from the OP it goes like this:\n\nPick a random number between 0 and 1.0\nIf the number is < 0.2 return the first element\nElse if the number is < 0.5 return the second element\nElse (if the number is < 1.0) return the third element\n\n", "Use a discrete uniform distribution from the random module over a sufficient number of values, then partition it:\nFor example, for case 701 use a distribution over 10 values, for 2 values return 1, for another 3, return 2, and for the other 5, return 3.\nYou can build any distribution using enough uniform distributions :)\n", "If your percent values will not be more precise than whole percent values, use a random number generator to generate a number 0-99.\nThen in your function, use (programmatic) cases to choose the correct number. For example (clean this up):\n\nif 701\n if random_num < 20\n return 1\n else if random number < 50 // ( 20 + 30 )\n return 2\n else if random number < 100 // ( 20 + 30 + 50 )\n return 3\n else\n // error\n\n", "A very quick hack:\nimport random\n\nd = {\n 701: [(1,0.2),(2,0.3),(3,0.5)],\n 702: [(1,0.2),(2,0.3),(3,0.5)]\n}\n\ndef func(value):\n possible_values=d[value]\n total=sum(p[-1] for p in possible_values)\n random_value=random.random()\n prob=possible_values[0][-1]/total\n index=1\n while index<len(possible_values) and prob<random_value:\n prob+=possible_values[index][-1]/total\n index+=1\n return possible_values[index-1][0]\n\nif __name__=='__main__':\n testcases=1000\n cnt=[0,0,0]\n for case in xrange(testcases):\n answer=func(701)\n cnt[answer-1]+=1\n for i in xrange(3):\n print \"Got %d %f%% of the time\"%(i+1,float(cnt[i])/testcases*100)\n\nIt isn't pretty, but it is the first thing that came to mind, and appears to work as expected.\nWhat this does is to get a random value in the interval [0,1) (using random.random()). It then uses whether the random value falls in the intervals [0,0.2),[0.2,0.5) or [0.5,1), to figure out which value to return.\n", "Two ideas (allow me to illustrate it with separated options and ratios for the sake of clarity in the argument names, if they're packed in a tuple you can save the \"zip\"):\na) Denormalize the weights to get integer ratios, then put in a list as many copies as the ratio and use random.choice.\ndef choice_with_ratios(options, ratios):\n tmp = sum([[v]*n for v, n in zip(options, ratios)], [])\n return random.choice(tmp)\n\nb) Use the normalized weights and start summing up until you reach a random generated uniform value\ndef choice_with_weights(options, weights):\n s = 0\n r = random.random()\n for v, w in zip(options, weights):\n s += w\n if s >= r: break\n return v\n\nBy the way, if the first field is used as a key, you should have it in a dictionary, like:\nd = {\n 701: ((1, 0.2), (2, 0.3), (3, 0.5),\n 702: ((1, 0.3), (2, 0.2), (3, 0.5)\n}\n\n", "You can also create a 100-element list for each value, and then let random.choice do the selecting from a seeded list whose members are loaded in the weighting that you want:\nimport random\nfrom collections import defaultdict\n\nd = ( \n (701, 1, 0.2), \n (701, 2, 0.3), \n (701, 3, 0.5), \n (702, 1, 0.2), \n (702, 2, 0.3), \n (702, 3, 0.5) \n) \n\nclass WeightedLookup(object):\n def __init__(self, valueTupleList):\n self.valdict = defaultdict(list)\n for key, val, prob in valueTupleList:\n self.valdict[key] += [val]*(int)(prob*100)\n\n def __getitem__(self,key):\n return random.choice(self.valdict[key])\n\n\nlookup = WeightedLookup(d)\n\n# test out our lookup distribution, sample it 100000 times\nres = { 1:0, 2:0, 3:0 }\nfor i in range(100000):\n res[lookup[701]] += 1\n\n# print how many times each value was returned\nfor k in (1,2,3):\n print k, res[k]\n\nPrints:\n1 20059\n2 30084\n3 49857\n\n" ]
[ 7, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002073235_python.txt
Q: Using an index to recursively get all files in a directory really fast Attempt #2: People don't seem to be understanding what I'm trying to do. Let me see if I can state it more clearly: 1) Reading a list of files is much faster than walking a directory. 2) So let's have a function that walks a directory and writes the resulting list to a file. Now, in the future, if we want to get all the files in that directory we can just read this file instead of walking the dir. I call this file the index. 3) Obviously, as the filesystem changes the index file gets out of sync. To overcome this, we have a separate program that hooks into the OS in order to monitor changes to the filesystem. It writes those changes to a file called the monitor log. Immediately after we read the index file for a particular directory, we use the monitor log to apply the various changes to the index so that it reflects the current state of the directory. Because reading files is so much cheaper than walking a directory, this should be much faster than walking for all calls after the first. Original post: I want a function that will recursively get all the files in any given directory and filter them according to various parameters. And I want it to be fast -- like, an order of magnitude faster than simply walking the dir. And I'd prefer to do it in Python. Cross-platform is preferable, but Windows is most important. Here's my idea for how to go about this: I have a function called all_files: def all_files(dir_path, ...parms...): ... The first time I call this function it will use os.walk to build a list of all the files, along with info about the files such as whether they are hidden, a symbolic link, etc. I'll write this data to a file called ".index" in the directory. On subsequent calls to all_files, the .index file will be detected, and I will read that file rather than walking the dir. This leaves the problem of the index getting out of sync as files are added and removed. For that I'll have a second program that runs on startup, detects all changes to the entire filesystem, and writes them to a file called "mod_log.txt". It detects changes via Windows signals, like the method described here. This file will contain one event per line, with each event consisting of the path affected, the type of event (create, delete, etc.), and a timestamp. The .index file will have a timestamp as well for the time it was last updated. After I read the .index file in all_files I will tail mod_log.txt and find any events that happened after the timestamp in the .index file. It will take these recent events, find any that apply to the current directory, and update the .index accordingly. Finally, I'll take the list of all files, filter it according to various parameters, and return the result. What do you think of my approach? Is there a better way to do this? Edit: Check this code out. I'm seeing a drastic speedup from reading a cached list over a recursive walk. import os from os.path import join, exists import cProfile, pstats dir_name = "temp_dir" index_path = ".index" def create_test_files(): os.mkdir(dir_name) index_file = open(index_path, 'w') for i in range(10): print "creating dir: ", i sub_dir = join(dir_name, str(i)) os.mkdir(sub_dir) for i in range(100): file_path = join(sub_dir, str(i)) open(file_path, 'w').close() index_file.write(file_path + "\n") index_file.close() # # 0.238 seconds def test_walk(): for info in os.walk("temp_dir"): pass # 0.001 seconds def test_read(): open(index_path).readlines() if not exists("temp_dir"): create_test_files() def profile(s): cProfile.run(s, 'profile_results.txt') p = pstats.Stats('profile_results.txt') p.strip_dirs().sort_stats('cumulative').print_stats(10) profile("test_walk()") profile("test_read()") A: Do not try to duplicate the work that the filesystem already does. You are not going to do better than it already does. Your scheme is flawed in many ways and it will not get you an order-of-magnitude improvement. Flaws and potential problems: You are always going to be working with a snapshot of the file system. You will never know with any certainty that it is not significantly disjoint from reality. If that is within the working parameters of your application, no sweat. The filesystem monitor program still has to recursively walk the file system, so the work is still being done. In order to increase the accuracy of the cache, you have to increase the frequency with which the filesystem monitor runs. The more it runs, the less actual time that you are saving. Your client application likely won't be able to read the index file while it is being updated by the filesystem monitor program, so you'll lose time while the client waits for the index to be readable. I could go on. If, in fact, you don't care about working with a snapshot of the filesystem that may be very disjoint from reality, I think that you'd be much better off with keeping the index in memory and updating from with the application itself. That will scrub any file contention issues that will otherwise arise. A: The best answer came from Michał Marczyk toward the bottom of the comment list on the initial question. He pointed out that what I'm describing is very close to the UNIX locate program. I found a Windows version here: http://locate32.net/index.php. It solved my problem. Edit: Actually the Everything search engine looks even better. Apparently Windows keeps journals of changes to the filesystem, and Everything uses that to keep the database up to date. A: Doesn't Windows Desktop Search provide such an index as a byproduct? On the mac the spotlight index can be queried for filenames like this: mdfind -onlyin . -name '*'. Of course it's much faster than walking the directory. A: The short answer is "no". You will not be able to build an indexing system in Python that will outpace the file system by an order of magnitude. "Indexing" a filesystem is an intensive/slow task, regardless of the caching implementation. The only realistic way to avoid the huge overhead of building filesystem indexes is to "index as you go" to avoid the big traversal. (After all, the filesystem itself is already a data indexer.) There are operating system features that are capable of doing this "build as you go" filesystem indexing. It's the very foundation of services like Spotlight on OSX and Windows Desktop Search. To have any hope of getting faster speeds than walking the directories, you'll want to leverage one of those OS or filesystem level tools. Also, try not to mislead yourself into thinking solutions are faster just because you've "moved" the work to a different time/process. Your example code does exactly that. You traverse the directory structure of your sample files while you're building the same files and create the index, and then later just read that file. There are two lessons, here. (a) To create a proper test it's essential to separate the "setup" from the "test". Here your performance test essentially says, "Which is faster, traversing a directory structure or reading an index that's already been created in advance?" Clearly this is not an apples to oranges comparison. However, (b) you've stumbled on the correct answer at the same time. You can get a list of files much faster if you use an already existing index. This is where you'd need to leverage something like the Windows Desktop Search or Spotlight indexes. Make no mistake, in order to build an index of a filesystem you must, by definition, "visit" every file. If your files are stored in a tree, then a recursive traversal is likely going to be the fastest way you can visit every file. If the question is "can I write Python code to do exactly what os.walk does but be an order of magnitude faster than os.walk" the answer is a resounding no. If the question is "can I write Python code to index every file on the system without taking the time to actually visit every file" then the answer is still no. (Edit in response to "I don't think you understand what I'm trying to do") Let's be clear here, virtually everyone here understands what you're trying to do. It seems that you're taking "no, this isn't going to work like you want it to work" to mean that we don't understand. Let's look at this from another angle. File systems have been an essential component to modern computing from the very beginning. The categorization, indexing, storage, and retrieval of data is a serious part of computer science and computer engineering and many of the most brilliant minds in computer science are working on it constantly. You want to be able to filter/select files based on attributes/metadata/data of the files. This is an extremely common task utilized constantly in computing. It's likely happening several times a second even on the computer you're working with right now. If it were as simple to speed up this process by an order of magnitude(!) by simply keeping a text file index of the filenames and attributes, don't you think every single file system and operating system in existence would do exactly that? That said, of course caching the results of your specific queries could net you some small performance increases. And, as expected, file system and disk caching is a fundamental part of every modern operating system and file system. But your question, as you asked it, has a clear answer: No. In the general case, you're not going to get an order of magnitude faster reimplementing os.walk. You may be able to get a better amortized runtime by caching, but you're not going to be beat it by an order of magnitude if you properly include the work to build the cache in your profiling. A: I would like to recommend you just use a combination of os.walk (to get directory trees) & os.stat (to get file information) for this. Using the std-lib will ensure it works on all platforms, and they do the job nicely. And no need to index anything. As other have stated, I don't really think you're going to buy much by attempting to index and re-index the filesystem, especially if you're already limiting your functionality by path and parameters. A: I'm new to Python, but I'm using a combination of list comprehensions, iterator and a generator should scream according to reports I've read. class DirectoryIterator: def __init__(self, start_dir, pattern): self.directory = start_dir self.pattern = pattern def __iter__(self): [([DirectoryIterator(dir, self.pattern) for dir in dirnames], [(yield os.path.join(dirpath, name)) for name in filenames if re.search(self.pattern, name) ]) for dirpath, dirnames, filenames in os.walk(self.directory)] ########### for file_name in DirectoryIterator(".", "\.py$"): print file_name
Using an index to recursively get all files in a directory really fast
Attempt #2: People don't seem to be understanding what I'm trying to do. Let me see if I can state it more clearly: 1) Reading a list of files is much faster than walking a directory. 2) So let's have a function that walks a directory and writes the resulting list to a file. Now, in the future, if we want to get all the files in that directory we can just read this file instead of walking the dir. I call this file the index. 3) Obviously, as the filesystem changes the index file gets out of sync. To overcome this, we have a separate program that hooks into the OS in order to monitor changes to the filesystem. It writes those changes to a file called the monitor log. Immediately after we read the index file for a particular directory, we use the monitor log to apply the various changes to the index so that it reflects the current state of the directory. Because reading files is so much cheaper than walking a directory, this should be much faster than walking for all calls after the first. Original post: I want a function that will recursively get all the files in any given directory and filter them according to various parameters. And I want it to be fast -- like, an order of magnitude faster than simply walking the dir. And I'd prefer to do it in Python. Cross-platform is preferable, but Windows is most important. Here's my idea for how to go about this: I have a function called all_files: def all_files(dir_path, ...parms...): ... The first time I call this function it will use os.walk to build a list of all the files, along with info about the files such as whether they are hidden, a symbolic link, etc. I'll write this data to a file called ".index" in the directory. On subsequent calls to all_files, the .index file will be detected, and I will read that file rather than walking the dir. This leaves the problem of the index getting out of sync as files are added and removed. For that I'll have a second program that runs on startup, detects all changes to the entire filesystem, and writes them to a file called "mod_log.txt". It detects changes via Windows signals, like the method described here. This file will contain one event per line, with each event consisting of the path affected, the type of event (create, delete, etc.), and a timestamp. The .index file will have a timestamp as well for the time it was last updated. After I read the .index file in all_files I will tail mod_log.txt and find any events that happened after the timestamp in the .index file. It will take these recent events, find any that apply to the current directory, and update the .index accordingly. Finally, I'll take the list of all files, filter it according to various parameters, and return the result. What do you think of my approach? Is there a better way to do this? Edit: Check this code out. I'm seeing a drastic speedup from reading a cached list over a recursive walk. import os from os.path import join, exists import cProfile, pstats dir_name = "temp_dir" index_path = ".index" def create_test_files(): os.mkdir(dir_name) index_file = open(index_path, 'w') for i in range(10): print "creating dir: ", i sub_dir = join(dir_name, str(i)) os.mkdir(sub_dir) for i in range(100): file_path = join(sub_dir, str(i)) open(file_path, 'w').close() index_file.write(file_path + "\n") index_file.close() # # 0.238 seconds def test_walk(): for info in os.walk("temp_dir"): pass # 0.001 seconds def test_read(): open(index_path).readlines() if not exists("temp_dir"): create_test_files() def profile(s): cProfile.run(s, 'profile_results.txt') p = pstats.Stats('profile_results.txt') p.strip_dirs().sort_stats('cumulative').print_stats(10) profile("test_walk()") profile("test_read()")
[ "Do not try to duplicate the work that the filesystem already does. You are not going to do better than it already does.\nYour scheme is flawed in many ways and it will not get you an order-of-magnitude improvement.\nFlaws and potential problems:\nYou are always going to be working with a snapshot of the file system. You will never know with any certainty that it is not significantly disjoint from reality. If that is within the working parameters of your application, no sweat.\nThe filesystem monitor program still has to recursively walk the file system, so the work is still being done.\nIn order to increase the accuracy of the cache, you have to increase the frequency with which the filesystem monitor runs. The more it runs, the less actual time that you are saving.\nYour client application likely won't be able to read the index file while it is being updated by the filesystem monitor program, so you'll lose time while the client waits for the index to be readable.\nI could go on.\nIf, in fact, you don't care about working with a snapshot of the filesystem that may be very disjoint from reality, I think that you'd be much better off with keeping the index in memory and updating from with the application itself. That will scrub any file contention issues that will otherwise arise.\n", "The best answer came from Michał Marczyk toward the bottom of the comment list on the initial question. He pointed out that what I'm describing is very close to the UNIX locate program. I found a Windows version here: http://locate32.net/index.php. It solved my problem.\nEdit: Actually the Everything search engine looks even better. Apparently Windows keeps journals of changes to the filesystem, and Everything uses that to keep the database up to date.\n", "Doesn't Windows Desktop Search provide such an index as a byproduct? On the mac the spotlight index can be queried for filenames like this: mdfind -onlyin . -name '*'.\nOf course it's much faster than walking the directory.\n", "The short answer is \"no\". You will not be able to build an indexing system in Python that will outpace the file system by an order of magnitude.\n\"Indexing\" a filesystem is an intensive/slow task, regardless of the caching implementation. The only realistic way to avoid the huge overhead of building filesystem indexes is to \"index as you go\" to avoid the big traversal. (After all, the filesystem itself is already a data indexer.)\nThere are operating system features that are capable of doing this \"build as you go\" filesystem indexing. It's the very foundation of services like Spotlight on OSX and Windows Desktop Search.\nTo have any hope of getting faster speeds than walking the directories, you'll want to leverage one of those OS or filesystem level tools.\nAlso, try not to mislead yourself into thinking solutions are faster just because you've \"moved\" the work to a different time/process. Your example code does exactly that. You traverse the directory structure of your sample files while you're building the same files and create the index, and then later just read that file.\nThere are two lessons, here. (a) To create a proper test it's essential to separate the \"setup\" from the \"test\". Here your performance test essentially says, \"Which is faster, traversing a directory structure or reading an index that's already been created in advance?\" Clearly this is not an apples to oranges comparison.\nHowever, (b) you've stumbled on the correct answer at the same time. You can get a list of files much faster if you use an already existing index. This is where you'd need to leverage something like the Windows Desktop Search or Spotlight indexes.\nMake no mistake, in order to build an index of a filesystem you must, by definition, \"visit\" every file. If your files are stored in a tree, then a recursive traversal is likely going to be the fastest way you can visit every file. If the question is \"can I write Python code to do exactly what os.walk does but be an order of magnitude faster than os.walk\" the answer is a resounding no. If the question is \"can I write Python code to index every file on the system without taking the time to actually visit every file\" then the answer is still no.\n(Edit in response to \"I don't think you understand what I'm trying to do\")\nLet's be clear here, virtually everyone here understands what you're trying to do. It seems that you're taking \"no, this isn't going to work like you want it to work\" to mean that we don't understand.\nLet's look at this from another angle. File systems have been an essential component to modern computing from the very beginning. The categorization, indexing, storage, and retrieval of data is a serious part of computer science and computer engineering and many of the most brilliant minds in computer science are working on it constantly.\nYou want to be able to filter/select files based on attributes/metadata/data of the files. This is an extremely common task utilized constantly in computing. It's likely happening several times a second even on the computer you're working with right now.\nIf it were as simple to speed up this process by an order of magnitude(!) by simply keeping a text file index of the filenames and attributes, don't you think every single file system and operating system in existence would do exactly that?\nThat said, of course caching the results of your specific queries could net you some small performance increases. And, as expected, file system and disk caching is a fundamental part of every modern operating system and file system.\nBut your question, as you asked it, has a clear answer: No. In the general case, you're not going to get an order of magnitude faster reimplementing os.walk. You may be able to get a better amortized runtime by caching, but you're not going to be beat it by an order of magnitude if you properly include the work to build the cache in your profiling.\n", "I would like to recommend you just use a combination of os.walk (to get directory trees) & os.stat (to get file information) for this. Using the std-lib will ensure it works on all platforms, and they do the job nicely. And no need to index anything.\nAs other have stated, I don't really think you're going to buy much by attempting to index and re-index the filesystem, especially if you're already limiting your functionality by path and parameters.\n", "I'm new to Python, but I'm using a combination of list comprehensions, iterator and a generator should scream according to reports I've read.\nclass DirectoryIterator:\n def __init__(self, start_dir, pattern):\n self.directory = start_dir\n self.pattern = pattern\n\n def __iter__(self):\n [([DirectoryIterator(dir, self.pattern) for dir in dirnames], [(yield os.path.join(dirpath, name)) for name in filenames if re.search(self.pattern, name) ]) for dirpath, dirnames, filenames in os.walk(self.directory)]\n\n ###########\n\n for file_name in DirectoryIterator(\".\", \"\\.py$\"): print file_name\n\n" ]
[ 7, 3, 2, 1, 0, 0 ]
[]
[]
[ "all_files", "directory", "indexing", "performance", "python" ]
stackoverflow_0002059912_all_files_directory_indexing_performance_python.txt
Q: django logging local javascript events Say there exists a template x.html in Django templates section. The contents of this page are <html> <a href="#" onclick="noserverrequest"> <input type="button onclick="noserverrequest"/> ... </html> I have n number of buttons and hyperlinks as said above in a page. My question is how to record all the clicks that are done in this page (local JavaScript actions) and when one server request is made to Django I have to record all the links that are clicked in this page. How is this achieved? I can use a hidden variable to record all the hyperlinks or button actions. But how to send it to server. Please indicate me how this is achieved. On Django side when the request is found I write the JavaScript events to the database. A: you should better trigger an image load in javascript : function log(info) { document.getElementById('pixel').src = '/tracker?'+info; } somewhere on your page : <img id='pixel' src='pixel.gif' style='display:none'/> then call it this way in javascript : log('clicked_Button_BuyStuff'); server side, you could have a django view then records all the data, including date, user, referer....
django logging local javascript events
Say there exists a template x.html in Django templates section. The contents of this page are <html> <a href="#" onclick="noserverrequest"> <input type="button onclick="noserverrequest"/> ... </html> I have n number of buttons and hyperlinks as said above in a page. My question is how to record all the clicks that are done in this page (local JavaScript actions) and when one server request is made to Django I have to record all the links that are clicked in this page. How is this achieved? I can use a hidden variable to record all the hyperlinks or button actions. But how to send it to server. Please indicate me how this is achieved. On Django side when the request is found I write the JavaScript events to the database.
[ "you should better trigger an image load in javascript : \nfunction log(info) {\n document.getElementById('pixel').src = '/tracker?'+info;\n}\n\nsomewhere on your page :\n<img id='pixel' src='pixel.gif' style='display:none'/>\n\nthen call it this way in javascript : \nlog('clicked_Button_BuyStuff');\n\nserver side, you could have a django view then records all the data, including date, user, referer....\n" ]
[ 0 ]
[]
[]
[ "django", "javascript", "jquery", "python" ]
stackoverflow_0002073962_django_javascript_jquery_python.txt
Q: wxpython GetStatusText() Hey, I have a wxpython frame object with a status bar. I can do self.SetStatusText() without any trouble, but when I do self.GetStatusText() I get this error: Traceback (most recent call last): File "D:\python\code\test.pyw", line 87, in <module> frame = mainframe() File "D:\python\code\test.pyw", line 40, in __init__ self.serverfield.SetValue(self.serverinfo()) File "D:\python\code\test.pyw", line 78, in serverinfo status = self.GetStatusText(0) AttributeError: 'mainframe' object has no attribute 'GetStatusText' A: Because there is no such function. See the documentation. Try self.GetStatusBar().GetStatusText(), as defined here.
wxpython GetStatusText()
Hey, I have a wxpython frame object with a status bar. I can do self.SetStatusText() without any trouble, but when I do self.GetStatusText() I get this error: Traceback (most recent call last): File "D:\python\code\test.pyw", line 87, in <module> frame = mainframe() File "D:\python\code\test.pyw", line 40, in __init__ self.serverfield.SetValue(self.serverinfo()) File "D:\python\code\test.pyw", line 78, in serverinfo status = self.GetStatusText(0) AttributeError: 'mainframe' object has no attribute 'GetStatusText'
[ "Because there is no such function. See the documentation. Try self.GetStatusBar().GetStatusText(), as defined here.\n" ]
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002075378_python_wxpython.txt
Q: Python fails Tor check using urllib2 to initiate requests After reading through the other questions on StackOverflow, I got a snippet of Python code that is able to make requests through a Tor proxy: import urllib2 proxy = urllib2.ProxyHandler({'http':'127.0.0.1:8118'}) opener = urllib2.build_opener(proxy) print opener.open('https://check.torproject.org/').read() Since Tor works fine in Firefox with TorButton, I expected it to work fine in Python. Unfortunately, included in the mess of HTML: Sorry. You are not using Tor. I am not sure why this is the case or how to get Tor working properly with urllib2. A: You've set up a proxy to your local Tor instance for the http protocol, but you're using https to talk to "check.torproject.org". Try: print opener.open('http://check.torproject.org/').read()
Python fails Tor check using urllib2 to initiate requests
After reading through the other questions on StackOverflow, I got a snippet of Python code that is able to make requests through a Tor proxy: import urllib2 proxy = urllib2.ProxyHandler({'http':'127.0.0.1:8118'}) opener = urllib2.build_opener(proxy) print opener.open('https://check.torproject.org/').read() Since Tor works fine in Firefox with TorButton, I expected it to work fine in Python. Unfortunately, included in the mess of HTML: Sorry. You are not using Tor. I am not sure why this is the case or how to get Tor working properly with urllib2.
[ "You've set up a proxy to your local Tor instance for the http protocol, but you're using https to talk to \"check.torproject.org\". Try:\nprint opener.open('http://check.torproject.org/').read()\n\n" ]
[ 5 ]
[]
[]
[ "python", "security", "tor", "urllib2" ]
stackoverflow_0002075469_python_security_tor_urllib2.txt
Q: Python 2 and IPv6 I'm trying to enable IPv6 in a Python 2 application and am running into trouble. Whenever I try to bind to an IPv6 socket, a socket.error: getsockaddrarg: bad family exception is thrown. I can reproduce the error simply by doing: import socket s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) s.bind(('', 12345)) This code works fine if I run in Python 3. Unfortunately the script would need a significant porting effort to work in Python 3 and I'd rather not have to do that yet. Is there something I need to do to get IPv6 working in Python 2 or am I S-O-L? Details: Python 2.6.2 (r262:71600, Oct 24 2009, 03:16:31) [GCC 4.4.1 [gcc-4_4-branch revision 150839]] on linux2 (it's the Python that's part of the standard openSUSE 11.2 install). Update After AndiDog helped me figure out that socket.AF_INET6 is defined even when IPv6 is not configured, I discovered socket.has_ipv6. This is defined as a boolean and indicates whether Python was build with IPv6. A: Okay here's the answer from the comments: Seems like Python wasn't configured with --enable-ipv6. It shouldn't be a OS problem because Python 3 works. Even if the OS doesn't have IPv6 support, it seems that socket.AF_INET6 is always available (if it is defined in the OS header files). Cf. socketmodule.c, line 4433 (in current Python 2.6.4 source code). A: Sounds like that particular Python was not compiled with IPv6 support. In which case, you can download the source for that version and build yourself a compatible Python that will work. You may even be able to do some editing in the Debian package and upgrade the system python. A: Works fine with 2.6.4 on my Mac (Mac OS X 10.5.8) -- and unfortunately I can't downgrade to 2.6.2 nor do I have any openSUSE around to check where the bug specifically comes from you. Could you try getting 2.6.4 and building from sources to see if the bug goes away, or check some openSUSE-specific bug tracker...? At least we do know it's not a generic Python 2.6 bug (with the latest, bug-fixed version of 2.6, at least)...
Python 2 and IPv6
I'm trying to enable IPv6 in a Python 2 application and am running into trouble. Whenever I try to bind to an IPv6 socket, a socket.error: getsockaddrarg: bad family exception is thrown. I can reproduce the error simply by doing: import socket s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) s.bind(('', 12345)) This code works fine if I run in Python 3. Unfortunately the script would need a significant porting effort to work in Python 3 and I'd rather not have to do that yet. Is there something I need to do to get IPv6 working in Python 2 or am I S-O-L? Details: Python 2.6.2 (r262:71600, Oct 24 2009, 03:16:31) [GCC 4.4.1 [gcc-4_4-branch revision 150839]] on linux2 (it's the Python that's part of the standard openSUSE 11.2 install). Update After AndiDog helped me figure out that socket.AF_INET6 is defined even when IPv6 is not configured, I discovered socket.has_ipv6. This is defined as a boolean and indicates whether Python was build with IPv6.
[ "Okay here's the answer from the comments:\nSeems like Python wasn't configured with --enable-ipv6.\nIt shouldn't be a OS problem because Python 3 works. Even if the OS doesn't have IPv6 support, it seems that socket.AF_INET6 is always available (if it is defined in the OS header files). Cf. socketmodule.c, line 4433 (in current Python 2.6.4 source code).\n", "Sounds like that particular Python was not compiled with IPv6 support.\nIn which case, you can download the source for that version and build yourself a compatible Python that will work. You may even be able to do some editing in the Debian package and upgrade the system python.\n", "Works fine with 2.6.4 on my Mac (Mac OS X 10.5.8) -- and unfortunately I can't downgrade to 2.6.2 nor do I have any openSUSE around to check where the bug specifically comes from you. Could you try getting 2.6.4 and building from sources to see if the bug goes away, or check some openSUSE-specific bug tracker...? At least we do know it's not a generic Python 2.6 bug (with the latest, bug-fixed version of 2.6, at least)...\n" ]
[ 4, 3, 2 ]
[]
[]
[ "ipv6", "python" ]
stackoverflow_0002075383_ipv6_python.txt
Q: Draw a colored sphere from cartesian coordinates in pymol I was looking in the wiki how to convert the following information about beads, cartesian coordinates + energy : 23.4 54.6 12.3 -123.5 54.5 23.1 9.45 -56.7 ....... to a draw in pymol that contains for each atom a sphere of radius R, centered on its coordinates, and with color, in a rainbow gradient. Thanks A: Does what you're rendering actually have anything to do with molecular structure (i.e. what is the motivation for using PyMol)? If you are drawing some molecular structure, I would recommend just outputting a custom PDB file with the sphere coordinates (you can use the B-factor field per ATOM line as a way of controlling per-atom coloring in PyMol). If you are not drawing a molecular structure, you would be best off using the CGO interface of PyMol. From the PyMol documentation: CGO spheres are generated by the SPHERE command. SPHERE, x,y,z,d where x,y,z are the coordinates of the sphere centre and d is the diameter of the sphere. Note how a COLOR command is used to set the colour of a sphere. As with LINES you only need a COLOR command when the colour of the next sphere to be drawn changes. A simple example: from pymol.cgo import * from pymol import cmd spherelist = [ COLOR, 0.100, 1.000, 0.000, SPHERE, 30.304, 30.407, 30.531,0.30, COLOR, 1.000, 0.000, 0.000, SPHERE, 30.250, 30.250, 30.250,0.20, ] cmd.load_cgo(spherelist, 'segment', 1)
Draw a colored sphere from cartesian coordinates in pymol
I was looking in the wiki how to convert the following information about beads, cartesian coordinates + energy : 23.4 54.6 12.3 -123.5 54.5 23.1 9.45 -56.7 ....... to a draw in pymol that contains for each atom a sphere of radius R, centered on its coordinates, and with color, in a rainbow gradient. Thanks
[ "Does what you're rendering actually have anything to do with molecular structure (i.e. what is the motivation for using PyMol)?\nIf you are drawing some molecular structure, I would recommend just outputting a custom PDB file with the sphere coordinates (you can use the B-factor field per ATOM line as a way of controlling per-atom coloring in PyMol).\nIf you are not drawing a molecular structure, you would be best off using the CGO interface of PyMol.\nFrom the PyMol documentation:\n\nCGO spheres are generated by the\n SPHERE command.\nSPHERE, x,y,z,d\nwhere x,y,z are the coordinates of the\n sphere centre and d is the diameter of\n the sphere. Note how a COLOR command\n is used to set the colour of a sphere.\n As with LINES you only need a COLOR\n command when the colour of the next\n sphere to be drawn changes.\n\nA simple example:\nfrom pymol.cgo import *\nfrom pymol import cmd\n\nspherelist = [\n COLOR, 0.100, 1.000, 0.000,\n SPHERE, 30.304, 30.407, 30.531,0.30,\n COLOR, 1.000, 0.000, 0.000,\n SPHERE, 30.250, 30.250, 30.250,0.20,\n ]\n\ncmd.load_cgo(spherelist, 'segment', 1)\n\n" ]
[ 10 ]
[]
[]
[ "bioinformatics", "python", "visualization" ]
stackoverflow_0002060582_bioinformatics_python_visualization.txt
Q: Connecting signals in GTK+: anonymous way? After reading "Using your signals" I am wondering if it is possible to connect the signals to "sinks" in an "anonymous" way? In order words, if the example following (snippet from reference above): aCar = Car() aCar.connect('engine-started', myCallback) Is it possible just to connect myCallback to all the signal engine-started sources in one go? Something along the lines of: gbus.connect('engine-started', myCallback) Of course gbus here is just an example. A: Yes, you can use gobject.add_emission_hook (g_signal_add_emission_hook).
Connecting signals in GTK+: anonymous way?
After reading "Using your signals" I am wondering if it is possible to connect the signals to "sinks" in an "anonymous" way? In order words, if the example following (snippet from reference above): aCar = Car() aCar.connect('engine-started', myCallback) Is it possible just to connect myCallback to all the signal engine-started sources in one go? Something along the lines of: gbus.connect('engine-started', myCallback) Of course gbus here is just an example.
[ "Yes, you can use gobject.add_emission_hook (g_signal_add_emission_hook).\n" ]
[ 1 ]
[]
[]
[ "gtk", "python" ]
stackoverflow_0002074372_gtk_python.txt
Q: Python: Help Me optimize this code. I am looking to see if this code can be optimized. def gB(a,b,c): x=len(b) d=a.find(b)+x e=a.find(c,d) return a[d:e] print gB("abc","a","c") A: There's a couple of problems with your code that you probably should fix before trying to optimize it. Firstly, it's undocumented and the naming is not helpful. I assume it is trying to extract a string between start and end markers. Secondly, it gives an apparent match even if the start and/or end markers aren't found: >>> print gB("abc", "d", "e") ab It would be much better to raise an exception or return None in this case. As for the speed, I doubt you can get faster for finding strings than using the builtin string finding functions. They are written in C and no doubt had a lot of time spent optimizing them. If someone can implement string finding faster in Python then the people who wrote find need to go back and look at their code again. A: What about this? import re def gB(a, b, c): return (re.findall('%s(.*?)%s' % (b, c), a) or [''])[0] If you are talking about smaller code, I think the re module can help you.
Python: Help Me optimize this code.
I am looking to see if this code can be optimized. def gB(a,b,c): x=len(b) d=a.find(b)+x e=a.find(c,d) return a[d:e] print gB("abc","a","c")
[ "There's a couple of problems with your code that you probably should fix before trying to optimize it.\nFirstly, it's undocumented and the naming is not helpful. I assume it is trying to extract a string between start and end markers.\nSecondly, it gives an apparent match even if the start and/or end markers aren't found:\n>>> print gB(\"abc\", \"d\", \"e\")\nab\n\nIt would be much better to raise an exception or return None in this case.\nAs for the speed, I doubt you can get faster for finding strings than using the builtin string finding functions. They are written in C and no doubt had a lot of time spent optimizing them. If someone can implement string finding faster in Python then the people who wrote find need to go back and look at their code again.\n", "What about this?\nimport re\n\ndef gB(a, b, c):\n return (re.findall('%s(.*?)%s' % (b, c), a) or [''])[0]\n\nIf you are talking about smaller code, I think the re module can help you.\n" ]
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002075573_python.txt
Q: Any tutorial for Python PalmDB library? I've downloaded the Python PalmDB lib, but can't find any info on how to use it. I've tried reading docstrings and so far I've been able to come up with the following code: from pprint import pprint from PalmDB.PalmDatabase import PalmDatabase pdb = PalmDatabase() with open('testdb.pdb','rb') as data: pdb.fromByteArray(data.read()) pprint(dir(pdb)) pprint(pdb.attributes) print pdb.__doc__ #print pdb.records print pdb.records[10].toXML() which gives me the xml representation of a record (?) with some nasty long payload attribute, which doesn't resemble any kind of human-readable text to me. I just want to read the contents of the pdb file. Is there a guide/tutorial for this library? What would you do to figure out the proper way to make things done in my situation? A: There are two problems with the PalmDB module. The first is that it comes with almost no documentation. The other is that in order to do anything useful with the records in the database you need to figure out the binary structure for the particular record type you're dealing with (it's different for each type) and unpack it yourself. I believe the package author did some work with the ToDo format, but none of the others as far as I know. What I needed was something to unpack Palm address records, so I rolled my own module. I posted it [1] so you can take a look get an idea of what's involved. If it's the address book records you're interested in, you're in luck. I created it several years ago, so I don't remember all the details of what I had to do, but I did update it to work with the current version [2] of PalmDB, which completely broke all code using older versions. Hope it's useful! [1] http://pastebin.com/f75a93f48 [2] 1.8.1
Any tutorial for Python PalmDB library?
I've downloaded the Python PalmDB lib, but can't find any info on how to use it. I've tried reading docstrings and so far I've been able to come up with the following code: from pprint import pprint from PalmDB.PalmDatabase import PalmDatabase pdb = PalmDatabase() with open('testdb.pdb','rb') as data: pdb.fromByteArray(data.read()) pprint(dir(pdb)) pprint(pdb.attributes) print pdb.__doc__ #print pdb.records print pdb.records[10].toXML() which gives me the xml representation of a record (?) with some nasty long payload attribute, which doesn't resemble any kind of human-readable text to me. I just want to read the contents of the pdb file. Is there a guide/tutorial for this library? What would you do to figure out the proper way to make things done in my situation?
[ "There are two problems with the PalmDB module. The first is that it comes with almost no documentation. The other is that in order to do anything useful with the records in the database you need to figure out the binary structure for the particular record type you're dealing with (it's different for each type) and unpack it yourself. I believe the package author did some work with the ToDo format, but none of the others as far as I know. What I needed was something to unpack Palm address records, so I rolled my own module. I posted it [1] so you can take a look get an idea of what's involved. If it's the address book records you're interested in, you're in luck. I created it several years ago, so I don't remember all the details of what I had to do, but I did update it to work with the current version [2] of PalmDB, which completely broke all code using older versions. Hope it's useful!\n[1] http://pastebin.com/f75a93f48\n [2] 1.8.1\n" ]
[ 2 ]
[]
[]
[ "palmdb", "pdb_palm", "python" ]
stackoverflow_0001700229_palmdb_pdb_palm_python.txt
Q: Is it possible to edit the inline code in with BeautifulSoup? I am aware of the ability to edit text with beautifulsoup, is it possible to edit the href links? I would like to be able to take say <a href="/foo/bar/"> and use beautifulsoup to change it to <a href="http://www.foobarinc.com/foo/bar/">. I am not sure how I would use beautifulsoup to do this? Any help, much appreciated. A: As in your other question: with BeautifulSoup you're parsing in the content to a set of hierarchically nested objects representing the document, then changing those objects before serialising them back to different text. You're not editing the text directly. The href="..." part of the markup represents an attribute. To access the attributes of each element in BeautifulSoup you use the el[name] item-style access. So to change rooted URLs into absolute ones in a href attributes, it's as simple as: for link in soup.findAll('a'): if link['href'].startswith('/'): link['href']= 'http://www.foobarinc.com'+link['href'] A: Despite what the OP says in a comment to bobince, the following code works just fine: from BeautifulSoup import BeautifulSoup ht = ''' <a href="/foo/bar/">Hello world</a> ''' soup = BeautifulSoup(ht) for link in soup.findAll('a'): if link['href'].startswith('/'): link['href']= 'http://www.foobarinc.com'+link['href'] print soup emits <a href="http://www.foobarinc.com/foo/bar/">Hello world</a> as desired. So, instead of vaguely claiming I was trying similar things to that, but kept getting [none] returned. I cannot find a list of the dictionary that matches the tags. I tried this, and it returned KeyError:href. (???), the OP had better try to modify the code I just posted, getting it closer and closer to his own, until the weird errors [none] returned and KeyError:href (???) appear: at that time, the very last change that made them appear should make it blatantly obvious what the OP is doing wrong -- if not, post the exact data and code, as I did, and the exactly copy-and-pasted traceback (not vague personal paraphrases!-), and I bet we'll be able to help!-)
Is it possible to edit the inline code in with BeautifulSoup?
I am aware of the ability to edit text with beautifulsoup, is it possible to edit the href links? I would like to be able to take say <a href="/foo/bar/"> and use beautifulsoup to change it to <a href="http://www.foobarinc.com/foo/bar/">. I am not sure how I would use beautifulsoup to do this? Any help, much appreciated.
[ "As in your other question: with BeautifulSoup you're parsing in the content to a set of hierarchically nested objects representing the document, then changing those objects before serialising them back to different text. You're not editing the text directly.\nThe href=\"...\" part of the markup represents an attribute. To access the attributes of each element in BeautifulSoup you use the el[name] item-style access. So to change rooted URLs into absolute ones in a href attributes, it's as simple as:\nfor link in soup.findAll('a'):\n if link['href'].startswith('/'):\n link['href']= 'http://www.foobarinc.com'+link['href']\n\n", "Despite what the OP says in a comment to bobince, the following code works just fine:\nfrom BeautifulSoup import BeautifulSoup\n\nht = '''\n <a href=\"/foo/bar/\">Hello world</a>\n'''\nsoup = BeautifulSoup(ht)\n\nfor link in soup.findAll('a'):\n if link['href'].startswith('/'):\n link['href']= 'http://www.foobarinc.com'+link['href']\nprint soup\n\nemits \n<a href=\"http://www.foobarinc.com/foo/bar/\">Hello world</a>\n\nas desired. So, instead of vaguely claiming \n\nI was trying similar things to that,\n but kept getting [none] returned. I\n cannot find a list of the dictionary\n that matches the tags. I tried this,\n and it returned KeyError:href.\n\n(???), the OP had better try to modify the code I just posted, getting it closer and closer to his own, until the weird errors [none] returned and KeyError:href (???) appear: at that time, the very last change that made them appear should make it blatantly obvious what the OP is doing wrong -- if not, post the exact data and code, as I did, and the exactly copy-and-pasted traceback (not vague personal paraphrases!-), and I bet we'll be able to help!-)\n" ]
[ 6, 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002075454_beautifulsoup_python.txt
Q: Accessing related object key without fetching object in App Engine In general, it's better to do a single query vs. many queries for a given object. Let's say I have a bunch of 'son' objects each with a 'father'. I get all the 'son' objects: sons = Son.all() Then, I'd like to get all the fathers for that group of sons. I do: father_keys = {} for son in sons: father_keys.setdefault(son.father.key(), None) Then I can do: fathers = Father.get(father_keys.keys()) Now, this assumes that son.father.key() doesn't actually go fetch the object. Am I wrong on this? I have a bunch of code that assumes the object.related_object.key() doesn't actually fetch related_object from the datastore. Am I doing this right? A: You can find the answer by studying the sources of appengine.ext.db in your download of the App Engine SDK sources -- and the answer is, no, there's no special-casing as you require: the __get__ method (line 2887 in the sources for the 1.3.0 SDK) of the ReferenceProperty descriptor gets invoked before knowing if .key() or anything else will later be invoked on the result, so it just doesn't get a chance to do the optimization you'd like. However, see line 2929: method get_value_for_datastore does do exactly what you want! Specifically, instead of son.father.key(), use Son.father.get_value_for_datastore(son) and you should be much happier as a result;-). A: I'd rather loop through the sons and get parent's keys using son.parent_key(). parent_key() Returns the Key of the parent entity of this instance, or None if this instance does not have a parent. Since all the path is saved in the instance's key, theoretically, there is no need to hit the database again to get the parent's key. After that, it's possible to get all parents' instances at once using db.get(). get(keys) Gets the entity or entities for the given key or keys, of any Model. Arguments: keys A Key object or a list of Key objects. If one Key is provided, the return value is an instance of the appropriate Model class, or None if no entity exists with the given Key. If a list of Keys is provided, the return value is a corresponding list of model instances, with None values when no entity exists for a corresponding Key.
Accessing related object key without fetching object in App Engine
In general, it's better to do a single query vs. many queries for a given object. Let's say I have a bunch of 'son' objects each with a 'father'. I get all the 'son' objects: sons = Son.all() Then, I'd like to get all the fathers for that group of sons. I do: father_keys = {} for son in sons: father_keys.setdefault(son.father.key(), None) Then I can do: fathers = Father.get(father_keys.keys()) Now, this assumes that son.father.key() doesn't actually go fetch the object. Am I wrong on this? I have a bunch of code that assumes the object.related_object.key() doesn't actually fetch related_object from the datastore. Am I doing this right?
[ "You can find the answer by studying the sources of appengine.ext.db in your download of the App Engine SDK sources -- and the answer is, no, there's no special-casing as you require: the __get__ method (line 2887 in the sources for the 1.3.0 SDK) of the ReferenceProperty descriptor gets invoked before knowing if .key() or anything else will later be invoked on the result, so it just doesn't get a chance to do the optimization you'd like.\nHowever, see line 2929: method get_value_for_datastore does do exactly what you want!\nSpecifically, instead of son.father.key(), use Son.father.get_value_for_datastore(son) and you should be much happier as a result;-).\n", "I'd rather loop through the sons and get parent's keys using son.parent_key().\n\nparent_key()\nReturns the Key of the parent entity of this instance, or None if\n this instance does not have a parent.\n\nSince all the path is saved in the instance's key, theoretically, there is no need to hit the database again to get the parent's key.\nAfter that, it's possible to get all parents' instances at once using db.get().\n\nget(keys)\nGets the entity or entities for the given key or keys, of any Model.\nArguments:\nkeys\n A Key object or a list of Key objects.\nIf one Key is provided, the return value is an instance of the\n appropriate Model class, or None if no\n entity exists with the given Key. If a\n list of Keys is provided, the return\n value is a corresponding list of model\n instances, with None values when no\n entity exists for a corresponding Key.\n\n" ]
[ 10, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002075951_google_app_engine_google_cloud_datastore_python.txt
Q: Get only the keys out of a reference property in GAE-Py I've got a an app where I'm storing posts and their authors. Very straightforward each post has one author model. The problem is this: I fetch the last 10 posts using one call, using fetch() with limit = 10. But when I print them out, GAE uses 10 extra gets to access the author details, because the author object is a reference property on the post... a classic n+1 query scenario - 1 query to get 10 posts and then 10 queries to get each author. Is there any way I can iterate over my posts to collect just the author object keys, so I can load them all up at one go using db.get(all_author_keys) A: See my response to this question just a couple hours ago -- a Q almost identical by amazing coincidence by this one, though by a different poster. In short, to do this, use the get_value_for_datastore of the Property object.
Get only the keys out of a reference property in GAE-Py
I've got a an app where I'm storing posts and their authors. Very straightforward each post has one author model. The problem is this: I fetch the last 10 posts using one call, using fetch() with limit = 10. But when I print them out, GAE uses 10 extra gets to access the author details, because the author object is a reference property on the post... a classic n+1 query scenario - 1 query to get 10 posts and then 10 queries to get each author. Is there any way I can iterate over my posts to collect just the author object keys, so I can load them all up at one go using db.get(all_author_keys)
[ "See my response to this question just a couple hours ago -- a Q almost identical by amazing coincidence by this one, though by a different poster.\nIn short, to do this, use the get_value_for_datastore of the Property object.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002076260_google_app_engine_python.txt
Q: Extract string from between quotations I want to extract information from user-inputted text. Imagine I input the following: SetVariables "a" "b" "c" How would I extract information between the first set of quotations? Then the second? Then the third? A: >>> import re >>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ') ['a', 'b', 'c'] A: You could do a string.split() on it. If the string is formatted properly with the quotation marks (i.e. even number of quotation marks), every odd value in the list will contain an element that is between quotation marks. >>> s = 'SetVariables "a" "b" "c"'; >>> l = s.split('"')[1::2]; # the [1::2] is a slicing which extracts odd values >>> print l; ['a', 'b', 'c'] >>> print l[2]; # to show you how to extract individual items from output c This is also a faster approach than regular expressions. With the timeit module, the speed of this code is around 4 times faster: % python timeit.py -s 'import re' 're.findall("\"([^\"]*)\"", "SetVariables \"a\" \"b\" \"c\" ")' 1000000 loops, best of 3: 2.37 usec per loop % python timeit.py '"SetVariables \"a\" \"b\" \"c\"".split("\"")[1::2];' 1000000 loops, best of 3: 0.569 usec per loop A: Regular expressions are good at this: import re quoted = re.compile('"[^"]*"') for value in quoted.findall(userInputtedText): print value
Extract string from between quotations
I want to extract information from user-inputted text. Imagine I input the following: SetVariables "a" "b" "c" How would I extract information between the first set of quotations? Then the second? Then the third?
[ ">>> import re\n>>> re.findall('\"([^\"]*)\"', 'SetVariables \"a\" \"b\" \"c\" ')\n['a', 'b', 'c']\n\n", "You could do a string.split() on it. If the string is formatted properly with the quotation marks (i.e. even number of quotation marks), every odd value in the list will contain an element that is between quotation marks. \n>>> s = 'SetVariables \"a\" \"b\" \"c\"';\n>>> l = s.split('\"')[1::2]; # the [1::2] is a slicing which extracts odd values\n>>> print l;\n['a', 'b', 'c']\n>>> print l[2]; # to show you how to extract individual items from output\nc\n\nThis is also a faster approach than regular expressions. With the timeit module, the speed of this code is around 4 times faster:\n% python timeit.py -s 'import re' 're.findall(\"\\\"([^\\\"]*)\\\"\", \"SetVariables \\\"a\\\" \\\"b\\\" \\\"c\\\" \")'\n1000000 loops, best of 3: 2.37 usec per loop\n\n% python timeit.py '\"SetVariables \\\"a\\\" \\\"b\\\" \\\"c\\\"\".split(\"\\\"\")[1::2];'\n1000000 loops, best of 3: 0.569 usec per loop\n\n", "Regular expressions are good at this:\nimport re\nquoted = re.compile('\"[^\"]*\"')\nfor value in quoted.findall(userInputtedText):\n print value\n\n" ]
[ 60, 40, 15 ]
[]
[]
[ "extraction", "python", "quotations", "string" ]
stackoverflow_0002076343_extraction_python_quotations_string.txt
Q: Simple modeling of existing SQL Server database schema in Python I'm looking to write a few small tools for managing table content for an existing SQL Server 2005 DB. I have a few dozen tables of reference content for an application that is deployed on many client databases (often for different schema versions) and I want to build a few python scripts to export, import, diff, and merge this content across versions while maintaining referential integrity. Is there a simple way to automatically generate python classes to model this content for each database release? I am primarily a sql developer with only a bit of python and java experience, so the simpler the better. EDIT: Forgot to mention that I'd not only like to be able to create the model, but also easily populate the objects from an existing db. A: SqlAlchemy may actually help you . You can have a look here http://www.sqlalchemy.org/docs/05/ormtutorial.html A: Django has documentation on using it with legacy databases, but you will still have to handle things such as specifying relations yourself.
Simple modeling of existing SQL Server database schema in Python
I'm looking to write a few small tools for managing table content for an existing SQL Server 2005 DB. I have a few dozen tables of reference content for an application that is deployed on many client databases (often for different schema versions) and I want to build a few python scripts to export, import, diff, and merge this content across versions while maintaining referential integrity. Is there a simple way to automatically generate python classes to model this content for each database release? I am primarily a sql developer with only a bit of python and java experience, so the simpler the better. EDIT: Forgot to mention that I'd not only like to be able to create the model, but also easily populate the objects from an existing db.
[ "SqlAlchemy may actually help you . You can have a look here http://www.sqlalchemy.org/docs/05/ormtutorial.html\n", "Django has documentation on using it with legacy databases, but you will still have to handle things such as specifying relations yourself.\n" ]
[ 1, 0 ]
[]
[]
[ "orm", "python", "sql_server" ]
stackoverflow_0002076365_orm_python_sql_server.txt
Q: Split list in python I have following list: mylist = ['Hello,\r', 'Whats going on.\r', 'some text'] When I write "mylist" to a file called file.txt open('file.txt', 'w').writelines(mylist) I get for every line a little bit text because of the \r: Hello, Whats going on. some text How can I manipulate mylist to substitute the \r with a space? In the end I need this in file.txt: Hello, Whats going on. sometext It must be a list. Thanks! A: mylist = [s.replace("\r", " ") for s in mylist] This loops through your list, and does a string replace on each element in it. A: open('file.txt', 'w').writelines(map(lambda x: x.replace('\r',' '),mylist)) A: Iterate through the list to a match with a regular expression to replace /r with a space. A: I don't know if you have this luxury, but I actually like to keep my lists of strings without newlines at the end. That way, I can manipulate them, doing things like dumping them out in debug mode, without having to do an "rstrip()" on them. For example, if your strings were saved like: mylist = ['Hello,', 'Whats going on.', 'some text'] Then you could display them like this: print "\n".join(mylist) or print " ".join(mylist) A: Use .rstrip(): >>> mylist = ['Hello,\r', 'Whats going on.\r', 'some text'] >>> ' '.join(map(str.rstrip,mylist)) 'Hello, Whats going on. some text' >>>
Split list in python
I have following list: mylist = ['Hello,\r', 'Whats going on.\r', 'some text'] When I write "mylist" to a file called file.txt open('file.txt', 'w').writelines(mylist) I get for every line a little bit text because of the \r: Hello, Whats going on. some text How can I manipulate mylist to substitute the \r with a space? In the end I need this in file.txt: Hello, Whats going on. sometext It must be a list. Thanks!
[ "mylist = [s.replace(\"\\r\", \" \") for s in mylist]\n\nThis loops through your list, and does a string replace on each element in it.\n", "open('file.txt', 'w').writelines(map(lambda x: x.replace('\\r',' '),mylist))\n\n", "Iterate through the list to a match with a regular expression to replace /r with a space.\n", "I don't know if you have this luxury, but I actually like to keep my lists of strings without newlines at the end. That way, I can manipulate them, doing things like dumping them out in debug mode, without having to do an \"rstrip()\" on them.\nFor example, if your strings were saved like:\nmylist = ['Hello,', 'Whats going on.', 'some text']\n\nThen you could display them like this:\nprint \"\\n\".join(mylist)\n\nor\nprint \" \".join(mylist)\n\n", "Use .rstrip(): \n>>> mylist = ['Hello,\\r', 'Whats going on.\\r', 'some text']\n>>> ' '.join(map(str.rstrip,mylist))\n'Hello, Whats going on. some text'\n>>>\n\n" ]
[ 5, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002075199_python.txt
Q: Using classes for Django views, is it Pythonic? I'm currently learning Python and coming from a strong C# background. I keep hearing about doing things in a Pythonic way to take advantage of the dynamic nature of the language and some of it I get and some I don't. I'm creating a site with Django and my approach to views is to use classes. My current thinking is to have a base class that has some stuff about the template and the model to use. This will have a default funky 404 type page with site search and stuff on then base all the other pages off this. So each area of the site will have its own EG News and all the model related functions and filtering will be in that class with a further class on top of that for HTML or AJAX requests. So you would have something like this: \site\common\ViewBase --\news\NewsBase(ViewBase) --\news\HtmlView(NewsBase) --\news\AJAXView(NewsBase) URLs would be mapped like http://tld/news/latest maps to site.news.htmlview and http://tld/news//to/ will be also be mapped site.news.htmlview but the class will figure out what to do with the extra params. This is pretty much what I would do in C# but the Django tutorial only shows using methods for views, making me wonder if this is not a very pythonic solution? Thoughts? Edit: After S.Lott comment about thread safety, Is it better to leave the functions as they are and have them create an instance of a class and call a method on it? What I am looking for is a place to put common code for each section of the site for filtering the model, authentication for the site, etc A: Certainly there's nothing wrong with using a class for a view, provided you route the URL to an actual instance of a class and not just a class directly. A: The Django admin does exactly this - look at the source code in django/contrib/admin. The advantage of classes is that they are much easier to customize, for example you can add hooks for permission checking. There is a proposal to move all existing generic views over to classes, it was supposed to get into 1.2 but failed to meet the deadline. As the above poster points out, be very careful about handling instance variables - if you look at the admin classes, you see the request being passed to the various methods instead of relying on "self". A: Setting aside other concerns (such as thread-safety issues), it feels like there's a real possible danger here to cross the bright lines between Model / View / Template. Or maybe it feels like a replacement for url dispatching (not that there's anything wrong with that :-). I'm not sure, but it just feels slightly off. A: While class-based views are useful, inheritance may not be the right tool for this particular job. Helper functions and decorators are two great ways to factor out common code from your views. They also tend to be be more familiar/natural to other (python) coders who might work on your code. I'm not sure what the best approach is in your case as I don't know how much you ultimately want to factor, just keep in mind that there are other ways to factor in python besides inheritance. p.s. kudos for seeking out a pythonic solution.
Using classes for Django views, is it Pythonic?
I'm currently learning Python and coming from a strong C# background. I keep hearing about doing things in a Pythonic way to take advantage of the dynamic nature of the language and some of it I get and some I don't. I'm creating a site with Django and my approach to views is to use classes. My current thinking is to have a base class that has some stuff about the template and the model to use. This will have a default funky 404 type page with site search and stuff on then base all the other pages off this. So each area of the site will have its own EG News and all the model related functions and filtering will be in that class with a further class on top of that for HTML or AJAX requests. So you would have something like this: \site\common\ViewBase --\news\NewsBase(ViewBase) --\news\HtmlView(NewsBase) --\news\AJAXView(NewsBase) URLs would be mapped like http://tld/news/latest maps to site.news.htmlview and http://tld/news//to/ will be also be mapped site.news.htmlview but the class will figure out what to do with the extra params. This is pretty much what I would do in C# but the Django tutorial only shows using methods for views, making me wonder if this is not a very pythonic solution? Thoughts? Edit: After S.Lott comment about thread safety, Is it better to leave the functions as they are and have them create an instance of a class and call a method on it? What I am looking for is a place to put common code for each section of the site for filtering the model, authentication for the site, etc
[ "Certainly there's nothing wrong with using a class for a view, provided you route the URL to an actual instance of a class and not just a class directly.\n", "The Django admin does exactly this - look at the source code in django/contrib/admin. \nThe advantage of classes is that they are much easier to customize, for example you can add hooks for permission checking.\nThere is a proposal to move all existing generic views over to classes, it was supposed to get into 1.2 but failed to meet the deadline.\nAs the above poster points out, be very careful about handling instance variables - if you look at the admin classes, you see the request being passed to the various methods instead of relying on \"self\".\n", "Setting aside other concerns (such as thread-safety issues), it feels like there's a real possible danger here to cross the bright lines between Model / View / Template. \nOr maybe it feels like a replacement for url dispatching (not that there's anything wrong with that :-). I'm not sure, but it just feels slightly off.\n", "While class-based views are useful, inheritance may not be the right tool for this particular job. Helper functions and decorators are two great ways to factor out common code from your views. They also tend to be be more familiar/natural to other (python) coders who might work on your code.\nI'm not sure what the best approach is in your case as I don't know how much you ultimately want to factor, just keep in mind that there are other ways to factor in python besides inheritance.\np.s. kudos for seeking out a pythonic solution.\n" ]
[ 4, 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002071258_django_python.txt
Q: Implementation limitations of float.as_integer_ratio() Recently, a correspondent mentioned float.as_integer_ratio(), new in Python 2.6, noting that typical floating point implementations are essentially rational approximations of real numbers. Intrigued, I had to try π: >>> float.as_integer_ratio(math.pi); (884279719003555L, 281474976710656L) I was mildly surprised not to see the more accurate result due to Arima,: (428224593349304L, 136308121570117L) For example, this code: #! /usr/bin/env python from decimal import * getcontext().prec = 36 print "python: ",Decimal(884279719003555) / Decimal(281474976710656) print "Arima: ",Decimal(428224593349304) / Decimal(136308121570117) print "Wiki: 3.14159265358979323846264338327950288" produces this output: python: 3.14159265358979311599796346854418516 Arima: 3.14159265358979323846264338327569743 Wiki: 3.14159265358979323846264338327950288 Certainly, the result is correct given the precision afforded by 64-bit floating-point numbers, but it leads me to ask: How can I find out more about the implementation limitations of as_integer_ratio()? Thanks for any guidance. Additional links: Stern-Brocot tree and Python source. A: You get better approximations using fractions.Fraction.from_float(math.pi).limit_denominator() Fractions are included since maybe version 3.0. However, math.pi doesn't have enough accuracy to return a 30 digit approximation. A: May I recommend gmpy's implementation of the Stern-Brocot tree: >>> import gmpy >>> import math >>> gmpy.mpq(math.pi) mpq(245850922,78256779) >>> x=_ >>> float(x) 3.1415926535897931 >>> again, the result is "correct within the precision of 64-bit floats" (53-bit "so-called" mantissas;-), but: >>> 245850922 + 78256779 324107701 >>> 884279719003555 + 281474976710656 1165754695714211L >>> 428224593349304L + 136308121570117 564532714919421L ...gmpy's precision is obtained so much cheaper (in terms of sum of numerator and denominator values) than Arima's, much less Python 2.6's!-) A: The algorithm used by as_integer_ratio only considers powers of 2 in the denominator. Here is a (probably) better algorithm.
Implementation limitations of float.as_integer_ratio()
Recently, a correspondent mentioned float.as_integer_ratio(), new in Python 2.6, noting that typical floating point implementations are essentially rational approximations of real numbers. Intrigued, I had to try π: >>> float.as_integer_ratio(math.pi); (884279719003555L, 281474976710656L) I was mildly surprised not to see the more accurate result due to Arima,: (428224593349304L, 136308121570117L) For example, this code: #! /usr/bin/env python from decimal import * getcontext().prec = 36 print "python: ",Decimal(884279719003555) / Decimal(281474976710656) print "Arima: ",Decimal(428224593349304) / Decimal(136308121570117) print "Wiki: 3.14159265358979323846264338327950288" produces this output: python: 3.14159265358979311599796346854418516 Arima: 3.14159265358979323846264338327569743 Wiki: 3.14159265358979323846264338327950288 Certainly, the result is correct given the precision afforded by 64-bit floating-point numbers, but it leads me to ask: How can I find out more about the implementation limitations of as_integer_ratio()? Thanks for any guidance. Additional links: Stern-Brocot tree and Python source.
[ "You get better approximations using\nfractions.Fraction.from_float(math.pi).limit_denominator()\n\nFractions are included since maybe version 3.0.\nHowever, math.pi doesn't have enough accuracy to return a 30 digit approximation.\n", "May I recommend gmpy's implementation of the Stern-Brocot tree:\n>>> import gmpy\n>>> import math\n>>> gmpy.mpq(math.pi)\nmpq(245850922,78256779)\n>>> x=_\n>>> float(x)\n3.1415926535897931\n>>> \n\nagain, the result is \"correct within the precision of 64-bit floats\" (53-bit \"so-called\" mantissas;-), but:\n>>> 245850922 + 78256779\n324107701\n>>> 884279719003555 + 281474976710656\n1165754695714211L\n>>> 428224593349304L + 136308121570117\n564532714919421L\n\n...gmpy's precision is obtained so much cheaper (in terms of sum of numerator and denominator values) than Arima's, much less Python 2.6's!-)\n", "The algorithm used by as_integer_ratio only considers powers of 2 in the denominator. Here is a (probably) better algorithm.\n" ]
[ 10, 5, 4 ]
[]
[]
[ "math", "python" ]
stackoverflow_0002076290_math_python.txt
Q: Python C-API Making len(...) work with extension class When creating a class in Python, I can simply make a def __len__(self): method to make the len(InstanceOfMyClass) work, however I can't find out how to do this with an extension class via the C-API. I tried adding a __len__ method, but that appears to not work {"__len__",(PyCFunction)&TestClass_GetLen,METH_NOARGS,""}, Python test code: def test(my_instance): x = len(my_instance)#exception return x TypeError: object of type 'test_module.test_class' has no len() Code for TestClass struct TestClass; static int TestClass_Init(TestClass *self, PyObject *args, PyObject* kwds); static void TestClass_Dealloc(TestClass *self); static PyObject* TestClass_GetLen(TestClass *self); struct TestClass { PyObject_HEAD; }; static PyMethodDef TestClass_methods[] = { {"__len__",(PyCFunction)&TestClass_GetLen,METH_O,""}, {NULL} }; static PyTypeObject TestClass_type = {PyObject_HEAD_INIT(NULL)}; bool InitTestClass(PyObject *module) { TestClass_type.tp_basicsize = sizeof(TestClass); TestClass_type.tp_name = PY_MODULE_NAME".TestClass"; TestClass_type.tp_doc = ""; TestClass_type.tp_flags = Py_TPFLAGS_DEFAULT; TestClass_type.tp_methods = TestClass_methods; TestClass_type.tp_new = PyType_GenericNew; TestClass_type.tp_init = (initproc)TestClass_Init; TestClass_type.tp_dealloc = (destructor)TestClass_Dealloc; if(PyType_Ready(TestClass_type) < 0) return false; Py_INCREF(TestClass_type); PyModule_AddObject(module, "TestClass", (PyObject*)&TestClass_type); return true; }; void TestClass_Dealloc(TestClass *self) { Py_TYPE(self)->tp_free((PyObject*)self); } int TestClass_Init(TestClass *self, PyObject *args, PyObject* kwds) { return 0; } PyObject* TestClass_GetLen(TestClass *self) { return PyLong_FromLong(55); } A: As Igniacio says, the correct way is to fill the tp_as_sequence member of your typeobject. Here is a minimal example: #include <Python.h> /** * C structure and methods definitions */ typedef struct { PyObject_HEAD; } TestObject; static Py_ssize_t TestClass_len(TestObject* self) { return 55; } /** * Python definitions */ static PySequenceMethods TestClass_sequence_methods = { TestClass_len, /* sq_length */ }; static PyTypeObject TestClass = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "testmodule.TestClass", /*tp_name*/ sizeof(TestObject), /*tp_basicsize*/ }; /** * Module entry point */ #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC inittestmodule(void) { PyObject* m; TestClass.tp_new = PyType_GenericNew; TestClass.tp_as_sequence = &TestClass_sequence_methods; TestClass.tp_flags = Py_TPFLAGS_DEFAULT; if (PyType_Ready(&TestClass) < 0) return; m = Py_InitModule3("testmodule", NULL, ""); Py_INCREF(&TestClass); PyModule_AddObject(m, "TestClass", (PyObject *)&TestClass); } Another (more complicated and slower) way is to add a __len__ method to your class dynamically in the module's init function with PyCFunction_New, PyMethod_New and PyObject_SetAttr. This would look more like the code you pasted, except that you defined __len__ in the C methods table, which doesn't work. A: The tp_as_sequence member of the typeobject structure should be filled in with something that has its sq_length member populated.
Python C-API Making len(...) work with extension class
When creating a class in Python, I can simply make a def __len__(self): method to make the len(InstanceOfMyClass) work, however I can't find out how to do this with an extension class via the C-API. I tried adding a __len__ method, but that appears to not work {"__len__",(PyCFunction)&TestClass_GetLen,METH_NOARGS,""}, Python test code: def test(my_instance): x = len(my_instance)#exception return x TypeError: object of type 'test_module.test_class' has no len() Code for TestClass struct TestClass; static int TestClass_Init(TestClass *self, PyObject *args, PyObject* kwds); static void TestClass_Dealloc(TestClass *self); static PyObject* TestClass_GetLen(TestClass *self); struct TestClass { PyObject_HEAD; }; static PyMethodDef TestClass_methods[] = { {"__len__",(PyCFunction)&TestClass_GetLen,METH_O,""}, {NULL} }; static PyTypeObject TestClass_type = {PyObject_HEAD_INIT(NULL)}; bool InitTestClass(PyObject *module) { TestClass_type.tp_basicsize = sizeof(TestClass); TestClass_type.tp_name = PY_MODULE_NAME".TestClass"; TestClass_type.tp_doc = ""; TestClass_type.tp_flags = Py_TPFLAGS_DEFAULT; TestClass_type.tp_methods = TestClass_methods; TestClass_type.tp_new = PyType_GenericNew; TestClass_type.tp_init = (initproc)TestClass_Init; TestClass_type.tp_dealloc = (destructor)TestClass_Dealloc; if(PyType_Ready(TestClass_type) < 0) return false; Py_INCREF(TestClass_type); PyModule_AddObject(module, "TestClass", (PyObject*)&TestClass_type); return true; }; void TestClass_Dealloc(TestClass *self) { Py_TYPE(self)->tp_free((PyObject*)self); } int TestClass_Init(TestClass *self, PyObject *args, PyObject* kwds) { return 0; } PyObject* TestClass_GetLen(TestClass *self) { return PyLong_FromLong(55); }
[ "As Igniacio says, the correct way is to fill the tp_as_sequence member of your typeobject. Here is a minimal example:\n#include <Python.h>\n\n/**\n * C structure and methods definitions\n */\n\ntypedef struct {\n PyObject_HEAD;\n} TestObject;\n\nstatic Py_ssize_t\nTestClass_len(TestObject* self) \n{ \n return 55;\n}\n\n/**\n * Python definitions\n */\n\nstatic PySequenceMethods TestClass_sequence_methods = {\n TestClass_len, /* sq_length */\n};\n\nstatic PyTypeObject TestClass = {\n PyObject_HEAD_INIT(NULL) \n 0, /*ob_size*/\n \"testmodule.TestClass\", /*tp_name*/\n sizeof(TestObject), /*tp_basicsize*/\n};\n\n/**\n * Module entry point\n */\n#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */\n#define PyMODINIT_FUNC void\n#endif\nPyMODINIT_FUNC\ninittestmodule(void) \n{\n PyObject* m;\n\n TestClass.tp_new = PyType_GenericNew;\n TestClass.tp_as_sequence = &TestClass_sequence_methods;\n TestClass.tp_flags = Py_TPFLAGS_DEFAULT;\n\n if (PyType_Ready(&TestClass) < 0)\n return;\n\n m = Py_InitModule3(\"testmodule\", NULL, \"\");\n\n Py_INCREF(&TestClass);\n PyModule_AddObject(m, \"TestClass\", (PyObject *)&TestClass);\n}\n\nAnother (more complicated and slower) way is to add a __len__ method to your class dynamically in the module's init function with PyCFunction_New, PyMethod_New and PyObject_SetAttr. This would look more like the code you pasted, except that you defined __len__ in the C methods table, which doesn't work.\n", "The tp_as_sequence member of the typeobject structure should be filled in with something that has its sq_length member populated.\n" ]
[ 3, 3 ]
[]
[]
[ "c", "python", "python_c_api" ]
stackoverflow_0002064276_c_python_python_c_api.txt
Q: Finding the performance bottleneck in a Python and MySQL script I have a script with a main for loop that repeats about 15k times. In this loop it queries a local MySQL database and does a SVN update on a local repository. I placed the SVN repository in a RAMdisk as before most of the time seemed to be spent reading/writing to disk. Now I have a script that runs at basically the same speed but CPU utilization for that script never goes over 10%. ProcessExplorer shows that mysqld is also not taking almost any CPU time or reading/writing a lot to disk. What steps would you take to figure out where the bottleneck is? A: Doing SQL queries in a for loop 15k times is a bottleneck in every language.. Is there any reason you query every time again ? If you do a single query before the for loop and then loop over the resultset and the SVN part, you will see a dramatic increase in speed. But I doubt that you will get a higher CPU usage. The reason is that you are not doing calculations, but mostly IO. Btw, you can't measure that in mysqld cpu usage, as it's in the actual code not complexity of the queries, but their count and the latency of the server engine to answer. So you will see only very short, not expensive queries, that do sum up in time, though. A: Profile your Python code. That will show you how long each function/method call takes. If that's the method call querying the MySQL database, you'll have a clue where to look. But it also may be something else. In any case, profiling is the usual approach to solve such problems. A: It is "well known", so to speak, that svn update waits up to a whole second after it has finished running, so that file modification timestamps get "in the past" (since many filesystems don't have a timestamp granularity finer than one second). You can find more information about it by Googling for "svn sleep_for_timestamps". I don't have any obvious solution to suggest. If this is really performance critical you could either: 1) not update as often as you are doing 2) try to use a lower-level Subversion API (good luck).
Finding the performance bottleneck in a Python and MySQL script
I have a script with a main for loop that repeats about 15k times. In this loop it queries a local MySQL database and does a SVN update on a local repository. I placed the SVN repository in a RAMdisk as before most of the time seemed to be spent reading/writing to disk. Now I have a script that runs at basically the same speed but CPU utilization for that script never goes over 10%. ProcessExplorer shows that mysqld is also not taking almost any CPU time or reading/writing a lot to disk. What steps would you take to figure out where the bottleneck is?
[ "Doing SQL queries in a for loop 15k times is a bottleneck in every language.. \nIs there any reason you query every time again ? If you do a single query before the for loop and then loop over the resultset and the SVN part, you will see a dramatic increase in speed.\nBut I doubt that you will get a higher CPU usage. The reason is that you are not doing calculations, but mostly IO. \nBtw, you can't measure that in mysqld cpu usage, as it's in the actual code not complexity of the queries, but their count and the latency of the server engine to answer. So you will see only very short, not expensive queries, that do sum up in time, though.\n", "Profile your Python code. That will show you how long each function/method call takes. If that's the method call querying the MySQL database, you'll have a clue where to look. But it also may be something else. In any case, profiling is the usual approach to solve such problems.\n", "It is \"well known\", so to speak, that svn update waits up to a whole second after it has finished running, so that file modification timestamps get \"in the past\" (since many filesystems don't have a timestamp granularity finer than one second). You can find more information about it by Googling for \"svn sleep_for_timestamps\".\nI don't have any obvious solution to suggest. If this is really performance critical you could either: 1) not update as often as you are doing 2) try to use a lower-level Subversion API (good luck).\n" ]
[ 4, 1, 1 ]
[]
[]
[ "mysql", "performance", "python", "svn" ]
stackoverflow_0002076582_mysql_performance_python_svn.txt
Q: GAE: Making many queries into one I have a productpart database containing a string property named 'type'. What I'm trying to do is to get all products by a given type (sometimes more then one type). I've tried to use GAE filter method but can't get it to work properly. The only solution I've got working is to make a new db.GqlQuery for each type. The reason I need to fetch each by type is to display them in different 's on the client side? Is there a way to use just one query for this? Currently it looks like this : productPartsEntries = { 'color' : db.GqlQuery("SELECT * FROM ProductParts WHERE type = :type", type = 'color'), 'style' : db.GqlQuery("SELECT * FROM ProductParts WHERE type = :type", type = 'style'), 'size' : db.GqlQuery("SELECT * FROM ProductParts WHERE type = :type", type = 'size') // add more.... } ..fredrik A: You can use the IN operator. It would create the three different queries and group the results together for you under the scenes. See the docs: GQL does not have an OR operator. However, it does have an IN operator, which provides a limited form of OR. The IN operator compares value of a property to each item in a list. The IN operator is equivalent to many = queries, one for each value, that are ORed together. An entity whose value for the given property equals any of the values in the list can be returned for the query. Note: The IN and != operators use multiple queries behind the scenes. For example, the IN operator executes a separate underlying datastore query for every item in the list. The entities returned are a result of the cross-product of all the underlying datastore queries and are de-duplicated. A maximum of 30 datastore queries are allowed for any single GQL query.
GAE: Making many queries into one
I have a productpart database containing a string property named 'type'. What I'm trying to do is to get all products by a given type (sometimes more then one type). I've tried to use GAE filter method but can't get it to work properly. The only solution I've got working is to make a new db.GqlQuery for each type. The reason I need to fetch each by type is to display them in different 's on the client side? Is there a way to use just one query for this? Currently it looks like this : productPartsEntries = { 'color' : db.GqlQuery("SELECT * FROM ProductParts WHERE type = :type", type = 'color'), 'style' : db.GqlQuery("SELECT * FROM ProductParts WHERE type = :type", type = 'style'), 'size' : db.GqlQuery("SELECT * FROM ProductParts WHERE type = :type", type = 'size') // add more.... } ..fredrik
[ "You can use the IN operator. It would create the three different queries and group the results together for you under the scenes. See the docs:\n\nGQL does not have an OR operator.\n However, it does have an IN operator,\n which provides a limited form of OR.\nThe IN operator compares value of a\n property to each item in a list. The\n IN operator is equivalent to many =\n queries, one for each value, that are\n ORed together. An entity whose value\n for the given property equals any of\n the values in the list can be returned\n for the query.\nNote: The IN and != operators use multiple queries behind the scenes.\n For example, the IN operator executes\n a separate underlying datastore query\n for every item in the list. The\n entities returned are a result of the\n cross-product of all the underlying\n datastore queries and are\n de-duplicated. A maximum of 30\n datastore queries are allowed for any\n single GQL query.\n\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002077034_google_app_engine_google_cloud_datastore_python.txt
Q: DB a table for the category and another table for the subcategory with similar fields, why? I recently joined a new company and the development team was in the progress of a project to rebuild the database categories structure as follows: if we have category and subcategory for items, like food category and italian food category in food category. They were building a table for each category, instead of having one table and a link to the category id. Now we have a table called food and another table called food_italian and both tables contain the same fields. I have asked around and it seems that some DBA prefers this design. I would like to know why? and how this design can improve the performance? A: First, the most obvious answer is that you should ask them, not us, since I can tell you this, that design seems bogus deluxe. The only reason I can come up with is that you have inexperienced DBA's that does not know how to performance-tune a database, and seems to think that a table with less rows will always vastly outperform a table with more rows. With good indices, that need not be the case. A: There are more than one way to do anything. The possible benefit I see in doing the food, food_italian... is that it allows for table partitioning. Using many different tables allow for better table locking mechanism if you are using myisam.
DB a table for the category and another table for the subcategory with similar fields, why?
I recently joined a new company and the development team was in the progress of a project to rebuild the database categories structure as follows: if we have category and subcategory for items, like food category and italian food category in food category. They were building a table for each category, instead of having one table and a link to the category id. Now we have a table called food and another table called food_italian and both tables contain the same fields. I have asked around and it seems that some DBA prefers this design. I would like to know why? and how this design can improve the performance?
[ "First, the most obvious answer is that you should ask them, not us, since I can tell you this, that design seems bogus deluxe.\nThe only reason I can come up with is that you have inexperienced DBA's that does not know how to performance-tune a database, and seems to think that a table with less rows will always vastly outperform a table with more rows.\nWith good indices, that need not be the case.\n", "There are more than one way to do anything.\nThe possible benefit I see in doing the food, food_italian... is that it allows for table partitioning. Using many different tables allow for better table locking mechanism if you are using myisam.\n" ]
[ 2, 0 ]
[]
[]
[ "database", "django", "mysql", "performance", "python" ]
stackoverflow_0002077522_database_django_mysql_performance_python.txt
Q: Why should I make multiple wx.Panel's? Following this tutorial on WxPython, I've noticed that in the Find/Replace Dialog example there are extra panels where it doesn't seem like they're actually doing anything. In fact, they seem to mess up even more the layout (though that is probably some mistake I made somewhere) For example, the tutorial has this code: panel = wx.Panel(self, -1) panel1 = wx.Panel(panel, -1) grid1 = wx.GridSizer(2, 2) grid1.Add(wx.StaticText(panel1, -1, 'Find: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL) grid1.Add(wx.ComboBox(panel1, -1, size=(120, -1))) grid1.Add(wx.StaticText(panel1, -1, 'Replace with: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL) grid1.Add(wx.ComboBox(panel1, -1, size=(120, -1))) panel1.SetSizer(grid1) vbox.Add(panel1, 0, wx.BOTTOM | wx.TOP, 9) Why is that different from: panel = wx.Panel(self, -1) grid1 = wx.GridSizer(2, 2) grid1.Add(wx.StaticText(panel, -1, 'Find: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL) grid1.Add(wx.ComboBox(panel, -1, size=(120, -1))) grid1.Add(wx.StaticText(panel, -1, 'Replace with: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL) grid1.Add(wx.ComboBox(panel, -1, size=(120, -1))) vbox.Add(grid1, 0, wx.BOTTOM | wx.TOP, 9) Note that I'm not creating a panel, just adding grid1 directly to vbox. A: I'm not sure. I've re-written the example into less code, although it's a bit hard to follow. I may e-mail this suggestions to her. import wx class FindReplace(wx.Dialog): def __init__(self, parent, id, title): wx.Dialog.__init__(self, parent, id, title, size=(255, 365)) vbox_top = wx.BoxSizer(wx.VERTICAL) vbox = wx.BoxSizer(wx.VERTICAL) grid1 = wx.GridSizer(2, 2) grid1.Add(wx.StaticText(self, -1, 'Find: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL) grid1.Add(wx.ComboBox(self, -1, size=(120, -1))) grid1.Add(wx.StaticText(self, -1, 'Replace with: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL) grid1.Add(wx.ComboBox(self, -1, size=(120, -1))) hbox2 = wx.BoxSizer(wx.HORIZONTAL) sizer21 = wx.StaticBoxSizer(wx.StaticBox(self, -1, 'Direction'), orient=wx.VERTICAL) sizer21.Add(wx.RadioButton(self, -1, 'Forward', style=wx.RB_GROUP)) sizer21.Add(wx.RadioButton(self, -1, 'Backward')) hbox2.Add(sizer21, 1, wx.RIGHT, 5) sizer22 = wx.StaticBoxSizer(wx.StaticBox(self, -1, 'Scope'), orient=wx.VERTICAL) # we must define wx.RB_GROUP style, otherwise all 4 RadioButtons would be mutually exclusive sizer22.Add(wx.RadioButton(self, -1, 'All', style=wx.RB_GROUP)) sizer22.Add(wx.RadioButton(self, -1, 'Selected Lines')) hbox2.Add(sizer22, 1) sizer3 = wx.StaticBoxSizer(wx.StaticBox(self, -1, 'Options'), orient=wx.VERTICAL) vbox3 = wx.BoxSizer(wx.VERTICAL) grid = wx.GridSizer(3, 2, 0, 5) grid.Add(wx.CheckBox(self, -1, 'Case Sensitive')) grid.Add(wx.CheckBox(self, -1, 'Wrap Search')) grid.Add(wx.CheckBox(self, -1, 'Whole Word')) grid.Add(wx.CheckBox(self, -1, 'Incremental')) vbox3.Add(grid) vbox3.Add(wx.CheckBox(self, -1, 'Regular expressions')) sizer3.Add(vbox3, 0, wx.TOP, 4) sizer4 = wx.GridSizer(2, 2, 2, 2) sizer4.Add(wx.Button(self, -1, 'Find', size=(120, -1))) sizer4.Add(wx.Button(self, -1, 'Replace/Find', size=(120, -1))) sizer4.Add(wx.Button(self, -1, 'Replace', size=(120, -1))) sizer4.Add(wx.Button(self, -1, 'Replace All', size=(120, -1))) sizer5 = wx.BoxSizer(wx.HORIZONTAL) sizer5.Add((191, -1), 1, wx.EXPAND | wx.ALIGN_RIGHT) sizer5.Add(wx.Button(self, -1, 'Close', size=(50, -1))) vbox.Add(grid1, 0, wx.BOTTOM | wx.TOP, 9) vbox.Add(hbox2, 0, wx.BOTTOM, 9) vbox.Add(sizer3, 0, wx.BOTTOM, 15) vbox.Add(sizer4, 0, wx.BOTTOM, 9) vbox.Add(sizer5, 1, wx.BOTTOM, 9) vbox_top.Add(vbox, 1, wx.LEFT, 5) self.SetSizer(vbox_top) self.Centre() app = wx.App(False) d = FindReplace(None, -1, 'Find/Replace') d.ShowModal() d.Destroy() app.MainLoop()
Why should I make multiple wx.Panel's?
Following this tutorial on WxPython, I've noticed that in the Find/Replace Dialog example there are extra panels where it doesn't seem like they're actually doing anything. In fact, they seem to mess up even more the layout (though that is probably some mistake I made somewhere) For example, the tutorial has this code: panel = wx.Panel(self, -1) panel1 = wx.Panel(panel, -1) grid1 = wx.GridSizer(2, 2) grid1.Add(wx.StaticText(panel1, -1, 'Find: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL) grid1.Add(wx.ComboBox(panel1, -1, size=(120, -1))) grid1.Add(wx.StaticText(panel1, -1, 'Replace with: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL) grid1.Add(wx.ComboBox(panel1, -1, size=(120, -1))) panel1.SetSizer(grid1) vbox.Add(panel1, 0, wx.BOTTOM | wx.TOP, 9) Why is that different from: panel = wx.Panel(self, -1) grid1 = wx.GridSizer(2, 2) grid1.Add(wx.StaticText(panel, -1, 'Find: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL) grid1.Add(wx.ComboBox(panel, -1, size=(120, -1))) grid1.Add(wx.StaticText(panel, -1, 'Replace with: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL) grid1.Add(wx.ComboBox(panel, -1, size=(120, -1))) vbox.Add(grid1, 0, wx.BOTTOM | wx.TOP, 9) Note that I'm not creating a panel, just adding grid1 directly to vbox.
[ "I'm not sure. I've re-written the example into less code, although it's a bit hard to follow. I may e-mail this suggestions to her.\nimport wx\n\nclass FindReplace(wx.Dialog):\n def __init__(self, parent, id, title):\n wx.Dialog.__init__(self, parent, id, title, size=(255, 365))\n\n vbox_top = wx.BoxSizer(wx.VERTICAL)\n vbox = wx.BoxSizer(wx.VERTICAL)\n\n grid1 = wx.GridSizer(2, 2)\n grid1.Add(wx.StaticText(self, -1, 'Find: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL)\n grid1.Add(wx.ComboBox(self, -1, size=(120, -1)))\n grid1.Add(wx.StaticText(self, -1, 'Replace with: ', (5, 5)), 0, wx.ALIGN_CENTER_VERTICAL)\n grid1.Add(wx.ComboBox(self, -1, size=(120, -1)))\n\n\n hbox2 = wx.BoxSizer(wx.HORIZONTAL)\n sizer21 = wx.StaticBoxSizer(wx.StaticBox(self, -1, 'Direction'), orient=wx.VERTICAL)\n sizer21.Add(wx.RadioButton(self, -1, 'Forward', style=wx.RB_GROUP))\n sizer21.Add(wx.RadioButton(self, -1, 'Backward'))\n hbox2.Add(sizer21, 1, wx.RIGHT, 5)\n\n sizer22 = wx.StaticBoxSizer(wx.StaticBox(self, -1, 'Scope'), orient=wx.VERTICAL)\n # we must define wx.RB_GROUP style, otherwise all 4 RadioButtons would be mutually exclusive\n sizer22.Add(wx.RadioButton(self, -1, 'All', style=wx.RB_GROUP))\n sizer22.Add(wx.RadioButton(self, -1, 'Selected Lines'))\n hbox2.Add(sizer22, 1)\n\n\n sizer3 = wx.StaticBoxSizer(wx.StaticBox(self, -1, 'Options'), orient=wx.VERTICAL)\n vbox3 = wx.BoxSizer(wx.VERTICAL)\n grid = wx.GridSizer(3, 2, 0, 5)\n grid.Add(wx.CheckBox(self, -1, 'Case Sensitive'))\n grid.Add(wx.CheckBox(self, -1, 'Wrap Search'))\n grid.Add(wx.CheckBox(self, -1, 'Whole Word'))\n grid.Add(wx.CheckBox(self, -1, 'Incremental'))\n vbox3.Add(grid)\n vbox3.Add(wx.CheckBox(self, -1, 'Regular expressions'))\n sizer3.Add(vbox3, 0, wx.TOP, 4)\n\n\n sizer4 = wx.GridSizer(2, 2, 2, 2)\n sizer4.Add(wx.Button(self, -1, 'Find', size=(120, -1)))\n sizer4.Add(wx.Button(self, -1, 'Replace/Find', size=(120, -1)))\n sizer4.Add(wx.Button(self, -1, 'Replace', size=(120, -1)))\n sizer4.Add(wx.Button(self, -1, 'Replace All', size=(120, -1)))\n\n sizer5 = wx.BoxSizer(wx.HORIZONTAL)\n sizer5.Add((191, -1), 1, wx.EXPAND | wx.ALIGN_RIGHT)\n sizer5.Add(wx.Button(self, -1, 'Close', size=(50, -1)))\n\n\n vbox.Add(grid1, 0, wx.BOTTOM | wx.TOP, 9) \n vbox.Add(hbox2, 0, wx.BOTTOM, 9) \n vbox.Add(sizer3, 0, wx.BOTTOM, 15) \n vbox.Add(sizer4, 0, wx.BOTTOM, 9) \n vbox.Add(sizer5, 1, wx.BOTTOM, 9)\n vbox_top.Add(vbox, 1, wx.LEFT, 5)\n\n self.SetSizer(vbox_top)\n self.Centre()\n\n\napp = wx.App(False)\nd = FindReplace(None, -1, 'Find/Replace')\nd.ShowModal()\nd.Destroy()\napp.MainLoop()\n\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002075638_python_wxpython.txt
Q: Python deque performance for small iterables I was playing around with Python's collection.deque and wrote the following benchmark: #!/usr/bin/python import timeit if __name__=='__main__': number = 1000000 for r in (1,10,100,1000,5000,10000,100000): print r print timeit.timeit("while x: x.pop(0);", "x = list(range("+str(r)+"))", number=number) print timeit.timeit("while x: x.popleft();", "from collections import deque; x = deque(range("+str(r)+"))", number=number) This will pop(0)/popleft() from a list/deque with various sizes. The results are: 1 0.0801048278809 0.0822219848633 10 0.081041097641 0.080836057663 100 0.0806250572205 0.0807700157166 1000 0.081248998642 0.082062959671 5000 0.0976719856262 0.0825741291046 10000 0.157499074936 0.0825819969177 100000 16.0247170925 0.097559928894 My question is: Why is the performance for small deques and lists (~1000 elements) almost the same? A: The timeit module runs the setup code once, and then the timed code number times (in this case, number==1000000). In your case this looks like (for the list case): x = list(range(r)) #timer is started here for iteration in xrange(1000000): while x: x.pop(0) #timer is stopped here As you can see, only the first iteration does anything, and the other 999999 iterations will just check the size of x once since it will be empty. This check will take approximately the same amount of time for lists and deques. For small lists/deques, the first iteration is short relative to the other 999999 iterations combined, so you are not really measuring anything relevant, and get similar times. If you use number==1 you won't have this problem. Another option is to have the timed code push and pop an item so that the list/deque is left at the same size. A: I always find timeit more suitable for use from the shell command line. Here, for example: $ python -mtimeit -s'from collections import deque; base=range(100); ctr=list' 'x=ctr(base)' 'while x: x.pop(0)' 10000 loops, best of 3: 77.3 usec per loop $ python -mtimeit -s'from collections import deque; base=range(100); ctr=deque' 'x=ctr(base)' 'while x: x.popleft()' 10000 loops, best of 3: 36 usec per loop The needed precautions (doing the import outside the loop, making a fresh copy of the data within the loop) are so much easier to see and implement, this way... A: For low numbers of elements, the time taken to construct the deque and list is significant. Once the number f elements grows, this it's no longer significant in the results. Rewrite the test so that construction of lists is outside of the timeit call. Edit: As @Interjar points out, the initialization of classes is done outside of the method timing so this is not the reason for the similar timings on low numbers of entries.
Python deque performance for small iterables
I was playing around with Python's collection.deque and wrote the following benchmark: #!/usr/bin/python import timeit if __name__=='__main__': number = 1000000 for r in (1,10,100,1000,5000,10000,100000): print r print timeit.timeit("while x: x.pop(0);", "x = list(range("+str(r)+"))", number=number) print timeit.timeit("while x: x.popleft();", "from collections import deque; x = deque(range("+str(r)+"))", number=number) This will pop(0)/popleft() from a list/deque with various sizes. The results are: 1 0.0801048278809 0.0822219848633 10 0.081041097641 0.080836057663 100 0.0806250572205 0.0807700157166 1000 0.081248998642 0.082062959671 5000 0.0976719856262 0.0825741291046 10000 0.157499074936 0.0825819969177 100000 16.0247170925 0.097559928894 My question is: Why is the performance for small deques and lists (~1000 elements) almost the same?
[ "The timeit module runs the setup code once, and then the timed code number times (in this case, number==1000000). In your case this looks like (for the list case):\nx = list(range(r))\n#timer is started here\nfor iteration in xrange(1000000):\n while x: x.pop(0)\n#timer is stopped here\n\nAs you can see, only the first iteration does anything, and the other 999999 iterations will just check the size of x once since it will be empty. This check will take approximately the same amount of time for lists and deques.\nFor small lists/deques, the first iteration is short relative to the other 999999 iterations combined, so you are not really measuring anything relevant, and get similar times.\nIf you use number==1 you won't have this problem. Another option is to have the timed code push and pop an item so that the list/deque is left at the same size.\n", "I always find timeit more suitable for use from the shell command line. Here, for example:\n$ python -mtimeit -s'from collections import deque; base=range(100); ctr=list' 'x=ctr(base)' 'while x: x.pop(0)'\n10000 loops, best of 3: 77.3 usec per loop\n$ python -mtimeit -s'from collections import deque; base=range(100); ctr=deque' 'x=ctr(base)' 'while x: x.popleft()'\n10000 loops, best of 3: 36 usec per loop\n\nThe needed precautions (doing the import outside the loop, making a fresh copy of the data within the loop) are so much easier to see and implement, this way...\n", "For low numbers of elements, the time taken to construct the deque and list is significant.\nOnce the number f elements grows, this it's no longer significant in the results.\nRewrite the test so that construction of lists is outside of the timeit call.\nEdit: As @Interjar points out, the initialization of classes is done outside of the method timing so this is not the reason for the similar timings on low numbers of entries.\n" ]
[ 4, 3, 2 ]
[]
[]
[ "deque", "performance", "python" ]
stackoverflow_0002077379_deque_performance_python.txt
Q: New field in Django model doesn't show up in admin interface or model forms I've created a model in one of my apps which works fine. However, I needed to add a new field. I did this, and used manage.py reset <appname> to drop the tables and add them again. This process went fine - the new field appears in the database. However, I can't get the field to show up in the admin interface, nor in the custom model form I've created. Because I haven't given it a default value (and don't want to, nor should I need to) I can't use either method to add a row into the database. Any ideas? Model snippet: use_balance = models.BooleanField() A: Have you restarted your server? A: By any chance, did you forget to update your ModelAdmin definitions?
New field in Django model doesn't show up in admin interface or model forms
I've created a model in one of my apps which works fine. However, I needed to add a new field. I did this, and used manage.py reset <appname> to drop the tables and add them again. This process went fine - the new field appears in the database. However, I can't get the field to show up in the admin interface, nor in the custom model form I've created. Because I haven't given it a default value (and don't want to, nor should I need to) I can't use either method to add a row into the database. Any ideas? Model snippet: use_balance = models.BooleanField()
[ "Have you restarted your server?\n", "By any chance, did you forget to update your ModelAdmin definitions?\n" ]
[ 7, 1 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0002077977_django_django_admin_django_models_python.txt
Q: Django: Chicken or Egg question I am building an application that will send an API call and save the resulting information after processing the information in a APIRecord(models.Model) class. 1) Should I build a separate class in such a way that the class does the API call, processes the information (including checking against business rules) and then creates an instance of my APIRecord() class? Or 2) Should I build a separate class with the appropriate methods for processing, and calling the API, and then in my model, override the APIRecord.save() method to call the separate class's API methods and then save the results? Or 3) Should I build my model class with the appropriate methods for calling the API and processing the response (including checking for certain values and other business rules)? I tried # 2 and ran into problems with flexibility (but am still open to suggestion). I'm leaning towards # 1, but I'm not sure of all the negatives yet? A: it is design decision. it depends to your design and programming interests. i used the combination of three methods you said. if i need to some informations that can be build from other fields then i will create an internal function in model class. if i need other records of database to do something i will create an function outside of model class. and other unusual needs will be computed everywhere i need them.
Django: Chicken or Egg question
I am building an application that will send an API call and save the resulting information after processing the information in a APIRecord(models.Model) class. 1) Should I build a separate class in such a way that the class does the API call, processes the information (including checking against business rules) and then creates an instance of my APIRecord() class? Or 2) Should I build a separate class with the appropriate methods for processing, and calling the API, and then in my model, override the APIRecord.save() method to call the separate class's API methods and then save the results? Or 3) Should I build my model class with the appropriate methods for calling the API and processing the response (including checking for certain values and other business rules)? I tried # 2 and ran into problems with flexibility (but am still open to suggestion). I'm leaning towards # 1, but I'm not sure of all the negatives yet?
[ "it is design decision.\nit depends to your design and programming interests.\ni used the combination of three methods you said. if i need to some informations that can be build from other fields then i will create an internal function in model class. if i need other records of database to do something i will create an function outside of model class. and other unusual needs will be computed everywhere i need them.\n" ]
[ 1 ]
[]
[]
[ "application_design", "design_patterns", "django", "python" ]
stackoverflow_0002076678_application_design_design_patterns_django_python.txt
Q: generating a binary tree from given data in python i wanted to know how to read values from a list into a binary tree. i have a triangle like this: 0 1 2 3 4 5 6 7 8 9 i have written a class node like this class node: def __init__(self,data,left=None,right=None): self.data=data self.left=left self.right=right basically what i want to do is something like this node(0,node(1),node(2)) i want to make a recursive function that can handle much bigger triangles. Can somehow tell me what i am supposed to do? edit: quite clearly binary tree is not the way to approach this problem. what i basically want to find out are all the different combination's from top to bottom. like 0,1,3,6 0,2,5,8 etc. A: This does sound like homework, so I won't write code, but here are a couple of hints: This could be done even if your triangle were written as a list, like 0 1 2 3 4 5 6 7 8 9 Because it seems like this is a full binary tree (assuming your triangle is wrong and the third row is actually supposed to be 3 4 5 6), you could maintain a parents queue whose head is the next parent that needs children. Note that I am specifically not recommending recursion. A full binary tree is one where each non-leaf node has exactly two children. If this is not supposed to be a full binary tree, then there is no deterministic way to interpret the problem (since each of node 1 and 2 could have 1 or 2 children, given your picture). A: For such list: a = 'aBCdef' The program below generates the following structure: - a - - B C B C - - d e d e f e f - Code (input list is assumed to correspond to a 'complete' triangular): class Node: def __init__(self,data,left=None,right=None): self.data=data self.left=left self.right=right def __unicode__(self): return '%s %s %s' % ( self.left.data if self.left or '-', self.data, self.right.data if self.right or '-') nodelist = [Node(c) for c in a] i,y = 0,1 while True: for x in range(y): nodelist[i].left = nodelist[i-1] if x!=0 else None nodelist[i].right = nodelist[i+1] if x!=y-1 else None i+=1 if i<len(a): y+=1 else: break for n in nodelist: print unicode(n)
generating a binary tree from given data in python
i wanted to know how to read values from a list into a binary tree. i have a triangle like this: 0 1 2 3 4 5 6 7 8 9 i have written a class node like this class node: def __init__(self,data,left=None,right=None): self.data=data self.left=left self.right=right basically what i want to do is something like this node(0,node(1),node(2)) i want to make a recursive function that can handle much bigger triangles. Can somehow tell me what i am supposed to do? edit: quite clearly binary tree is not the way to approach this problem. what i basically want to find out are all the different combination's from top to bottom. like 0,1,3,6 0,2,5,8 etc.
[ "This does sound like homework, so I won't write code, but here are a couple of hints:\n\nThis could be done even if your triangle were written as a list, like \n0 1 2 3 4 5 6 7 8 9\nBecause it seems like this is a full binary tree (assuming your triangle is wrong and the third row is actually supposed to be 3 4 5 6), you could maintain a parents queue whose head is the next parent that needs children. Note that I am specifically not recommending recursion.\n\nA full binary tree is one where each non-leaf node has exactly two children. If this is not supposed to be a full binary tree, then there is no deterministic way to interpret the problem (since each of node 1 and 2 could have 1 or 2 children, given your picture).\n", "For such list:\na = 'aBCdef'\n\nThe program below generates the following structure:\n- a -\n- B C\nB C -\n- d e\nd e f\ne f -\n\nCode (input list is assumed to correspond to a 'complete' triangular):\nclass Node:\n def __init__(self,data,left=None,right=None):\n self.data=data\n self.left=left\n self.right=right\n\n def __unicode__(self):\n return '%s %s %s' % (\n self.left.data if self.left or '-', \n self.data, \n self.right.data if self.right or '-')\n\n\nnodelist = [Node(c) for c in a]\n\ni,y = 0,1\n\nwhile True:\n for x in range(y):\n nodelist[i].left = nodelist[i-1] if x!=0 else None\n nodelist[i].right = nodelist[i+1] if x!=y-1 else None\n i+=1\n if i<len(a):\n y+=1\n else:\n break\n\nfor n in nodelist:\n print unicode(n)\n\n" ]
[ 1, 0 ]
[]
[]
[ "binary_tree", "python" ]
stackoverflow_0002078669_binary_tree_python.txt
Q: GAE Simple Searching + Autocomplete I'm looking to create a search function for my flash game website. One of the problems with the site is that it is difficult to find a specific game you want, as users must go to the alphabetical list to find one they want. It's run with Google App Engine written in python, using the webapp framework. At the very least I need a simple way to search games by their name. It might be easier to do searching in Javascript from the looks of it. I would prefer an autocomplete functionality. I've tried to figure out how to go about this and it seems that the only way is to create a huge index with each name broken up into various stages of being typed ("S", "Sh", "Sho" ... "Shopping Cart Hero"). Is there anyway to do this simply and easily? I'm beginning to think I'll have to create a web service on a PHP+MySql server and search using it. A: I have written the code below to handle this. Basically, I save all the possible word "starts" in a list instead of whole sentences. That's how the jquery autocomplete of this site works. import unicodedata import re splitter = re.compile(r'[\s|\-|\)|\(|/]+') def remove_accents(text): nkfd_form = unicodedata.normalize('NFKD', unicode(text)) return u"".join([c for c in nkfd_form if not unicodedata.combining(c)]) def get_words(text): return [s.lower() for s in splitter.split(remove_accents(text)) if s!= ''] def get_unique_words(text): word_set = set(get_words(text)) return word_set def get_starts(text): word_set = get_unique_words(text) starts = set() for word in word_set: for i in range(len(word)): starts.add(word[:i+1]) return sorted(starts) A: Have you looked at gae-search? I believe the Django + jQuery "autocomplete" feature is not part of the free version (it's just in the for-pay premium version), but maybe it's worth a little money to you.
GAE Simple Searching + Autocomplete
I'm looking to create a search function for my flash game website. One of the problems with the site is that it is difficult to find a specific game you want, as users must go to the alphabetical list to find one they want. It's run with Google App Engine written in python, using the webapp framework. At the very least I need a simple way to search games by their name. It might be easier to do searching in Javascript from the looks of it. I would prefer an autocomplete functionality. I've tried to figure out how to go about this and it seems that the only way is to create a huge index with each name broken up into various stages of being typed ("S", "Sh", "Sho" ... "Shopping Cart Hero"). Is there anyway to do this simply and easily? I'm beginning to think I'll have to create a web service on a PHP+MySql server and search using it.
[ "I have written the code below to handle this. Basically, I save all the possible word \"starts\" in a list instead of whole sentences. That's how the jquery autocomplete of this site works.\nimport unicodedata\nimport re\n\nsplitter = re.compile(r'[\\s|\\-|\\)|\\(|/]+')\n\ndef remove_accents(text):\n nkfd_form = unicodedata.normalize('NFKD', unicode(text))\n return u\"\".join([c for c in nkfd_form if not unicodedata.combining(c)])\n\ndef get_words(text): \n return [s.lower() for s in splitter.split(remove_accents(text)) if s!= '']\n\ndef get_unique_words(text):\n word_set = set(get_words(text))\n return word_set\n\ndef get_starts(text):\n word_set = get_unique_words(text)\n starts = set()\n for word in word_set:\n for i in range(len(word)):\n starts.add(word[:i+1])\n return sorted(starts)\n\n", "Have you looked at gae-search? I believe the Django + jQuery \"autocomplete\" feature is not part of the free version (it's just in the for-pay premium version), but maybe it's worth a little money to you.\n" ]
[ 5, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002078738_google_app_engine_python.txt
Q: Pythonic way to sort list of objects by a dict value (by key) contained within the object I'm seeking advice on doing the following in a more pythonic way. Consider: class MyObj(object): def __init__(self): self.dict_properties = {} Suppose I've got a list which contains multiple MyObj instances: mylist = [<__main__.MyObj object at 0x1005e3b90, ...] Now i want to sort mylist based on the value of a certain key in dict_properties in MyObj. What does work is: mylist.sort(lambda x,y: cmp(x.dict_properties['mykey'], y.dict_properties['mykey'])) but that hardly feels pythonic. Is there a better way (perhaps using operator.attrgetter)? A: mylist.sort(key=lambda x: x.dict_properties['mykey']) is way simpler, and faster. You could reach for operator and try to compose an attrgetter and an itemgetter, but a straightforward lambda (or def) seems simplest here. A: I'd just do: mylist.sort(key=lambda o: o.dict_properties["kykey"]) You could also overide cmp on the class. A: If speed is an issue, then use decorate-sort-undecorate: mylist_decorated = [(elem.dict_properties['mykey'], elem) for elem in mylist] mylist_decorated.sort() mylist = [elem[1] for elem in mylist_decorated] # or zip(*mylist_decorated)[1] :) this way sort() can spread its wings.
Pythonic way to sort list of objects by a dict value (by key) contained within the object
I'm seeking advice on doing the following in a more pythonic way. Consider: class MyObj(object): def __init__(self): self.dict_properties = {} Suppose I've got a list which contains multiple MyObj instances: mylist = [<__main__.MyObj object at 0x1005e3b90, ...] Now i want to sort mylist based on the value of a certain key in dict_properties in MyObj. What does work is: mylist.sort(lambda x,y: cmp(x.dict_properties['mykey'], y.dict_properties['mykey'])) but that hardly feels pythonic. Is there a better way (perhaps using operator.attrgetter)?
[ "mylist.sort(key=lambda x: x.dict_properties['mykey'])\n\nis way simpler, and faster. You could reach for operator and try to compose an attrgetter and an itemgetter, but a straightforward lambda (or def) seems simplest here.\n", "I'd just do:\nmylist.sort(key=lambda o: o.dict_properties[\"kykey\"])\nYou could also overide cmp on the class.\n", "If speed is an issue, then use decorate-sort-undecorate:\n mylist_decorated = [(elem.dict_properties['mykey'], elem) for elem in mylist]\n mylist_decorated.sort()\n mylist = [elem[1] for elem in mylist_decorated] # or zip(*mylist_decorated)[1] :)\n\n\nthis way sort() can spread its wings.\n\n" ]
[ 9, 3, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002078986_python_sorting.txt
Q: Better way to port Java into Python? After several hours of working on porting this program over, it appears to finally be in a working state. However, I was wondering if anyone knew of a better way or more complete way of porting Java servlets over into Python. The beginning of the Python script contains a lot of support code to make it easier to port the program line-by-line directly into Python. Does anyone know of a better way to go about this? Java // -------------------------------------------------------- // File: Hello.java // Description: A simple "Hello World" servlet // -------------------------------------------------------- import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import sun.servlet.http.HttpServer; public class Hello extends HttpServlet { int count; public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // setup response response.setContentType("text/html"); PrintWriter out = response.getWriter(); // send response out.println("<html><body>"); out.println("<h5>Stephen Paul Chappell (SPC)</h5>"); out.println("<h5>:) (ZTD) Zero The Dragon :(</h5>"); String name = request.getParameter("NAME"); if (name != null && !name.equals("")) { out.println("<h2>Hello, " + name + "</h2>"); } else { out.println(); if (name != null && name.equals("")) { out.println(" <h2>You didn't enter your name. Please enter your name. </h2>"); } else { out.println(" <h2>What's your name? </h2>"); } out.println(" <hr>"); out.println(" <form action=\"http://127.0.0.1:8080/servlet/Hello\">"); out.println(); out.println(" Enter your name: <input type=\"text\" name=\"NAME\" value=\"Fred\"><br>"); out.println(" <input type=\"submit\" value=\"Click for greeting\">"); out.println(); out.println(" </form>"); } String color = request.getParameter("FAVCOLOR"); if (color != null) { out.println("<h2>Why, " + color + " is my favorite color too!</h2>"); } count++; out.println("This page has been hit " + count + " time(s)."); out.print("</body></html>"); } // start web server public static void main(String[] args) throws Exception { HttpServer.main(args); } } Python import urllib.parse import http.server import cgitb import sys import io ################################################################################ class HttpServlet(http.server.BaseHTTPRequestHandler): __debug = False @staticmethod def debug(value): HttpServlet.__debug = value def do_GET(self): if self.path == '/favicon.ico': self.send_error(404) return request = HttpServletRequest(self.path) response = HttpServletResponse() try: self.service(request, response) except Exception: if HttpServlet.__debug: self.send_response(500) self.send_header('Content-type', 'text/html') self.end_headers() klass, value, trace = sys.exc_info() html = cgitb.html((klass, value, trace.tb_next)) self.wfile.write(html.encode()) else: self.send_error(500) else: self.send_response(200) self.send_header('Content-type', response._type) self.end_headers() self.wfile.write(response._value) def service(self, request, response): raise NotImplementedError() ################################################################################ class HttpServletRequest: def __init__(self, path): query = urllib.parse.urlparse(path).query self.__dict = urllib.parse.parse_qs(query, True) def getParameter(self, name): return self.__dict.get(name, [None])[0] ################################################################################ class HttpServletResponse: def __init__(self): self.__content_type = 'text/plain' self.__print_writer = PrintWriter() def setContentType(self, content_type): self.__content_type = content_type def getWriter(self): return self.__print_writer @property def _type(self): return self.__content_type @property def _value(self): return self.__print_writer.getvalue().encode() ################################################################################ class PrintWriter(io.StringIO): print = io.StringIO.write def println(self, string): self.write(string + '\r\n') ################################################################################ class HttpServer(http.server.HTTPServer): @staticmethod def main(RequestHandlerClass, port=80): server = HttpServer(('', port), RequestHandlerClass) socket = server.socket.getsockname() print('Serving HTTP on', socket[0], 'port', socket[1], '...') try: server.serve_forever() except KeyboardInterrupt: print('Keyboard interrupt received: EXITING') server.server_close() ################################################################################ ################################################################################ ## --------------------------------------------------------- ## File: Hello.py ## Description: A simple "Hello World" servlet ## --------------------------------------------------------- class Hello(HttpServlet): count = 0 def service(self, request, response): # Setup for a response. response.setContentType('text/html') out = response.getWriter() # Send an appropriate response. out.println('''\ <html> <head> <title>Java to Python servlet</title> </head> <body> <h5>Stephen Paul Chappell (SPC)</h5> <h5>:) (ZTD) Zero The Dragon :(</h5>''') name = request.getParameter('NAME') if name: out.println('''\ <h2>Hello, {}!</h2>'''.format(name)) else: if name == '': out.println('''\ <h2>You did not enter your name.</h2> <h3>Please enter your name.</h3>''') else: out.println('''\ <h2>What is your name?</h2>''') out.println('''\ <form> <fieldset> <legend>About Yourself</legend> <label for='NAME'>Enter your name:</label> <input id='NAME' name='NAME' type='text' value='John Doe' /> <br /> <input type='submit' value='Click me!' /> </fieldset> </form>''') color = request.getParameter('FAVCOLOR') if color: out.println('''\ <h2>Why, {} is my favorite color too!</h2>'''.format(color)) Hello.count += 1 out.println('''\ This page has been hit {} times.'''.format(Hello.count)) out.print('''\ </body> </html>''') # Start the web server. def main(): HttpServlet.debug(True) HttpServer.main(Hello) ################################################################################ if __name__ == '__main__': main() In case anyone is wondering what the purpose of this project is, the original Java program was given as an introductory exercise in freshman-level computer-science course. Since then, it has been about six years since I have worked with Java and am going through the old programs, porting them over to Python for the challenge and learning experience. Porting the servlets are presenting extra difficulties. A: My best suggestion is to not write a line by line port. Python is not Java and you're hamstringing yourself if you're just writing Java style code in the Python language. Here's a starter for recognizing some of the common differences/mistakes: http://dirtsimple.org/2004/12/python-is-not-java.html If you're lucky enough to be working with a codebase that contains unit tests, a great way to go about this is to port your unit tests from Java to Python, and then write new python to match the unit tests. If that's not something that you have, then it's much more important to recognize what the software does in Java, and then write Python code that does the same thing. It will almost certainly not be in the same way, at least not at the line-by-line level. A: Isn't this a translation and not a port? :) I just googled and found java2python as well as a similar SO question. Anyway ... Ideally, i think you should understand what you're translating so you can know what to translate and what you shouldn't need to translate. You need a reasonable understanding of both languages to know how constructs in Java relate to the similar in Python and how libraries play roles in the translations. A direct translation between languages is often not a good approach. I mention this simply because the translated Python in your question isn't very Pythonic. And also because a fair amount of the Python is concerned with the HTTP Server aspects. That isn't the case with the Java code. So to produce a "fair" translation, i would have relied on a Python framework that does for Python what Servlet containers do for Java. Maybe Tornado/Django. My point being, a Java Servlet is wrapped up in a significant set of standards so it makes sense that the Python version follow a similar route, which, at a minimum, probably means WSGI. A: Not a direct answer but, any good reason to not use something like Webware which offers, among other features (see the Overview): Servlets. Similar to Java servlets, they provide a familiar basis for construction web applications. A: Creating a python webapp in this way is confusing and non pythonic. You might have better success rewriting your app in Django rather than porting it line by line from Java
Better way to port Java into Python?
After several hours of working on porting this program over, it appears to finally be in a working state. However, I was wondering if anyone knew of a better way or more complete way of porting Java servlets over into Python. The beginning of the Python script contains a lot of support code to make it easier to port the program line-by-line directly into Python. Does anyone know of a better way to go about this? Java // -------------------------------------------------------- // File: Hello.java // Description: A simple "Hello World" servlet // -------------------------------------------------------- import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import sun.servlet.http.HttpServer; public class Hello extends HttpServlet { int count; public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // setup response response.setContentType("text/html"); PrintWriter out = response.getWriter(); // send response out.println("<html><body>"); out.println("<h5>Stephen Paul Chappell (SPC)</h5>"); out.println("<h5>:) (ZTD) Zero The Dragon :(</h5>"); String name = request.getParameter("NAME"); if (name != null && !name.equals("")) { out.println("<h2>Hello, " + name + "</h2>"); } else { out.println(); if (name != null && name.equals("")) { out.println(" <h2>You didn't enter your name. Please enter your name. </h2>"); } else { out.println(" <h2>What's your name? </h2>"); } out.println(" <hr>"); out.println(" <form action=\"http://127.0.0.1:8080/servlet/Hello\">"); out.println(); out.println(" Enter your name: <input type=\"text\" name=\"NAME\" value=\"Fred\"><br>"); out.println(" <input type=\"submit\" value=\"Click for greeting\">"); out.println(); out.println(" </form>"); } String color = request.getParameter("FAVCOLOR"); if (color != null) { out.println("<h2>Why, " + color + " is my favorite color too!</h2>"); } count++; out.println("This page has been hit " + count + " time(s)."); out.print("</body></html>"); } // start web server public static void main(String[] args) throws Exception { HttpServer.main(args); } } Python import urllib.parse import http.server import cgitb import sys import io ################################################################################ class HttpServlet(http.server.BaseHTTPRequestHandler): __debug = False @staticmethod def debug(value): HttpServlet.__debug = value def do_GET(self): if self.path == '/favicon.ico': self.send_error(404) return request = HttpServletRequest(self.path) response = HttpServletResponse() try: self.service(request, response) except Exception: if HttpServlet.__debug: self.send_response(500) self.send_header('Content-type', 'text/html') self.end_headers() klass, value, trace = sys.exc_info() html = cgitb.html((klass, value, trace.tb_next)) self.wfile.write(html.encode()) else: self.send_error(500) else: self.send_response(200) self.send_header('Content-type', response._type) self.end_headers() self.wfile.write(response._value) def service(self, request, response): raise NotImplementedError() ################################################################################ class HttpServletRequest: def __init__(self, path): query = urllib.parse.urlparse(path).query self.__dict = urllib.parse.parse_qs(query, True) def getParameter(self, name): return self.__dict.get(name, [None])[0] ################################################################################ class HttpServletResponse: def __init__(self): self.__content_type = 'text/plain' self.__print_writer = PrintWriter() def setContentType(self, content_type): self.__content_type = content_type def getWriter(self): return self.__print_writer @property def _type(self): return self.__content_type @property def _value(self): return self.__print_writer.getvalue().encode() ################################################################################ class PrintWriter(io.StringIO): print = io.StringIO.write def println(self, string): self.write(string + '\r\n') ################################################################################ class HttpServer(http.server.HTTPServer): @staticmethod def main(RequestHandlerClass, port=80): server = HttpServer(('', port), RequestHandlerClass) socket = server.socket.getsockname() print('Serving HTTP on', socket[0], 'port', socket[1], '...') try: server.serve_forever() except KeyboardInterrupt: print('Keyboard interrupt received: EXITING') server.server_close() ################################################################################ ################################################################################ ## --------------------------------------------------------- ## File: Hello.py ## Description: A simple "Hello World" servlet ## --------------------------------------------------------- class Hello(HttpServlet): count = 0 def service(self, request, response): # Setup for a response. response.setContentType('text/html') out = response.getWriter() # Send an appropriate response. out.println('''\ <html> <head> <title>Java to Python servlet</title> </head> <body> <h5>Stephen Paul Chappell (SPC)</h5> <h5>:) (ZTD) Zero The Dragon :(</h5>''') name = request.getParameter('NAME') if name: out.println('''\ <h2>Hello, {}!</h2>'''.format(name)) else: if name == '': out.println('''\ <h2>You did not enter your name.</h2> <h3>Please enter your name.</h3>''') else: out.println('''\ <h2>What is your name?</h2>''') out.println('''\ <form> <fieldset> <legend>About Yourself</legend> <label for='NAME'>Enter your name:</label> <input id='NAME' name='NAME' type='text' value='John Doe' /> <br /> <input type='submit' value='Click me!' /> </fieldset> </form>''') color = request.getParameter('FAVCOLOR') if color: out.println('''\ <h2>Why, {} is my favorite color too!</h2>'''.format(color)) Hello.count += 1 out.println('''\ This page has been hit {} times.'''.format(Hello.count)) out.print('''\ </body> </html>''') # Start the web server. def main(): HttpServlet.debug(True) HttpServer.main(Hello) ################################################################################ if __name__ == '__main__': main() In case anyone is wondering what the purpose of this project is, the original Java program was given as an introductory exercise in freshman-level computer-science course. Since then, it has been about six years since I have worked with Java and am going through the old programs, porting them over to Python for the challenge and learning experience. Porting the servlets are presenting extra difficulties.
[ "My best suggestion is to not write a line by line port. Python is not Java and you're hamstringing yourself if you're just writing Java style code in the Python language.\nHere's a starter for recognizing some of the common differences/mistakes: http://dirtsimple.org/2004/12/python-is-not-java.html\nIf you're lucky enough to be working with a codebase that contains unit tests, a great way to go about this is to port your unit tests from Java to Python, and then write new python to match the unit tests. If that's not something that you have, then it's much more important to recognize what the software does in Java, and then write Python code that does the same thing. It will almost certainly not be in the same way, at least not at the line-by-line level.\n", "Isn't this a translation and not a port? :)\nI just googled and found java2python as well as a similar SO question.\nAnyway ...\nIdeally, i think you should understand what you're translating so you can know what to translate and what you shouldn't need to translate. You need a reasonable understanding of both languages to know how constructs in Java relate to the similar in Python and how libraries play roles in the translations.\nA direct translation between languages is often not a good approach. I mention this simply because the translated Python in your question isn't very Pythonic. And also because a fair amount of the Python is concerned with the HTTP Server aspects. That isn't the case with the Java code. So to produce a \"fair\" translation, i would have relied on a Python framework that does for Python what Servlet containers do for Java. Maybe Tornado/Django. My point being, a Java Servlet is wrapped up in a significant set of standards so it makes sense that the Python version follow a similar route, which, at a minimum, probably means WSGI.\n", "Not a direct answer but, any good reason to not use something like Webware which offers, among other features (see the Overview):\n\n\nServlets. Similar to Java servlets, they provide a familiar basis for construction web applications.\n\n\n", "Creating a python webapp in this way is confusing and non pythonic. You might have better success rewriting your app in Django rather than porting it line by line from Java\n" ]
[ 7, 3, 2, 2 ]
[]
[]
[ "java", "porting", "python", "servlets" ]
stackoverflow_0002079076_java_porting_python_servlets.txt
Q: Which methods implement the buffer interface in Python? I have a custom class with a serialize method, and I want to be able to write this class directly to files and have the return value of the serialize method get written, in Python 2.6. (I'm not trying to pickle my objects, this is something totally different.) For example: class Foo(object): def serialize(self): return "Hello World!" __str__ = serialize foo = Foo() f = open("foo.dat", "wb") f.write(foo) However, when I run this code, I get the following exception Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: argument 1 must be convertible to a buffer, not Foo Okay, so I need my Foo class to implement the buffer interface. I even see in the buffer documentation that it says: "An example user of the buffer interface is the file object’s write() method. Any object that can export a series of bytes through the buffer interface can be written to a file." So apparently I can do what I want, but the docs don't actually say which methods I need to implement in order to have implemented the buffer interface. I've tried implementing __str__, __unicode__, __len__, and even __sizeof__. I've implemented __getitem__, __setitem__, and __delitem__, accepting both int and slice arguments. I've even tried implementing the deprecated __getslice__, __setslice__, and __delslice__ methods just to be safe. No matter what I try, I still get exactly the same exception. For reference, here are the methods of the buffer builtin class: >>> dir(buffer) ['__add__', '__class__', '__cmp__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__len__', '__mul__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__'] I'd like to avoid implementing all of them one by one, and I'd especially like to find the documentation on exactly which methods are necessary. Is this something that can only be implemented in C extension classes? Or am I missing something obvious? A: Peculiarly, there are no special methods that a pure-Python coded class can directly implement to support the buffer interface -- that would have been PEP 298, but it was withdrawn. I'm afraid you'll have to use some explicit attribute or method (or a built-in like str which internally calls a special method) to pass your class's instances to file.write &c:-(. A: The documentation says, Python objects implemented in C can export a group of functions called the “buffer interface.” Your Foo class is not implemented in C, is it...?
Which methods implement the buffer interface in Python?
I have a custom class with a serialize method, and I want to be able to write this class directly to files and have the return value of the serialize method get written, in Python 2.6. (I'm not trying to pickle my objects, this is something totally different.) For example: class Foo(object): def serialize(self): return "Hello World!" __str__ = serialize foo = Foo() f = open("foo.dat", "wb") f.write(foo) However, when I run this code, I get the following exception Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: argument 1 must be convertible to a buffer, not Foo Okay, so I need my Foo class to implement the buffer interface. I even see in the buffer documentation that it says: "An example user of the buffer interface is the file object’s write() method. Any object that can export a series of bytes through the buffer interface can be written to a file." So apparently I can do what I want, but the docs don't actually say which methods I need to implement in order to have implemented the buffer interface. I've tried implementing __str__, __unicode__, __len__, and even __sizeof__. I've implemented __getitem__, __setitem__, and __delitem__, accepting both int and slice arguments. I've even tried implementing the deprecated __getslice__, __setslice__, and __delslice__ methods just to be safe. No matter what I try, I still get exactly the same exception. For reference, here are the methods of the buffer builtin class: >>> dir(buffer) ['__add__', '__class__', '__cmp__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__len__', '__mul__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__'] I'd like to avoid implementing all of them one by one, and I'd especially like to find the documentation on exactly which methods are necessary. Is this something that can only be implemented in C extension classes? Or am I missing something obvious?
[ "Peculiarly, there are no special methods that a pure-Python coded class can directly implement to support the buffer interface -- that would have been PEP 298, but it was withdrawn.\nI'm afraid you'll have to use some explicit attribute or method (or a built-in like str which internally calls a special method) to pass your class's instances to file.write &c:-(.\n", "The documentation says,\n\nPython objects implemented in C can\n export a group of functions called the\n “buffer interface.”\n\nYour Foo class is not implemented in C, is it...?\n" ]
[ 13, 1 ]
[]
[]
[ "buffer", "python" ]
stackoverflow_0002079272_buffer_python.txt
Q: Missing datetime.time.__sub__? Why can't subtract two time objects? For example, 12:00 - 11:00 = 1:00 from datetime import time time(12,00) - time(11,00) # -> timedelta(hours=1) It seems that datetime.time.__sub__ is missing TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' do you know why? A: The time objects have no date, so for example, the 12:00 might be (say) on a Wed and the 11:00 on the preceding Tue, making the difference 25 hours, not one (any multiple of 24 might be added or subtracted). If you know they're actually on the same date, just apply any arbitrary date to each of them (making two datetime objects) and then you'll be able to subtract them. E.g.: import datetime def timediff(t1, t2): td = datetime.date.today() return datetime.datetime.combine(td, t1) - datetime.datetime.combine(td, t2) A: You can get your desired result by t1 = time(12, 0) t2 = time(11, 0) td = timedelta(hours=t1.hour-t2.hour, minutes=t1.minute-t2.minute)
Missing datetime.time.__sub__?
Why can't subtract two time objects? For example, 12:00 - 11:00 = 1:00 from datetime import time time(12,00) - time(11,00) # -> timedelta(hours=1) It seems that datetime.time.__sub__ is missing TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' do you know why?
[ "The time objects have no date, so for example, the 12:00 might be (say) on a Wed and the 11:00 on the preceding Tue, making the difference 25 hours, not one (any multiple of 24 might be added or subtracted). If you know they're actually on the same date, just apply any arbitrary date to each of them (making two datetime objects) and then you'll be able to subtract them. E.g.:\nimport datetime\n\ndef timediff(t1, t2):\n td = datetime.date.today()\n return datetime.datetime.combine(td, t1) - datetime.datetime.combine(td, t2)\n\n", "You can get your desired result by\nt1 = time(12, 0)\nt2 = time(11, 0)\ntd = timedelta(hours=t1.hour-t2.hour, minutes=t1.minute-t2.minute)\n\n" ]
[ 6, 0 ]
[]
[]
[ "datetime", "missing_features", "python", "time" ]
stackoverflow_0002079323_datetime_missing_features_python_time.txt
Q: Passing options to Python executable in non-interactive mode I would like to pass some options to Python (version 2.6) every time, not just in interactive mode. Is there a file I can put such commands in? EDIT: Specifically, I'm wanting to silence the Deprecation warnings. A: The #!/usr/bin/python line at the beginning of a Python script under Linux can be used to also pass options to the interpreter. There are also a number of modules imported whenever Python starts up. On my system, a likely candidate for modification to set options in the manner suggested by other posters are here: /usr/lib/python2.6/site-packages/sitecustomize.py If you simply put this code in that file: import warnings warnings.simplefilter("ignore", DeprecationWarning) it will turn off deprecation warnings for everything always, which may not be what you want. You could instead put in code that would check your own PYTHONNODEPRECATIONWARNING environment variable so you had more control. After finding a reference to sitecustomize.py in Dive Into Python and this reference to the sitecustomize module in the Python 2.6 documentation, I think that file is your best bet for what you want. In Python 2.6, with its user specific site-packages directory it's possible to set this up on a per-user basis, though you may want to find any system-wide sitecustomize.py file and either copy it into yours or find a way to explicitly import it in yours. A: Most of the options can be passed in as environment variables -- do python -h to see the list: $ py26 -h|grep PYTH -B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x -d : debug output from parser; also PYTHONDEBUG=x -E : ignore PYTHON* environment variables (such as PYTHONPATH) if stdin does not appear to be a terminal; also PYTHONINSPECT=x -O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x -s : don't add user site directory to sys.path; also PYTHONNOUSERSITE -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x -v : verbose (trace import statements); also PYTHONVERBOSE=x PYTHONSTARTUP: file executed on interactive startup (no default) PYTHONPATH : ':'-separated list of directories prefixed to the PYTHONHOME : alternate <prefix> directory (or <prefix>:<exec_prefix>). PYTHONCASEOK : ignore case in 'import' statements (Windows). PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr. Are you concerned with other flags that can't be set via environment variables? PS the PYTHONINSPECT=x is the equivalent of -i (the grep cut that info because it comes on the immediately previous line;-). A: Have you tried ~/.pythonrc.py? It is listed in the Python man page with the following description: User-specific initialization file loaded by the user module; not used by default or by most applications. I'm not sure what it means by the 'user' module but I think it's worth a shot to try this. EDIT: It looks like you have to import user in your python scripts and then Python will automatically execute this ~/.pythonrc.py file upon startup (and not just in interactive mode). This should work in Python version < 3.0. http://docs.python.org/library/user.html A: I'm sorry, I don't quite understand exactly what your question is, but, you might try: import warnings warnings.simplefilter("ignore", DeprecationWarning) So, this might not really answer the question.
Passing options to Python executable in non-interactive mode
I would like to pass some options to Python (version 2.6) every time, not just in interactive mode. Is there a file I can put such commands in? EDIT: Specifically, I'm wanting to silence the Deprecation warnings.
[ "The #!/usr/bin/python line at the beginning of a Python script under Linux can be used to also pass options to the interpreter.\nThere are also a number of modules imported whenever Python starts up. On my system, a likely candidate for modification to set options in the manner suggested by other posters are here:\n/usr/lib/python2.6/site-packages/sitecustomize.py\n\nIf you simply put this code in that file:\nimport warnings\nwarnings.simplefilter(\"ignore\", DeprecationWarning)\n\nit will turn off deprecation warnings for everything always, which may not be what you want. You could instead put in code that would check your own PYTHONNODEPRECATIONWARNING environment variable so you had more control.\nAfter finding a reference to sitecustomize.py in Dive Into Python and this reference to the sitecustomize module in the Python 2.6 documentation, I think that file is your best bet for what you want. In Python 2.6, with its user specific site-packages directory it's possible to set this up on a per-user basis, though you may want to find any system-wide sitecustomize.py file and either copy it into yours or find a way to explicitly import it in yours.\n", "Most of the options can be passed in as environment variables -- do python -h to see the list:\n$ py26 -h|grep PYTH\n-B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x\n-d : debug output from parser; also PYTHONDEBUG=x\n-E : ignore PYTHON* environment variables (such as PYTHONPATH)\n if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n-O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x\n-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE\n-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x\n-v : verbose (trace import statements); also PYTHONVERBOSE=x\nPYTHONSTARTUP: file executed on interactive startup (no default)\nPYTHONPATH : ':'-separated list of directories prefixed to the\nPYTHONHOME : alternate <prefix> directory (or <prefix>:<exec_prefix>).\nPYTHONCASEOK : ignore case in 'import' statements (Windows).\nPYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\nAre you concerned with other flags that can't be set via environment variables?\nPS the PYTHONINSPECT=x is the equivalent of -i (the grep cut that info because it comes on the immediately previous line;-).\n", "Have you tried ~/.pythonrc.py? It is listed in the Python man page with the following description:\n\nUser-specific initialization file\n loaded by the user module; not used by\n default or by most applications.\n\nI'm not sure what it means by the 'user' module but I think it's worth a shot to try this.\nEDIT: It looks like you have to import user in your python scripts and then Python will automatically execute this ~/.pythonrc.py file upon startup (and not just in interactive mode). This should work in Python version < 3.0. \nhttp://docs.python.org/library/user.html\n", "I'm sorry, I don't quite understand exactly what your question is, but, you might try:\nimport warnings\nwarnings.simplefilter(\"ignore\", DeprecationWarning)\n\nSo, this might not really answer the question.\n" ]
[ 6, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002078752_python.txt
Q: String matching in Python does anyone know which string matching algorithm is implemented in Python? A: Per the sources, it's a fast search/count implementation, based on a mix between boyer-moore and horspool, with a few more bells and whistles on the top. for some more background, see: http://effbot.org/zone/stringlib.htm The essay in question is really well worth reading! A: I assume you're talking about CPython. In that case, you could always check the source (see fastsearch.h).
String matching in Python
does anyone know which string matching algorithm is implemented in Python?
[ "Per the sources, it's a\n\nfast search/count implementation,\n based on a mix between boyer-moore and\n horspool, with a few more bells and\n whistles on the top. for some more\n background, see:\n http://effbot.org/zone/stringlib.htm\n\nThe essay in question is really well worth reading!\n", "I assume you're talking about CPython. In that case, you could always check the source (see fastsearch.h).\n" ]
[ 9, 1 ]
[]
[]
[ "python", "string_matching" ]
stackoverflow_0002079676_python_string_matching.txt
Q: Data modeling advice for a forum application on Google App Engine I'm writing a simple forum-like application on Google App Engine and trying to avoid scalability issues. I'm new to this non-RBDMS approach, i'd like to avoid pitfalls from the beginning. The forum design is pretty simple, posts and replies will be the only concepts. What will be the best approach to the problem if the forum have millions of posts? The model so far (stripped from useless properties): class Message(db.Model): user = db.StringProperty() # will be a google account user_id text = db.TextProperty() # the text of the message reply_to = db.SelfReferenceProperty() # if null is a post, if not null a reply (useful for reply-to-reply) Splitting the model, i think it's faster because it will query less items when retrieving "all posts": class Post(db.Model): user = db.StringProperty() # will be a google account user_id text = db.TextProperty() # the text of the message class Reply(db.Model): user = db.StringProperty() # will be a google account user_id text = db.TextProperty() # the text of the message reply_to = db.ReferenceProperty(Post) This is a many-to-one relation in a RDBMS world, should a ListProperty be used instead? If so, how? Edit: Jaiku uses something like this class StreamEntry(DeletedMarkerModel): ... entry = models.StringProperty() # ref - the parent of this, should it be a comment ... A: Firstly, why don't you use user = db.UserProperty() instead of user = db.StringProperty()? Secondly, I'm quite sure you should use whatever it works and is more readable and test the performance later, for three reasons: KISS (Keep it simple) Early optimizations are bad You can't improve what you can't measure So when you are ready to measure, then start the optimizations. I'm not saying this because I don't know nothing about RDBMS, No-SQL DBMS or Google Datastore performance optimizations, but because I usually get all my knowledge about it from testing, which seems to contradict previous assumptions more usually than I expected.
Data modeling advice for a forum application on Google App Engine
I'm writing a simple forum-like application on Google App Engine and trying to avoid scalability issues. I'm new to this non-RBDMS approach, i'd like to avoid pitfalls from the beginning. The forum design is pretty simple, posts and replies will be the only concepts. What will be the best approach to the problem if the forum have millions of posts? The model so far (stripped from useless properties): class Message(db.Model): user = db.StringProperty() # will be a google account user_id text = db.TextProperty() # the text of the message reply_to = db.SelfReferenceProperty() # if null is a post, if not null a reply (useful for reply-to-reply) Splitting the model, i think it's faster because it will query less items when retrieving "all posts": class Post(db.Model): user = db.StringProperty() # will be a google account user_id text = db.TextProperty() # the text of the message class Reply(db.Model): user = db.StringProperty() # will be a google account user_id text = db.TextProperty() # the text of the message reply_to = db.ReferenceProperty(Post) This is a many-to-one relation in a RDBMS world, should a ListProperty be used instead? If so, how? Edit: Jaiku uses something like this class StreamEntry(DeletedMarkerModel): ... entry = models.StringProperty() # ref - the parent of this, should it be a comment ...
[ "Firstly, why don't you use user = db.UserProperty() instead of user = db.StringProperty()?\nSecondly, I'm quite sure you should use whatever it works and is more readable and test the performance later, for three reasons:\n\nKISS (Keep it simple)\nEarly optimizations are bad\nYou can't improve what you can't measure\n\nSo when you are ready to measure, then start the optimizations.\nI'm not saying this because I don't know nothing about RDBMS, No-SQL DBMS or Google Datastore performance optimizations, but because I usually get all my knowledge about it from testing, which seems to contradict previous assumptions more usually than I expected.\n" ]
[ 2 ]
[ "You might want to take a look at a good tutorial on creating a php forum from scratch. Sure that one is about PHP but it also covers the general overview of forum design.\nBasically, don't split posts and replies or threads and posts. It will lead to some really awkward queries later on. A thread is simply a post that isn't replying to anything.\n" ]
[ -2 ]
[ "data_modeling", "google_app_engine", "python" ]
stackoverflow_0002079763_data_modeling_google_app_engine_python.txt
Q: static file with mod_wsgi in django I've searched a lot but I still have a problem with the static files (css, image,...) with my django website. I'm using mod_wsgi with apache on archlinux 64bits I've added it in my http.conf : LoadModule wsgi_module modules/mod_wsgi.so <VirtualHost *:80> WSGIDaemonProcess mart.localhost user=mart group=users processes=2 threads=25 WSGIProcessGroup mart.localhost LogLevel debug Alias /media /home/mart/programmation/python/django/martfiles/media/ <Directory /home/mart/programmation/python/django/martfiles/> Order allow,deny Allow from all </Directory> WSGIScriptAlias / /srv/http/wsgi-scripts/django.wsgi </VirtualHost> I tried to use the django.wsgi in my home folder but it doesn't work (permission denied to access /) (strangely it works if I use the test script given here) all the directories and content (apache folder, wsgi-script, martfiles) have the permission 775 root:devusers with the group devusers including my user, http and root in my template base.html, I call the css this way : <html> <head> <link rel="stylesheet" href="/media/css/style.css" /> and the error in /var/log/http/error.log [Sat Jan 16 13:22:21 2010] [error] [client 127.0.0.1] (13)Permission denied: access to /media/css/style.css denied, referer: http://localhost/ [Sat Jan 16 13:22:21 2010] [info] mod_wsgi (pid=14783): Attach interpreter '' /etc/httpd/conf/http.conf /srv/http/wsgi-script/django.wsgi /home/.../martfiles/settings.py thank you edit : I precise that my django website is working fine (except the sessions but I don't think it's related) so I'm not sure it's related to the django.wsgi file (maybe I'm wrong) but what is sure is that I should be able to use the django.wsgi from outside the apache folder if I change the line Alias /media /home/mart/programmation/python/django/martfiles/media/ with Alias /media /srv/http/media/ and gives the right permissions, it works. But I don't want (and shouldn't) to put all my media in the apache folder A: It is not sufficient for just the directory '/home/mart/programmation/python/django/martfiles/media' containing static files to be readable and searchable. The user that Apache runs as must have read and potentially search access, to all parent directories of it back up to root directory. Since home directories on many systems are 'rwx------' this would deny Apache access irrespective of the Deny/Allow directives in Apache configuration. Suggest you place the Django project and static files outside of your home account somewhere and relax the file system permissions as necessary. A: Your django.wsgi file, WSGIScriptAlias / /srv/http/wsgi-scripts/django.wsgi is outside of the <Directory> defined by: <Directory /home/mart/programmation/python/django/martfiles/> Try adding this to httpd.conf: <Directory /srv/http/wsgi-scripts/> Order allow,deny Allow from all </Directory> Or, put your django.wsgi file somewhere inside /home/mart/programmation/python/django/martfiles/. That should work. EDIT: alright, here's an example httpd.conf that is working on a production machine: <VirtualHost *:80> # Admin email, Server Name (domain name) and any aliases ServerAdmin testing@example.de ServerName www.example.de DocumentRoot /home/example/testing/parts/public Alias /media /home/example/testing/parts/public/media # WSGI Settings WSGIDaemonProcess example user=example group=example threads=25 WSGIProcessGroup example WSGIScriptAlias / /home/example/testing/parts/public/django.wsgi <Directory "/home/example/testing/parts/public"> # Allow Apache to follow links Options FollowSymLinks # Turn on the ability to use .htaccess files AllowOverride All # Controls who can get stuff from this directory Order allow,deny Allow from all </Directory> </VirtualHost> So, if your dhango.wsgi is defined in a place set as accessible by a <Directory> directive, you could also sudo su httpd if that's the user that runs apache on your system, and simply try to read the css files, to see if apache can really access them... A: This seems to be what I have for my application except that I didn't see the NameVirtualHost directive in the http.conf which is required if you want to setup virtual servers. You can try adding NameVirtualHost *:80 before the virtual host definition.
static file with mod_wsgi in django
I've searched a lot but I still have a problem with the static files (css, image,...) with my django website. I'm using mod_wsgi with apache on archlinux 64bits I've added it in my http.conf : LoadModule wsgi_module modules/mod_wsgi.so <VirtualHost *:80> WSGIDaemonProcess mart.localhost user=mart group=users processes=2 threads=25 WSGIProcessGroup mart.localhost LogLevel debug Alias /media /home/mart/programmation/python/django/martfiles/media/ <Directory /home/mart/programmation/python/django/martfiles/> Order allow,deny Allow from all </Directory> WSGIScriptAlias / /srv/http/wsgi-scripts/django.wsgi </VirtualHost> I tried to use the django.wsgi in my home folder but it doesn't work (permission denied to access /) (strangely it works if I use the test script given here) all the directories and content (apache folder, wsgi-script, martfiles) have the permission 775 root:devusers with the group devusers including my user, http and root in my template base.html, I call the css this way : <html> <head> <link rel="stylesheet" href="/media/css/style.css" /> and the error in /var/log/http/error.log [Sat Jan 16 13:22:21 2010] [error] [client 127.0.0.1] (13)Permission denied: access to /media/css/style.css denied, referer: http://localhost/ [Sat Jan 16 13:22:21 2010] [info] mod_wsgi (pid=14783): Attach interpreter '' /etc/httpd/conf/http.conf /srv/http/wsgi-script/django.wsgi /home/.../martfiles/settings.py thank you edit : I precise that my django website is working fine (except the sessions but I don't think it's related) so I'm not sure it's related to the django.wsgi file (maybe I'm wrong) but what is sure is that I should be able to use the django.wsgi from outside the apache folder if I change the line Alias /media /home/mart/programmation/python/django/martfiles/media/ with Alias /media /srv/http/media/ and gives the right permissions, it works. But I don't want (and shouldn't) to put all my media in the apache folder
[ "It is not sufficient for just the directory '/home/mart/programmation/python/django/martfiles/media' containing static files to be readable and searchable. The user that Apache runs as must have read and potentially search access, to all parent directories of it back up to root directory. Since home directories on many systems are 'rwx------' this would deny Apache access irrespective of the Deny/Allow directives in Apache configuration.\nSuggest you place the Django project and static files outside of your home account somewhere and relax the file system permissions as necessary.\n", "Your django.wsgi file,\nWSGIScriptAlias / /srv/http/wsgi-scripts/django.wsgi\n\nis outside of the <Directory> defined by:\n<Directory /home/mart/programmation/python/django/martfiles/>\n\nTry adding this to httpd.conf:\n<Directory /srv/http/wsgi-scripts/>\n Order allow,deny\n Allow from all\n</Directory>\n\nOr, put your django.wsgi file somewhere inside /home/mart/programmation/python/django/martfiles/. That should work.\nEDIT: alright, here's an example httpd.conf that is working on a production machine:\n<VirtualHost *:80>\n # Admin email, Server Name (domain name) and any aliases\n ServerAdmin testing@example.de\n ServerName www.example.de\n\n DocumentRoot /home/example/testing/parts/public\n\n Alias /media /home/example/testing/parts/public/media\n\n # WSGI Settings\n WSGIDaemonProcess example user=example group=example threads=25\n WSGIProcessGroup example\n WSGIScriptAlias / /home/example/testing/parts/public/django.wsgi\n\n <Directory \"/home/example/testing/parts/public\">\n # Allow Apache to follow links\n Options FollowSymLinks\n # Turn on the ability to use .htaccess files\n AllowOverride All\n # Controls who can get stuff from this directory\n Order allow,deny\n Allow from all\n </Directory>\n</VirtualHost>\n\nSo, if your dhango.wsgi is defined in a place set as accessible by a <Directory> directive, you could also sudo su httpd if that's the user that runs apache on your system, and simply try to read the css files, to see if apache can really access them...\n", "This seems to be what I have for my application except that I didn't see the NameVirtualHost directive in the http.conf which is required if you want to setup virtual servers. You can try adding NameVirtualHost *:80 before the virtual host definition.\n" ]
[ 7, 3, 0 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0002078160_apache_django_mod_wsgi_python.txt
Q: Undesired python feedparser instantiation relic Question: How do I kill an instantiation or insure i'm creating a new instantiation of the python universal feedparser? Info: I'm working on a program right now that downloads and catalogs large numbers of blogs. It has worked well so for except for an unfortunate bug. My code is set up to take a list of blog urls and run them through a for loop. each run it picks a url and sends it down to a separate class which manages the downloading, extracting, and saving of the data to a file. The first url works just fine. It downloads the entirety of the blog and saves it to a file. But the second blog it downloads will have all the data from the first one as well, I'm totally clueless as to why. Code snippets: class BlogHarvester: def __init__(self,folder): f = open(folder,'r') stop = folder[len(folder)-1] while stop != '/': folder = folder[0:len(folder)-1] stop = folder[len(folder)-1] blogs = [] for line in f: blogs.append(line) for herf in blogs: blog = BlogParser(herf) sPath = "" uid = newguid()##returns random hash. sPath = uid sPath = sPath + " - " + blog.posts[0].author[1:5] + ".blog" print sPath blog.storeAsFile(sPath) class BlogParser: def __init__(self, blogherf='null', path='null', posts = []): self.blogherf = blogherf self.blog = feedparser.parse(blogherf) self.path = path self.posts = posts if blogherf != 'null': self.makeList() elif path != 'null': self.loadFromFile() class BlogPeices: def __init__(self,title,author,post,date,publisher,rights,comments): self.author = author self.title = title self.post = post self.date = date self.publisher = publisher self.rights = rights self.comments = comments I included snippets I figured that would probably be useful. Sorry if there are any confusing artifacts. This program has been a pain in the butt. A: The problem is posts=[]. Default arguments are calculated at compile time, not runtime, so mutations to the object remain for the lifetime of the class. Instead use posts=None and test: if posts is None: self.posts = [] A: As what Ignacio said, any mutations that happen to the default arguments in the function list will stay for the life of the class. From http://docs.python.org/reference/compound_stmts.html#function-definitions Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function. But this brings up sort of a gotcha, you are modifying a reference... So you may be modifying a list that the consumer of the class that wasn't expected to be modified: For example: class A: def foo(self, x = [] ): x.append(1) self.x = x a = A() a.foo() print a.x # prints: [1] a.foo() print a.x # prints: [1,1] # !!!! Consumer would expect this to be [1] y = [1,2,3] a.foo(y) print a.x # prints: [1, 2, 3, 1] print y # prints: [1, 2, 3, 1] # !!!! My list was modified If you were to copy it instead: (See http://docs.python.org/library/copy.html ) import copy class A: def foo(self, x = [] ): x = copy.copy(x) x.append(1) self.x = x a = A() a.foo() print a.x # prints: [1] a.foo() print a.x # prints: [1] # !!! Much better =) y = [1,2,3] a.foo(y) print a.x # prints: [1, 2, 3, 1] print y # prints: [1, 2, 3] # !!!! My list is how I made it
Undesired python feedparser instantiation relic
Question: How do I kill an instantiation or insure i'm creating a new instantiation of the python universal feedparser? Info: I'm working on a program right now that downloads and catalogs large numbers of blogs. It has worked well so for except for an unfortunate bug. My code is set up to take a list of blog urls and run them through a for loop. each run it picks a url and sends it down to a separate class which manages the downloading, extracting, and saving of the data to a file. The first url works just fine. It downloads the entirety of the blog and saves it to a file. But the second blog it downloads will have all the data from the first one as well, I'm totally clueless as to why. Code snippets: class BlogHarvester: def __init__(self,folder): f = open(folder,'r') stop = folder[len(folder)-1] while stop != '/': folder = folder[0:len(folder)-1] stop = folder[len(folder)-1] blogs = [] for line in f: blogs.append(line) for herf in blogs: blog = BlogParser(herf) sPath = "" uid = newguid()##returns random hash. sPath = uid sPath = sPath + " - " + blog.posts[0].author[1:5] + ".blog" print sPath blog.storeAsFile(sPath) class BlogParser: def __init__(self, blogherf='null', path='null', posts = []): self.blogherf = blogherf self.blog = feedparser.parse(blogherf) self.path = path self.posts = posts if blogherf != 'null': self.makeList() elif path != 'null': self.loadFromFile() class BlogPeices: def __init__(self,title,author,post,date,publisher,rights,comments): self.author = author self.title = title self.post = post self.date = date self.publisher = publisher self.rights = rights self.comments = comments I included snippets I figured that would probably be useful. Sorry if there are any confusing artifacts. This program has been a pain in the butt.
[ "The problem is posts=[]. Default arguments are calculated at compile time, not runtime, so mutations to the object remain for the lifetime of the class. Instead use posts=None and test:\nif posts is None:\n self.posts = []\n\n", "As what Ignacio said, any mutations that happen to the default arguments in the function list will stay for the life of the class. \nFrom http://docs.python.org/reference/compound_stmts.html#function-definitions\n\nDefault parameter values are evaluated\n when the function definition is\n executed. This means that the\n expression is evaluated once, when the\n function is defined, and that that\n same “pre-computed” value is used for\n each call. This is especially\n important to understand when a default\n parameter is a mutable object, such as\n a list or a dictionary: if the\n function modifies the object (e.g. by\n appending an item to a list), the\n default value is in effect modified.\n This is generally not what was\n intended. A way around this is to use\n None as the default, and explicitly\n test for it in the body of the\n function.\n\nBut this brings up sort of a gotcha, you are modifying a reference... So you may be modifying a list that the consumer of the class that wasn't expected to be modified:\nFor example:\nclass A:\n def foo(self, x = [] ):\n x.append(1)\n self.x = x\n\na = A()\na.foo()\nprint a.x\n# prints: [1]\na.foo()\nprint a.x\n# prints: [1,1] # !!!! Consumer would expect this to be [1]\ny = [1,2,3]\na.foo(y)\nprint a.x\n# prints: [1, 2, 3, 1]\nprint y\n# prints: [1, 2, 3, 1] # !!!! My list was modified\n\nIf you were to copy it instead: (See http://docs.python.org/library/copy.html )\nimport copy\nclass A:\n def foo(self, x = [] ):\n x = copy.copy(x)\n x.append(1)\n self.x = x\n\na = A()\na.foo()\nprint a.x\n# prints: [1]\na.foo()\nprint a.x\n# prints: [1] # !!! Much better =)\ny = [1,2,3]\na.foo(y)\nprint a.x\n# prints: [1, 2, 3, 1]\nprint y\n# prints: [1, 2, 3] # !!!! My list is how I made it\n\n" ]
[ 1, 0 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0002080071_feedparser_python.txt
Q: Django TemplateSyntaxError: too many values to unpack I'm working with a django form, and I have a choice field. I think the problem may be that the choices are fetched dynamically, and right now there's only one value. I'm getting the TemplateSyntaxError: too many values to unpack. Some of the other posts seem to say that having only one value is a problem, so i adjusted my function that fetches the choices, and changed it so it added to blank options at the beginning, just as a test. However this brought up another error: need more than 0 values to unpack Not really sure what to do about this, because even if there is only one value, I need it to still execute. Form: class UploadFileForm(forms.Form): category = forms.ChoiceField(get_category_list()) file = forms.FileField() Category Fetch Function: def get_category_list(): cats = [(), ()] for i in os.listdir(settings.MEDIA_ROOT + '/forms'): cats.append(i) return cats Template Section: <div id='addformdialog' title='Add Form'> {{ form.as_p }} </div> View: def fm(request): if request.session['SecurityLevel'] != 2: return HttpResponse('Access Denied!') if request.method == 'POST': form = UpoadFileForm(request.POST, request.FILES) if form.is_valid(): destination = open(settings.MEDIA_ROOT + "/forms/" + request.POST['category'] + "/" + request.FILES['file'].name, 'wb+') for chunk in request.FILES['file'].chunks(): destination.write(chunk) destination.close() form = UploadFileForm() return render_to_response('admin/fm.html', {'categories':cats, 'form':form, 'uploadsuccess':True}) else: cats = get_category_list() form = UploadFileForm() return render_to_response('admin/fm.html', {'categories':cats, 'form':form}) A: choices is supposed to be an iterable of 2-tuples. You are only appending a single string, which is causing chaos due to how strings and tuples interact (I'll give you details if you really care). Append 2-tuples instead.
Django TemplateSyntaxError: too many values to unpack
I'm working with a django form, and I have a choice field. I think the problem may be that the choices are fetched dynamically, and right now there's only one value. I'm getting the TemplateSyntaxError: too many values to unpack. Some of the other posts seem to say that having only one value is a problem, so i adjusted my function that fetches the choices, and changed it so it added to blank options at the beginning, just as a test. However this brought up another error: need more than 0 values to unpack Not really sure what to do about this, because even if there is only one value, I need it to still execute. Form: class UploadFileForm(forms.Form): category = forms.ChoiceField(get_category_list()) file = forms.FileField() Category Fetch Function: def get_category_list(): cats = [(), ()] for i in os.listdir(settings.MEDIA_ROOT + '/forms'): cats.append(i) return cats Template Section: <div id='addformdialog' title='Add Form'> {{ form.as_p }} </div> View: def fm(request): if request.session['SecurityLevel'] != 2: return HttpResponse('Access Denied!') if request.method == 'POST': form = UpoadFileForm(request.POST, request.FILES) if form.is_valid(): destination = open(settings.MEDIA_ROOT + "/forms/" + request.POST['category'] + "/" + request.FILES['file'].name, 'wb+') for chunk in request.FILES['file'].chunks(): destination.write(chunk) destination.close() form = UploadFileForm() return render_to_response('admin/fm.html', {'categories':cats, 'form':form, 'uploadsuccess':True}) else: cats = get_category_list() form = UploadFileForm() return render_to_response('admin/fm.html', {'categories':cats, 'form':form})
[ "choices is supposed to be an iterable of 2-tuples. You are only appending a single string, which is causing chaos due to how strings and tuples interact (I'll give you details if you really care). Append 2-tuples instead.\n" ]
[ 6 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002080186_django_django_templates_python.txt
Q: Finding intersections Given a scenario where there are millions of potentially overlapping bounding boxes of variable sizes less the 5km in width. Create a fast function with the arguments findIntersections(Longitude,Latitude,Radius) and the output is a list of those bounding boxes ids where each bounding box origin is inside the perimeter of the function argument dimensions. How do I solve this problem elegantly? A: This is normally done using an R-tree data structure dbs like mysql or postgresql have GIS modules that use an r-tree under the hood to quickly retrieve locations within a certain proximity to a point on a map. From http://en.wikipedia.org/wiki/R-tree: R-trees are tree data structures that are similar to B-trees, but are used for spatial access methods, i.e., for indexing multi-dimensional information; for example, the (X, Y) coordinates of geographical data. A common real-world usage for an R-tree might be: "Find all museums within 2 kilometres (1.2 mi) of my current location". The data structure splits space with hierarchically nested, and possibly overlapping, minimum bounding rectangles (MBRs, otherwise known as bounding boxes, i.e. "rectangle", what the "R" in R-tree stands for). The Priority R-Tree (PR-tree) is a variant that has a maximum running time of: "O((N/B)^(1-1/d)+T/B) I/Os, where N is the number of d-dimensional (hyper-) rectangles stored in the R-tree, B is the disk block size, and T is the output size." In practice most real-world queries will have a much quicker average case run time. fyi, in addition to the other great code posted, there's some cool stuff like SpatiaLite and SQLite R-tree module A: PostGIS is an open-source GIS extention for postgresql. They have ST_Intersects and ST_Intersection functions available. If your interested you can dig around and see how it's implemented there: http://svn.osgeo.org/postgis/trunk/postgis/ A: This seems like a better more general approach GiST http://en.wikipedia.org/wiki/GiST
Finding intersections
Given a scenario where there are millions of potentially overlapping bounding boxes of variable sizes less the 5km in width. Create a fast function with the arguments findIntersections(Longitude,Latitude,Radius) and the output is a list of those bounding boxes ids where each bounding box origin is inside the perimeter of the function argument dimensions. How do I solve this problem elegantly?
[ "This is normally done using an R-tree data structure\ndbs like mysql or postgresql have GIS modules that use an r-tree under the hood to quickly retrieve locations within a certain proximity to a point on a map.\nFrom http://en.wikipedia.org/wiki/R-tree:\n\nR-trees are tree data structures that\n are similar to B-trees, but are used\n for spatial access methods, i.e., for\n indexing multi-dimensional\n information; for example, the (X, Y)\n coordinates of geographical data. A\n common real-world usage for an R-tree\n might be: \"Find all museums within 2\n kilometres (1.2 mi) of my current\n location\".\nThe data structure splits space with\n hierarchically nested, and possibly\n overlapping, minimum bounding\n rectangles (MBRs, otherwise known as\n bounding boxes, i.e. \"rectangle\", what\n the \"R\" in R-tree stands for).\n\nThe Priority R-Tree (PR-tree) is a variant that has a maximum running time of:\n\"O((N/B)^(1-1/d)+T/B) I/Os, where N is the number of d-dimensional (hyper-)\nrectangles stored in the R-tree, B is the disk block size, and T is the output\nsize.\"\n\nIn practice most real-world queries will have a much quicker average case run time.\nfyi, in addition to the other great code posted, there's some cool stuff like SpatiaLite and SQLite R-tree module\n", "PostGIS is an open-source GIS extention for postgresql.\nThey have ST_Intersects and ST_Intersection functions available.\nIf your interested you can dig around and see how it's implemented there:\nhttp://svn.osgeo.org/postgis/trunk/postgis/\n", "This seems like a better more general approach GiST\nhttp://en.wikipedia.org/wiki/GiST\n" ]
[ 4, 1, 0 ]
[]
[]
[ "algorithm", "localization", "optimization", "performance", "python" ]
stackoverflow_0002062325_algorithm_localization_optimization_performance_python.txt
Q: @register.filter in my code from django import template register = template.Library() class_converter = { "textinput":"textinput textInput", "fileinput":"fileinput fileUpload" } @register.filter#<-------- def is_checkbox(field): return field.field.widget.__class__.__name__.lower() == "checkboxinput" @register.filter#<-------- def with_class(field): class_name = field.field.widget.__class__.__name__.lower() class_name = class_converter.get(class_name, class_name) if "class" in field.field.widget.attrs: field.field.widget.attrs['class'] += " %s" % class_name else: field.field.widget.attrs['class'] = class_name return unicode(field) and register.filter function is: def filter(self, name=None, filter_func=None): if name == None and filter_func == None: # @register.filter() return self.filter_function elif filter_func == None: if(callable(name)): # @register.filter return self.filter_function(name) else: # @register.filter('somename') or @register.filter(name='somename') def dec(func): return self.filter(name, func) return dec elif name != None and filter_func != None: # register.filter('somename', somefunc) self.filters[name] = filter_func return filter_func else: raise InvalidTemplateLibrary("Unsupported arguments to Library.filter: (%r, %r)", (name, filter_func)) so @register.filter def a(): pass is Equal register.filter(name=None,filter_func=a) yes?? A: Not exactly. The decorator syntax: @register.filter def a(): pass is syntactic sugar for: def a(): pass a = register.filter(a) So register.filter in this case will be called with the first positional argument, 'name' being your function. The django register.filter function handles that usage however and returns the right thing even if the filter is sent as the first argument (see the if callable(name) branch) It's more common to make decorators that can take multiple arguments do so with the function to be decorated being the first positional argument (or alternately being function factories/closures), but I have a feeling the reason django did it this way was for backwards-compatibility. Actually I vaguely remember it not being a decorator in the past, and then becoming a decorator in a later django version. A: No. Simple decorators take the function they decorate as a parameter, and return a new function. a = register.filter(a)
@register.filter in my code
from django import template register = template.Library() class_converter = { "textinput":"textinput textInput", "fileinput":"fileinput fileUpload" } @register.filter#<-------- def is_checkbox(field): return field.field.widget.__class__.__name__.lower() == "checkboxinput" @register.filter#<-------- def with_class(field): class_name = field.field.widget.__class__.__name__.lower() class_name = class_converter.get(class_name, class_name) if "class" in field.field.widget.attrs: field.field.widget.attrs['class'] += " %s" % class_name else: field.field.widget.attrs['class'] = class_name return unicode(field) and register.filter function is: def filter(self, name=None, filter_func=None): if name == None and filter_func == None: # @register.filter() return self.filter_function elif filter_func == None: if(callable(name)): # @register.filter return self.filter_function(name) else: # @register.filter('somename') or @register.filter(name='somename') def dec(func): return self.filter(name, func) return dec elif name != None and filter_func != None: # register.filter('somename', somefunc) self.filters[name] = filter_func return filter_func else: raise InvalidTemplateLibrary("Unsupported arguments to Library.filter: (%r, %r)", (name, filter_func)) so @register.filter def a(): pass is Equal register.filter(name=None,filter_func=a) yes??
[ "Not exactly. The decorator syntax:\n@register.filter\ndef a():\n pass\n\nis syntactic sugar for:\ndef a():\n pass\na = register.filter(a)\n\nSo register.filter in this case will be called with the first positional argument, 'name' being your function. The django register.filter function handles that usage however and returns the right thing even if the filter is sent as the first argument (see the if callable(name) branch)\nIt's more common to make decorators that can take multiple arguments do so with the function to be decorated being the first positional argument (or alternately being function factories/closures), but I have a feeling the reason django did it this way was for backwards-compatibility. Actually I vaguely remember it not being a decorator in the past, and then becoming a decorator in a later django version.\n", "No. Simple decorators take the function they decorate as a parameter, and return a new function.\na = register.filter(a)\n\n" ]
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002080296_django_python.txt
Q: What happen when I add a Django app to INSTALLED_APPS? Here is the situation. I have a django project with two installed apps. Both apps appear to function properly if they are installed independently of each other. However if I list both apps in the settings.INSTALLED_APPS the reverse() function seems to break for urls in the first app. So this leads me to believe that a bug in the second app is causing the problem. If I simply remove app_2 from the settings.INSTALLED_APPS, app_1's url reverse() begins working again. So the question becomes what "Magic" is happening when I add app_2 to the settings.INSTALLED_APPS? Where should I be looking in app_2 for code causing this problem? UPDATE: I have narrowed down the problem a little, but it just gets stranger. app_2 has an admin.py file that defines a few custom admin views. In that file is a line that calls reverse: reverse('init_script_view', args=['id_content']) As long as that line is in the admin.py file all calls to reverse() fail with a NoReverseMatch exception. If I remove that line, everything seems to work fine. A: Nothing particular happens when you add an app to INSTALLED_APPS, but the main thing that affects you is that its views are checked when you call reverse(). The way reverse works is to import all the views in the project, and see which ones match the URL name you have given. However, it is quite fragile, and if any of the views cause an error for some reason, or can't be imported, the reverse call will fail. The fact that it is only failing once you include app2 indicates that there is an issue with the views in app2 somewhere. Try importing them individually from the shell and see what errors you get. Edited after update Thanks for the extra detail. I have seen this before in my own code. It is probably because the admin files are being imported before the urlconf is processed, so this reverse gives an error. Try moving the admin.autodiscover() line down to the very bottom of urls.py, so that it is the last line in that file. A: Without seeing the code, it's hard to say for sure, but I would guess that the urls.py of app_1 and app_2 contain the same name for different urls, e.g.: app_1/urls.py: ... url(r'^app_1/foo/$', 'app_1.views.foo', name='foo') ... app_2/urls.py: ... url(r'^app_2/foo/$', 'app_2.views.foo', name='foo') ... If you clean up those names (the most common convention I've seen is appname_viewname) it should start working.
What happen when I add a Django app to INSTALLED_APPS?
Here is the situation. I have a django project with two installed apps. Both apps appear to function properly if they are installed independently of each other. However if I list both apps in the settings.INSTALLED_APPS the reverse() function seems to break for urls in the first app. So this leads me to believe that a bug in the second app is causing the problem. If I simply remove app_2 from the settings.INSTALLED_APPS, app_1's url reverse() begins working again. So the question becomes what "Magic" is happening when I add app_2 to the settings.INSTALLED_APPS? Where should I be looking in app_2 for code causing this problem? UPDATE: I have narrowed down the problem a little, but it just gets stranger. app_2 has an admin.py file that defines a few custom admin views. In that file is a line that calls reverse: reverse('init_script_view', args=['id_content']) As long as that line is in the admin.py file all calls to reverse() fail with a NoReverseMatch exception. If I remove that line, everything seems to work fine.
[ "Nothing particular happens when you add an app to INSTALLED_APPS, but the main thing that affects you is that its views are checked when you call reverse(). \nThe way reverse works is to import all the views in the project, and see which ones match the URL name you have given. However, it is quite fragile, and if any of the views cause an error for some reason, or can't be imported, the reverse call will fail.\nThe fact that it is only failing once you include app2 indicates that there is an issue with the views in app2 somewhere. Try importing them individually from the shell and see what errors you get.\nEdited after update Thanks for the extra detail. I have seen this before in my own code. It is probably because the admin files are being imported before the urlconf is processed, so this reverse gives an error. Try moving the admin.autodiscover() line down to the very bottom of urls.py, so that it is the last line in that file.\n", "Without seeing the code, it's hard to say for sure, but I would guess that the urls.py of app_1 and app_2 contain the same name for different urls, e.g.:\napp_1/urls.py:\n ...\n url(r'^app_1/foo/$', 'app_1.views.foo', name='foo')\n ...\n\napp_2/urls.py:\n ...\n url(r'^app_2/foo/$', 'app_2.views.foo', name='foo')\n ...\n\nIf you clean up those names (the most common convention I've seen is appname_viewname) it should start working.\n" ]
[ 4, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002079898_django_python.txt
Q: How to copy a file via the browser to Amazon S3 using Python (and boto)? Creating a file (key) into Amazon S3 using Python (and boto) is not a problem. With this code, I can connect to a bucket and create a key with a specific content: bucket_instance = connection.get_bucket('bucketname') key = bucket_instance.new_key('testfile.txt') key.set_contents_from_string('Content for File') I want to upload a file via the browser (file dialogue) into Amazon S3. How can I realize this with boto? Thanks in advance A: You can't do this with boto, because what you're asking for is purely client-side - there's no direct involvement from the server except to generate the form to post. What you need to use is Amazon's browser-based upload with POST support. There's a demo of it here. A: do you mean this one? Upload files in Google App Engine
How to copy a file via the browser to Amazon S3 using Python (and boto)?
Creating a file (key) into Amazon S3 using Python (and boto) is not a problem. With this code, I can connect to a bucket and create a key with a specific content: bucket_instance = connection.get_bucket('bucketname') key = bucket_instance.new_key('testfile.txt') key.set_contents_from_string('Content for File') I want to upload a file via the browser (file dialogue) into Amazon S3. How can I realize this with boto? Thanks in advance
[ "You can't do this with boto, because what you're asking for is purely client-side - there's no direct involvement from the server except to generate the form to post.\nWhat you need to use is Amazon's browser-based upload with POST support. There's a demo of it here.\n", "do you mean this one? Upload files in Google App Engine\n" ]
[ 2, 0 ]
[]
[]
[ "amazon_ec2", "amazon_s3", "boto", "google_app_engine", "python" ]
stackoverflow_0002079594_amazon_ec2_amazon_s3_boto_google_app_engine_python.txt
Q: Why the following python code works? class Square: def __init__(self,start,stop): self.value = start - 1 self.stop = stop def __iter__(self): return self def next(self): if self.value == self.stop: raise StopIteration self.value += 1 return self.value ** 2 for i in Square(1,4): print i, Which outputs 1 4 9 16 A: why wouldn't it? It looks like a normal iterator to me... the next() method is a 'known' method in python that along with the __iter__() method signals a generator. Here is the python docs on iterators. A: This is a Python iterator: every time through the loop the next() method is called A: It's an iterator. Normally though, you would write it using yield. def Square(start, stop): for value in xrange(start, stop + 1): yield value ** 2 for i in Square(1, 4): print i, A: The typical Python iteration protocol: for y in x... is as follows: iter = x.__iter__() # get iterator try: while 1: y = iter.next() # get each item ... # process y except StopIteration: pass # iterator exhausted from http://www.boost.org/doc/libs/1_41_0/libs/python/doc/tutorial/doc/html/python/iterators.html
Why the following python code works?
class Square: def __init__(self,start,stop): self.value = start - 1 self.stop = stop def __iter__(self): return self def next(self): if self.value == self.stop: raise StopIteration self.value += 1 return self.value ** 2 for i in Square(1,4): print i, Which outputs 1 4 9 16
[ "why wouldn't it? It looks like a normal iterator to me...\nthe next() method is a 'known' method in python that along with the __iter__() method signals a generator.\nHere is the python docs on iterators.\n", "This is a Python iterator: every time through the loop the next() method is called\n", "It's an iterator.\nNormally though, you would write it using yield.\ndef Square(start, stop):\n for value in xrange(start, stop + 1):\n yield value ** 2\n\nfor i in Square(1, 4):\n print i,\n\n", "The typical Python iteration protocol: for y in x... is as follows:\niter = x.__iter__() # get iterator\ntry:\n while 1:\n y = iter.next() # get each item\n ... # process y\nexcept StopIteration: pass # iterator exhausted\n\nfrom\nhttp://www.boost.org/doc/libs/1_41_0/libs/python/doc/tutorial/doc/html/python/iterators.html\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002054124_python_syntax.txt
Q: os.unlink multiple file in python Possible Duplicate: Deleting files by type in Python on Windows How can I delete all files with the extension ".txt" in a directory? I normally just do import os filepath = 'C:\directory\thefile.txt' os.unlink(filepath) Is there a command like os.unlink('C:\directory\*.txt') that would delete all .txt files? How can I do that? Thanks! A: #!/usr/bin/env python import glob import os for i in glob.glob(u'*.txt'): os.unlink (i) should do the job. Edit: You can also do it in "one line" using map operation: #!/usr/bin/env python import glob import os map(os.unlink, glob.glob(u'*.txt')) A: Use the glob module to get a list of files matching the pattern and call unlink on all of them in a loop. A: Iterate through all files in C:\directory\, check if the extension is .txt, unlink if yes.
os.unlink multiple file in python
Possible Duplicate: Deleting files by type in Python on Windows How can I delete all files with the extension ".txt" in a directory? I normally just do import os filepath = 'C:\directory\thefile.txt' os.unlink(filepath) Is there a command like os.unlink('C:\directory\*.txt') that would delete all .txt files? How can I do that? Thanks!
[ "#!/usr/bin/env python\n\nimport glob\nimport os\n\nfor i in glob.glob(u'*.txt'):\n os.unlink (i)\n\nshould do the job.\nEdit: You can also do it in \"one line\" using map operation:\n#!/usr/bin/env python\n\nimport glob\nimport os\n\nmap(os.unlink, glob.glob(u'*.txt'))\n\n", "Use the glob module to get a list of files matching the pattern and call unlink on all of them in a loop.\n", "Iterate through all files in C:\\directory\\, check if the extension is .txt, unlink if yes.\n" ]
[ 15, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002081139_python.txt
Q: Python calling raw_input from a subprocess I'm calling a python script from the below one using subprocess. From the command line the user chooses which file to open using raw_input import optparse import subprocess import readline import os def main(): options = {'0': './option_0.py', '1': './option_1.py', '2': './option_2.py', '3': './option_3.py'} input = -1 while True: if input in options: file = options[input] subprocess.Popen(file) else: print "Welcome" print "0. option_0" print "1. option_1" print "2. option_2" print "3. option_3" input = raw_input("Please make a selection: ") if __name__ == '__main__': main() However on the subprocess called(say option_1.py is called) I have a problem using raw_input again to accept prompt from the user. I am aware of the .PIPE arguments and have tried subprocess.Popen(file, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) But again no luck. A: Here's an example where the subprocess receives my input: import subprocess import sys command = 'python -c \'print raw_input("Please make a selection: ")\'' sp = subprocess.Popen(command, shell = True, stdin = sys.stdin) sp.wait() A: If I understand your question, you want to redirect the current standard input to the subprocess. Which can be done this way: subprocess.Popen(file, stdin=sys.stdin, ...)
Python calling raw_input from a subprocess
I'm calling a python script from the below one using subprocess. From the command line the user chooses which file to open using raw_input import optparse import subprocess import readline import os def main(): options = {'0': './option_0.py', '1': './option_1.py', '2': './option_2.py', '3': './option_3.py'} input = -1 while True: if input in options: file = options[input] subprocess.Popen(file) else: print "Welcome" print "0. option_0" print "1. option_1" print "2. option_2" print "3. option_3" input = raw_input("Please make a selection: ") if __name__ == '__main__': main() However on the subprocess called(say option_1.py is called) I have a problem using raw_input again to accept prompt from the user. I am aware of the .PIPE arguments and have tried subprocess.Popen(file, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) But again no luck.
[ "Here's an example where the subprocess receives my input:\nimport subprocess\nimport sys\n\ncommand = 'python -c \\'print raw_input(\"Please make a selection: \")\\''\nsp = subprocess.Popen(command, shell = True, stdin = sys.stdin)\nsp.wait()\n\n", "If I understand your question, you want to redirect the current standard input to the subprocess. Which can be done this way:\nsubprocess.Popen(file, stdin=sys.stdin, ...)\n\n" ]
[ 3, 2 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0002081124_python_subprocess.txt
Q: How to print nicely? I have two classes: class Dog(object): def __init__(self, name): self.name = name class Toy(object): def play(self): print "Squeak!" I need to come up with a method called play(self, toy, n) for class Dog. It prints "Yip! " (with a space) followed by the output from toy.play on the same line. This happens n times, with the n outputs on separate lines. If n is negative, it is the same as if it were 0. What I did is def play(self, toy, n): count = 1 if n > 0: while count <= n: print "Yip! %s " % Toy().play() count += 1 else: print None However, when I call Dog('big').play(toy, 3) or whatever n is, it shows that Squeak! Yip! None Squeak! Yip! None Squeak! Yip! None I don't know what's wrong. Squeal! and Yip! should suppose to be at the same line while there are at separate now and there order should be opposite. And why there is a None? Can anyone please help me out? A: In your example call, Dog('big').play(0), you are not passing the toy argument -- that's what it's complaining about! Pass a toy argument before n and that will be better. Then you can start addressing the bugs in your play implementation: why are you making a new toy rather than use the argument, why are you printing 'None' when that's not part of the specs, how you're uselessly printing the return value of the Toy.play method (which returns None, implicitly) rather than working along with the fact that the latter method is printing something, and never incrementing count and so ending up in infinite loops. (four serious bugs in eight lines plus one in the call just has to be some sort of a record, I believe;-). BTW, homework is normally tagged with the tag homework, not exercise. (And, there's a further bug in your Q's title, as no classmethod is actually around, just a good old plain and perfectly normal instance method). A: The first thing I see wrong is the you are attempting to call the class 'Toy' instead of the variable representing the instance 'toy' passed to you 'play' method. I don't believe you can instantiate a class and call one of its methods at the same time which is what 'Toy().play()' is trying to do. The other is that I'm not quite sure I understand what you are trying to do with the design of your classes. Here is how I would implement the classes and then use them to get your desired behavior. class Toy(object): def play(self): return "Squeak!" class Dog(object): speak = 'Yip! %s' def __init__(self, name, toy): self.name = name self.toy = toy def play(self,n): if n > 0: for each in range(n): print(self.speak % self.toy.play()) else: print(None) and here is how I would use it Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from toy import Toy, Dog >>> spike = Dog("Spike",Toy()) >>> spike.play(3) Yip! Squeak! Yip! Squeak! Yip! Squeak! >>>
How to print nicely?
I have two classes: class Dog(object): def __init__(self, name): self.name = name class Toy(object): def play(self): print "Squeak!" I need to come up with a method called play(self, toy, n) for class Dog. It prints "Yip! " (with a space) followed by the output from toy.play on the same line. This happens n times, with the n outputs on separate lines. If n is negative, it is the same as if it were 0. What I did is def play(self, toy, n): count = 1 if n > 0: while count <= n: print "Yip! %s " % Toy().play() count += 1 else: print None However, when I call Dog('big').play(toy, 3) or whatever n is, it shows that Squeak! Yip! None Squeak! Yip! None Squeak! Yip! None I don't know what's wrong. Squeal! and Yip! should suppose to be at the same line while there are at separate now and there order should be opposite. And why there is a None? Can anyone please help me out?
[ "In your example call, Dog('big').play(0), you are not passing the toy argument -- that's what it's complaining about! Pass a toy argument before n and that will be better.\nThen you can start addressing the bugs in your play implementation: why are you making a new toy rather than use the argument, why are you printing 'None' when that's not part of the specs, how you're uselessly printing the return value of the Toy.play method (which returns None, implicitly) rather than working along with the fact that the latter method is printing something, and never incrementing count and so ending up in infinite loops.\n(four serious bugs in eight lines plus one in the call just has to be some sort of a record, I believe;-).\nBTW, homework is normally tagged with the tag homework, not exercise. (And, there's a further bug in your Q's title, as no classmethod is actually around, just a good old plain and perfectly normal instance method).\n", "The first thing I see wrong is the you are attempting to call the class 'Toy' instead of the variable representing the instance 'toy' passed to you 'play' method. I don't believe you can instantiate a class and call one of its methods at the same time which is what 'Toy().play()' is trying to do. The other is that I'm not quite sure I understand what you are trying to do with the design of your classes. Here is how I would implement the classes and then use them to get your desired behavior.\nclass Toy(object):\n def play(self):\n return \"Squeak!\"\n\nclass Dog(object):\n speak = 'Yip! %s'\n\n def __init__(self, name, toy):\n self.name = name\n self.toy = toy\n\n def play(self,n):\n if n > 0:\n for each in range(n):\n print(self.speak % self.toy.play())\n else:\n print(None)\n\nand here is how I would use it\nPython 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)\n[GCC 4.0.1 (Apple Inc. build 5493)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from toy import Toy, Dog\n>>> spike = Dog(\"Spike\",Toy())\n>>> spike.play(3)\nYip! Squeak!\nYip! Squeak!\nYip! Squeak!\n>>> \n\n" ]
[ 1, 0 ]
[]
[]
[ "printing", "python" ]
stackoverflow_0002080101_printing_python.txt
Q: How to test type of an object in Python? import string print string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz print type(string.ascii_lowercase) # <type 'str'> print string.ascii_lowercase is str # False Shouldn't it be True? A: The is operator compares the identity of two objects. This is what I believe it does behind the scenes: id(string.ascii_lowercase) == id(str) Actual strings are always going to have a different identity than the type str, so this will always be False. Here is the most Pythonic way to test whether something is a string: isinstance(string.ascii_lowercase, basestring) This will match both str and unicode strings. A: use: >>> isinstance('dfab', str) True is intended for identity testing. A: string.ascii_lowercase is str should not be True. type(string.ascii_lowercase) is str is True. The is keyword checks object identity, not type. You may have seen code like foo is None often and thought that None is a type. None is actually a singleton object. A: Don't you want type(string.ascii_lowercase) is str ?
How to test type of an object in Python?
import string print string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz print type(string.ascii_lowercase) # <type 'str'> print string.ascii_lowercase is str # False Shouldn't it be True?
[ "The is operator compares the identity of two objects. This is what I believe it does behind the scenes:\nid(string.ascii_lowercase) == id(str)\n\nActual strings are always going to have a different identity than the type str, so this will always be False.\nHere is the most Pythonic way to test whether something is a string:\nisinstance(string.ascii_lowercase, basestring)\n\nThis will match both str and unicode strings.\n", "use: \n>>> isinstance('dfab', str)\nTrue\n\nis intended for identity testing.\n", "string.ascii_lowercase is str should not be True.\ntype(string.ascii_lowercase) is str is True.\nThe is keyword checks object identity, not type.\nYou may have seen code like foo is None often and thought that None is a type. None is actually a singleton object.\n", "Don't you want type(string.ascii_lowercase) is str ?\n" ]
[ 4, 3, 2, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0002081377_python_types.txt
Q: Can you/should you modify objects in the database in the model of other classes I want to perform some delete() and some save() methods on some objects that are not an instance of the current class I'm in. I'm trying to do this in an overloaded save() method of a class. Here is the scenerio: class Item(models.Model): name = models.CharField(max_length=500) category = models.ForeignKey(Category, null=True, related_name='add_item') tag = models.ManyToManyField(Category, null=True, related_name='tag_item') def save(self, *args, **kwargs): super(Item, self).save(*args, **kwargs) for a_tag in self.tag.all(): #do stuff here a_tag.delete() cat = self.category while cat is not None: cat.add_item.add(self) #do stuff here cat.save() cat = cat.parent This doesn't work and when I try to do this I get the following exception: Exception AttributeError: "'Cursor' object has no attribute 'connection'" in <bound method Cursor.__del__ of <MySQLdb.cursors.Cursor object at 0x905c3ac>> ignored A: I notice you are trying to update a ManyToMany in your save(). You might take a look at my answer to this thread and see if it applies to your situation. If you are using the admin interface and are encountering this error, then it is almost certainly part of the problem you are having. You also might want to look at the MonkeyPatch mentioned. A: I ended up resolving this issue. You can in fact accomplish what I was trying to do. The issue was that I was using the managers completely wrong. a_tag above was actually a reference to a Category object, so calling delete() on that was actually deleting my Categories, which is why I was getting the weird Exception I'm assuming. Here's a code snippet of the newly working model code: def save(self, *args, **kwargs): super(Item, self).save(*args, **kwargs) for a_tag in self.tag.all(): a_tag.tag_item.clear() cat = self.category while cat is not None: cat.tag_item.add(self) cat = cat.parent
Can you/should you modify objects in the database in the model of other classes
I want to perform some delete() and some save() methods on some objects that are not an instance of the current class I'm in. I'm trying to do this in an overloaded save() method of a class. Here is the scenerio: class Item(models.Model): name = models.CharField(max_length=500) category = models.ForeignKey(Category, null=True, related_name='add_item') tag = models.ManyToManyField(Category, null=True, related_name='tag_item') def save(self, *args, **kwargs): super(Item, self).save(*args, **kwargs) for a_tag in self.tag.all(): #do stuff here a_tag.delete() cat = self.category while cat is not None: cat.add_item.add(self) #do stuff here cat.save() cat = cat.parent This doesn't work and when I try to do this I get the following exception: Exception AttributeError: "'Cursor' object has no attribute 'connection'" in <bound method Cursor.__del__ of <MySQLdb.cursors.Cursor object at 0x905c3ac>> ignored
[ "I notice you are trying to update a ManyToMany in your save(). You might take a look at my answer to this thread and see if it applies to your situation. If you are using the admin interface and are encountering this error, then it is almost certainly part of the problem you are having. You also might want to look at the MonkeyPatch mentioned.\n", "I ended up resolving this issue. You can in fact accomplish what I was trying to do. The issue was that I was using the managers completely wrong. a_tag above was actually a reference to a Category object, so calling delete() on that was actually deleting my Categories, which is why I was getting the weird Exception I'm assuming. Here's a code snippet of the newly working model code:\ndef save(self, *args, **kwargs):\n super(Item, self).save(*args, **kwargs)\n for a_tag in self.tag.all():\n a_tag.tag_item.clear()\n cat = self.category\n while cat is not None:\n cat.tag_item.add(self)\n cat = cat.parent\n\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_models", "model_view_controller", "python" ]
stackoverflow_0002075411_django_django_models_model_view_controller_python.txt
Q: Prompt on file/directory delete When coding in Python, I often need to write a function like this one: def delete_dir(dir_name): if os.path.exists(dir_name): reply = raw_input("Delete directory "+dir_name+"? [y/[n]] ") if reply=='y': os.system('rm -r '+dir_name) else: print "Aborting..." sys.exit() Which is basically just a remove command with a user prompt to double-check (I also have one for deleting files). Given the large amounts of Python modules out there, including in the standard library, I'm wondering if something like this already exists out there? A: It wouldn't be a Python thing, but if you keep using os.system() to make the delete call, you can pass the -i parameter to rm. The man page explains it: -i       prompt before every removal EDIT: I just read your code again and it looks like you're only prompting once before the entire delete process, not for each file. You might be interested in the -I flag instead: -I       prompt once before removing more than three files, or when removing recursively. Less intrusive than -i, while still giving protection against most mistakes A: to remove directory, use os module os.rmdir(), os.removedirs(). Or shutil.rmtree() .check the docs for more information A: well ,you could save this function in a module and reuse it in other modules,that way ,your problem will be solved !
Prompt on file/directory delete
When coding in Python, I often need to write a function like this one: def delete_dir(dir_name): if os.path.exists(dir_name): reply = raw_input("Delete directory "+dir_name+"? [y/[n]] ") if reply=='y': os.system('rm -r '+dir_name) else: print "Aborting..." sys.exit() Which is basically just a remove command with a user prompt to double-check (I also have one for deleting files). Given the large amounts of Python modules out there, including in the standard library, I'm wondering if something like this already exists out there?
[ "It wouldn't be a Python thing, but if you keep using os.system() to make the delete call, you can pass the -i parameter to rm. The man page explains it:\n\n-i       prompt before every removal\n\nEDIT: I just read your code again and it looks like you're only prompting once before the entire delete process, not for each file. You might be interested in the -I flag instead:\n\n-I       prompt once before removing more than three files, or when\n removing recursively. Less intrusive\n than -i, while still giving protection\n against most mistakes\n\n", "to remove directory, use os module os.rmdir(), os.removedirs(). Or shutil.rmtree() .check the docs for more information\n", "well ,you could save this function in a module and reuse it in other modules,that way ,your problem will be solved !\n" ]
[ 2, 1, 0 ]
[]
[]
[ "delete_directory", "file_io", "prompt", "python" ]
stackoverflow_0002081407_delete_directory_file_io_prompt_python.txt
Q: Technique for multi-language support of big static portions text in Django For small portions of text we use django standart {% trans %} tag What to do with big texts such as FAQ, terms and other static pages A: There is a {% blocktrans %} templatetag you can use. You could also write a simple templatetag yourself which includes anathor template based on the current language. {% i18ninclude "faq/question1.html" "en" %} Would include faq/question1.en.html. Here is the code: import os from django import template register = template.Library() @register.simpletag def i18ninclude(template_name, language): template_name, extension = os.path.splitext(template_name) template_name = '%s.%s%s' % (template_name, language, extension) return template.loader.render_to_string(template_name) Put this in a templatetag library of your app. I also recommend to read the documentation about custom templatetags if you haven't done it yet. A: Take a look at django-better-chunks. It allows to insert snippets of static HTML inside your templates and it has i18n support. For static pages I recommend to use some kind of CMS, for example django-cms. It's also i18n-enabled.
Technique for multi-language support of big static portions text in Django
For small portions of text we use django standart {% trans %} tag What to do with big texts such as FAQ, terms and other static pages
[ "There is a {% blocktrans %} templatetag you can use.\nYou could also write a simple templatetag yourself which includes anathor template based on the current language.\n{% i18ninclude \"faq/question1.html\" \"en\" %}\n\nWould include faq/question1.en.html. Here is the code:\nimport os\nfrom django import template\nregister = template.Library()\n\n@register.simpletag\ndef i18ninclude(template_name, language):\n template_name, extension = os.path.splitext(template_name)\n template_name = '%s.%s%s' % (template_name, language, extension)\n return template.loader.render_to_string(template_name)\n\nPut this in a templatetag library of your app. I also recommend to read the documentation about custom templatetags if you haven't done it yet.\n", "Take a look at django-better-chunks. It allows to insert snippets of static HTML inside your templates and it has i18n support.\nFor static pages I recommend to use some kind of CMS, for example django-cms. It's also i18n-enabled.\n" ]
[ 6, 2 ]
[]
[]
[ "django", "multilingual", "python" ]
stackoverflow_0002081436_django_multilingual_python.txt
Q: Python list : How to sort by timestamp? ( App Engine related ) I have ten entities in my Feed model ( this is an App Engine model) class Feed(db.Model): sometext = db.StringProperty() timestamp = db.DateTimeProperty(auto_now=True) list_of_keys = ["key1","key2","key3".... "key10"] so i call my entities using db.key() method: feeds = db.keys(list_of_keys) # this loop below prints the feed for feed in feeds: print humanizeTimeDiff(feed.timestamp) # humanizeTimeDiff is a function to change the raw timestamp into a human friendly # version: eg-> 10 mins ago, 20 seconds ago but now, how do I sort the feeds according to timestamp? ( I want the newest feeds at the top and the oldest ones at the bottom) any sort function I can use on the raw timestamp? ( my rough plan is to sort according to the raw timestamp, then humanize the time difference ) PS: I don't plan to use GQL query to query my entities according to timestamp, because I get my input in the form of a list of keys. And using db.key() is a faster method. hope I supplied enough info. wish to hear your thoughts/solutions. A: import operator ... for feed in sorted(feeds, key=operator.attrgetter('timestamp'), reverse=True): print humanizeTimeDiff(feed.timestamp)
Python list : How to sort by timestamp? ( App Engine related )
I have ten entities in my Feed model ( this is an App Engine model) class Feed(db.Model): sometext = db.StringProperty() timestamp = db.DateTimeProperty(auto_now=True) list_of_keys = ["key1","key2","key3".... "key10"] so i call my entities using db.key() method: feeds = db.keys(list_of_keys) # this loop below prints the feed for feed in feeds: print humanizeTimeDiff(feed.timestamp) # humanizeTimeDiff is a function to change the raw timestamp into a human friendly # version: eg-> 10 mins ago, 20 seconds ago but now, how do I sort the feeds according to timestamp? ( I want the newest feeds at the top and the oldest ones at the bottom) any sort function I can use on the raw timestamp? ( my rough plan is to sort according to the raw timestamp, then humanize the time difference ) PS: I don't plan to use GQL query to query my entities according to timestamp, because I get my input in the form of a list of keys. And using db.key() is a faster method. hope I supplied enough info. wish to hear your thoughts/solutions.
[ "import operator\n\n ...\n\nfor feed in sorted(feeds, key=operator.attrgetter('timestamp'), reverse=True):\n print humanizeTimeDiff(feed.timestamp) \n\n" ]
[ 10 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002081754_google_app_engine_python.txt
Q: Python raw strings and unicode : how to use Web input as regexp patterns? EDIT : This question doesn't really make sense once you have picked up what the "r" flag means. More details here. For people looking for a quick anwser, I added on below. If I enter a regexp manually in a Python script, I can use 4 combinations of flags for my pattern strings : p1 = "pattern" p2 = u"pattern" p3 = r"pattern" p4 = ru"pattern" I have a bunch a unicode strings coming from a Web form input and want to use them as regexp patterns. I want to know what process I should apply to the strings so I can expect similar result from the usage of the manual form above. Something like : import re assert re.match(p1, some_text) == re.match(someProcess1(web_input), some_text) assert re.match(p2, some_text) == re.match(someProcess2(web_input), some_text) assert re.match(p3, some_text) == re.match(someProcess3(web_input), some_text) assert re.match(p4, some_text) == re.match(someProcess4(web_input), some_text) What would be someProcess1 to someProcessN and why ? I suppose that someProcess2 doesn't need to do anything while someProcess1 should do some unicode conversion to the local encoding. For the raw string literals, I am clueless. A: Apart from possibly having to encode Unicode properly (in Python 2.*), no processing is needed because there is no specific type for "raw strings" -- it's just a syntax for literals, i.e. for string constants, and you don't have any string constants in your code snippet, so there's nothing to "process". A: "r" flags just prevent Python from interpreting "\" in a string. Since the Web doesn't care about what kind of data it carries, your web input will be a bunch of bytes you are free to interpret the way you want. So to address this problem : be sure you use Unicode (e.g. utf-8) all long the way when you get the string, it will be Unicode and "\n", "\t" and "\a" will be literals, so you don't need to care about if you need to escape them of not. A: Note the following in your first example: >>> p1 = "pattern" >>> p2 = u"pattern" >>> p3 = r"pattern" >>> p4 = ur"pattern" # it's ur"", not ru"" btw >>> p1 == p2 == p3 == p4 True While these constructs look different, they all do the same thing, they create a string object (p1 and p3 a str and p2 and p4 a unicode object in Python 2.x), containing the value "pattern". The u, r and ur just tell the parser, how to interpret the following quoted string, namely as a unicode text (u) and/or a raw text (r) where backslashes to encode other characters are ignored. However in the end it doesn't matter how a string was created, being it a raw string or not, internally it is stored the same. When you get unicode text as input, you have to differ (in Python 2.x) if it is a unicode text or a str object. If you want to work with the unicode content, you should internally work only with those, and convert all str objects to unicode objects (either with str.decode() or with the u'text' syntax for hard-coded texts). If you however encode it to your local encoding, you will get problems with unicode symbols. A different approach would be using Python 3, which str object supports unicode directly and stores everything as unicode and where you simply don't need to care about the encoding.
Python raw strings and unicode : how to use Web input as regexp patterns?
EDIT : This question doesn't really make sense once you have picked up what the "r" flag means. More details here. For people looking for a quick anwser, I added on below. If I enter a regexp manually in a Python script, I can use 4 combinations of flags for my pattern strings : p1 = "pattern" p2 = u"pattern" p3 = r"pattern" p4 = ru"pattern" I have a bunch a unicode strings coming from a Web form input and want to use them as regexp patterns. I want to know what process I should apply to the strings so I can expect similar result from the usage of the manual form above. Something like : import re assert re.match(p1, some_text) == re.match(someProcess1(web_input), some_text) assert re.match(p2, some_text) == re.match(someProcess2(web_input), some_text) assert re.match(p3, some_text) == re.match(someProcess3(web_input), some_text) assert re.match(p4, some_text) == re.match(someProcess4(web_input), some_text) What would be someProcess1 to someProcessN and why ? I suppose that someProcess2 doesn't need to do anything while someProcess1 should do some unicode conversion to the local encoding. For the raw string literals, I am clueless.
[ "Apart from possibly having to encode Unicode properly (in Python 2.*), no processing is needed because there is no specific type for \"raw strings\" -- it's just a syntax for literals, i.e. for string constants, and you don't have any string constants in your code snippet, so there's nothing to \"process\".\n", "\"r\" flags just prevent Python from interpreting \"\\\" in a string. Since the Web doesn't care about what kind of data it carries, your web input will be a bunch of bytes you are free to interpret the way you want.\nSo to address this problem :\n\nbe sure you use Unicode (e.g. utf-8) all long the way\nwhen you get the string, it will be Unicode and \"\\n\", \"\\t\" and \"\\a\" will be literals, so you don't need to care about if you need to escape them of not.\n\n", "Note the following in your first example:\n>>> p1 = \"pattern\"\n>>> p2 = u\"pattern\"\n>>> p3 = r\"pattern\"\n>>> p4 = ur\"pattern\" # it's ur\"\", not ru\"\" btw\n>>> p1 == p2 == p3 == p4\nTrue\n\nWhile these constructs look different, they all do the same thing, they create a string object (p1 and p3 a str and p2 and p4 a unicode object in Python 2.x), containing the value \"pattern\". The u, r and ur just tell the parser, how to interpret the following quoted string, namely as a unicode text (u) and/or a raw text (r) where backslashes to encode other characters are ignored. However in the end it doesn't matter how a string was created, being it a raw string or not, internally it is stored the same.\nWhen you get unicode text as input, you have to differ (in Python 2.x) if it is a unicode text or a str object. If you want to work with the unicode content, you should internally work only with those, and convert all str objects to unicode objects (either with str.decode() or with the u'text' syntax for hard-coded texts). If you however encode it to your local encoding, you will get problems with unicode symbols.\nA different approach would be using Python 3, which str object supports unicode directly and stores everything as unicode and where you simply don't need to care about the encoding.\n" ]
[ 7, 2, 2 ]
[]
[]
[ "python", "rawstring", "regex", "unicode" ]
stackoverflow_0002081622_python_rawstring_regex_unicode.txt
Q: Authentication in django I'm trying to do connect form on my django website If in a shell I do : $ ./manage.py shell Python 2.6.4 (r264:75706, Oct 27 2009, 06:25:13) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib import auth >>> user = auth.authenticate(username='user', password='password') >>> no problem as you can see but if on my views, I have : # views.py ... from django.contrib import auth ... def check_pass(request): ... user = auth.authenticate(username='user', password='password') ... I've got an 500 error page with the stacktrace : Environment: Request Method: POST Request URL: http://localhost/check_pass/ Django Version: 1.1.1 Python Version: 2.6.4 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/home/mart/programmation/python/django/martfiles/views.py" in check_pass 67. user = auth.authenticate(username='user', password='password') File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py" in authenticate 37. user = backend.authenticate(**credentials) File "/usr/lib/python2.6/site-packages/django/contrib/auth/backends.py" in authenticate 18. user = User.objects.get(username=username) File "/usr/lib/python2.6/site-packages/django/db/models/manager.py" in get 120. return self.get_query_set().get(*args, **kwargs) File "/usr/lib/python2.6/site-packages/django/db/models/query.py" in get 300. num = len(clone) File "/usr/lib/python2.6/site-packages/django/db/models/query.py" in __len__ 81. self._result_cache = list(self.iterator()) File "/usr/lib/python2.6/site-packages/django/db/models/query.py" in iterator 238. for row in self.query.results_iter(): File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py" in results_iter 287. for rows in self.execute_sql(MULTI): File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py" in execute_sql 2369. cursor.execute(sql, params) File "/usr/lib/python2.6/site-packages/django/db/backends/util.py" in execute 19. return self.cursor.execute(sql, params) File "/usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py" in execute 193. return Database.Cursor.execute(self, query, params) Exception Type: OperationalError at /check_pass/ Exception Value: no such table: auth_user my settings.py MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ... INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', ) I've run 'syncdb' without any changes and I'm sure it's this line the problem as I isolated it with assert False user = auth... AssertionError user = auth... assert False no such table auth_user A: This works for me: In the top of your script: from django.contrib.auth import authenticate, login, logout Authentification: user = authenticate(username=request.POST['username'], password=request.POST['password']) if user is not None: if user.is_active: login(request, user) #user is loged in else: # user is not active else: # false authentification I hope it will work for you to:) A: ok I've found. Same as for the static files, I needed to put my database outside my home folder and not next to my python files...
Authentication in django
I'm trying to do connect form on my django website If in a shell I do : $ ./manage.py shell Python 2.6.4 (r264:75706, Oct 27 2009, 06:25:13) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib import auth >>> user = auth.authenticate(username='user', password='password') >>> no problem as you can see but if on my views, I have : # views.py ... from django.contrib import auth ... def check_pass(request): ... user = auth.authenticate(username='user', password='password') ... I've got an 500 error page with the stacktrace : Environment: Request Method: POST Request URL: http://localhost/check_pass/ Django Version: 1.1.1 Python Version: 2.6.4 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/home/mart/programmation/python/django/martfiles/views.py" in check_pass 67. user = auth.authenticate(username='user', password='password') File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py" in authenticate 37. user = backend.authenticate(**credentials) File "/usr/lib/python2.6/site-packages/django/contrib/auth/backends.py" in authenticate 18. user = User.objects.get(username=username) File "/usr/lib/python2.6/site-packages/django/db/models/manager.py" in get 120. return self.get_query_set().get(*args, **kwargs) File "/usr/lib/python2.6/site-packages/django/db/models/query.py" in get 300. num = len(clone) File "/usr/lib/python2.6/site-packages/django/db/models/query.py" in __len__ 81. self._result_cache = list(self.iterator()) File "/usr/lib/python2.6/site-packages/django/db/models/query.py" in iterator 238. for row in self.query.results_iter(): File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py" in results_iter 287. for rows in self.execute_sql(MULTI): File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py" in execute_sql 2369. cursor.execute(sql, params) File "/usr/lib/python2.6/site-packages/django/db/backends/util.py" in execute 19. return self.cursor.execute(sql, params) File "/usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py" in execute 193. return Database.Cursor.execute(self, query, params) Exception Type: OperationalError at /check_pass/ Exception Value: no such table: auth_user my settings.py MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ... INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', ) I've run 'syncdb' without any changes and I'm sure it's this line the problem as I isolated it with assert False user = auth... AssertionError user = auth... assert False no such table auth_user
[ "This works for me:\nIn the top of your script:\nfrom django.contrib.auth import authenticate, login, logout\n\nAuthentification:\n user = authenticate(username=request.POST['username'], password=request.POST['password'])\n if user is not None:\n if user.is_active:\n login(request, user)\n #user is loged in\n else:\n # user is not active\n else:\n # false authentification\n\nI hope it will work for you to:)\n", "ok I've found. Same as for the static files, I needed to put my database outside my home folder and not next to my python files...\n" ]
[ 1, 0 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0002080854_authentication_django_python.txt
Q: Passing multiple values to a function call (Python) import re def strip_tags(value): "Return the given HTML with all tags stripped." return re.sub(r'<[^>]*?>', '', value) I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple (not fixed) values at once? Thanks A: Python offers a way to use arbitrary-length argument lists: def myfunc(*args): for argument in args: print "myfunc was given", argument If you put *args in your function definition, all values passed to the function are available as a tuple called args. Note that you can also put additional arguments before *args, like def my_other_func(name, *args): so the first argument will be available as name, the rest will be in the tuple args. It is convention, but not neccessary, to call this parameter args. As long as there's an asterisk in front of it, you can call it whatever you like. A: Could you use a loop. for value in values: strip_tags(value) A: You could pass in value as an array of strings, and then return the array of cleaned values. A: import re def strip_tags(values): return map(lambda i: re.sub(r'<[^>]*?>', '', i), values) A: If the values are independent of each other, then don't modify strip_tags, just change how you call it: values = [some_value, another_value] values = [strip_tags(v) for v in values] # values[0] is now the strip_tags version of the old values[0] # similar to values[0] = strip_tags(values[0]), except for every item If the values are related, such as being adjacent pieces of the same file, then concatenate them before using strip_tags: values = [some_value, another_value] result = strip_tags("".join(values)) # note result is single string A: here is a function written over the function you have provided. this would take in a list of values and return the corresponding processed list: import re def strip_tags_list(values): return map(strip_tags, values) note: this would work on python 2.6 and earleir versions. on python 3.0, you would have to explicitly convert the result of map() to list using list().
Passing multiple values to a function call (Python)
import re def strip_tags(value): "Return the given HTML with all tags stripped." return re.sub(r'<[^>]*?>', '', value) I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple (not fixed) values at once? Thanks
[ "Python offers a way to use arbitrary-length argument lists:\ndef myfunc(*args):\n for argument in args:\n print \"myfunc was given\", argument\n\nIf you put *args in your function definition, all values passed to the function are available as a tuple called args. Note that you can also put additional arguments before *args,\nlike\ndef my_other_func(name, *args):\n\nso the first argument will be available as name, the rest will be in the tuple args.\nIt is convention, but not neccessary, to call this parameter args. As long as there's an asterisk in front of it, you can call it whatever you like.\n", "Could you use a loop.\nfor value in values:\n strip_tags(value)\n\n", "You could pass in value as an array of strings, and then return the array of cleaned values.\n", "import re\ndef strip_tags(values):\n return map(lambda i: re.sub(r'<[^>]*?>', '', i), values)\n\n", "If the values are independent of each other, then don't modify strip_tags, just change how you call it:\nvalues = [some_value, another_value]\nvalues = [strip_tags(v) for v in values]\n# values[0] is now the strip_tags version of the old values[0]\n# similar to values[0] = strip_tags(values[0]), except for every item\n\nIf the values are related, such as being adjacent pieces of the same file, then concatenate them before using strip_tags:\nvalues = [some_value, another_value]\nresult = strip_tags(\"\".join(values))\n# note result is single string\n\n", "here is a function written over the function you have provided. this would take in a list of values and return the corresponding processed list:\nimport re\ndef strip_tags_list(values):\n return map(strip_tags, values)\n\nnote: this would work on python 2.6 and earleir versions. on python 3.0, you would have to explicitly convert the result of map() to list using list().\n" ]
[ 8, 2, 1, 1, 1, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0002081929_function_python.txt
Q: Simplest way to integrate python gui app with c console app I have a c console app which converts a c file to a html file, the c file location is passed to the program as a command line argument.(the app is for the windows platform) What I would like to do is have a python gui app to allow the user to select a file and pass the location of the file to the c app for processing. I already know how to create a basic python gui with tkinter, but I can't figure out or find any usefull info on how I would go about intgrating the two programs. Maybe its possible to pipe the string to the c app with the pOpen() method? (but I can't figure out how...) Note: Im new to python so code examples might be helpful rather then just description, (as Im not familiar with all of the python libraries etc,) although any help at all would be appreciated. A: You probably want the subprocess module. At the very minimum: import subprocess retcode = subprocess.call(["/path/to/myCprogram", "/path/to/file.c"]) if retcode == 0: print "success!" This will run the program with the arguments, and then return its return code. Note that subprocess.call will block until the program has completed, so if it's not one which runs quickly, your entire Tkinter GUI will stop redrawing until it's completed. For more advanced use, you may want to use subprocess.Popen. This will require you polling until the command has completed, but allows you to do it with less blocking. If your C program prints the HTML to standard out, you will need to pipe the output like so: proc = subprocess.Popen(["/path/to/myCprogram", "/path/to/file.c"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err_output = proc.communicate() # output will now contain the stdout of the program in a string A: There are a number of ways you could acheive this, but in your case the requirements seems so straightforward all you need is to use Popen from the subprocess module. process = subprocess.Popen(['myutil', file_location]...) process.wait() If you need to get the results back to the caller, use a PIPE for the stdout and read the resulting data from it when the subprocess has finished.
Simplest way to integrate python gui app with c console app
I have a c console app which converts a c file to a html file, the c file location is passed to the program as a command line argument.(the app is for the windows platform) What I would like to do is have a python gui app to allow the user to select a file and pass the location of the file to the c app for processing. I already know how to create a basic python gui with tkinter, but I can't figure out or find any usefull info on how I would go about intgrating the two programs. Maybe its possible to pipe the string to the c app with the pOpen() method? (but I can't figure out how...) Note: Im new to python so code examples might be helpful rather then just description, (as Im not familiar with all of the python libraries etc,) although any help at all would be appreciated.
[ "You probably want the subprocess module.\nAt the very minimum:\nimport subprocess\nretcode = subprocess.call([\"/path/to/myCprogram\", \"/path/to/file.c\"])\nif retcode == 0:\n print \"success!\"\n\nThis will run the program with the arguments, and then return its return code.\nNote that subprocess.call will block until the program has completed, so if it's not one which runs quickly, your entire Tkinter GUI will stop redrawing until it's completed.\nFor more advanced use, you may want to use subprocess.Popen. This will require you polling until the command has completed, but allows you to do it with less blocking.\nIf your C program prints the HTML to standard out, you will need to pipe the output like so:\nproc = subprocess.Popen([\"/path/to/myCprogram\", \"/path/to/file.c\"], \n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\noutput, err_output = proc.communicate()\n# output will now contain the stdout of the program in a string\n\n", "There are a number of ways you could acheive this, but in your case the requirements seems so straightforward all you need is to use Popen from the subprocess module.\n process = subprocess.Popen(['myutil', file_location]...)\n process.wait()\n\nIf you need to get the results back to the caller, use a PIPE for the stdout and read the resulting data from it when the subprocess has finished.\n" ]
[ 10, 2 ]
[]
[]
[ "c", "integrate", "python", "user_interface" ]
stackoverflow_0002082028_c_integrate_python_user_interface.txt
Q: How to create a custom django filter tag I am having trouble in getting my site to recognise custom template tags. I have the following dir structure: project_name project_name templatetags _ __init __ _.py getattribute.py views _ __init __ _.py index.html views settings.py main.py manage.py urls.py nbproject Then I have added this to the INSTALLED_APPS: INSTALLED_APPS = ( # 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.sites', 'project_name' ) I then reference this inside the template like this: {% load getattribute %} {% for header in headers %} <td>{{ obj|getattribute:header }}</td> {% endfor %} The error which I get is as follows: Could not import controllers.EventController. Error was: No module named project_name Any help would be appreciated for this: TIA Andrew UPDATE: The site works but I cannot get the template tags to work. If I remove the project_name from the installed_apps I get the following error: Exception Value: 'getattribute' is not a valid tag library: Could not load template library from django.templatetags.getattribute, No module named getattribute A: The error is becaus you have wrong your folder's structure, i think you must read the docs, this tutorial (part1) explains the right structure: You have a project that isn't same thing that app: project_name app_name templatetags getattribute.py models.py views.py settings.py manage.py And in your INSTALLED_APPS: INSTALLED_APPS = ( # 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.sites', 'project_name.app_name', ) That is all A: Ae you sure this is specifically to do with the template tag? It sounds like the project_name directory is not on your python path. The output on the error page should show your current python path, so you can check if it is as expected. Read this to learn how to fix it: http://djangotricks.blogspot.com/2008/09/note-on-python-paths.html A: Your project structure is, not to put too fine a point on it, a mess. Some of the many things you need to do: don't use the same name for the containing directory (project) and the inner one (which should be an app name). manage.py and settings.py should be in the outer level, not inside an application. I don't know what the second views is - is it actually views.py? In which case it will never be used. The empty files inside templatetags and views should be __init__.py, ie two underscores either side. Probably the actual cause of your problem: you need a models.py inside an application, even if it's empty, for Django to load it at all - templatetags won't work without it.
How to create a custom django filter tag
I am having trouble in getting my site to recognise custom template tags. I have the following dir structure: project_name project_name templatetags _ __init __ _.py getattribute.py views _ __init __ _.py index.html views settings.py main.py manage.py urls.py nbproject Then I have added this to the INSTALLED_APPS: INSTALLED_APPS = ( # 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.sites', 'project_name' ) I then reference this inside the template like this: {% load getattribute %} {% for header in headers %} <td>{{ obj|getattribute:header }}</td> {% endfor %} The error which I get is as follows: Could not import controllers.EventController. Error was: No module named project_name Any help would be appreciated for this: TIA Andrew UPDATE: The site works but I cannot get the template tags to work. If I remove the project_name from the installed_apps I get the following error: Exception Value: 'getattribute' is not a valid tag library: Could not load template library from django.templatetags.getattribute, No module named getattribute
[ "The error is becaus you have wrong your folder's structure, i think you must read the docs, this tutorial (part1) explains the right structure:\nYou have a project that isn't same thing that app:\n\nproject_name\n\n\napp_name\n\n\ntemplatetags\n\n\ngetattribute.py\n\nmodels.py\nviews.py \n\n\nsettings.py\nmanage.py\n\nAnd in your INSTALLED_APPS:\nINSTALLED_APPS = (\n# 'django.contrib.auth',\n 'django.contrib.contenttypes',\n# 'django.contrib.sessions',\n 'django.contrib.sites',\n 'project_name.app_name',\n)\n\nThat is all\n", "Ae you sure this is specifically to do with the template tag?\nIt sounds like the project_name directory is not on your python path. The output on the error page should show your current python path, so you can check if it is as expected.\nRead this to learn how to fix it:\nhttp://djangotricks.blogspot.com/2008/09/note-on-python-paths.html\n", "Your project structure is, not to put too fine a point on it, a mess. Some of the many things you need to do:\n\ndon't use the same name for the containing directory (project) and the inner one (which should be an app name).\nmanage.py and settings.py should be in the outer level, not inside an application.\nI don't know what the second views is - is it actually views.py? In which case it will never be used.\nThe empty files inside templatetags and views should be __init__.py, ie two underscores either side.\nProbably the actual cause of your problem: you need a models.py inside an application, even if it's empty, for Django to load it at all - templatetags won't work without it.\n\n" ]
[ 2, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002081834_django_python.txt
Q: Strange bug while combining images in Python I have a hundred 10x10 px images, and I want to combine them into a big 100x100 image. I'm using the Image library to first create a blank image and then paste in the smaller images: blank = Image.new('P',(100,100)) blank.paste(im,box) The smaller images are in color, but the resulting image turns out in all grayscale. Is there a fix or workaround for this? A: It's probably something to do with using a palette type image (mode P). Is there a specific reason you are doing this? If not, try passing 'RGB' as the first argument.
Strange bug while combining images in Python
I have a hundred 10x10 px images, and I want to combine them into a big 100x100 image. I'm using the Image library to first create a blank image and then paste in the smaller images: blank = Image.new('P',(100,100)) blank.paste(im,box) The smaller images are in color, but the resulting image turns out in all grayscale. Is there a fix or workaround for this?
[ "It's probably something to do with using a palette type image (mode P). Is there a specific reason you are doing this? If not, try passing 'RGB' as the first argument.\n" ]
[ 2 ]
[]
[]
[ "image", "image_processing", "python", "python_imaging_library" ]
stackoverflow_0002082145_image_image_processing_python_python_imaging_library.txt
Q: How to export C# methods? How can we export C# methods? I have a dll and I want to use its methods in the Python language with the ctypes module. Because I need to use the ctypes module, I need to export the C# methods for them to be visible in Python. So, how can I export the C# methods (like they do in C++)? A: Contrary to popular belief, this is possible. See here. A: With the normal Python implementation ("CPython"), you can't, at least not directly. You could write native C wrappers around our C# methods using C++/CLI, and call these wrappers from Python. Or, you could try IronPython. This lets you run Python code and call code in any .Net language, including C#. A: (This may no longer be relevant since SLaks has found that ingenious link, but I'll leave an edited version for reference...) The "normal" way of exposing .NET/C# objects to unmanaged code (like Python) is to create a COM-callable wrapper for the C# DLL (.NET assembly), and call that using Python's COM/OLE support. To create the COM-callable wrapper, use the tlbexp and/or regasm command-line utilities. Obviously, however, this does not provide the C/DLL-style API that SLaks' link does. A: That's not possible. If you need DLL exports you'll need to use the C++/CLI language. For example: public ref class Class1 { public: static int add(int a, int b) { return a + b; } }; extern "C" __declspec(dllexport) int add(int a, int b) { return Class1::add(a, b); } The class can be written in C# as well. The C++/CLI compiler emits a special thunk for the export that ensures that the CLR is loaded and execution switches to managed mode. This is not exactly fast. Writing [ComVisible(true)] code in C# is another possibility.
How to export C# methods?
How can we export C# methods? I have a dll and I want to use its methods in the Python language with the ctypes module. Because I need to use the ctypes module, I need to export the C# methods for them to be visible in Python. So, how can I export the C# methods (like they do in C++)?
[ "Contrary to popular belief, this is possible.\nSee here.\n", "With the normal Python implementation (\"CPython\"), you can't, at least not directly.\nYou could write native C wrappers around our C# methods using C++/CLI, and call these wrappers from Python.\nOr, you could try IronPython. This lets you run Python code and call code in any .Net language, including C#.\n", "(This may no longer be relevant since SLaks has found that ingenious link, but I'll leave an edited version for reference...)\nThe \"normal\" way of exposing .NET/C# objects to unmanaged code (like Python) is to create a COM-callable wrapper for the C# DLL (.NET assembly), and call that using Python's COM/OLE support. To create the COM-callable wrapper, use the tlbexp and/or regasm command-line utilities.\nObviously, however, this does not provide the C/DLL-style API that SLaks' link does.\n", "That's not possible. If you need DLL exports you'll need to use the C++/CLI language. For example:\npublic ref class Class1 {\npublic:\n static int add(int a, int b) {\n return a + b;\n }\n};\n\nextern \"C\" __declspec(dllexport) \nint add(int a, int b) {\n return Class1::add(a, b);\n}\n\nThe class can be written in C# as well. The C++/CLI compiler emits a special thunk for the export that ensures that the CLR is loaded and execution switches to managed mode. This is not exactly fast.\nWriting [ComVisible(true)] code in C# is another possibility.\n" ]
[ 22, 1, 1, 1 ]
[]
[]
[ "c#", "export", "methods", "python", "python.net" ]
stackoverflow_0002082159_c#_export_methods_python_python.net.txt
Q: Python function returning None after recursion I can't figure out why this python function returns None if it calls itself recursively. It was part of my solution to a Project Euler problem. I have solved the problem in a better way anyhow, but this is still annoying me as the function seems to work OK - and it seems to know the value of the variable I wanted to return. def next_prime(previous): if previous % 2 == 0: candidate = previous + 1 else: candidate = previous + 2 print "trying", candidate prime = True for div in range(2,candidate//2,1): if candidate % div == 0: prime = False print candidate, "is not prime - divisible by", div next_prime(candidate) break if prime is True: print candidate, "is prime" #return candidate last = 896576 print "After", last, ", the next prime is..." next_prime(last) This gives: After 896576 , the next prime is... trying 896577 896577 is not prime - divisible by 3 trying 896579 896579 is not prime - divisible by 701 trying 896581 896581 is not prime - divisible by 7 trying 896583 896583 is not prime - divisible by 3 trying 896585 896585 is not prime - divisible by 5 trying 896587 896587 is prime But if I uncomment the return statement it only returns a value if the first try is prime, otherwise it returns None. A: You forgot to return a value when there is failure to find a prime: for div in range(2,candidate//2,1): if candidate % div == 0: prime = False print candidate, "is not prime - divisible by", div return next_prime(candidate) Recursion isn't really suitable here though. It isn't much more elegant than the simple iterative approach. Also, you could overflow the stack if you hit an area where there are lot of non-primes between two consecutive primes. A: As others have said, this is not really the place for recursion. Here is an example using iteration. I've also defined another function which tests the primality of an integer - I think this makes the code simpler. def is_prime(n): """Return True if n is prime.""" for i in xrange(2, n//2): if n%i == 0: return False return True def next_prime(n): """Returns the next prime number after n.""" if n % 2 == 0: candidate = n + 1 else: candidate = n + 2 while not is_prime(candidate): candidate += 2 return candidate if __name__ == '__main__': n = 896576 print next_prime(n) A: Notice that you are making recursive calls to the next_prime function, but not returning the value from it from the calling function. Replace the lines: print candidate, "is not prime - divisible by", div next_prime(candidate) with print candidate, "is not prime - divisible by", div return next_prime(candidate)
Python function returning None after recursion
I can't figure out why this python function returns None if it calls itself recursively. It was part of my solution to a Project Euler problem. I have solved the problem in a better way anyhow, but this is still annoying me as the function seems to work OK - and it seems to know the value of the variable I wanted to return. def next_prime(previous): if previous % 2 == 0: candidate = previous + 1 else: candidate = previous + 2 print "trying", candidate prime = True for div in range(2,candidate//2,1): if candidate % div == 0: prime = False print candidate, "is not prime - divisible by", div next_prime(candidate) break if prime is True: print candidate, "is prime" #return candidate last = 896576 print "After", last, ", the next prime is..." next_prime(last) This gives: After 896576 , the next prime is... trying 896577 896577 is not prime - divisible by 3 trying 896579 896579 is not prime - divisible by 701 trying 896581 896581 is not prime - divisible by 7 trying 896583 896583 is not prime - divisible by 3 trying 896585 896585 is not prime - divisible by 5 trying 896587 896587 is prime But if I uncomment the return statement it only returns a value if the first try is prime, otherwise it returns None.
[ "You forgot to return a value when there is failure to find a prime:\nfor div in range(2,candidate//2,1):\n if candidate % div == 0:\n prime = False\n print candidate, \"is not prime - divisible by\", div\n return next_prime(candidate)\n\nRecursion isn't really suitable here though. It isn't much more elegant than the simple iterative approach. Also, you could overflow the stack if you hit an area where there are lot of non-primes between two consecutive primes.\n", "As others have said, this is not really the place for recursion. Here is an example using iteration. I've also defined another function which tests the primality of an integer - I think this makes the code simpler.\ndef is_prime(n):\n \"\"\"Return True if n is prime.\"\"\"\n for i in xrange(2, n//2):\n if n%i == 0:\n return False\n return True\n\ndef next_prime(n):\n \"\"\"Returns the next prime number after n.\"\"\"\n if n % 2 == 0:\n candidate = n + 1\n else:\n candidate = n + 2\n while not is_prime(candidate):\n candidate += 2\n return candidate\n\nif __name__ == '__main__':\n n = 896576\n print next_prime(n)\n\n", "Notice that you are making recursive calls to the next_prime function, but not returning the value from it from the calling function.\nReplace the lines:\nprint candidate, \"is not prime - divisible by\", div\nnext_prime(candidate)\n\nwith\nprint candidate, \"is not prime - divisible by\", div\nreturn next_prime(candidate)\n\n" ]
[ 6, 1, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0002082635_python_recursion.txt
Q: How make a better markdown for developer blog I'm rebuilding my blog at http://www.elmalabarista.com/blog/. I have use in my previous version markdown and now I remember why I have almost zero code samples. Doing code samples in markdown is very fragile. I try to put some python there I can't make markdown mark it as code!. The main culprit? The syntax is markdown for code is out spaces. Despite the fact I use wmd as the editor (how that work here in SO is a mistery for me), it never be able to move rigth the text so never get as code. this is the problem: I put something simple: :::python def hello(): pass But the problem is that something I have: :::python def hello(): pass or :::python def hello(): pass (yes bot was formatted but you see? not work). Any mistake -using tabs, too much, too litle spaces) is punished heavily. And if the code is long, the chance of a problem increase too. So, exist any way to simply do: ### My article My list entry one My list entry two :::python def x (a, b): return a * b and get converted rigth and never bother about this small thing again??? By the way, I'm using pygments & python markdown. A: Consider using reStructuredText -- it's the standard lightweight markup for Python, and is often used for docstrings and embedded documentation. It's quite easy, but also powerful -- if I remember correctly, the core Python libraries and Django both use it. A: I've been using google-code-prettify, which works pretty well. Usage: Put code snippets in <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code> and it will automatically be pretty printed. A: You need to indent code more than 4 spaces (btw have you noticed on SO if you add 4 spaces it gets recognized as code), this is 4 space indented: :::python def hello(): pass
How make a better markdown for developer blog
I'm rebuilding my blog at http://www.elmalabarista.com/blog/. I have use in my previous version markdown and now I remember why I have almost zero code samples. Doing code samples in markdown is very fragile. I try to put some python there I can't make markdown mark it as code!. The main culprit? The syntax is markdown for code is out spaces. Despite the fact I use wmd as the editor (how that work here in SO is a mistery for me), it never be able to move rigth the text so never get as code. this is the problem: I put something simple: :::python def hello(): pass But the problem is that something I have: :::python def hello(): pass or :::python def hello(): pass (yes bot was formatted but you see? not work). Any mistake -using tabs, too much, too litle spaces) is punished heavily. And if the code is long, the chance of a problem increase too. So, exist any way to simply do: ### My article My list entry one My list entry two :::python def x (a, b): return a * b and get converted rigth and never bother about this small thing again??? By the way, I'm using pygments & python markdown.
[ "Consider using reStructuredText -- it's the standard lightweight markup for Python, and is often used for docstrings and embedded documentation. It's quite easy, but also powerful -- if I remember correctly, the core Python libraries and Django both use it.\n", "I've been using google-code-prettify, which works pretty well.\nUsage:\nPut code snippets in <pre class=\"prettyprint\">...</pre> or <code class=\"prettyprint\">...</code> and it will automatically be pretty printed.\n", "You need to indent code more than 4 spaces (btw have you noticed on SO if you add 4 spaces it gets recognized as code), this is 4 space indented:\n:::python\ndef hello():\n pass\n\n" ]
[ 3, 1, 1 ]
[]
[]
[ "code_formatting", "markdown", "python" ]
stackoverflow_0001540834_code_formatting_markdown_python.txt
Q: Opening and Printing files using Recursion in python So I am trying to write a code that opens a file and inside that file might be empty or contains the name of other files to open on each line. For example. 1.txt has 2.txt. on the first line and 3.txt on the second line. 2.txt is a empty file and 3.txt has 4.txt on the first line. I have to have an output that prints the files that the code runs through like "opening 1.txt..opening 2.txt and so on until all the files are open. the problem I am having is that my program stops printing when the opens the file that is empty. Looking at the example, I am not sure how to make it read the second line (3.txt) in 1.txt after it opened 2.txt and found out that it is empty. The code I have so far is this: (this is an recursion problem): def search(doc): a=open(doc) b=a.readline() if line == "": print ("Visiting " + doc) else: print ("Visiting " + doc) open(b[:-1]) search(b[:-1]) A: I am going to assume that a line contains the full path to the file. If this is not the case, then you should be able to make the necessary path modifications very easily. This IS homework, so I'll let you figure that out on your own Try this: def search(doc): print "Visiting", doc f = open(doc, 'r') for line in f: if line.strip(): search(line.strip()) Cheers
Opening and Printing files using Recursion in python
So I am trying to write a code that opens a file and inside that file might be empty or contains the name of other files to open on each line. For example. 1.txt has 2.txt. on the first line and 3.txt on the second line. 2.txt is a empty file and 3.txt has 4.txt on the first line. I have to have an output that prints the files that the code runs through like "opening 1.txt..opening 2.txt and so on until all the files are open. the problem I am having is that my program stops printing when the opens the file that is empty. Looking at the example, I am not sure how to make it read the second line (3.txt) in 1.txt after it opened 2.txt and found out that it is empty. The code I have so far is this: (this is an recursion problem): def search(doc): a=open(doc) b=a.readline() if line == "": print ("Visiting " + doc) else: print ("Visiting " + doc) open(b[:-1]) search(b[:-1])
[ "I am going to assume that a line contains the full path to the file. If this is not the case, then you should be able to make the necessary path modifications very easily. This IS homework, so I'll let you figure that out on your own\nTry this:\ndef search(doc):\n print \"Visiting\", doc\n f = open(doc, 'r')\n for line in f:\n if line.strip():\n search(line.strip())\n\nCheers\n" ]
[ 4 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0002083185_python_recursion.txt
Q: preprocessing RIPEMD-160 is the padding of RIPEMD-160 exactly the same as MD4 padding, down to the little-endian change? if i input "abc" in ascii, the processed data in hex should be 8063626100000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000001800000000 right? A: Yes, per the good pseudocode file found here (for ripemd-128, but ripemd-160 just extends that), Padding is identical to that of MD4.
preprocessing RIPEMD-160
is the padding of RIPEMD-160 exactly the same as MD4 padding, down to the little-endian change? if i input "abc" in ascii, the processed data in hex should be 8063626100000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000001800000000 right?
[ "Yes, per the good pseudocode file found here (for ripemd-128, but ripemd-160 just extends that),\nPadding is identical to that of MD4.\n\n" ]
[ 0 ]
[]
[]
[ "cryptography", "python" ]
stackoverflow_0002082474_cryptography_python.txt
Q: "Pre-importing" a variable into a module Python beginner here, so I apologize if this question has a simple answer. (I hope it does.) I am working on a python module--a plugin for a larger program. I'm trying to develop the module using the Eclipse IDE (with pydev), which means I need to be able to run this module stand-alone, i.e. not as a plugin from the larger program. I've actually sorted out a lot of the hairy details of this on my own, much of it involving creating a sort of "harness" that launches the plugin from my IDE in a way that simulates (from the plugin's perspective) being launched from within its real operating environment. But one thing eludes me. When the module is run from within it's "real" environment, it somehow has a certain name (call it "Bob") already defined in its dir() results. When I run it in my own environment, "Bob" doesn't appear in dir() unless I load it manually. Naturally, if I wrote code to load "Bob" manually just so that the plugin will work in my IDE, that interferes with the plugin when it is running "for real". What I need help with is: how do I get my plugin to start up (via my launching harness) with "Bob" already loaded? Naively, I'm kind of hoping to somehow be able to "force" the plugin to import "Bob" somehow, without actually having to add "import Bob" to the plugin itself. But I'm open to suggestions on a better way...? A: Presumably, when you run it "stand-alone" under Eclipse (or "stand-alone" without Eclipse, for that matter, just as "python foobar.py" at a shell prompt), your module's __name__ global variable has the value of '__main__' (if the module gets imported, instead, that global variable's value will be 'foobar' -- or however the module's named). So, just do if __name__ == '__main__': import Bob and you can have Bob imported when your module is run stand-alone, without any ill-effect when your module is instead getting imported.
"Pre-importing" a variable into a module
Python beginner here, so I apologize if this question has a simple answer. (I hope it does.) I am working on a python module--a plugin for a larger program. I'm trying to develop the module using the Eclipse IDE (with pydev), which means I need to be able to run this module stand-alone, i.e. not as a plugin from the larger program. I've actually sorted out a lot of the hairy details of this on my own, much of it involving creating a sort of "harness" that launches the plugin from my IDE in a way that simulates (from the plugin's perspective) being launched from within its real operating environment. But one thing eludes me. When the module is run from within it's "real" environment, it somehow has a certain name (call it "Bob") already defined in its dir() results. When I run it in my own environment, "Bob" doesn't appear in dir() unless I load it manually. Naturally, if I wrote code to load "Bob" manually just so that the plugin will work in my IDE, that interferes with the plugin when it is running "for real". What I need help with is: how do I get my plugin to start up (via my launching harness) with "Bob" already loaded? Naively, I'm kind of hoping to somehow be able to "force" the plugin to import "Bob" somehow, without actually having to add "import Bob" to the plugin itself. But I'm open to suggestions on a better way...?
[ "Presumably, when you run it \"stand-alone\" under Eclipse (or \"stand-alone\" without Eclipse, for that matter, just as \"python foobar.py\" at a shell prompt), your module's __name__ global variable has the value of '__main__' (if the module gets imported, instead, that global variable's value will be 'foobar' -- or however the module's named).\nSo, just do\nif __name__ == '__main__':\n import Bob\n\nand you can have Bob imported when your module is run stand-alone, without any ill-effect when your module is instead getting imported.\n" ]
[ 2 ]
[]
[]
[ "pydev", "python" ]
stackoverflow_0002083350_pydev_python.txt
Q: Cannot change global variables in a function through an exec() statement? Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem: >>> myvar = 'test' >>> def myfunc(): ... global myvar ... exec('myvar = "changed!"') ... print(myvar) ... >>> myfunc() test >>> print(myvar) test A: Per the docs, the exec statement takes two optional expressions, defaulting to globals() and locals(), and always performs changes (if any) in the locals() one. So, just be more explicit/specific/precise...: >>> def myfunc(): ... exec('myvar="boooh!"', globals()) ... >>> myfunc() >>> myvar 'boooh!' ...and you'll be able to clobber global variables to your heart's contents. A: To add to Alex's answer: although when you omit the locals/globals arguments they default to the locals and globals of the caller, this only a convenience hack; it does not mean they are inheriting the full execution context of the caller. In particular: a. nested scope cells are not available to the execed code. So this fails: def f(): foo= 1 def g(): exec('print foo') g() f() b. global declarations do not carry over into the execed code. So by default as in your example, written variables are put in the locals dictionary. However, you could make it work by saying exec('global myvar\nmyvar = "changed!"') You don't really want to be doing this if you can help it. global already isn't nice and exec is pretty much a code smell in itself! You wouldn't want to combine them unless there was really no alternative. A: How about this: >>> myvar = 'test' >>> def myfunc(): ... exec('globals()["myvar"] = "changed!"') ... print(myvar) ... >>> myfunc() changed! >>> print(myvar) changed! It worked for me in Python 2.6. EDIT: Actually Alex Martelli's explanation is much better than mine :)
Cannot change global variables in a function through an exec() statement?
Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem: >>> myvar = 'test' >>> def myfunc(): ... global myvar ... exec('myvar = "changed!"') ... print(myvar) ... >>> myfunc() test >>> print(myvar) test
[ "Per the docs, the exec statement takes two optional expressions, defaulting to globals() and locals(), and always performs changes (if any) in the locals() one.\nSo, just be more explicit/specific/precise...:\n>>> def myfunc():\n... exec('myvar=\"boooh!\"', globals())\n... \n>>> myfunc()\n>>> myvar\n'boooh!'\n\n...and you'll be able to clobber global variables to your heart's contents.\n", "To add to Alex's answer: although when you omit the locals/globals arguments they default to the locals and globals of the caller, this only a convenience hack; it does not mean they are inheriting the full execution context of the caller. In particular:\na. nested scope cells are not available to the execed code. So this fails:\ndef f():\n foo= 1\n def g():\n exec('print foo')\n g()\nf()\n\nb. global declarations do not carry over into the execed code. So by default as in your example, written variables are put in the locals dictionary. However, you could make it work by saying\nexec('global myvar\\nmyvar = \"changed!\"')\n\nYou don't really want to be doing this if you can help it. global already isn't nice and exec is pretty much a code smell in itself! You wouldn't want to combine them unless there was really no alternative.\n", "How about this:\n>>> myvar = 'test'\n>>> def myfunc():\n... exec('globals()[\"myvar\"] = \"changed!\"')\n... print(myvar)\n... \n>>> myfunc()\nchanged!\n>>> print(myvar)\nchanged!\n\nIt worked for me in Python 2.6.\nEDIT: Actually Alex Martelli's explanation is much better than mine :)\n" ]
[ 42, 5, 4 ]
[]
[]
[ "exec", "global", "python" ]
stackoverflow_0002083353_exec_global_python.txt
Q: Is there any difference between UserDict and Dict? If I want a class to have a dictionary behavior, why should I inherit from dict or UserDict? A: You can inherit from dict in any Python that's version 2.2 or better, but you'll have to override every single method of interest -- for example, your override of __getitem__ will not be used by get unless you also override that one, and so on, and so forth. The UserDict.DictMixin mix-in goes back a lot further and lets you implement just a few methods: the other methods, as supplied by the mix-in, will pick up and use your own overrides. Note, however, from the docs: Starting with Python version 2.6, it is recommended to use collections.MutableMapping instead of DictMixin. The new ABCs (Abstract Base Classes) in the collections module have much the same advantages as good old UserDict.DictMixin, wider applicability, and more regularity.
Is there any difference between UserDict and Dict?
If I want a class to have a dictionary behavior, why should I inherit from dict or UserDict?
[ "You can inherit from dict in any Python that's version 2.2 or better, but you'll have to override every single method of interest -- for example, your override of __getitem__ will not be used by get unless you also override that one, and so on, and so forth.\nThe UserDict.DictMixin mix-in goes back a lot further and lets you implement just a few methods: the other methods, as supplied by the mix-in, will pick up and use your own overrides. Note, however, from the docs:\n\nStarting with Python version 2.6, it\n is recommended to use\n collections.MutableMapping instead of\n DictMixin.\n\nThe new ABCs (Abstract Base Classes) in the collections module have much the same advantages as good old UserDict.DictMixin, wider applicability, and more regularity.\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0002083504_python.txt
Q: Python C-API module exit handler - an atexit equivalent? I'm using Python ver 2.6.4 There is a function I have to call from a C library when my extension module exits/is unloaded. What would be the equivalent of atexit for a C extension module? A: The Py_AtExit() function can be used to register up to 32 cleanup functions.
Python C-API module exit handler - an atexit equivalent?
I'm using Python ver 2.6.4 There is a function I have to call from a C library when my extension module exits/is unloaded. What would be the equivalent of atexit for a C extension module?
[ "The Py_AtExit() function can be used to register up to 32 cleanup functions.\n" ]
[ 4 ]
[]
[]
[ "python", "python_c_api", "python_c_extension" ]
stackoverflow_0002083523_python_python_c_api_python_c_extension.txt
Q: ftplib in combination with os.unlink in python With the following code I upload file.txt to a ftp server. When the file has been uploaded I delete it on my local machine. import os from ftplib import FTP HOST = 'host.com' FTP_NAME = 'username' FTP_PASS = 'password' filepath = 'C:\file.txt' while True: try: ftp = FTP(HOST) ftp.login(FTP_NAME, FTP_PASS) file = open(filepath, 'r') ftp.storlines('STOR file.txt', file) ftp.quit() file.close() # from this point on the file should not be in use anymore print 'File uploaded, now deleting...' except all_errors as e: #EDIT: Got exception here 'timed out' print 'error' # then the upload restarted. print str(e) os.unlink(filepath) # now delete the file The code works, but sometimes (every ~10th upload) I get this error message: Traceback (most recent call last): in os.unlink(filepath) WindowsError: [Error 32] The process cannot access the file because it is being usedby another process: 'C:\file.txt' So the file cannot be deleted because 'it has not been released' or something? I also tried to unlink the file this way: while True: # try to delete the file until it is deleted... try: os.unlink(filepath) break except all_errors as e: print 'Cannot delete the File. Will try it again...' print str(e) But with the "try except block" I also get the same error "The process cannot access the file because it is being usedby another process"! The script didn't even try to print the exception: 'Cannot delete the File. Will try it again...' and just stopped (like above). How can I make os.unlink do his job properly? Thanks! A: import os from ftplib import FTP HOST = 'host.com' FTP_NAME = 'username' FTP_PASS = 'password' filepath = 'C:\file.txt' file = open(filepath, 'r') while True: try: ftp = FTP(HOST) ftp.login(FTP_NAME, FTP_PASS) ftp.storlines('STOR file.txt', file) except all_errors as e: #EDIT: Got exception here 'timed out' print 'error' # then the upload restarted. print str(e) else: ftp.quit() file.close() # from this point on the file should not be in use anymore print 'File uploaded, now deleting...' os.unlink(filepath) # now delete the file break A: You need to close (file and ftp session) on the except leg of the try/except, else the file keeps being referenced by the "old" timed-out ftp session (so as a consequence you need to open the file within the while loop, not outside it) -- it's not enough to close the file and ftp session on the else leg as that doesn't get rid of the references from the failed, timed out attempts (if any). A: I have still problems with the code, it is not as robust as I need it to be. For example it is possible that the login process fails. Maybe user+pass is wrong, maybe the sesrver is busy. try: ftp = FTP(HOST) # HOST is a valid host address ftp.login('test', 'test111111') # WRONG user + pass to test code robustness ftp.quit() except all_errors as e: ftp.quit() print str(e) The problem is the ftp.quit() in the except block. Python returns the following error (NOT exception): Traceback (most recent call last): File "test.py", line 9, in <module> ftp.quit() NameError: name 'ftp' is not defined
ftplib in combination with os.unlink in python
With the following code I upload file.txt to a ftp server. When the file has been uploaded I delete it on my local machine. import os from ftplib import FTP HOST = 'host.com' FTP_NAME = 'username' FTP_PASS = 'password' filepath = 'C:\file.txt' while True: try: ftp = FTP(HOST) ftp.login(FTP_NAME, FTP_PASS) file = open(filepath, 'r') ftp.storlines('STOR file.txt', file) ftp.quit() file.close() # from this point on the file should not be in use anymore print 'File uploaded, now deleting...' except all_errors as e: #EDIT: Got exception here 'timed out' print 'error' # then the upload restarted. print str(e) os.unlink(filepath) # now delete the file The code works, but sometimes (every ~10th upload) I get this error message: Traceback (most recent call last): in os.unlink(filepath) WindowsError: [Error 32] The process cannot access the file because it is being usedby another process: 'C:\file.txt' So the file cannot be deleted because 'it has not been released' or something? I also tried to unlink the file this way: while True: # try to delete the file until it is deleted... try: os.unlink(filepath) break except all_errors as e: print 'Cannot delete the File. Will try it again...' print str(e) But with the "try except block" I also get the same error "The process cannot access the file because it is being usedby another process"! The script didn't even try to print the exception: 'Cannot delete the File. Will try it again...' and just stopped (like above). How can I make os.unlink do his job properly? Thanks!
[ "import os\nfrom ftplib import FTP\n\nHOST = 'host.com'\nFTP_NAME = 'username'\nFTP_PASS = 'password'\nfilepath = 'C:\\file.txt'\nfile = open(filepath, 'r')\nwhile True:\n try:\n ftp = FTP(HOST)\n ftp.login(FTP_NAME, FTP_PASS) \n ftp.storlines('STOR file.txt', file)\n except all_errors as e: #EDIT: Got exception here 'timed out'\n print 'error' # then the upload restarted.\n print str(e)\n else:\n ftp.quit()\n file.close() # from this point on the file should not be in use anymore\n print 'File uploaded, now deleting...' \n os.unlink(filepath) # now delete the file\n break\n\n", "You need to close (file and ftp session) on the except leg of the try/except, else the file keeps being referenced by the \"old\" timed-out ftp session (so as a consequence you need to open the file within the while loop, not outside it) -- it's not enough to close the file and ftp session on the else leg as that doesn't get rid of the references from the failed, timed out attempts (if any).\n", "I have still problems with the code, it is not as robust as I need it to be.\nFor example it is possible that the login process fails. Maybe user+pass is wrong, maybe the sesrver is busy.\ntry:\n ftp = FTP(HOST) # HOST is a valid host address\n ftp.login('test', 'test111111') # WRONG user + pass to test code robustness\n ftp.quit()\nexcept all_errors as e:\n ftp.quit()\n print str(e)\n\nThe problem is the ftp.quit() in the except block. Python returns the following error (NOT exception):\nTraceback (most recent call last):\n File \"test.py\", line 9, in <module>\n ftp.quit()\nNameError: name 'ftp' is not defined\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0002081289_exception_python.txt
Q: Checking for value within same type in python a = 0 if a == False: print a in php I can say: $a = 0; if $a === false { echo $a; } The triple === in php check for the value within the same type, thus making the integer 0 not be read as a boolean value False How can I do this in python? I would like to differentiate between 0 the integer and False the boolean value in a simple if statement. A: You should use the is keyword in that case. It's the identity operator, the same as === in PHP. >>> a = 0 >>> if a is False: ... print a ... >>> A: type() will give you the type of an object. But if you're worried about distinguishing between 0 and False then perhaps you should use None instead.
Checking for value within same type in python
a = 0 if a == False: print a in php I can say: $a = 0; if $a === false { echo $a; } The triple === in php check for the value within the same type, thus making the integer 0 not be read as a boolean value False How can I do this in python? I would like to differentiate between 0 the integer and False the boolean value in a simple if statement.
[ "You should use the is keyword in that case. It's the identity operator, the same as === in PHP.\n>>> a = 0\n>>> if a is False:\n... print a\n...\n>>> \n\n", "type() will give you the type of an object. But if you're worried about distinguishing between 0 and False then perhaps you should use None instead.\n" ]
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002084017_python.txt
Q: How to remove expired items from database with Scrapy I am using spidering a video site that expires content frequently. I am considering using scrapy to do my spidering, but am not sure how to delete expired items. Strategies to detect if an item is expired are: Spider the site's "delete.rss". Every few days, try reloading the contents page and making sure it still works. Spider every page of the site's content indexes, and remove the video if it's not found. Please let me know how to remove expired items in scrapy. I will be storing my scrapy items in a mysql DB via django. 2010-01-18 Update I have found a solution that is working, but still may not be optimal. I am maintaining a "found_in_last_scan" flag on every video that I sync. When the spider starts, it sets all the flags to False. When it finishes, it deletes videos who still have the flag set to False. I did this by attaching to the signals.spider_opened and signals.spider_closed Please confirm this is a valid strategy and there are no problems with it. A: I haven't tested this! I have to confess that I haven't tried using the Django models in Scrapy, but here goes: The simplest way I imagine would be to create a new spider for the deleted.rss file by extending the XMLFeedSpider (Copied from the scrapy documentation, then modified). I suggest you do create a new spider because very little of the following logic is related to the logic used for scraping the site: from scrapy import log from scrapy.contrib.spiders import XMLFeedSpider from myproject.items import DeletedUrlItem class MySpider(XMLFeedSpider): domain_name = 'example.com' start_urls = ['http://www.example.com/deleted.rss'] iterator = 'iternodes' # This is actually unnecesary, since it's the default value itertag = 'item' def parse_node(self, response, url): url['url'] = node.select('#path/to/url').extract() return url # return an Item SPIDER = MySpider() This is not a working spider for you to use, but IIRC the RSS files are pure XML. I'm not sure how the deleted.rss looks like but I'm sure you can figure out how to extract the URLs from the XML. Now, this example imports myproject.items.DeletedUrlItem which is just a string in this example, but you need to create t he DeletedUrlItem using something like the code below: You need to create the DeletedUrlItem: class DeletedUrlItem(Item): url = Field() Instead of saving, you delete the items using Django's Model API in a Scrapy's ItemPipeline - I assume you're using a DjangoItem: # we raise a DropItem exception so Scrapy # doesn't try to process the item any further from scrapy.core.exceptions import DropItem # import your model import django.Model.yourModel class DeleteUrlPipeline(item): def process_item(self, spider, item): if item['url']: delete_item = yourModel.objects.get(url=item['url']) delete_item.delete() # actually delete the item! raise DropItem("Deleted: %s" % item) Notice the delete_item.delete(). I'm aware that this answer may contain errors, it's written by memory :-) but I will definitely update if you've got comments or cannot figure this out. A: If you have a HTTP URL which you suspect might not be valid at all any more (because you found it in a "deleted" feed, or just because you haven't checked it in a while), the simplest, fastest way to check is to send an HTTP HEAD request for that URL. In Python, that's best done with the httplib module of the standard library: make a connection object c to the host of interest with HTTPConnection (if HTTP 1.1, it may be reusable to check multiple URLs with better performance and lower systrem load), then do one (or more, if feasible, i.e. if HTTP 1.1 is in use) calls of c's request method, first argument 'HEAD', second argument the URL you're checking (without the host part of course;-). After each request you call c.getresponse() to get an HTTPResponse object, whose status attribute will tell you if the URL is still valid. Yes, it's a bit low-level, but exactly for this reason it lets you optimize your task a lot better, with just a little knowledge of HTTP;-).
How to remove expired items from database with Scrapy
I am using spidering a video site that expires content frequently. I am considering using scrapy to do my spidering, but am not sure how to delete expired items. Strategies to detect if an item is expired are: Spider the site's "delete.rss". Every few days, try reloading the contents page and making sure it still works. Spider every page of the site's content indexes, and remove the video if it's not found. Please let me know how to remove expired items in scrapy. I will be storing my scrapy items in a mysql DB via django. 2010-01-18 Update I have found a solution that is working, but still may not be optimal. I am maintaining a "found_in_last_scan" flag on every video that I sync. When the spider starts, it sets all the flags to False. When it finishes, it deletes videos who still have the flag set to False. I did this by attaching to the signals.spider_opened and signals.spider_closed Please confirm this is a valid strategy and there are no problems with it.
[ "I haven't tested this!\nI have to confess that I haven't tried using the Django models in Scrapy, but here goes:\nThe simplest way I imagine would be to create a new spider for the deleted.rss file by extending the XMLFeedSpider (Copied from the scrapy documentation, then modified). I suggest you do create a new spider because very little of the following logic is related to the logic used for scraping the site:\nfrom scrapy import log\nfrom scrapy.contrib.spiders import XMLFeedSpider\nfrom myproject.items import DeletedUrlItem\n\nclass MySpider(XMLFeedSpider):\n domain_name = 'example.com'\n start_urls = ['http://www.example.com/deleted.rss']\n iterator = 'iternodes' # This is actually unnecesary, since it's the default value\n itertag = 'item'\n\n def parse_node(self, response, url):\n url['url'] = node.select('#path/to/url').extract()\n\n return url # return an Item \n\nSPIDER = MySpider()\n\nThis is not a working spider for you to use, but IIRC the RSS files are pure XML. I'm not sure how the deleted.rss looks like but I'm sure you can figure out how to extract the URLs from the XML. Now, this example imports myproject.items.DeletedUrlItem which is just a string in this example, but you need to create t he DeletedUrlItem using something like the code below:\nYou need to create the DeletedUrlItem:\nclass DeletedUrlItem(Item):\n url = Field()\n\nInstead of saving, you delete the items using Django's Model API in a Scrapy's ItemPipeline - I assume you're using a DjangoItem:\n# we raise a DropItem exception so Scrapy\n# doesn't try to process the item any further\nfrom scrapy.core.exceptions import DropItem\n\n# import your model\nimport django.Model.yourModel\n\nclass DeleteUrlPipeline(item):\n\n def process_item(self, spider, item):\n if item['url']:\n delete_item = yourModel.objects.get(url=item['url'])\n delete_item.delete() # actually delete the item!\n raise DropItem(\"Deleted: %s\" % item)\n\nNotice the delete_item.delete().\n\nI'm aware that this answer may contain errors, it's written by memory :-) but I will definitely update if you've got comments or cannot figure this out.\n", "If you have a HTTP URL which you suspect might not be valid at all any more (because you found it in a \"deleted\" feed, or just because you haven't checked it in a while), the simplest, fastest way to check is to send an HTTP HEAD request for that URL. In Python, that's best done with the httplib module of the standard library: make a connection object c to the host of interest with HTTPConnection (if HTTP 1.1, it may be reusable to check multiple URLs with better performance and lower systrem load), then do one (or more, if feasible, i.e. if HTTP 1.1 is in use) calls of c's request method, first argument 'HEAD', second argument the URL you're checking (without the host part of course;-).\nAfter each request you call c.getresponse() to get an HTTPResponse object, whose status attribute will tell you if the URL is still valid.\nYes, it's a bit low-level, but exactly for this reason it lets you optimize your task a lot better, with just a little knowledge of HTTP;-).\n" ]
[ 4, 0 ]
[]
[]
[ "python", "scrapy", "screen_scraping" ]
stackoverflow_0002051842_python_scrapy_screen_scraping.txt
Q: sendinput to directinput(like games) I'm trying to simulate keypress to my games that use direct input. I googled around and I found out the method SendIput(). It works fine if I try to send keypress to notepad.exe but nothing happend when I tried to games. I checked this site, and I edited my code a little bit but still I don't get any of keypress event from the game. Can anybody can help me with this? I used Python but since I imported ctypes module, c/c++ explanation is okay. A: It seems you are looking for a Python answer, but personally I would try using AutoHotkey. Its scripting language is on the ugly side, but rather easy to use. There are forum posts (both on Warhammer forums and AutoHotkey forums) to indicate that other Warhammer players are using AutoHotkey.
sendinput to directinput(like games)
I'm trying to simulate keypress to my games that use direct input. I googled around and I found out the method SendIput(). It works fine if I try to send keypress to notepad.exe but nothing happend when I tried to games. I checked this site, and I edited my code a little bit but still I don't get any of keypress event from the game. Can anybody can help me with this? I used Python but since I imported ctypes module, c/c++ explanation is okay.
[ "It seems you are looking for a Python answer, but personally I would try using AutoHotkey. Its scripting language is on the ugly side, but rather easy to use. There are forum posts (both on Warhammer forums and AutoHotkey forums) to indicate that other Warhammer players are using AutoHotkey.\n" ]
[ 0 ]
[]
[]
[ "c", "directinput", "keypress", "python", "sendinput" ]
stackoverflow_0002084634_c_directinput_keypress_python_sendinput.txt
Q: Running syncdb on Django project not working: Can't create/write to file When I run: $ python manage.py syncdb I get the following output: Creating table auth_permission Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 222, in execute output = self.handle(*args, **options) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 351, in handle return self.handle_noargs(**options) File "/Library/Python/2.6/site-packages/django/core/management/commands/syncdb.py", line 78, in handle_noargs cursor.execute(statement) File "/Library/Python/2.6/site-packages/django/db/backends/util.py", line 19, in execute return self.cursor.execute(sql, params) File "/Library/Python/2.6/site-packages/django/db/backends/mysql/base.py", line 84, in execute return self.cursor.execute(query, args) File "build/bdist.macosx-10.6-universal/egg/MySQLdb/cursors.py", line 173, in execute File "build/bdist.macosx-10.6-universal/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler _mysql_exceptions.InternalError: (1, "Can't create/write to file '/usr/local/mysql/data/wzhere/auth_permission.MYI' (Errcode: 2)") Any ideas on how to debug? I've given the database user all the permissions it should need. Not sure what MySQL is balking at here. UPDATE: The problem here ended up being that I had installed MySQL multiple times (first 32-bit, then 64-bit when I realized I should be doing that) and although I followed some instructions on how to un-install MySQL, the instructions are slightly different for Snow Leopard. Once I actually did an uninstall and clean install, this problem went away. A: The question was how to debug the problem and as already pointed out by Agos, Errno 2 is 'No such file or directory'. You might want to look in the data directory of MySQL and check if the directory is actually there and has correct permissions shell> cd /usr/local/mysql/data/ shell> ls -ld * drwx------ 17 geert admin 578 Oct 1 19:33 someabstract The above should give you list of directories (which are the MySQL databases) and their permissions. Check whether the 'wzhere' directory in particular.. It's a bit weird error message you get I should say. (Trying another Django DB back-end wouldn't solve anything in this case.) A: This might help: agos@server:~$ perror 2 OS error code 2: No such file or directory Is your MySQL configured correctly? Try querying it yourself via mysql command. Also, as luc suggested in the comment, try with sqlite.
Running syncdb on Django project not working: Can't create/write to file
When I run: $ python manage.py syncdb I get the following output: Creating table auth_permission Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 222, in execute output = self.handle(*args, **options) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 351, in handle return self.handle_noargs(**options) File "/Library/Python/2.6/site-packages/django/core/management/commands/syncdb.py", line 78, in handle_noargs cursor.execute(statement) File "/Library/Python/2.6/site-packages/django/db/backends/util.py", line 19, in execute return self.cursor.execute(sql, params) File "/Library/Python/2.6/site-packages/django/db/backends/mysql/base.py", line 84, in execute return self.cursor.execute(query, args) File "build/bdist.macosx-10.6-universal/egg/MySQLdb/cursors.py", line 173, in execute File "build/bdist.macosx-10.6-universal/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler _mysql_exceptions.InternalError: (1, "Can't create/write to file '/usr/local/mysql/data/wzhere/auth_permission.MYI' (Errcode: 2)") Any ideas on how to debug? I've given the database user all the permissions it should need. Not sure what MySQL is balking at here. UPDATE: The problem here ended up being that I had installed MySQL multiple times (first 32-bit, then 64-bit when I realized I should be doing that) and although I followed some instructions on how to un-install MySQL, the instructions are slightly different for Snow Leopard. Once I actually did an uninstall and clean install, this problem went away.
[ "The question was how to debug the problem and as already pointed out by Agos, Errno 2 is 'No such file or directory'. You might want to look in the data directory of MySQL and check if the directory is actually there and has correct permissions\nshell> cd /usr/local/mysql/data/\nshell> ls -ld *\ndrwx------ 17 geert admin 578 Oct 1 19:33 someabstract\n\nThe above should give you list of directories (which are the MySQL databases) and their permissions. Check whether the 'wzhere' directory in particular..\nIt's a bit weird error message you get I should say.\n(Trying another Django DB back-end wouldn't solve anything in this case.)\n", "This might help:\n\nagos@server:~$ perror 2\n OS error code 2: No such file or directory\n\nIs your MySQL configured correctly? Try querying it yourself via mysql command.\nAlso, as luc suggested in the comment, try with sqlite.\n" ]
[ 4, 2 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0002084760_django_mysql_python.txt
Q: Python: create graph based on degree correlation I want to create a graph using networkx which has positive or negative degree correlation. Like a graph for a social network or citations in academic papers etc. Can you suggest some function for this? A: If you are talking about producing a visual graph (diagram) you could look at using matplotlib to generate them. I'm not sure if there is going to be a single function that will do what you want (not enough detail) but its a comprehensive library used in many projects to achieve complex graphing related tasks.
Python: create graph based on degree correlation
I want to create a graph using networkx which has positive or negative degree correlation. Like a graph for a social network or citations in academic papers etc. Can you suggest some function for this?
[ "If you are talking about producing a visual graph (diagram) you could look at using matplotlib to generate them. I'm not sure if there is going to be a single function that will do what you want (not enough detail) but its a comprehensive library used in many projects to achieve complex graphing related tasks.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002085231_python.txt
Q: When loading a dll in Python does the dir function shows its methods? Does this code shows the methods from a dll? from ctypes import * x = cdll.LoadLibrary("olari.dll") dir(x) if not, how can we see the .dll methods in python? A: No, it doesn't. But It can cache when you call, and will show in dir after that. You could take a look this SO Thread, even in Win32, seems like need to parse PE Header. I think python need to do similar way. UPDATE: I found pefile read/write module written in python, there you can find exported entries. for entry in pe.DIRECTORY_ENTRY_IMPORT: print entry.dll for imp in entry.imports: print '\t', hex(imp.address), imp.name Output comdlg32.dll 0x10012A0L PageSetupDlgW 0x10012A4L FindTextW 0x10012A8L PrintDlgExW [snip] SHELL32.dll 0x1001154L DragFinish 0x1001158L DragQueryFileW imp.name will be the one you are looking for. You could use that name in ctypes like >>> ctypes.windll.comdlg32.PageSetupDlgW <_FuncPtr object at 0x00A97210> >>> ctypes.windll.comdlg32.FindTextW <_FuncPtr object at 0x00A97288> ...
When loading a dll in Python does the dir function shows its methods?
Does this code shows the methods from a dll? from ctypes import * x = cdll.LoadLibrary("olari.dll") dir(x) if not, how can we see the .dll methods in python?
[ "No, it doesn't. But It can cache when you call, and will show in dir after that.\nYou could take a look this SO Thread, even in Win32, seems like need to parse PE Header. I think python need to do similar way.\nUPDATE:\nI found pefile read/write module written in python, there you can find exported entries.\nfor entry in pe.DIRECTORY_ENTRY_IMPORT:\n print entry.dll\n for imp in entry.imports:\n print '\\t', hex(imp.address), imp.name\nOutput\ncomdlg32.dll\n 0x10012A0L PageSetupDlgW\n 0x10012A4L FindTextW\n 0x10012A8L PrintDlgExW\n[snip]\nSHELL32.dll\n 0x1001154L DragFinish\n 0x1001158L DragQueryFileW\n\nimp.name will be the one you are looking for. You could use that name in ctypes like \n>>> ctypes.windll.comdlg32.PageSetupDlgW\n<_FuncPtr object at 0x00A97210>\n>>> ctypes.windll.comdlg32.FindTextW\n<_FuncPtr object at 0x00A97288>\n...\n\n" ]
[ 2 ]
[]
[]
[ "dllimport", "methods", "python" ]
stackoverflow_0002085295_dllimport_methods_python.txt
Q: Python matplotlib graph problem import matplotlib import matplotlib.pyplot as plt import pylab as PL matplotlib.rcParams['axes.unicode_minus'] = False fig = plt.figure() ax = fig.add_subplot(111) PL.loglog(a, b,'o') ax.set_title('Graph Example') plt.show() 1) This displays the graph with points on the plot. Is there a way to join these points with a smooth curve. 2) I want to draw more than one plot in the same graph(i.e. for a different set of values of lists a and b) . How do I do that? I want to represent points of each graph with a different symbol(cross,square,circle) or color. A: See @Ber's comment Simply call PL.loglog multiple times.
Python matplotlib graph problem
import matplotlib import matplotlib.pyplot as plt import pylab as PL matplotlib.rcParams['axes.unicode_minus'] = False fig = plt.figure() ax = fig.add_subplot(111) PL.loglog(a, b,'o') ax.set_title('Graph Example') plt.show() 1) This displays the graph with points on the plot. Is there a way to join these points with a smooth curve. 2) I want to draw more than one plot in the same graph(i.e. for a different set of values of lists a and b) . How do I do that? I want to represent points of each graph with a different symbol(cross,square,circle) or color.
[ "\nSee @Ber's comment\nSimply call PL.loglog multiple times.\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002084805_python.txt
Q: Pylons Custom Middleware return 404 I have the following code as a middleware in an pylons application: import testing.model as model import re from pylons.controllers.util import abort class SubdomainCheckMiddleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): if 'subdomaincheck' in environ: return self.app(environ, start_response) p = re.compile('([a-z0-9\-]+)', re.IGNORECASE) subdomain = p.match(environ['HTTP_HOST']).group(0) query = "SELECT \"nspname\" FROM \"pg_namespace\" WHERE \"nspname\" = '%s';" % subdomain result = model.meta.Session.execute(query) for row in result: if row['nspname'] == subdomain: environ['subdomaincheck'] = 'done' return self.app(environ, start_response) What it basicly does is checking if a schema in postgresql is present with the given subdomain, but I need it to return 404 not found if the schema is not present, how can I do that? A: It's pretty straightforward to return a basic 404 in a WSGI app: if error: start_response("404 Not Found", [('Content-type', 'text/plain')]) return ['Page not found'] If you want something more elaborate you could use some other middleware to handle errors for you. It actually looks like Pylons comes with a StatusCodeRedirect middleware that might help you out here if you wanted it.
Pylons Custom Middleware return 404
I have the following code as a middleware in an pylons application: import testing.model as model import re from pylons.controllers.util import abort class SubdomainCheckMiddleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): if 'subdomaincheck' in environ: return self.app(environ, start_response) p = re.compile('([a-z0-9\-]+)', re.IGNORECASE) subdomain = p.match(environ['HTTP_HOST']).group(0) query = "SELECT \"nspname\" FROM \"pg_namespace\" WHERE \"nspname\" = '%s';" % subdomain result = model.meta.Session.execute(query) for row in result: if row['nspname'] == subdomain: environ['subdomaincheck'] = 'done' return self.app(environ, start_response) What it basicly does is checking if a schema in postgresql is present with the given subdomain, but I need it to return 404 not found if the schema is not present, how can I do that?
[ "It's pretty straightforward to return a basic 404 in a WSGI app: \nif error:\n start_response(\"404 Not Found\", [('Content-type', 'text/plain')])\n return ['Page not found']\n\nIf you want something more elaborate you could use some other middleware to handle errors for you. It actually looks like Pylons comes with a StatusCodeRedirect middleware that might help you out here if you wanted it.\n" ]
[ 2 ]
[]
[]
[ "paster", "pylons", "python", "wsgi" ]
stackoverflow_0002085334_paster_pylons_python_wsgi.txt
Q: How to read file headers in Python similar to C? I am new to Python. I am a C programmer by profession. I have file, whose header has some specific data, that I need to extract. For example, Byte 0-5 has a magic, Byte 6-8 has offset etc. In C (An Example) : struct { int32_t payload_offset, int32_t len, char *magic, int32_t type int32_t header_size } file_hdr; Then in my function, I do the following: file_hdr *hdr; ptr = &hdr; fd = open(path_to_file, "r"); num_read = read(fd, ptr, bytes). Then I can access header data like this ptr->type, ptr->magic etc. How do I achieve similar effect in Python? Since Python variables do not have types, what is the best way to access file header data? I need to use the header data for making some decisions. Thanks in Advance. A: One way is to use the python struct module, docs are here. Another option, if you need something more powerful, is to use the awesome construct library that can do the above and much more. A: This is typically done using the struct module in Python. It allows you to extract values from packed binary representations, driven by format-specification strings that you provide. You would load the data in using binary I/O into a string, then unpack it using struct.unpack().
How to read file headers in Python similar to C?
I am new to Python. I am a C programmer by profession. I have file, whose header has some specific data, that I need to extract. For example, Byte 0-5 has a magic, Byte 6-8 has offset etc. In C (An Example) : struct { int32_t payload_offset, int32_t len, char *magic, int32_t type int32_t header_size } file_hdr; Then in my function, I do the following: file_hdr *hdr; ptr = &hdr; fd = open(path_to_file, "r"); num_read = read(fd, ptr, bytes). Then I can access header data like this ptr->type, ptr->magic etc. How do I achieve similar effect in Python? Since Python variables do not have types, what is the best way to access file header data? I need to use the header data for making some decisions. Thanks in Advance.
[ "One way is to use the python struct module, docs are here.\nAnother option, if you need something more powerful, is to use the awesome construct library that can do the above and much more.\n", "This is typically done using the struct module in Python. It allows you to extract values from packed binary representations, driven by format-specification strings that you provide.\nYou would load the data in using binary I/O into a string, then unpack it using struct.unpack().\n" ]
[ 7, 3 ]
[]
[]
[ "file_io", "header", "python" ]
stackoverflow_0002085464_file_io_header_python.txt
Q: Interpolate Question import re from decimal import * import numpy from scipy.signal import cspline1d, cspline1d_eval import scipy.interpolate import scipy import math import numpy from scipy import interpolate Y1 =[0.48960000000000004, 0.52736099999999997, 0.56413900000000006, 0.60200199999999993, 0.64071400000000001, 0.67668399999999995, 0.71315899999999999, 0.75050499999999998, 0.61494199999999999, 0.66246900000000009] X1 =[0.024, 0.026000000000000002, 0.028000000000000004, 0.029999999999999999, 0.032000000000000001, 0.034000000000000002, 0.035999999999999997, 0.038000000000000006, 0.029999999999999999, 0.032500000000000001] rep = scipy.interpolate.splrep(X1,Y1) IN the above code i am getting and error of Traceback (most recent call last): File "/home/vibhor/Desktop/timing_tool/timing/interpolation_cap.py", line 64, in <module> rep = scipy.interpolate.splrep(X1,Y1) File "/usr/lib/python2.6/site-packages/scipy/interpolate/fitpack.py", line 418, in splrep raise _iermess[ier][1],_iermess[ier][0] ValueError: Error on input data Don't know what is happening A: I believe it's due to the X1 values not being ordered from smallest to largest plus also you have one duplicate x point, i.e, you need to sort the values for X1 and Y1 before you can use the splrep and remove duplicates. splrep from the docs seem to be low level access to FITPACK libraries which expects a sorted, non-duplicate list that's why it returns an error interpolate.interp1d might seem to work, but have you actually tried to use it to find a new point? I think you'll find an error when you call it i.e. rep(2) A: The X value 0.029999999999999999 occurs twice, with two different Y coordinates. It wouldn't surprise me if that caused a problem trying to fit a polynomial spline segment....
Interpolate Question
import re from decimal import * import numpy from scipy.signal import cspline1d, cspline1d_eval import scipy.interpolate import scipy import math import numpy from scipy import interpolate Y1 =[0.48960000000000004, 0.52736099999999997, 0.56413900000000006, 0.60200199999999993, 0.64071400000000001, 0.67668399999999995, 0.71315899999999999, 0.75050499999999998, 0.61494199999999999, 0.66246900000000009] X1 =[0.024, 0.026000000000000002, 0.028000000000000004, 0.029999999999999999, 0.032000000000000001, 0.034000000000000002, 0.035999999999999997, 0.038000000000000006, 0.029999999999999999, 0.032500000000000001] rep = scipy.interpolate.splrep(X1,Y1) IN the above code i am getting and error of Traceback (most recent call last): File "/home/vibhor/Desktop/timing_tool/timing/interpolation_cap.py", line 64, in <module> rep = scipy.interpolate.splrep(X1,Y1) File "/usr/lib/python2.6/site-packages/scipy/interpolate/fitpack.py", line 418, in splrep raise _iermess[ier][1],_iermess[ier][0] ValueError: Error on input data Don't know what is happening
[ "I believe it's due to the X1 values not being ordered from smallest to largest plus also you have one duplicate x point, i.e, you need to sort the values for X1 and Y1 before you can use the splrep and remove duplicates.\nsplrep from the docs seem to be low level access to FITPACK libraries which expects a sorted, non-duplicate list that's why it returns an error\ninterpolate.interp1d might seem to work, but have you actually tried to use it to find a new point? I think you'll find an error when you call it i.e. rep(2)\n", "The X value 0.029999999999999999 occurs twice, with two different Y coordinates. It wouldn't\nsurprise me if that caused a problem trying to fit a polynomial spline segment....\n" ]
[ 12, 1 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0002009379_python_scipy.txt
Q: Windows file creation date/time using python I need to get a file creation date&time using python. I tried: os.stat(r"path")[ST_CTIME] But it is returning: 1263538277 This is not the creation date time. Is there a way to do it? A: Why not? >>> import time >>> time.ctime(1263538277) 'Fri Jan 15 04:51:17 2010' Looks like a valid creation time to me. A: From bytes.com: import os import time create_date = os.stat('/tmp/myfile.txt')[9] print time.strftime("%Y-%m-%d", time.gmtime(create_date)) Which gives: 2009-11-25 You can also try: print time.gmtime(create_date) (2009, 11, 25, 13, 37, 9, 2, 329, 0) For a more accurate timestamp. Note that the time returned by time.gmtime() returns GMT; See the time module documentation for other functions, like localtime(). A: Are you sure it isn't? Using unixtimestamp.com it converts to "01/18/2010 @ 7:34am" which at least makes sense. The timestamp is returned as a time in seconds from 1970-01-01. A: See http://docs.python.org/library/os.html#os.stat st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows) Everything is OK.
Windows file creation date/time using python
I need to get a file creation date&time using python. I tried: os.stat(r"path")[ST_CTIME] But it is returning: 1263538277 This is not the creation date time. Is there a way to do it?
[ "Why not?\n>>> import time\n>>> time.ctime(1263538277)\n'Fri Jan 15 04:51:17 2010'\n\nLooks like a valid creation time to me.\n", "From bytes.com:\nimport os\nimport time\ncreate_date = os.stat('/tmp/myfile.txt')[9]\nprint time.strftime(\"%Y-%m-%d\", time.gmtime(create_date))\n\nWhich gives:\n2009-11-25\n\nYou can also try:\nprint time.gmtime(create_date)\n(2009, 11, 25, 13, 37, 9, 2, 329, 0)\n\nFor a more accurate timestamp.\nNote that the time returned by time.gmtime() returns GMT; See the time module documentation for other functions, like localtime().\n", "Are you sure it isn't? Using unixtimestamp.com it converts to \"01/18/2010 @ 7:34am\" which at least makes sense.\nThe timestamp is returned as a time in seconds from 1970-01-01.\n", "See http://docs.python.org/library/os.html#os.stat\n\nst_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)\n\nEverything is OK.\n" ]
[ 10, 5, 3, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002085992_datetime_python.txt
Q: How do I customize formish error messages? I'm using formish to handle web forms but I don't like the automatically generated error messages when validation fails. Where do I customize those error messages? A: The best place for feedback on formish is in the google groups which is linked to from the http://form.ish.io page.. As for customising the error messages, the best way would be to create your own validator (which is pretty simple, have a look in the validatish module). However, you've inspired me to think about making all of the validators take a custom argument for each type of message... I'll have a think about that one. If you struggle customising your own errors, drop into the google group... A: I've added custom messages to the validatish module for you .. If you get it from github, you'll see how it works (you pass a dictionary of messages to the validate function or object - e.g. Required(messages={'required': 'dont forget it!'}) ) If you need a release for it quickly, let me know..
How do I customize formish error messages?
I'm using formish to handle web forms but I don't like the automatically generated error messages when validation fails. Where do I customize those error messages?
[ "The best place for feedback on formish is in the google groups which is linked to from the http://form.ish.io page.. \nAs for customising the error messages, the best way would be to create your own validator (which is pretty simple, have a look in the validatish module). However, you've inspired me to think about making all of the validators take a custom argument for each type of message... I'll have a think about that one. If you struggle customising your own errors, drop into the google group... \n", "I've added custom messages to the validatish module for you .. If you get it from github, you'll see how it works (you pass a dictionary of messages to the validate function or object - e.g. Required(messages={'required': 'dont forget it!'}) )\nIf you need a release for it quickly, let me know..\n" ]
[ 0, 0 ]
[]
[]
[ "formish", "python", "webforms" ]
stackoverflow_0001923634_formish_python_webforms.txt
Q: What is the difference between these codes, and what does the repr do? 1. >>> s = u"4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf" >>> print s 4-12个英文字母、数字和下划线 >>> print repr(s) u'4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf' 2. print repr("4-12个英文字母、数字和下划线") '4-12\xb8\xf6\xd3\xa2\xce\xc4\xd7\xd6\xc4\xb8\xa1\xa2\xca\xfd\xd7\xd6\xba\xcd\xcf\xc2\xbb\xae\xcf\xdf' 1 and 2 are different, but the original string is the same,both are '4-12个英文字母、数字和下划线' what does the repr exactly do? the same value is : >>> print '4-12个英文字母、数字和下划线'.decode('gb2312').encode('unicode-escape') 4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf A: I'll take a stab at this, 'repr' is the machine representation of the object while 'print' shows the human readable representation of the object. There are built in methods 'repr', 'str', and 'unicode' that can be used by programmers to implement the different printable representations of an object. Here is a simple example class PrintObject(object): def __repr__(self): return 'repr' def __str__(self): return 'str' def __unicode__(self): return 'unicode' Now if you load this object into a python shell and play around with it you can see how these different methods are used to represent the printable representation of the object Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from printobject import PrintObject >>> printObj = PrintObject() >>> printObj >>> repr(printObj) 'repr' >>> str(printObj) 'str' >>> unicode(printObj) u'unicode' The 'repr' method is used if you just type the instance and return >>> printObj repr The 'str' method is used if you use print on the instance >>> print(printObj) str and the 'unicode' method is used if you use the instance in a unicode string. >>> print(u'%s' % printObj) unicode When and if you start writing your own classes these methods come in really handy. A: Regarding repr >>> help(repr) Help on built-in function repr in module __builtin__: repr(...) repr(object) -> string Return the canonical string representation of the object. For most object types, eval(repr(object)) == object. A: In the first case, the Python interpreter has automatically decoded the bytes passed to it in the characters by the terminal encoding since it is a unicode literal. Printing the repr() of that yields Unicode escape sequences. In the second case, no decoding is done since it is a str literal, and so its repr() is composed of byte escape sequences corresponding to the characters in the terminal's encoding (in this case, GB2312). A: In the first case, you are getting the repr of a unicode object. This is conceptually a series of unicode characters, and the repr is giving you the sequence of unicode codepoints for these characters as an escape sequence. ie '\u4e2a' is codepoint 20010 (0x4e2a is the hexidecimal representation), which is displayed as "个". In the second case, you are getting the repr of a string object. Strings are essentially sequences of 8 bit values, with no internal knowledge about how these values relate to characters. When you print or enter those characters at the prompt, they are interpreted using your system's default encoding. When you print the repr of the object, you see the raw bytes that make it up - the printable ASCII characters are printed as is, everything else is shown as an escape sequence (ie \xb8 is the value 184 (written 0xB8 in hexidecimal)). In your system's encoding (gb2312) the sequence of bytes [184, 246] ('\xb8\xf6') corresponds to the unicode codepoint 0x4e2a. However the string has no idea what encoding it is in, or even that it represents a sequence of characters, so it's repr just gives you the raw underlying data. To convert it into a unicode object, you need to decode it from this data, indicating how the raw data should be interpreted: >>> s=s.decode('gb2312') In python3, this distinction between "characters" and "data" is made a bit more clear, as the str object is renamed as "bytes", and what are now unicode strings become just strings.
What is the difference between these codes, and what does the repr do?
1. >>> s = u"4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf" >>> print s 4-12个英文字母、数字和下划线 >>> print repr(s) u'4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf' 2. print repr("4-12个英文字母、数字和下划线") '4-12\xb8\xf6\xd3\xa2\xce\xc4\xd7\xd6\xc4\xb8\xa1\xa2\xca\xfd\xd7\xd6\xba\xcd\xcf\xc2\xbb\xae\xcf\xdf' 1 and 2 are different, but the original string is the same,both are '4-12个英文字母、数字和下划线' what does the repr exactly do? the same value is : >>> print '4-12个英文字母、数字和下划线'.decode('gb2312').encode('unicode-escape') 4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf
[ "I'll take a stab at this, 'repr' is the machine representation of the object while 'print' shows the human readable representation of the object. There are built in methods 'repr', 'str', and 'unicode' that can be used by programmers to implement the different printable representations of an object. Here is a simple example\nclass PrintObject(object):\n def __repr__(self):\n return 'repr'\n\n def __str__(self):\n return 'str'\n\n def __unicode__(self):\n return 'unicode'\n\nNow if you load this object into a python shell and play around with it you can see how these different methods are used to represent the printable representation of the object\nPython 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)\n[GCC 4.0.1 (Apple Inc. build 5493)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from printobject import PrintObject\n>>> printObj = PrintObject()\n>>> printObj\n>>> repr(printObj)\n'repr'\n>>> str(printObj)\n'str'\n>>> unicode(printObj)\nu'unicode'\n\nThe 'repr' method is used if you just type the instance and return\n>>> printObj\nrepr\n\nThe 'str' method is used if you use print on the instance\n>>> print(printObj)\nstr\n\nand the 'unicode' method is used if you use the instance in a unicode string.\n>>> print(u'%s' % printObj)\nunicode\n\nWhen and if you start writing your own classes these methods come in really handy.\n", "Regarding repr\n>>> help(repr)\nHelp on built-in function repr in module __builtin__:\n\nrepr(...)\n repr(object) -> string\n\n Return the canonical string representation of the object.\n For most object types, eval(repr(object)) == object.\n\n", "In the first case, the Python interpreter has automatically decoded the bytes passed to it in the characters by the terminal encoding since it is a unicode literal. Printing the repr() of that yields Unicode escape sequences.\nIn the second case, no decoding is done since it is a str literal, and so its repr() is composed of byte escape sequences corresponding to the characters in the terminal's encoding (in this case, GB2312).\n", "In the first case, you are getting the repr of a unicode object. This is conceptually a series of unicode characters, and the repr is giving you the sequence of unicode codepoints for these characters as an escape sequence. ie '\\u4e2a' is codepoint 20010 (0x4e2a is the hexidecimal representation), which is displayed as \"个\".\nIn the second case, you are getting the repr of a string object. Strings are essentially sequences of 8 bit values, with no internal knowledge about how these values relate to characters. When you print or enter those characters at the prompt, they are interpreted using your system's default encoding. When you print the repr of the object, you see the raw bytes that make it up - the printable ASCII characters are printed as is, everything else is shown as an escape sequence (ie \\xb8 is the value 184 (written 0xB8 in hexidecimal)). In your system's encoding (gb2312) the sequence of bytes [184, 246] ('\\xb8\\xf6') corresponds to the unicode codepoint 0x4e2a. However the string has no idea what encoding it is in, or even that it represents a sequence of characters, so it's repr just gives you the raw underlying data. To convert it into a unicode object, you need to decode it from this data, indicating how the raw data should be interpreted:\n>>> s=s.decode('gb2312')\n\nIn python3, this distinction between \"characters\" and \"data\" is made a bit more clear, as the str object is renamed as \"bytes\", and what are now unicode strings become just strings.\n" ]
[ 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002084728_python.txt
Q: Regex for removing whitespace def remove_whitespaces(value): "Remove all whitespaces" p = re.compile(r'\s+') return p.sub(' ', value) The above code strips tags but doesn't remove "all" whitespaces from the value. Thanks A: The fastest general approach eschews REs in favor of string's fast, powerful .translate method: import string identity = string.maketrans('', '') def remove_whitespace(value): return value.translate(identity, string.whitespace) In 2.6, it's even simpler, just return value.translate(None, string.whitespace) Note that this applies to "plain" Python 2.* strings, i.e., bytestrings -- Unicode's strings' .translate method is somewhat different -- it takes a single argument which must be a mapping of ord values for Unicode characters to Unicode strings, or None for deletion. I.e., taking advantage of dict's handy .fromkeys classmethod: nospace = dict.fromkeys(ord(c) for c in string.whitespace) def unicode_remove_whitespace(value): return value.translate(nospace) to remove exactly the same set of characters. Of course, Unicode also has more characters you could consider whitespace and want to remove -- so you'd probably want to build a mapping unicode_nospace based on information from module unicodedata, rather than using this simpler approach based on module string. A: p.sub(' ', value) should be p.sub('', value) The former replaces all whitespace with a single space, the latter replaces with nothing. A: Maybe value.join(p.split()) ''.join(value.split()) could work for you? A: re.sub('\s*', '', value) should also work! A: re.sub(r'\s', '', value) function works well for me, in this case. A: @OP, compile your regex pattern outside, so you don't have to call re.compile everytime you use the procedure. Also you are substituting back to one space, that is not removing spaces is it? p = re.compile(r'\s+') def remove_whitespaces(p,value): "Remove all whitespaces" return p.sub('', value) lastly, another method not using regex is to just split on whitespaces and joining them up again def remove_whitespaces(value): "Remove all whitespaces" return ''.join(value.split())
Regex for removing whitespace
def remove_whitespaces(value): "Remove all whitespaces" p = re.compile(r'\s+') return p.sub(' ', value) The above code strips tags but doesn't remove "all" whitespaces from the value. Thanks
[ "The fastest general approach eschews REs in favor of string's fast, powerful .translate method:\nimport string\nidentity = string.maketrans('', '')\n\ndef remove_whitespace(value):\n return value.translate(identity, string.whitespace)\n\nIn 2.6, it's even simpler, just\n return value.translate(None, string.whitespace)\n\nNote that this applies to \"plain\" Python 2.* strings, i.e., bytestrings -- Unicode's strings' .translate method is somewhat different -- it takes a single argument which must be a mapping of ord values for Unicode characters to Unicode strings, or None for deletion. I.e., taking advantage of dict's handy .fromkeys classmethod:\nnospace = dict.fromkeys(ord(c) for c in string.whitespace)\n\ndef unicode_remove_whitespace(value):\n return value.translate(nospace)\n\nto remove exactly the same set of characters. Of course, Unicode also has more characters you could consider whitespace and want to remove -- so you'd probably want to build a mapping unicode_nospace based on information from module unicodedata, rather than using this simpler approach based on module string.\n", "p.sub(' ', value)\n\nshould be\np.sub('', value)\n\nThe former replaces all whitespace with a single space, the latter replaces with nothing.\n", "Maybe value.join(p.split()) ''.join(value.split()) could work for you?\n", "re.sub('\\s*', '', value) should also work!\n", "re.sub(r'\\s', '', value) function works well for me, in this case.\n", "@OP, compile your regex pattern outside, so you don't have to call re.compile everytime you use the procedure. Also you are substituting back to one space, that is not removing spaces is it?\np = re.compile(r'\\s+')\ndef remove_whitespaces(p,value):\n \"Remove all whitespaces\" \n return p.sub('', value)\n\nlastly, another method not using regex is to just split on whitespaces and joining them up again\ndef remove_whitespaces(value):\n \"Remove all whitespaces\" \n return ''.join(value.split())\n\n" ]
[ 6, 3, 1, 1, 0, 0 ]
[]
[]
[ "function", "python", "regex" ]
stackoverflow_0002081991_function_python_regex.txt
Q: what is the encoding of this string,'base64' or 'utf-8'??? ,how can i get it readable print "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf".decode('base64')#no thanks and if i have '4-12个英文字母、数字和下划线' how can i get the string '4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf' is print '4-12个英文字母、数字和下划线'.decode('what')# i write: print u'4-12个英文字母、数字和下划线'.encode('unicode-escape') it print 4-12\xb8\xf6\xd3\xa2\xce\xc4\xd7\xd6\xc4\xb8\xa1\xa2\xca\xfd\xd7\xd6\xba\xcd\xcf\xc2\xbb\xae\xcf\xdf not the string "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf print u'4-12个英文字母、数字和下划线'.decode('utf-8').encode('unicode-escape') Traceback (most recent call last): File "<input>", line 1, in <module> File "encodings\utf_8.pyo", line 16, in decode UnicodeEncodeError: 'ascii' codec can't encode characters in position 4-27: ordinal not in range(128) no 'u' is also error: print '4-12个英文字母、数字和下划线'.decode('utf-8').encode('unicode-escape') Traceback (most recent call last): File "<input>", line 1, in <module> File "encodings\utf_8.pyo", line 16, in decode UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 4: unexpected code byte it's ok,thanks >>> print '4-12个英文字母、数字和下划线'.decode('gb2312').encode('unicode-escape') 4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf A: It's a Unicode representation. Try .decode('unicode-escape'). EDIT: For the second decode, what you use depends on your terminal/console settings. 'utf-8' is a sane starting point, then encode using 'unicode-escape' in order to get the Unicode escape sequences. A: It's encoded as a python unicode literal: >>> print u"4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf" 4-12个英文字母、数字和下划线 A: That string says "4-12个英文字母、数字和下划线", by just typing it in to a JavaScript interpreter (in this case, the WebKit inspector). It does not appear to have any base64 encoded information in it. Was there something else that you wanted to know? A: I guess it is python 3.x representation of unicode string. In python 2.x you will need u"" at the start of unicode string. A: Your final comment: >>> print '4-12个英文字母、数字和下划线'.decode('gb2312').encode('unicode-escape') would only work if your source file is saved in gb2312 encoding. Make sure you declare that at the top of your file, then you can use Unicode strings: # coding: gb2312 print u'4-12个英文字母、数字和下划线'.encode('unicode-escape')
what is the encoding of this string,'base64' or 'utf-8'??? ,how can i get it readable
print "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf".decode('base64')#no thanks and if i have '4-12个英文字母、数字和下划线' how can i get the string '4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf' is print '4-12个英文字母、数字和下划线'.decode('what')# i write: print u'4-12个英文字母、数字和下划线'.encode('unicode-escape') it print 4-12\xb8\xf6\xd3\xa2\xce\xc4\xd7\xd6\xc4\xb8\xa1\xa2\xca\xfd\xd7\xd6\xba\xcd\xcf\xc2\xbb\xae\xcf\xdf not the string "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf print u'4-12个英文字母、数字和下划线'.decode('utf-8').encode('unicode-escape') Traceback (most recent call last): File "<input>", line 1, in <module> File "encodings\utf_8.pyo", line 16, in decode UnicodeEncodeError: 'ascii' codec can't encode characters in position 4-27: ordinal not in range(128) no 'u' is also error: print '4-12个英文字母、数字和下划线'.decode('utf-8').encode('unicode-escape') Traceback (most recent call last): File "<input>", line 1, in <module> File "encodings\utf_8.pyo", line 16, in decode UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 4: unexpected code byte it's ok,thanks >>> print '4-12个英文字母、数字和下划线'.decode('gb2312').encode('unicode-escape') 4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf
[ "It's a Unicode representation. Try .decode('unicode-escape').\nEDIT:\nFor the second decode, what you use depends on your terminal/console settings. 'utf-8' is a sane starting point, then encode using 'unicode-escape' in order to get the Unicode escape sequences.\n", "It's encoded as a python unicode literal:\n>>> print u\"4-12\\u4e2a\\u82f1\\u6587\\u5b57\\u6bcd\\u3001\\u6570\\u5b57\\u548c\\u4e0b\\u5212\\u7ebf\"\n4-12个英文字母、数字和下划线\n\n", "That string says \"4-12个英文字母、数字和下划线\", by just typing it in to a JavaScript interpreter (in this case, the WebKit inspector).\nIt does not appear to have any base64 encoded information in it.\nWas there something else that you wanted to know?\n", "I guess it is python 3.x representation of unicode string.\nIn python 2.x you will need u\"\" at the start of unicode string.\n", "Your final comment:\n>>> print '4-12个英文字母、数字和下划线'.decode('gb2312').encode('unicode-escape')\n\nwould only work if your source file is saved in gb2312 encoding. Make sure you declare that at the top of your file, then you can use Unicode strings:\n# coding: gb2312\nprint u'4-12个英文字母、数字和下划线'.encode('unicode-escape')\n\n" ]
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0002083734_javascript_python.txt
Q: Is the new GIL in Python 3.2 sufficient to make the switch? I was reading this page on the new GIL found/to be found in Python 3.2 and I was wondering if it is the "killer feature" that will trigger a transition from Python 2.x to 3.x. What do you guys think? A: It's still a GIL. Python implementations without any GIL at all have been available for over a decade now. Python implementations that are much faster than CPython have been available for years. (Almost) noone uses them, which clearly shows that nobody cares about performance or the GIL, so I hardly see them being a "killer feature". Killer features are something that people actually want. A: The New GIL could be considered a killer feature of Python 3.2 if you use threading heavily. Integration of unladen swallow could also be considered a killer feature from a performance perspective. In general, I think py3k already has enough features to warrant switching; what it doesn't have is broad library support. Most libraries have already started looking at the transition, but it is a good ways away. By the time 3.2 comes out a year from now, I expect most of the libraries I depend on to have made strong progress with compatibility, and that is what would make me switch. A: 3.2 is roughly a year away. By that time hopefully there will be some progress on switching to py3k, it also coincides with the two year "grace" period that was supposedly promised by Guido to some big projects. I don't think that there will be any single "killer" feature, and even if anyone would need it, I'd imagine unicode support would be much higher on priority ladder.
Is the new GIL in Python 3.2 sufficient to make the switch?
I was reading this page on the new GIL found/to be found in Python 3.2 and I was wondering if it is the "killer feature" that will trigger a transition from Python 2.x to 3.x. What do you guys think?
[ "It's still a GIL. Python implementations without any GIL at all have been available for over a decade now. Python implementations that are much faster than CPython have been available for years.\n(Almost) noone uses them, which clearly shows that nobody cares about performance or the GIL, so I hardly see them being a \"killer feature\". Killer features are something that people actually want.\n", "The New GIL could be considered a killer feature of Python 3.2 if you use threading heavily. Integration of unladen swallow could also be considered a killer feature from a performance perspective.\nIn general, I think py3k already has enough features to warrant switching; what it doesn't have is broad library support. Most libraries have already started looking at the transition, but it is a good ways away. By the time 3.2 comes out a year from now, I expect most of the libraries I depend on to have made strong progress with compatibility, and that is what would make me switch.\n", "3.2 is roughly a year away. By that time hopefully there will be some progress on switching to py3k, it also coincides with the two year \"grace\" period that was supposedly promised by Guido to some big projects. I don't think that there will be any single \"killer\" feature, and even if anyone would need it, I'd imagine unicode support would be much higher on priority ladder.\n" ]
[ 9, 3, 0 ]
[]
[]
[ "gil", "python" ]
stackoverflow_0002086840_gil_python.txt