content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
35
137
Q: How do I find userid by login (Python under *NIX) I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find uid if I have login? I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody? A: You might want to have a look at the pwd module in the python stdlib, for example: import pwd pw = pwd.getpwnam("nobody") uid = pw.pw_uid it uses /etc/passwd (well, technically it uses the posix C API, so I suppose it might work on an OS if it didn't use /etc/passwd but exposed the needed functions) but is cleaner than parsing it manually A: Never directly scan /etc/passwd. For instance, on a Linux system I administer, the user accounts are not on /etc/passwd, but on a LDAP server. The correct way is to use getpwent/getgrent and related C functions (as in @TFKyle's answer), which will get the information on the correct way for each system (on Linux glibc, it reads /etc/nsswitch.conf to know which NSS dynamic libraries to load to get the information).
How do I find userid by login (Python under *NIX)
I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find uid if I have login? I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody?
[ "You might want to have a look at the pwd module in the python stdlib, for example:\nimport pwd\npw = pwd.getpwnam(\"nobody\")\nuid = pw.pw_uid\n\nit uses /etc/passwd (well, technically it uses the posix C API, so I suppose it might work on an OS if it didn't use /etc/passwd but exposed the needed functions) but is cleaner than parsing it manually\n", "Never directly scan /etc/passwd.\nFor instance, on a Linux system I administer, the user accounts are not on /etc/passwd, but on a LDAP server.\nThe correct way is to use getpwent/getgrent and related C functions (as in @TFKyle's answer), which will get the information on the correct way for each system (on Linux glibc, it reads /etc/nsswitch.conf to know which NSS dynamic libraries to load to get the information).\n" ]
[ 21, 5 ]
[]
[]
[ "linux", "process_management", "python", "unix" ]
stackoverflow_0000294470_linux_process_management_python_unix.txt
Q: Flattening one-to-many relationship in Django I have a few model classes with basic one-to-many relationships. For example, a book has many recipes, and each recipe has many ingredients: class Book(models.Model): name = models.CharField(max_length=64) class Recipe(models.Model): book = models.ForeignKey(Book) name = models.CharField(max_length=64) class Ingredient(models.Model): text = models.CharField(max_length=128) recipe = models.ForeignKey(Recipe) I'd like a flat list of all ingredients in all recipes from a particular book. What's the best way to express this in Python? If I was using LINQ, I might write something like this: var allIngredients = from recipe in book.Recipes from ingredient in recipe.Ingredients select ingredient; A: Actually, it looks like there's a better approach using filter: my_book = Book.objects.get(pk=1) all_ingredients = Ingredient.objects.filter(recipe__book=my_book) A: To print each recipe and its ingredients: mybook = Book.objects.get(name="Jason's Cookbook") for recipe in mybook.recipe_set.all(): print recipe.name for ingredient in recipe.ingredients: print ingredient.text And if you just want to get a list of all ingredient objects: mybook = Book.objects.get(name="Jason's Cookbook") ingredient_list = [] for recipe in mybook.recipe_set.all(): for ingredient in recipe.ingredients: ingredient_list.append(ingredient) Documentation.
Flattening one-to-many relationship in Django
I have a few model classes with basic one-to-many relationships. For example, a book has many recipes, and each recipe has many ingredients: class Book(models.Model): name = models.CharField(max_length=64) class Recipe(models.Model): book = models.ForeignKey(Book) name = models.CharField(max_length=64) class Ingredient(models.Model): text = models.CharField(max_length=128) recipe = models.ForeignKey(Recipe) I'd like a flat list of all ingredients in all recipes from a particular book. What's the best way to express this in Python? If I was using LINQ, I might write something like this: var allIngredients = from recipe in book.Recipes from ingredient in recipe.Ingredients select ingredient;
[ "Actually, it looks like there's a better approach using filter:\nmy_book = Book.objects.get(pk=1)\nall_ingredients = Ingredient.objects.filter(recipe__book=my_book)\n\n", "To print each recipe and its ingredients:\nmybook = Book.objects.get(name=\"Jason's Cookbook\")\nfor recipe in mybook.recipe_set.all():\n print recipe.name\n for ingredient in recipe.ingredients:\n print ingredient.text\n\nAnd if you just want to get a list of all ingredient objects:\nmybook = Book.objects.get(name=\"Jason's Cookbook\")\ningredient_list = []\nfor recipe in mybook.recipe_set.all():\n for ingredient in recipe.ingredients:\n ingredient_list.append(ingredient)\n\nDocumentation.\n" ]
[ 11, 1 ]
[]
[]
[ "django", "flatten", "list", "python" ]
stackoverflow_0000294712_django_flatten_list_python.txt
Q: Django multiselect checkboxes I have a list of objects, each with it's own checkbox, where the user can select multiple of these. The list is a result of a query. How can I mark in the view which checkboxes are already selected? There doesn't seem to be an in operator in the template language. I want something along the lines of: <input {% if id in selectedIds %}checked {% endif %}> A: You could use a templatetag like the one in this snippet comments: http://www.djangosnippets.org/snippets/177/ @register.filter def in_list(value,arg): return value in arg To be used in templates: The item is {% if item|in_list:list %} in list {% else %} not in list {% endif %} Not very smart, but it works.
Django multiselect checkboxes
I have a list of objects, each with it's own checkbox, where the user can select multiple of these. The list is a result of a query. How can I mark in the view which checkboxes are already selected? There doesn't seem to be an in operator in the template language. I want something along the lines of: <input {% if id in selectedIds %}checked {% endif %}>
[ "You could use a templatetag like the one in this snippet comments:\nhttp://www.djangosnippets.org/snippets/177/\n@register.filter\ndef in_list(value,arg):\n return value in arg\n\nTo be used in templates:\nThe item is \n{% if item|in_list:list %} \n in list \n{% else %} \n not in list\n{% endif %}\n\nNot very smart, but it works.\n" ]
[ 0 ]
[]
[]
[ "checkbox", "django", "django_templates", "python" ]
stackoverflow_0000286558_checkbox_django_django_templates_python.txt
Q: Inplace substitution from ConfigParser I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from ConfigParser. For example, I need to read self.post.id from a .cfg file and use it as a variable in the script. How do I achieve this? I suppose I was unclear in my query. The .cfg file looks something like: [head] test: me some variable : self.post.id This self.post.id is to be replaced at the run time, taking values from the script. A: test.ini: [head] var: self.post.id python: import ConfigParser class Test: def __init__(self): self.post = TestPost(5) def getPost(self): config = ConfigParser.ConfigParser() config.read('/path/to/test.ini') newvar = config.get('head', 'var') print eval(newvar) class TestPost: def __init__(self, id): self.id = id test = Test() test.getPost() # prints 5 A: This is a bit silly. You have a dynamic language, distributed in source form. You're trying to make what amounts to a change to the source. Which is easy-to-read, plain text Python. Why not just change the Python source and stop messing about with a configuration file? It's a lot easier to have a block of code like this # Change this for some reason or another x = self.post.id # Standard Configuration # x = self.post.somethingElse # Another Configuration # x = self.post.yetAnotherCase # A third configuration it's just as complex to change this as it is to change a configuration file. And your Python program is simpler and more clear.
Inplace substitution from ConfigParser
I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from ConfigParser. For example, I need to read self.post.id from a .cfg file and use it as a variable in the script. How do I achieve this? I suppose I was unclear in my query. The .cfg file looks something like: [head] test: me some variable : self.post.id This self.post.id is to be replaced at the run time, taking values from the script.
[ "test.ini:\n[head]\nvar: self.post.id\n\npython:\nimport ConfigParser\n\nclass Test:\n def __init__(self):\n self.post = TestPost(5)\n def getPost(self):\n config = ConfigParser.ConfigParser()\n config.read('/path/to/test.ini')\n newvar = config.get('head', 'var')\n print eval(newvar) \n\nclass TestPost:\n def __init__(self, id):\n self.id = id\n\ntest = Test()\ntest.getPost() # prints 5\n\n", "This is a bit silly.\nYou have a dynamic language, distributed in source form.\nYou're trying to make what amounts to a change to the source. Which is easy-to-read, plain text Python.\nWhy not just change the Python source and stop messing about with a configuration file?\nIt's a lot easier to have a block of code like this\n# Change this for some reason or another\nx = self.post.id # Standard Configuration \n# x = self.post.somethingElse # Another Configuration\n# x = self.post.yetAnotherCase # A third configuration\n\nit's just as complex to change this as it is to change a configuration file. And your Python program is simpler and more clear.\n" ]
[ 5, 0 ]
[]
[]
[ "configuration_files", "python" ]
stackoverflow_0000295028_configuration_files_python.txt
Q: How do I remove a specific number of files using python (version 2.5)? I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance. A: It sounds like what you really want is a temp file: http://docs.python.org/library/tempfile.html A: It is perfectly acceptable to have a 'cleanup()' function that you call at the end of your script, which will call 'os.remove()' on your files. A: Just call os.remove("path/to/file"). For example, to remove the file .emacs, call os.remove(".emacs") The path should be a str that's the pathname of the file. It may be relative or absolute.
How do I remove a specific number of files using python (version 2.5)?
I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance.
[ "It sounds like what you really want is a temp file:\nhttp://docs.python.org/library/tempfile.html\n", "It is perfectly acceptable to have a 'cleanup()' function that you call at the end of your script, which will call 'os.remove()' on your files.\n", "Just call os.remove(\"path/to/file\"). For example, to remove the file .emacs, call\nos.remove(\".emacs\")\n\nThe path should be a str that's the pathname of the file. It may be relative or absolute.\n" ]
[ 4, 0, -1 ]
[]
[]
[ "file", "python" ]
stackoverflow_0000296490_file_python.txt
Q: Which is more efficient in Python: standard imports or contextual imports? I apologize in advance if this question seems remedial. Which would be considered more efficient in Python: Standard import import logging try: ...some code... exception Exception, e: logging.error(e) ...or... Contextual import try: ...some code... exception Exception, e: import logging logging.error(e) A: Contextual imports are technically more efficient, but I think they can create other problems. Later, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any unforeseen issues in your code. A: It depends on how often you execute the contextual import. An import statement requires checking to see if the module exists, which has a non-zero cost. Lots of contextual imports will be a performance penalty for no real gain in simplicity. There's very little benefit, unless you are really sure that the import will be used rarely or never. Contextual imports inside if statements make sense, especially when it's done at the top level, which means precisely once. if someConfig: import this as bigDeal else: import that as bigDeal A: This is a microoptimization. Don't worry about it. A: They're essentially the same. The Python interpreter will only load a used module once, no matter how many times you import it. Changing the location of the import statement only has an effect on where the name is bound -- for example, if your import statement is inside a function, the name can only be used in that function. Generally, though, imports are usually done as close to the "top" of a file as possible. A: The performance differences between these two approaches will be very small in practice. I have never seen a case where this has made a difference that was noticeable. It is worth remembering that the python interpreter will only ever do the work of parsing the module once when it is 1st imported. In general you will end up with more maintainable code it you just import all the modules you need at the top of the file.
Which is more efficient in Python: standard imports or contextual imports?
I apologize in advance if this question seems remedial. Which would be considered more efficient in Python: Standard import import logging try: ...some code... exception Exception, e: logging.error(e) ...or... Contextual import try: ...some code... exception Exception, e: import logging logging.error(e)
[ "Contextual imports are technically more efficient, but I think they can create other problems.\nLater, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any unforeseen issues in your code.\n", "It depends on how often you execute the contextual import.\nAn import statement requires checking to see if the module exists, which has a non-zero cost.\nLots of contextual imports will be a performance penalty for no real gain in simplicity. There's very little benefit, unless you are really sure that the import will be used rarely or never.\nContextual imports inside if statements make sense, especially when it's done at the top level, which means precisely once. \nif someConfig:\n import this as bigDeal\nelse:\n import that as bigDeal\n\n", "This is a microoptimization. Don't worry about it.\n", "They're essentially the same. The Python interpreter will only load a used module once, no matter how many times you import it. Changing the location of the import statement only has an effect on where the name is bound -- for example, if your import statement is inside a function, the name can only be used in that function.\nGenerally, though, imports are usually done as close to the \"top\" of a file as possible.\n", "The performance differences between these two approaches will be very small in practice. I have never seen a case where this has made a difference that was noticeable. \nIt is worth remembering that the python interpreter will only ever do the work of parsing the module once when it is 1st imported.\nIn general you will end up with more maintainable code it you just import all the modules you need at the top of the file.\n" ]
[ 6, 3, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000296270_python.txt
Q: Pycurl WRITEDATA WRITEFUNCTION collision/crash How do I turnoff WRITEFUNCTION and WRITEDATA? Using pycurl I have a class call curlUtil. In it I have pageAsString (self, URL) which returns a string. To do this I setopt WRITEFUNCTION. Now in downloadFile (self, URL, fn, overwrite=0) I do an open and self.c.Setopt (pycurl.WRITEFUNCTION, 0) which cause problems. Int is not a valid argument. I then assumed WRITEDATA would overwrite the value or there would be a NOWRITEFUNCTION commend. NOWRITEFUNCTION didn't exist so I just used WRITEDATA and Python crashed. I wrote a quick func called reboot() which closes curl, opens it again, and calls reset to put it in the default state. I call it in both pageAsString and downloadFile and there is no problem at all. But, I don't want to reinitialize curl. There might be some special options I set. How do I turnoff WRITEFUNCTION and WRITEDATA? A: using the writefunction, instead of turning it off would save you a lot off trouble. you might want to rewrite your pageAsString by utilizing WRITEFUNCTION.. as an example: from cStringIO import StringIO c = pycurl.Curl() buffer = StringIO() c.setopt(pycurl.WRITEFUNCTION, buffer.write) c.setopt(pycurl.URL, "http://example.com") c.perform() ... buffer.getvalue() # will return the data fetched.
Pycurl WRITEDATA WRITEFUNCTION collision/crash
How do I turnoff WRITEFUNCTION and WRITEDATA? Using pycurl I have a class call curlUtil. In it I have pageAsString (self, URL) which returns a string. To do this I setopt WRITEFUNCTION. Now in downloadFile (self, URL, fn, overwrite=0) I do an open and self.c.Setopt (pycurl.WRITEFUNCTION, 0) which cause problems. Int is not a valid argument. I then assumed WRITEDATA would overwrite the value or there would be a NOWRITEFUNCTION commend. NOWRITEFUNCTION didn't exist so I just used WRITEDATA and Python crashed. I wrote a quick func called reboot() which closes curl, opens it again, and calls reset to put it in the default state. I call it in both pageAsString and downloadFile and there is no problem at all. But, I don't want to reinitialize curl. There might be some special options I set. How do I turnoff WRITEFUNCTION and WRITEDATA?
[ "using the writefunction, instead of turning it off would save you a lot off trouble. you might want to rewrite your pageAsString by utilizing WRITEFUNCTION..\nas an example: \nfrom cStringIO import StringIO\nc = pycurl.Curl()\nbuffer = StringIO()\nc.setopt(pycurl.WRITEFUNCTION, buffer.write)\nc.setopt(pycurl.URL, \"http://example.com\")\nc.perform()\n...\nbuffer.getvalue() # will return the data fetched.\n\n" ]
[ 2 ]
[]
[]
[ "crash", "libcurl", "pycurl", "python" ]
stackoverflow_0000294960_crash_libcurl_pycurl_python.txt
Q: how do i use python libraries in C++? I want to use the nltk libraries in c++. Is there a glue language/mechanism I can use to do this? Reason: I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time. Thanks A: Although calling c++ libs from python is more normal - you can call a python module from c++ by bascially calling the python intepreter and have it execute the python source. This is called embedding Alternatively the boost.python library makes it very easy. A: You can also try the Boost.Python library; which has this capability. This library is mainly used to expose C++ to Python, but can be used the other way around. A: Pyrex can be cleanly used for this purpose. There's an example in the source-code release. A: I haven't tried directly calling Python functions from C++, but here are some alternative ideas... Generally, it's easier to call C++ code from a high-level language like Python than the other way around. If you're interested in this approach, then you could create a C++ codebase and access it from Python. You could either directly use the external API provided by python [it should be described somewhere in the Python docs] or use a tool like SWIG to automate the C++-to-Python wrapping process. Depending on how you want to use the library, you could alternatively create Python scripts which you call from C++ with the exec* functions.
how do i use python libraries in C++?
I want to use the nltk libraries in c++. Is there a glue language/mechanism I can use to do this? Reason: I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time. Thanks
[ "Although calling c++ libs from python is more normal - you can call a python module from c++ by bascially calling the python intepreter and have it execute the python source.\nThis is called embedding\nAlternatively the boost.python library makes it very easy.\n", "You can also try the Boost.Python library; which has this capability. This library is mainly used to expose C++ to Python, but can be used the other way around.\n", "Pyrex can be cleanly used for this purpose. There's an example in the source-code release.\n", "I haven't tried directly calling Python functions from C++, but here are some alternative ideas...\nGenerally, it's easier to call C++ code from a high-level language like Python than the other way around. If you're interested in this approach, then you could create a C++ codebase and access it from Python. You could either directly use the external API provided by python [it should be described somewhere in the Python docs] or use a tool like SWIG to automate the C++-to-Python wrapping process.\nDepending on how you want to use the library, you could alternatively create Python scripts which you call from C++ with the exec* functions.\n" ]
[ 17, 14, 2, 1 ]
[]
[]
[ "c++", "nltk", "python" ]
stackoverflow_0000297112_c++_nltk_python.txt
Q: How do I count bytecodes in Python so I can modify sys.setcheckinterval appropriately I have a port scanning application that uses work queues and threads. It uses simple TCP connections and spends a lot of time waiting for packets to come back (up to half a second). Thus the threads don't need to fully execute (i.e. first half sends a packet, context switch, does stuff, comes back to thread which has network data waiting for it). I suspect I can improve performance by modifying the sys.setcheckinterval from the default of 100 (which lets up to 100 bytecodes execute before switching to another thread). But without knowing how many bytecodes are actually executing in a thread or function I'm flying blind and simply guessing values, testing and relying on the testing shows a measurable difference (which is difficult since the amount of code being executed is minimal; a simple socket connection, thus network jitter will likely affect any measurements more than changing sys.setcheckinterval). Thus I would like to find out how many bytecodes are in certain code executions (i.e. total for a function or in execution of a thread) so I can make more intelligent guesses at what to set sys.setcheckinterval to. A: For higher level (method, class) wise, dis module should help. But if one needs finer grain, tracing will be unavoidable. Tracing does operate line by line basis but explained here is a great hack to dive deeper at the bytecode level. Hats off to Ned Batchelder. A: Reasoning about a system of this complexity will rarely produce the right answer. Measure the results, and use the setting that runs the fastest. If as you say, testing can't measure the difference in various settings of setcheckinterval, then why bother changing it? Only measurable differences are interesting. If your test run is too short to provide meaningful data, then make the run longer until it does. A: " I suspect I can improve performance by modifying the sys.setcheckinterval" This rarely works. Correct behavior can't depend on timing -- you can't control timing. Slight changes on OS, hardware, patch level of Python or phase of the moon will change how your application behaves. The select module is what you use to wait for I/O's. Your application can be structured as a main loop that does the select and queues up work for other threads. The other threads are waiting for an entries in their queue of requests to process.
How do I count bytecodes in Python so I can modify sys.setcheckinterval appropriately
I have a port scanning application that uses work queues and threads. It uses simple TCP connections and spends a lot of time waiting for packets to come back (up to half a second). Thus the threads don't need to fully execute (i.e. first half sends a packet, context switch, does stuff, comes back to thread which has network data waiting for it). I suspect I can improve performance by modifying the sys.setcheckinterval from the default of 100 (which lets up to 100 bytecodes execute before switching to another thread). But without knowing how many bytecodes are actually executing in a thread or function I'm flying blind and simply guessing values, testing and relying on the testing shows a measurable difference (which is difficult since the amount of code being executed is minimal; a simple socket connection, thus network jitter will likely affect any measurements more than changing sys.setcheckinterval). Thus I would like to find out how many bytecodes are in certain code executions (i.e. total for a function or in execution of a thread) so I can make more intelligent guesses at what to set sys.setcheckinterval to.
[ "For higher level (method, class) wise, dis module should help.\nBut if one needs finer grain, tracing will be unavoidable. Tracing does operate line by line basis but explained here is a great hack to dive deeper at the bytecode level. Hats off to Ned Batchelder.\n", "Reasoning about a system of this complexity will rarely produce the right answer. Measure the results, and use the setting that runs the fastest. If as you say, testing can't measure the difference in various settings of setcheckinterval, then why bother changing it? Only measurable differences are interesting. If your test run is too short to provide meaningful data, then make the run longer until it does.\n", "\" I suspect I can improve performance by modifying the sys.setcheckinterval\" \nThis rarely works. Correct behavior can't depend on timing -- you can't control timing. Slight changes on OS, hardware, patch level of Python or phase of the moon will change how your application behaves.\nThe select module is what you use to wait for I/O's. Your application can be structured as a main loop that does the select and queues up work for other threads. The other threads are waiting for an entries in their queue of requests to process.\n" ]
[ 3, 2, 1 ]
[]
[]
[ "internals", "multithreading", "performance", "python" ]
stackoverflow_0000294963_internals_multithreading_performance_python.txt
Q: Recommended data format for describing the rules of chess I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves. I would prefer the format to be: textual human readable based on a standard (e.g. YAML, XML) easily parsable in a variety of languages But I am willing to sacrifice any of these for a suitable solution. My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format? A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point? Edit: In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner. A: Let's think. We're describing objects (locations and pieces) with states and behaviors. We need to note a current state and an ever-changing set of allowed state changes from a current state. This is programming. You don't want some "meta-language" that you can then parse in a regular programming language. Just use a programming language. Start with ordinary class definitions in an ordinary language. Get it all to work. Then, those class definitions are the definition of chess. With only miniscule exceptions, all programming languages are Textual Human readable Reasonably standardized Easily parsed by their respective compilers or interpreters. Just pick a language, and you're done. Since it will take a while to work out the nuances, you'll probably be happier with a dynamic language like Python or Ruby than with a static language like Java or C#. If you want portability. Pick a portable language. If you want the language embedded in a "larger" application, then, pick the language for your "larger" application. Since the original requirements were incomplete, a secondary minor issue is how to have code that runs in conjunction with multiple clients. Don't have clients in multiple languages. Pick one. Java, for example, and stick with it. If you must have clients in multiple languages, then you need a language you can embed in all three language run-time environments. You have two choices. Embed an interpreter. For example Python, Tcl and JavaScript are lightweight interpreters that you can call from C or C# programs. This approach works for browsers, it can work for you. Java, via JNI can make use of this, also. There are BPEL rules engines that you can try this with. Spawn an interpreter as a separate subprocess. Open a named pipe or socket or something between your app and your spawned interpreter. Your Java and C# clients can talk with a Python subprocess. Your Python server can simply use this code. A: Edit: Overly wordy answer deleted. The short answer is, write the rules in Python. Use Iron Python to interface that to the C# client, and Jython for the Java client. A: This is answering the followup question :-) I can point out that one of the most popular chess servers around documents its protocol here (Warning, FTP link, and does not support passive FTP), but only to write interfaces to it, not for any other purpose. You could start writing a client for this server as a learning experience. One thing that's relevant is that good chess servers offer many more features than just a move relay. That said, there is a more basic protocol used to interface to chess engines, documented here. Oh, and by the way: Board Representation at Wikipedia Anything beyond board representation belongs to the program itself, as many have already pointed out. A: There's already a widely used format specific to chess called Portable Game Notation. There's also Smart Game Format, which is adaptable to many different games. A: I would suggest Prolog for describing the rules. A: What I've gathered from the responses so far: For chess board data representations: See the Wikipedia article on [chess board representations](http://en.wikipedia.org/wiki/Board_representation_(chess)). For chess move data representations: See the Wikipedia articles on Portable Game Notation and Algebraic Chess Notation For chess rules representations: This must be done using a programming language. If one wants to reduce the amount of code written in the case where the rules will be implemented in more than one language then there are a few options Use a language where an embedable interpreter exists for the target languages (e.g. Lua, Python). Use a Virtual Machine that the common languages can compile to (e.g. IronPython for C#, JPython for Java). Use a background daemon or sub-process for the rules with which the target languages can communicate. Reimplement the rules algorithms in each target language. Although I would have liked a declarative syntax that could have been interpreted by mutliple languages to enforce the rules of chess my research has lead me to no likely candidate. I have a suspicion that Constraint Based Programming may be a possible route given that solvers exist for many languages but I am not sure they would truly fulfill this requirement. Thanks for all the attention and perhaps in the future an answer will appear. A: Drools has a modern human readable rules implementation -- https://www.jboss.org/drools/. They have a way users can enter their rules in Excel. A lot more users can understand what is in Excel than in other tools. A: To represent the current state of a board (including castling possibilities etc) you can use Forsyth-Edwards Notation, which will give you a short ascii representation. e.g.: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 Would be the opening board position. Then to represent a particular move from a position you could use numeric move notation (as used in correspondence chess), which give you a short (4-5 digits) representation of a move on the board. As to represent the rules - I'd love to know myself. Currently the rules for my chess engine are just written in Python and probably aren't as declarative as I'd like. A: I would agree with the comment left by ΤΖΩΤΖΙΟΥ, viz. just let the server do the validation and let the clients submit a potential move. If that's not the way you want to take the design, then just write the rules in Python as suggested by S. Lott and others. It really shouldn't be that hard. You can break the rules down into three major categories: - Rules that rely on the state of the board (castling, en passant, draws, check, checkmate, passing through check, is it even this player's turn, etc.) - Rules that apply to all pieces (can't occupy the same square as another piece of your own colour, moving to a square w/ opponent's piece == capture, can't move off the board) - Rules that apply to each individual piece. (pawns can't move backwards, castles can't move diagonally, etc) Each rule can be implemented as a function, and then for each half-move, validity is determined by seeing if it passes all of the validations. For each potential move submitted, you would just need to check the rules in the following order: is the proposed move potentially valid? (the right "shape" for the piece) does it fit the restraints of the board? (is the piece blocked, would it move off the edge) does the move violate state requirements? (am I in check after this move? do I move through check? is this en passant capture legal?) If all of those are ok, then the server should accept the move as legal…
Recommended data format for describing the rules of chess
I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves. I would prefer the format to be: textual human readable based on a standard (e.g. YAML, XML) easily parsable in a variety of languages But I am willing to sacrifice any of these for a suitable solution. My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format? A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point? Edit: In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner.
[ "Let's think. We're describing objects (locations and pieces) with states and behaviors. We need to note a current state and an ever-changing set of allowed state changes from a current state.\nThis is programming. You don't want some \"meta-language\" that you can then parse in a regular programming language. Just use a programming language.\nStart with ordinary class definitions in an ordinary language. Get it all to work. Then, those class definitions are the definition of chess. \nWith only miniscule exceptions, all programming languages are\n\nTextual\nHuman readable\nReasonably standardized\nEasily parsed by their respective compilers or interpreters.\n\nJust pick a language, and you're done. Since it will take a while to work out the nuances, you'll probably be happier with a dynamic language like Python or Ruby than with a static language like Java or C#.\nIf you want portability. Pick a portable language. If you want the language embedded in a \"larger\" application, then, pick the language for your \"larger\" application.\n\nSince the original requirements were incomplete, a secondary minor issue is how to have code that runs in conjunction with multiple clients.\n\nDon't have clients in multiple languages. Pick one. Java, for example, and stick with it. \nIf you must have clients in multiple languages, then you need a language you can embed in all three language run-time environments. You have two choices.\n\nEmbed an interpreter. For example Python, Tcl and JavaScript are lightweight interpreters that you can call from C or C# programs. This approach works for browsers, it can work for you. Java, via JNI can make use of this, also. There are BPEL rules engines that you can try this with.\nSpawn an interpreter as a separate subprocess. Open a named pipe or socket or something between your app and your spawned interpreter. Your Java and C# clients can talk with a Python subprocess. Your Python server can simply use this code.\n\n\n", "Edit: Overly wordy answer deleted.\nThe short answer is, write the rules in Python. Use Iron Python to interface that to the C# client, and Jython for the Java client.\n", "This is answering the followup question :-)\nI can point out that one of the most popular chess servers around documents its protocol here (Warning, FTP link, and does not support passive FTP), but only to write interfaces to it, not for any other purpose. You could start writing a client for this server as a learning experience.\nOne thing that's relevant is that good chess servers offer many more features than just a move relay.\nThat said, there is a more basic protocol used to interface to chess engines, documented here.\nOh, and by the way: Board Representation at Wikipedia\nAnything beyond board representation belongs to the program itself, as many have already pointed out.\n", "There's already a widely used format specific to chess called Portable Game Notation. There's also Smart Game Format, which is adaptable to many different games.\n", "I would suggest Prolog for describing the rules. \n", "What I've gathered from the responses so far:\nFor chess board data representations:\nSee the Wikipedia article on [chess board representations](http://en.wikipedia.org/wiki/Board_representation_(chess)).\nFor chess move data representations:\nSee the Wikipedia articles on Portable Game Notation and Algebraic Chess Notation\nFor chess rules representations:\nThis must be done using a programming language. If one wants to reduce the amount of code written in the case where the rules will be implemented in more than one language then there are a few options\n\nUse a language where an embedable interpreter exists for the target languages (e.g. Lua, Python).\nUse a Virtual Machine that the common languages can compile to (e.g. IronPython for C#, JPython for Java).\nUse a background daemon or sub-process for the rules with which the target languages can communicate.\nReimplement the rules algorithms in each target language.\n\nAlthough I would have liked a declarative syntax that could have been interpreted by mutliple languages to enforce the rules of chess my research has lead me to no likely candidate. I have a suspicion that Constraint Based Programming may be a possible route given that solvers exist for many languages but I am not sure they would truly fulfill this requirement. Thanks for all the attention and perhaps in the future an answer will appear.\n", "Drools has a modern human readable rules implementation -- https://www.jboss.org/drools/.\nThey have a way users can enter their rules in Excel. A lot more users can understand what is in Excel than in other tools.\n", "To represent the current state of a board (including castling possibilities etc) you can use \nForsyth-Edwards Notation, which will give you a short ascii representation. e.g.:\n\nrnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\n\nWould be the opening board position.\nThen to represent a particular move from a position you could use numeric move notation (as used in correspondence chess), which give you a short (4-5 digits) representation of a move on the board.\nAs to represent the rules - I'd love to know myself. Currently the rules for my chess engine are just written in Python and probably aren't as declarative as I'd like.\n", "I would agree with the comment left by ΤΖΩΤΖΙΟΥ, viz. just let the server do the validation and let the clients submit a potential move. If that's not the way you want to take the design, then just write the rules in Python as suggested by S. Lott and others.\nIt really shouldn't be that hard. You can break the rules down into three major categories:\n - Rules that rely on the state of the board (castling, en passant, draws, check, checkmate, passing through check, is it even this player's turn, etc.)\n - Rules that apply to all pieces (can't occupy the same square as another piece of your own colour, moving to a square w/ opponent's piece == capture, can't move off the board)\n - Rules that apply to each individual piece. (pawns can't move backwards, castles can't move diagonally, etc)\nEach rule can be implemented as a function, and then for each half-move, validity is determined by seeing if it passes all of the validations.\nFor each potential move submitted, you would just need to check the rules in the following order:\n\nis the proposed move potentially valid? (the right \"shape\" for the piece)\ndoes it fit the restraints of the board? (is the piece blocked, would it move off the edge)\ndoes the move violate state requirements? (am I in check after this move? do I move through check? is this en passant capture legal?)\n\nIf all of those are ok, then the server should accept the move as legal…\n" ]
[ 4, 2, 2, 2, 2, 2, 0, 0, 0 ]
[]
[]
[ "c#", "chess", "dataformat", "java", "python" ]
stackoverflow_0000194289_c#_chess_dataformat_java_python.txt
Q: Formatting dict.items() for wxPython I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like [(u'BC',45) (u'CHM',25) (u'CPM',30)] I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython. I've tried iterating through the list and tuples. If I use a print statement, the output is fine. But when I replace the print statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple. I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both. Any suggestions? Edit: Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like: BC 45 CHM 25 CMP 30 Nothing special, just simply pulling each value from each tuple and making a visual list. I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it. A: There is no built-in dictionary method that would return your desired result. You can, however, achieve your goal by creating a helper function that will format the dictionary, e.g.: def getNiceDictRepr(aDict): return '\n'.join('%s %s' % t for t in aDict.iteritems()) This will produce your exact desired output: >>> myDict = dict([(u'BC',45), (u'CHM',25), (u'CPM',30)]) >>> print getNiceDictRepr(myDict) BC 45 CHM 25 CPM 30 Then, in your application code, you can use it by passing it to SetValue: self.textCtrl.SetValue(getNiceDictRepr(myDict)) A: Maybe the pretty print module will help: >>> import pprint >>> pprint.pformat({ "my key": "my value"}) "{'my key': 'my value'}" >>> A: text_for_display = '\n'.join(item + u' ' + unicode(value) for item, value in my_dictionary.items()) A: use % formatting (known in C as sprintf), e.g: "%10s - %d" % dict.items()[0] Number of % conversion specifications in the format string should match tuple length, in the dict.items() case, 2. The result of the string formatting operator is a string, so that using it as an argument to SetValue() is no problem. To translate the whole dict to a string: '\n'.join(("%10s - %d" % t) for t in dict.items()) The format conversion types are specified in the doc. A: That data seems much better displayed as a Table/Grid. A: I figured out a "better" way of formatting the output. As usual, I was trying to nuke it out when a more elegant method will do. for key, value in sorted(self.dict.items()): self.current_list.WriteText(key + " " + str(self.dict[key]) + "\n") This way also sorts the dictionary alphabetically, which is a big help when identifying items that have already been selected or used.
Formatting dict.items() for wxPython
I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like [(u'BC',45) (u'CHM',25) (u'CPM',30)] I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a nice format that is also compatible with the SetValue() method of wxPython. I've tried iterating through the list and tuples. If I use a print statement, the output is fine. But when I replace the print statement with SetValue(), it only seems to get the last value of each tuple, rather than both items in the tuple. I've also tried creating a string and passing that string to SetValue() but, again, I can only get one item in the tuple or the other, not both. Any suggestions? Edit: Yes, I am passing the results of the dictionary.items() to a text field in a wxPython application. Rather than having the results like above, I'm simply looking for something like: BC 45 CHM 25 CMP 30 Nothing special, just simply pulling each value from each tuple and making a visual list. I have tried making a string format and passing that to SetValue() but it gets hung up on the two values in the tuple. It will either double print each string and add the integers together or it simply returns the integer, depending on how I format it.
[ "There is no built-in dictionary method that would return your desired result.\nYou can, however, achieve your goal by creating a helper function that will format the dictionary, e.g.:\ndef getNiceDictRepr(aDict):\n return '\\n'.join('%s %s' % t for t in aDict.iteritems())\n\nThis will produce your exact desired output:\n>>> myDict = dict([(u'BC',45), (u'CHM',25), (u'CPM',30)])\n>>> print getNiceDictRepr(myDict)\nBC 45\nCHM 25\nCPM 30\n\nThen, in your application code, you can use it by passing it to SetValue:\nself.textCtrl.SetValue(getNiceDictRepr(myDict))\n\n", "Maybe the pretty print module will help:\n>>> import pprint\n>>> pprint.pformat({ \"my key\": \"my value\"})\n\"{'my key': 'my value'}\"\n>>> \n\n", "text_for_display = '\\n'.join(item + u' ' + unicode(value) for item, value in my_dictionary.items())\n\n", "use % formatting (known in C as sprintf), e.g:\n\"%10s - %d\" % dict.items()[0]\n\nNumber of % conversion specifications in the format string should match tuple length, in the dict.items() case, 2. The result of the string formatting operator is a string, so that using it as an argument to SetValue() is no problem. To translate the whole dict to a string:\n'\\n'.join((\"%10s - %d\" % t) for t in dict.items())\n\nThe format conversion types are specified in the doc.\n", "That data seems much better displayed as a Table/Grid.\n", "I figured out a \"better\" way of formatting the output. As usual, I was trying to nuke it out when a more elegant method will do.\nfor key, value in sorted(self.dict.items()):\n self.current_list.WriteText(key + \" \" + str(self.dict[key]) + \"\\n\")\n\nThis way also sorts the dictionary alphabetically, which is a big help when identifying items that have already been selected or used.\n" ]
[ 5, 0, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "python", "wxpython" ]
stackoverflow_0000237859_dictionary_python_wxpython.txt
Q: python (jython) archiving library Is there a neat archiving library that automatically handles archiving a folder or directories for you out there? I am using Jython, so Java libs are also open for use. -UPDATE- Also Im looking for timestamp archiving. ie archive-dir/2008/11/16/zipfilebypreference.zip then the next day call it again and it creates another folder. Im sure there is something out there on the internet, who knows? A: You have either the: gzip library used here in a Jython servlet:   import javax.servlet.http.HttpServlet import cStringIO import gzip import string def compressBuf(buf): zbuf = cStringIO.StringIO() zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 6) zfile.write(buf) zfile.close() return zbuf.getvalue() or the direct used of java.util.zip as illustrated here, for one file, or for a all directory content. A: You can use java.util.zip, when I was using Jython the built in zip library in python didn't work
python (jython) archiving library
Is there a neat archiving library that automatically handles archiving a folder or directories for you out there? I am using Jython, so Java libs are also open for use. -UPDATE- Also Im looking for timestamp archiving. ie archive-dir/2008/11/16/zipfilebypreference.zip then the next day call it again and it creates another folder. Im sure there is something out there on the internet, who knows?
[ "You have either the:\n\ngzip library used here in a Jython servlet: \n\n \nimport javax.servlet.http.HttpServlet\n\nimport cStringIO\nimport gzip\nimport string\n\ndef compressBuf(buf):\n zbuf = cStringIO.StringIO()\n zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 6)\n zfile.write(buf)\n zfile.close()\n return zbuf.getvalue()\n\n\nor the direct used of java.util.zip as illustrated here, for one file, or for a all directory content.\n\n", "You can use java.util.zip, when I was using Jython the built in zip library in python didn't work \n" ]
[ 3, 1 ]
[]
[]
[ "archive", "java", "jython", "python" ]
stackoverflow_0000298004_archive_java_jython_python.txt
Q: Python MySQL Statement returning Error hey, I'm very new to all this so please excuse stupidity :) import os import MySQLdb import time db = MySQLdb.connect(host="localhost", user="root", passwd="********", db="workspace") cursor = db.cursor() tailoutputfile = os.popen('tail -f syslog.log') while 1: x = tailoutputfile.readline() if len(x)==0: break y = x.split() if y[2] == 'BAD': timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") if y[2] == 'GOOD': print y[4] + '\t' + y[7] so i run the program and this is the error message I am getting user@machine:~/$ python reader.py Traceback (most recent call last): File "reader.py", line 17, in ? cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[4], y[7]' at line 1") user@machine:~/$ So i'm assuming that the error is obviously coming from the SQL Statement cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") Here is an example of what y[4] and y[7] will look like. YES Mail.Sent.To.User:user@work.com.11.2.2008:23.17 Is this error happening because I should be escaping those values before I try and Insert them into the Database? Or am I completely missing the point?? Any help would be appreciated! thanks in advance. A: As pointed out, you're failing to copy the Python variable values into the query, only their names, which mean nothing to MySQL. However the direct string concatenation option: cursor.execute("INSERT INTO releases (date, cat, name) VALUES ('%s', '%s', '%s')" % (timestring, y[4], y[7])) is dangerous and should never be used. If those strings have out-of-bounds characters like ' or \ in, you've got an SQL injection leading to possible security compromise. Maybe in your particular app that can never happen, but it's still a very bad practice, which beginners' SQL tutorials really need to stop using. The solution using MySQLdb is to let the DBAPI layer take care of inserting and escaping parameter values into SQL for you, instead of trying to % it yourself: cursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7])) A: cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") should be cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, '%s', '%s')" % (y[4], y[7])) Your best bet to debug things like this is to put the query into a variable and use that: query = "INSERT INTO releases (date, cat, name) values (timestring, '%s', '%s')" % (y[4], y[7]) print query cursor.execute(query) That print statement would make it very obvious what the problem is. If you're going to be using list variables a lot like this it can get very confusing, consider using the list just once and putting the variables into a dictionary. It's a bit longer to type, but is much, much easier to keep track of what's going on. A: never use "direct string concatenation" with SQL, because it's not secure, more correct variant: cursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7])) it automatically escaping forbidden symbols in values (such as ", ' etc)
Python MySQL Statement returning Error
hey, I'm very new to all this so please excuse stupidity :) import os import MySQLdb import time db = MySQLdb.connect(host="localhost", user="root", passwd="********", db="workspace") cursor = db.cursor() tailoutputfile = os.popen('tail -f syslog.log') while 1: x = tailoutputfile.readline() if len(x)==0: break y = x.split() if y[2] == 'BAD': timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") if y[2] == 'GOOD': print y[4] + '\t' + y[7] so i run the program and this is the error message I am getting user@machine:~/$ python reader.py Traceback (most recent call last): File "reader.py", line 17, in ? cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[4], y[7]' at line 1") user@machine:~/$ So i'm assuming that the error is obviously coming from the SQL Statement cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") Here is an example of what y[4] and y[7] will look like. YES Mail.Sent.To.User:user@work.com.11.2.2008:23.17 Is this error happening because I should be escaping those values before I try and Insert them into the Database? Or am I completely missing the point?? Any help would be appreciated! thanks in advance.
[ "As pointed out, you're failing to copy the Python variable values into the query, only their names, which mean nothing to MySQL.\nHowever the direct string concatenation option:\ncursor.execute(\"INSERT INTO releases (date, cat, name) VALUES ('%s', '%s', '%s')\" % (timestring, y[4], y[7]))\n\nis dangerous and should never be used. If those strings have out-of-bounds characters like ' or \\ in, you've got an SQL injection leading to possible security compromise. Maybe in your particular app that can never happen, but it's still a very bad practice, which beginners' SQL tutorials really need to stop using.\nThe solution using MySQLdb is to let the DBAPI layer take care of inserting and escaping parameter values into SQL for you, instead of trying to % it yourself:\ncursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7]))\n\n", " cursor.execute(\"INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]\")\n\nshould be\n cursor.execute(\"INSERT INTO releases (date, cat, name) values (timestring, '%s', '%s')\" % (y[4], y[7]))\n\nYour best bet to debug things like this is to put the query into a variable and use that:\nquery = \"INSERT INTO releases (date, cat, name) values (timestring, '%s', '%s')\" % (y[4], y[7])\nprint query\ncursor.execute(query)\n\nThat print statement would make it very obvious what the problem is.\nIf you're going to be using list variables a lot like this it can get very confusing, consider using the list just once and putting the variables into a dictionary. It's a bit longer to type, but is much, much easier to keep track of what's going on.\n", "never use \"direct string concatenation\" with SQL, because it's not secure, more correct variant:\ncursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7]))\n\nit automatically escaping forbidden symbols in values (such as \", ' etc)\n" ]
[ 10, 4, 1 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0000257563_python_sql.txt
Q: How to make the keywords recognizable in simpleparse? I've been trying to create a parser using simpleparse. I've defined the grammar like this: <w> := [ \n]* statement_list := statement,(w,statement)? statement := "MOVE",w,word,w,"TO",w,(word,w)+ word := [A-Za-z],[A-Za-z0-9]*,([-]+,[A-Za-z0-9]+)* Now if I try to parse a string MOVE ABC-DEF TO ABC MOVE DDD TO XXX The second statement gets interpreted as parameters of the first one... This sucks and is obviously not what I want. I have been able to get this working using pyparsing like this: word = Word(alphas,alphanums+'-') statement = "MOVE"+word+"TO"+word statement_list = OneOrMore(statement.setResultsName('statement',True)) Is there any way to get this working in simpleparse as well? EDIT: clarification below I am not trying to achieve a line-based grammar. What I would like to see being parsed is: Simple case MOVE AA TO BB More comlex case MOVE AA TO BB CC DD EE FF Several of the above statments MOVE AA TO BB CC MOVE CC TO EE MOVE EE TO FF GG HH IIJJK A: The grammar is currently ambiguous. On paper you cannot parse if "MOVE A TO B MOVE C TO D" is two statements, or one statement with particular badly named destinations. You have two answers. You may like neither. You explicitly make your WORD not match any reserved word. That is, you specifically disallow matching MOVE or TO. This is equivalent to saying "MOVE is not a valid parameter name". This makes "MOVE TL TO TM TN TO" an error. You modify your grammar so that you can tell where the statement ends. You could add commas "MOVE AA TO BB, CC MOVE TM TO TN, TO, TP". You could add semi-colons or blank lines at the end of statements. You could require that MOVE be the least indented, like Python.
How to make the keywords recognizable in simpleparse?
I've been trying to create a parser using simpleparse. I've defined the grammar like this: <w> := [ \n]* statement_list := statement,(w,statement)? statement := "MOVE",w,word,w,"TO",w,(word,w)+ word := [A-Za-z],[A-Za-z0-9]*,([-]+,[A-Za-z0-9]+)* Now if I try to parse a string MOVE ABC-DEF TO ABC MOVE DDD TO XXX The second statement gets interpreted as parameters of the first one... This sucks and is obviously not what I want. I have been able to get this working using pyparsing like this: word = Word(alphas,alphanums+'-') statement = "MOVE"+word+"TO"+word statement_list = OneOrMore(statement.setResultsName('statement',True)) Is there any way to get this working in simpleparse as well? EDIT: clarification below I am not trying to achieve a line-based grammar. What I would like to see being parsed is: Simple case MOVE AA TO BB More comlex case MOVE AA TO BB CC DD EE FF Several of the above statments MOVE AA TO BB CC MOVE CC TO EE MOVE EE TO FF GG HH IIJJK
[ "The grammar is currently ambiguous. On paper you cannot parse if \"MOVE A TO B MOVE C TO D\" is two statements, or one statement with particular badly named destinations.\nYou have two answers. You may like neither.\n\nYou explicitly make your WORD not match any reserved word. That is, you specifically disallow matching MOVE or TO. This is equivalent to saying \"MOVE is not a valid parameter name\". This makes \"MOVE TL TO TM TN TO\" an error.\nYou modify your grammar so that you can tell where the statement ends. You could add commas \"MOVE AA TO BB, CC MOVE TM TO TN, TO, TP\". You could add semi-colons or blank lines at the end of statements. You could require that MOVE be the least indented, like Python.\n\n" ]
[ 2 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0000298034_parsing_python.txt
Q: Python xml.dom.minidom.parse() function ignores DTDs I have the following Python code: import xml.dom.minidom import xml.parsers.expat try: domTree = ml.dom.minidom.parse(myXMLFileName) except xml.parsers.expat.ExpatError, e: return e.args[0] which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, it completely ignores the DTD specified at the top of the XML file: <?xml version="1.0" encoding="UTF-8" standalone="no" ?> <!DOCTYPE ServerConfig SYSTEM "ServerConfig.dtd"> so it doesn't notice when mandatory elements are missing, for example. How can I switch on DTD checking? A: See this question - the accepted answer is to use lxml validation. A: Just by way of explanation: Python xml.dom.minidom and xml.sax use the expat parser by default, which is a non-validating parser. It may read the DTD in order to do entity replacement, but it won't validate against the DTD. gimel and Tim recommend lxml, which is a nicely pythonic binding for the libxml2 and libxslt libraries. It supports validation against a DTD. I've been using lxml, and I like it a lot. A: Just for the record, this is what my code looks like now: from lxml import etree try: parser = etree.XMLParser(dtd_validation=True) domTree = etree.parse(myXMLFileName, parser=parser) except etree.XMLSyntaxError, e: return e.args[0] A: I recommend lxml over xmlproc because the PyXML package (containing xmlproc) is not being developed any more; the latest Python version that PyXML can be used with is 2.4. A: I believe you need to switch from expat to xmlproc. See: http://code.activestate.com/recipes/220472/
Python xml.dom.minidom.parse() function ignores DTDs
I have the following Python code: import xml.dom.minidom import xml.parsers.expat try: domTree = ml.dom.minidom.parse(myXMLFileName) except xml.parsers.expat.ExpatError, e: return e.args[0] which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, it completely ignores the DTD specified at the top of the XML file: <?xml version="1.0" encoding="UTF-8" standalone="no" ?> <!DOCTYPE ServerConfig SYSTEM "ServerConfig.dtd"> so it doesn't notice when mandatory elements are missing, for example. How can I switch on DTD checking?
[ "See this question - the accepted answer is to use lxml validation.\n", "Just by way of explanation: Python xml.dom.minidom and xml.sax use the expat parser by default, which is a non-validating parser. It may read the DTD in order to do entity replacement, but it won't validate against the DTD.\ngimel and Tim recommend lxml, which is a nicely pythonic binding for the libxml2 and libxslt libraries. It supports validation against a DTD. I've been using lxml, and I like it a lot.\n", "Just for the record, this is what my code looks like now: \nfrom lxml import etree\n\ntry:\n parser = etree.XMLParser(dtd_validation=True)\n domTree = etree.parse(myXMLFileName, parser=parser)\nexcept etree.XMLSyntaxError, e:\n return e.args[0]\n\n", "I recommend lxml over xmlproc because the PyXML package (containing xmlproc) is not being developed any more; the latest Python version that PyXML can be used with is 2.4.\n", "I believe you need to switch from expat to xmlproc.\nSee:\nhttp://code.activestate.com/recipes/220472/\n" ]
[ 5, 3, 2, 1, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0000298782_python_xml.txt
Q: How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line? I am familiar with using the os.system to run from the command line. However, I would like to be able to run a jar file from inside of a specific folder, eg. my 'test' folder. This is because my jar (located in my 'test' folder) requires a file inside of my 'test' folder. So, how would I write a function in my script that does the following: c:\test>java -jar run_this.jar required_parameter.ext ? I'm a python newbie so details are greatly appreciated. Thanks in advance. A: Here is a small script to get you started. There are ways to make it "better", but not knowing the full scope of what you are trying to accomplish this should be sufficient. import os if __name__ == "__main__": startingDir = os.getcwd() # save our current directory testDir = "\\test" # note that \ is windows specific, and we have to escape it os.chdir(testDir) # change to our test directory os.system("java -jar run_this.jar required_paramter.ext") os.chdir(startingDir) # change back to where we started A: In general: Use os.chdir to change the directory of the parent process, then os.system to run the jar file. If you need to keep Python's working directory stable, you need to chdir back to original working directory - you need to record that with os.getcwd(). On Unix: Create a child process with os.fork explicitly. In the parent, wait for the child with os.waitpid. In the child, use os.chdir, then os.exec to run java.
How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line?
I am familiar with using the os.system to run from the command line. However, I would like to be able to run a jar file from inside of a specific folder, eg. my 'test' folder. This is because my jar (located in my 'test' folder) requires a file inside of my 'test' folder. So, how would I write a function in my script that does the following: c:\test>java -jar run_this.jar required_parameter.ext ? I'm a python newbie so details are greatly appreciated. Thanks in advance.
[ "Here is a small script to get you started. There are ways to make it \"better\", but not knowing the full scope of what you are trying to accomplish this should be sufficient.\nimport os\n\nif __name__ == \"__main__\":\n startingDir = os.getcwd() # save our current directory\n testDir = \"\\\\test\" # note that \\ is windows specific, and we have to escape it\n os.chdir(testDir) # change to our test directory\n os.system(\"java -jar run_this.jar required_paramter.ext\")\n os.chdir(startingDir) # change back to where we started\n\n", "In general: Use os.chdir to change the directory of the parent process, then os.system to run the jar file. If you need to keep Python's working directory stable, you need to chdir back to original working directory - you need to record that with os.getcwd().\nOn Unix: Create a child process with os.fork explicitly. In the parent, wait for the child with os.waitpid. In the child, use os.chdir, then os.exec to run java.\n" ]
[ 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000299249_python.txt
Q: Calling Java (or python or perl) from a PHP script I've been trying to build a simple prototype application in Django, and am reaching the point of giving up, sadly, as it's just too complicated (I know it would be worth it in the long-run, but I really just don't have enough time available -- I need something up and running in a few days). So, I'm now thinking of going with PHP instead, as it's the method for creating dynamic web content I'm most familiar with, and I know I can get something working quickly. My application, while simple, is probably going to be doing some reasonably complex AI stuff, and it may be that libraries don't exist for what I need in PHP. So I'm wondering how easy / possible it is for a PHP script to "call" a Java program or Python script or a program or script in another language. It's not entirely clear to me what exactly I mean by "call" in this context, but I guess I probably mean that ideally I'd like to define a function in, let's say Java, and then be able to call it from PHP. If that's not possible, then I guess my best bet (assuming I do go with PHP) will be to pass control directly to the external program explicitly through a POST or GET to a CGI program or similar. Feel free to convince me I should stick with Django, although I'm really at the point where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex... Alternatively, anyone who can offer any advice on linking PHP and other languages, that'll be grateful received. A: "where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex" Common problem. Root cause: Too much programming. Solution. Do less programming. Seriously. Define the Django model. Use the default admin pages to see if it's right. Fix the model. Regenerate the database. Look at the default admin pages. Repeat until the default admin pages work correctly and simply. Once it's right in the default admin pages, you have a model that works. It's testable. And the automatic stuff is hooked up correctly. Choices are defined correctly. Computations are in the model mmethods. Queries work. Now you can start working on other presentations of the data. Django generally starts (and ends) with the model. The forms, view and templates are derived from the model. A: For an easy access of Java classes from PHP scripts you can use a php-java bridge. There is a open source solution: http://php-java-bridge.sourceforge.net/pjb/ or a solution from Zend (http://www.zend.com/en/products/platform/product-comparison/java-bridge). I'm more familiar with the later, and it's very easy and intuitive to use.
Calling Java (or python or perl) from a PHP script
I've been trying to build a simple prototype application in Django, and am reaching the point of giving up, sadly, as it's just too complicated (I know it would be worth it in the long-run, but I really just don't have enough time available -- I need something up and running in a few days). So, I'm now thinking of going with PHP instead, as it's the method for creating dynamic web content I'm most familiar with, and I know I can get something working quickly. My application, while simple, is probably going to be doing some reasonably complex AI stuff, and it may be that libraries don't exist for what I need in PHP. So I'm wondering how easy / possible it is for a PHP script to "call" a Java program or Python script or a program or script in another language. It's not entirely clear to me what exactly I mean by "call" in this context, but I guess I probably mean that ideally I'd like to define a function in, let's say Java, and then be able to call it from PHP. If that's not possible, then I guess my best bet (assuming I do go with PHP) will be to pass control directly to the external program explicitly through a POST or GET to a CGI program or similar. Feel free to convince me I should stick with Django, although I'm really at the point where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex... Alternatively, anyone who can offer any advice on linking PHP and other languages, that'll be grateful received.
[ "\"where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex\" \nCommon problem.\nRoot cause: Too much programming.\nSolution. Do less programming. Seriously.\nDefine the Django model. Use the default admin pages to see if it's right. Fix the model. Regenerate the database. Look at the default admin pages. Repeat until the default admin pages work correctly and simply.\nOnce it's right in the default admin pages, you have a model that works. It's testable. And the automatic stuff is hooked up correctly. Choices are defined correctly. Computations are in the model mmethods. Queries work. Now you can start working on other presentations of the data.\nDjango generally starts (and ends) with the model. The forms, view and templates are derived from the model.\n", "For an easy access of Java classes from PHP scripts you can use a php-java bridge.\nThere is a open source solution: http://php-java-bridge.sourceforge.net/pjb/\nor a solution from Zend (http://www.zend.com/en/products/platform/product-comparison/java-bridge).\nI'm more familiar with the later, and it's very easy and intuitive to use.\n" ]
[ 4, 2 ]
[]
[]
[ "dynamic_linking", "java", "php", "python" ]
stackoverflow_0000299913_dynamic_linking_java_php_python.txt
Q: Is it possible to bind an event against a menu instead of a menu item in wxPython? Nothing to add A: Do you want an event when your menu is opened? Use EVT_MENU_OPEN(func) (wxMenuEvent). But it's not in particular precise. As the documentation says, it is only sent once if you open a menu. For another event you have to close it and open another menu again. I.e in between, you can open other menus (by hovering other items in the menubar), and the event won't be sent again. What do you need this for? Probably there is another way to do it, instead of listening for this kind of event. If you want an event for all items of a menu, use EVT_MENU_RANGE(id1, id2, func) (it's using wxCommandEvent). All IDs starting from id1 up to and including id2 will be connected to the given event handler. Using a range instead of connecting each item separate will provide for better performance, as there are fewer items in the event-handler list.
Is it possible to bind an event against a menu instead of a menu item in wxPython?
Nothing to add
[ "Do you want an event when your menu is opened? Use EVT_MENU_OPEN(func) (wxMenuEvent). But it's not in particular precise. As the documentation says, it is only sent once if you open a menu. For another event you have to close it and open another menu again. I.e in between, you can open other menus (by hovering other items in the menubar), and the event won't be sent again. \nWhat do you need this for? Probably there is another way to do it, instead of listening for this kind of event. \nIf you want an event for all items of a menu, use EVT_MENU_RANGE(id1, id2, func) (it's using wxCommandEvent). All IDs starting from id1 up to and including id2 will be connected to the given event handler. Using a range instead of connecting each item separate will provide for better performance, as there are fewer items in the event-handler list.\n" ]
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0000300032_python_wxpython.txt
Q: Looping in Django forms I've just started building a prototype application in Django. I started out by working through the Django app tutorial on the Django site which was pretty helpful, and gave me what I needed to get started. Now I have a couple of what I hope are very simple questions: I want to put a loop into views.py, looping over a set of variables that have been passed in from a form. So I have a load of items in the HTML form, each of which has a SELECT drop-down list for people to select a score from 0-10, like this: <select name="score1"> <option value=0 SELECTED>No score</option> <option value=1>1</option> <option value=2>2</option> <option value=3>3</option> <option value=4>4</option> <option value=5>5</option> <option value=6>6</option> <option value=7>7</option> <option value=8>8</option> <option value=9>9</option> <option value=10>10</option> </select> So I have, let's say, 100 of these variables, score1, score2, score3, ..., score99, score100. When the form is submitted, I want to loop through each of these variables and see if it's been set (i.e. is not 0) and if so, I want to store that value in a suitable place in the database. My problem is that I can't figure out how to loop through those variables. I'm guessing that I want something like this: for o in request.POST.all endfor but then I'm really not sure what to do with that. I'm not looking for someone to write the code for me, really: I just would like some guidance on how to write a loop like this in python / Django, and also maybe some pointers as to a good reference guide I can either see online or buy that will give me access to this kind of thing. Also, the select object above I created pretty much by hand, and I'd really like to be able to ue a loop to generate it in the template in the first place. My template currently has this: <table> {% for movie in movie_list %} <tr> <td> {{ movie }} </td> <td> <select name="score{{ movie.id }}"> <option value=0 SELECTED>No score</option> <option value=1>1</option> <option value=2>2</option> <option value=3>3</option> <option value=4>4</option> <option value=5>5</option> <option value=6>6</option> <option value=7>7</option> <option value=8>8</option> <option value=9>9</option> <option value=10>10</option> </select> </td></tr> {% endfor %} </table> I feel like there must be a way to create a simple loop that counts from 1 to 10 that would generate most of those options for me, but I can't figure out how to do that... A: You need to look at the Django forms. You should never build your own form like that. You should declare a Form class which includes a ChoiceField and provide the domain of choices to that field. Everything will happen pretty much automatically from there. The choices, BTW, should be defined in your Model as the range of values for that Model field. Your page merely includes {{form}}. Django builds the form with the choices and decodes the choices to a final result. A: I feel like there must be a way to create a simple loop that counts from 1 to 10 that would generate most of those options for me, but I can't figure out how to do that... If you don't want to use Django forms (why btw?), check out this custom range tag or just pass a range(1, 11) object into your template and use it in the {% for %} loop. A: Follow S.Lotts advice on forms, it'll save time in the long run to do them the Django way now. For that loop you were looking for: <select name="score{{ movie.id }}"> <option value=0 SELECTED>No score</option> {% for i in range(1, 11) %} <option value={{ i }}>{{ i }}</option> {% endfor %} </select>
Looping in Django forms
I've just started building a prototype application in Django. I started out by working through the Django app tutorial on the Django site which was pretty helpful, and gave me what I needed to get started. Now I have a couple of what I hope are very simple questions: I want to put a loop into views.py, looping over a set of variables that have been passed in from a form. So I have a load of items in the HTML form, each of which has a SELECT drop-down list for people to select a score from 0-10, like this: <select name="score1"> <option value=0 SELECTED>No score</option> <option value=1>1</option> <option value=2>2</option> <option value=3>3</option> <option value=4>4</option> <option value=5>5</option> <option value=6>6</option> <option value=7>7</option> <option value=8>8</option> <option value=9>9</option> <option value=10>10</option> </select> So I have, let's say, 100 of these variables, score1, score2, score3, ..., score99, score100. When the form is submitted, I want to loop through each of these variables and see if it's been set (i.e. is not 0) and if so, I want to store that value in a suitable place in the database. My problem is that I can't figure out how to loop through those variables. I'm guessing that I want something like this: for o in request.POST.all endfor but then I'm really not sure what to do with that. I'm not looking for someone to write the code for me, really: I just would like some guidance on how to write a loop like this in python / Django, and also maybe some pointers as to a good reference guide I can either see online or buy that will give me access to this kind of thing. Also, the select object above I created pretty much by hand, and I'd really like to be able to ue a loop to generate it in the template in the first place. My template currently has this: <table> {% for movie in movie_list %} <tr> <td> {{ movie }} </td> <td> <select name="score{{ movie.id }}"> <option value=0 SELECTED>No score</option> <option value=1>1</option> <option value=2>2</option> <option value=3>3</option> <option value=4>4</option> <option value=5>5</option> <option value=6>6</option> <option value=7>7</option> <option value=8>8</option> <option value=9>9</option> <option value=10>10</option> </select> </td></tr> {% endfor %} </table> I feel like there must be a way to create a simple loop that counts from 1 to 10 that would generate most of those options for me, but I can't figure out how to do that...
[ "You need to look at the Django forms.\nYou should never build your own form like that.\nYou should declare a Form class which includes a ChoiceField and provide the domain of choices to that field. Everything will happen pretty much automatically from there.\nThe choices, BTW, should be defined in your Model as the range of values for that Model field.\nYour page merely includes {{form}}. Django builds the form with the choices and decodes the choices to a final result.\n", "\nI feel like there must be a way to\n create a simple loop that counts from\n 1 to 10 that would generate most of\n those options for me, but I can't\n figure out how to do that...\n\nIf you don't want to use Django forms (why btw?), check out this custom range tag or just pass a range(1, 11) object into your template and use it in the {% for %} loop.\n", "Follow S.Lotts advice on forms, it'll save time in the long run to do them the Django way now. For that loop you were looking for:\n<select name=\"score{{ movie.id }}\">\n <option value=0 SELECTED>No score</option>\n {% for i in range(1, 11) %}\n <option value={{ i }}>{{ i }}</option>\n {% endfor %}\n</select>\n\n" ]
[ 7, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000298446_django_python.txt
Q: Why is fuse not using the class supplied in file_class I have a python fuse project based on the Xmp example in the fuse documentation. I have included a small piece of the code to show how this works. For some reason get_file does get called and the class gets created, but instead of fuse calling .read() on the class from get_file (file_class) fuse keeps calling Dstorage.read() which defeats the purpose in moving the read function out of that class. class Dstorage(Fuse, Distributor): def get_file(self, server, path, flags, *mode): pass # This does some work and passes back an instance of # a class very similar to XmpFile def main(self, *a, **kw): self.file_class = self.get_file return Fuse.main(self, *a, **kw) I have my code hosted on launchpad, you can download it with this command. bzr co https://code.launchpad.net/~asa-ayers/+junk/dstorage bzr branch lp:~asa-ayers/dstorage/trunk solution: I used a proxy class that subclasses the one I needed and in the constructor I get the instance of the class I need and overwrite all of the proxy's methods to simply call the instance methods. A: Looking at the code of the Fuse class (which is a maze of twisty little passages creating method proxies), I see this bit (which is a closure used to create a setter inside Fuse.MethodProxy._add_class_type, line 865): def setter(self, xcls): setattr(self, type + '_class', xcls) for m in inits: self.mdic[m] = xcls for m in proxied: if hasattr(xcls, m): self.mdic[m] = self.proxyclass(m) When you do self.file_class = self.get_file, this gets called with self.get_file, which is a bound method. The loop over proxied attributes is expecting to be able to get the attributes off the class you set, to put them into its mdic proxy dictionary after wrapping them, but they aren't there, because it's a bound method, rather than a class. Since it can't find them, it reverts to calling them on Dstorage. So, long story short, you can't use a callable that returns an instance (kind of a pseudo-class) instead of a class here, because Fuse is introspecting the object that you set to find the methods it should call. You need to assign a class to file_class - if you need to refer back to the parent instance, you can use the nested class trick they show in the docs.
Why is fuse not using the class supplied in file_class
I have a python fuse project based on the Xmp example in the fuse documentation. I have included a small piece of the code to show how this works. For some reason get_file does get called and the class gets created, but instead of fuse calling .read() on the class from get_file (file_class) fuse keeps calling Dstorage.read() which defeats the purpose in moving the read function out of that class. class Dstorage(Fuse, Distributor): def get_file(self, server, path, flags, *mode): pass # This does some work and passes back an instance of # a class very similar to XmpFile def main(self, *a, **kw): self.file_class = self.get_file return Fuse.main(self, *a, **kw) I have my code hosted on launchpad, you can download it with this command. bzr co https://code.launchpad.net/~asa-ayers/+junk/dstorage bzr branch lp:~asa-ayers/dstorage/trunk solution: I used a proxy class that subclasses the one I needed and in the constructor I get the instance of the class I need and overwrite all of the proxy's methods to simply call the instance methods.
[ "Looking at the code of the Fuse class (which is a maze of twisty little passages creating method proxies), I see this bit (which is a closure used to create a setter inside Fuse.MethodProxy._add_class_type, line 865):\n def setter(self, xcls):\n\n setattr(self, type + '_class', xcls)\n\n for m in inits:\n self.mdic[m] = xcls\n\n for m in proxied:\n if hasattr(xcls, m):\n self.mdic[m] = self.proxyclass(m)\n\nWhen you do self.file_class = self.get_file, this gets called with self.get_file, which is a bound method. The loop over proxied attributes is expecting to be able to get the attributes off the class you set, to put them into its mdic proxy dictionary after wrapping them, but they aren't there, because it's a bound method, rather than a class. Since it can't find them, it reverts to calling them on Dstorage.\nSo, long story short, you can't use a callable that returns an instance (kind of a pseudo-class) instead of a class here, because Fuse is introspecting the object that you set to find the methods it should call. \nYou need to assign a class to file_class - if you need to refer back to the parent instance, you can use the nested class trick they show in the docs.\n" ]
[ 1 ]
[]
[]
[ "fuse", "python" ]
stackoverflow_0000300047_fuse_python.txt
Q: loadComponentFromURL falls over and dies, howto do CPR? Well I testing my jython program, that does some neat [".xls", ".doc", ".rtf", ".tif", ".tiff", ".pdf" files] -> pdf (intermediary file) -> tif (final output) conversion using Open Office. We moved away from MS Office due to the problems we had with automation. Now it seems we have knocked down many bottles related to show stopper errors with one bottle remaining. OO hangs after a while. It happens where you see this line '<<<<<<<<<<<<' in the code What is the correct way for me to handle a stalled Open Office process. could you please provide useful links, and give me a good suggestion on the way out. Also one more question. Sum up: * How to handle a stalled Open Office instance? * How to make conversion with java headless, so I dont have a GUI popping up all the time wasting memory. * also any general suggestions on code quality, optimizations and general coding standards will be most appreciated. Traceback (innermost last): File "dcmail.py", line 184, in ? File "dcmail.py", line 174, in main File "C:\DCMail\digestemails.py", line 126, in process_inbox File "C:\DCMail\digestemails.py", line 258, in _convert File "C:\DCMail\digestemails.py", line 284, in _choose_conversion_type File "C:\DCMail\digestemails.py", line 287, in _open_office_convert File "C:\DCMail\digestemails.py", line 299, in _load_attachment_to_convert com.sun.star.lang.DisposedException: java.io.EOFException at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge$MessageDi spatcher.run(java_remote_bridge.java:176) com.sun.star.lang.DisposedException: com.sun.star.lang.DisposedException: java.i o.EOFException Just to clear up this exception only throws when I kill the open office process. Otherwise the program just waits for open office to complete. Indefinitely The Code (with non functional code tags) [code] #ghost script handles these file types GS_WHITELIST=[".pdf"] #Open Office handles these file types OO_WHITELIST=[".xls", ".doc", ".rtf", ".tif", ".tiff"] #whitelist is used to check against any unsupported files. WHITELIST=GS_WHITELIST + OO_WHITELIST def _get_service_manager(self): try: self._context=Bootstrap.bootstrap(); self._xMultiCompFactory=self._context.getServiceManager() self._xcomponentloader=UnoRuntime.queryInterface(XComponentLoader, self._xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", self._context)) except: raise OpenOfficeException("Exception Occurred with Open Office") def _choose_conversion_type(self,fn): ext=os.path.splitext(fn)[1] if ext in GS_WHITELIST: self._ghostscript_convert_to_tiff(fn) elif ext in OO_WHITELIST: self._open_office_convert(fn) def _open_office_convert(self,fn): self._load_attachment_to_convert(fn) self._save_as_pdf(fn) self._ghostscript_convert_to_tiff(fn) def _load_attachment_to_convert(self, file): file=self._create_UNO_File_URL(file) properties=[] p=PropertyValue() p.Name="Hidden" p.Value=True properties.append(p) properties=tuple(properties) self._doc=self._xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) <<<<<<<<<<<<<<< here is line 299 def _create_UNO_File_URL(self, filepath): try: file=str("file:///" + filepath) file=file.replace("\\", "/") except MalformedURLException, e: raise e return file def _save_as_pdf(self, docSource): dirName=os.path.dirname(docSource) baseName=os.path.basename(docSource) baseName, ext=os.path.splitext(baseName) dirTmpPdfConverted=os.path.join(dirName + DIR + PDF_TEMP_CONVERT_DIR) if not os.path.exists(dirTmpPdfConverted): os.makedirs(dirTmpPdfConverted) pdfDest=os.path.join(dirTmpPdfConverted + DIR + baseName + ".pdf") url_save=self._create_UNO_File_URL(pdfDest) properties=self._create_properties(ext) try: try: self._xstorable=UnoRuntime.queryInterface(XStorable, self._doc); self._xstorable.storeToURL(url_save, properties) except AttributeError,e: self.logger.info("pdf file already created (" + str(e) + ")") raise e finally: try: self._doc.dispose() except: raise def _create_properties(self,ext): properties=[] p=PropertyValue() p.Name="Overwrite" p.Value=True properties.append(p) p=PropertyValue() p.Name="FilterName" if ext==".doc": p.Value='writer_pdf_Export' elif ext==".rtf": p.Value='writer_pdf_Export' elif ext==".xls": p.Value='calc_pdf_Export' elif ext==".tif": p.Value='draw_pdf_Export' elif ext==".tiff": p.Value='draw_pdf_Export' properties.append(p) return tuple(properties) def _ghostscript_convert_to_tiff(self, docSource): dest, source=self._get_dest_and_source_conversion_file(docSource) try: command = ' '.join([ self._ghostscriptPath + 'gswin32c.exe', '-q', '-dNOPAUSE', '-dBATCH', '-r500', '-sDEVICE=tiffg4', '-sPAPERSIZE=a4', '-sOutputFile=%s %s' % (dest, source), ]) self._execute_ghostscript(command) self.convertedTifDocList.append(dest) except OSError, e: self.logger.info(e) raise e except TypeError, (e): raise e except AttributeError, (e): raise e except: raise [/code] A: OpenOffice.org has a "-headless" parameter to run it without a GUI. I'm not sure this actually frees up all resources that would be spent on GUI. Here's how I run my server-side headless instance: soffice -headless -accept="socket,port=1234;urp" -display :25 I can't tell what's causing the stalling problems for your Python script, but you might want to to check out PyODConverter, and see what this script does differently to maybe catch the error causing your trouble. A: The icky solution is to have a monitor for the OpenOffice process. If your monitor knows the PID and has privileges, it can get CPU time used every few seconds. If OO hangs in a stalled state (no more CPU), then the monitor can kill it. The easiest way to handle this is to have the "wrapper" that's firing off the open office task watch it while it runs and kill it when it hangs. The parent process has to do a wait anyway, so it may as well monitor. If OpenOffuce hangs in a loop, then it's tougher to spot. CPU usually goes through the roof, stays there, and the priority plummets to the lowest possible priority. Processing or hung? Judgement call. You have to let it hang like this for "a while" (pick a random duration, 432 seconds (3 dozen dozen) for instance; you'll always be second-guessing yourself.)
loadComponentFromURL falls over and dies, howto do CPR?
Well I testing my jython program, that does some neat [".xls", ".doc", ".rtf", ".tif", ".tiff", ".pdf" files] -> pdf (intermediary file) -> tif (final output) conversion using Open Office. We moved away from MS Office due to the problems we had with automation. Now it seems we have knocked down many bottles related to show stopper errors with one bottle remaining. OO hangs after a while. It happens where you see this line '<<<<<<<<<<<<' in the code What is the correct way for me to handle a stalled Open Office process. could you please provide useful links, and give me a good suggestion on the way out. Also one more question. Sum up: * How to handle a stalled Open Office instance? * How to make conversion with java headless, so I dont have a GUI popping up all the time wasting memory. * also any general suggestions on code quality, optimizations and general coding standards will be most appreciated. Traceback (innermost last): File "dcmail.py", line 184, in ? File "dcmail.py", line 174, in main File "C:\DCMail\digestemails.py", line 126, in process_inbox File "C:\DCMail\digestemails.py", line 258, in _convert File "C:\DCMail\digestemails.py", line 284, in _choose_conversion_type File "C:\DCMail\digestemails.py", line 287, in _open_office_convert File "C:\DCMail\digestemails.py", line 299, in _load_attachment_to_convert com.sun.star.lang.DisposedException: java.io.EOFException at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge$MessageDi spatcher.run(java_remote_bridge.java:176) com.sun.star.lang.DisposedException: com.sun.star.lang.DisposedException: java.i o.EOFException Just to clear up this exception only throws when I kill the open office process. Otherwise the program just waits for open office to complete. Indefinitely The Code (with non functional code tags) [code] #ghost script handles these file types GS_WHITELIST=[".pdf"] #Open Office handles these file types OO_WHITELIST=[".xls", ".doc", ".rtf", ".tif", ".tiff"] #whitelist is used to check against any unsupported files. WHITELIST=GS_WHITELIST + OO_WHITELIST def _get_service_manager(self): try: self._context=Bootstrap.bootstrap(); self._xMultiCompFactory=self._context.getServiceManager() self._xcomponentloader=UnoRuntime.queryInterface(XComponentLoader, self._xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", self._context)) except: raise OpenOfficeException("Exception Occurred with Open Office") def _choose_conversion_type(self,fn): ext=os.path.splitext(fn)[1] if ext in GS_WHITELIST: self._ghostscript_convert_to_tiff(fn) elif ext in OO_WHITELIST: self._open_office_convert(fn) def _open_office_convert(self,fn): self._load_attachment_to_convert(fn) self._save_as_pdf(fn) self._ghostscript_convert_to_tiff(fn) def _load_attachment_to_convert(self, file): file=self._create_UNO_File_URL(file) properties=[] p=PropertyValue() p.Name="Hidden" p.Value=True properties.append(p) properties=tuple(properties) self._doc=self._xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) <<<<<<<<<<<<<<< here is line 299 def _create_UNO_File_URL(self, filepath): try: file=str("file:///" + filepath) file=file.replace("\\", "/") except MalformedURLException, e: raise e return file def _save_as_pdf(self, docSource): dirName=os.path.dirname(docSource) baseName=os.path.basename(docSource) baseName, ext=os.path.splitext(baseName) dirTmpPdfConverted=os.path.join(dirName + DIR + PDF_TEMP_CONVERT_DIR) if not os.path.exists(dirTmpPdfConverted): os.makedirs(dirTmpPdfConverted) pdfDest=os.path.join(dirTmpPdfConverted + DIR + baseName + ".pdf") url_save=self._create_UNO_File_URL(pdfDest) properties=self._create_properties(ext) try: try: self._xstorable=UnoRuntime.queryInterface(XStorable, self._doc); self._xstorable.storeToURL(url_save, properties) except AttributeError,e: self.logger.info("pdf file already created (" + str(e) + ")") raise e finally: try: self._doc.dispose() except: raise def _create_properties(self,ext): properties=[] p=PropertyValue() p.Name="Overwrite" p.Value=True properties.append(p) p=PropertyValue() p.Name="FilterName" if ext==".doc": p.Value='writer_pdf_Export' elif ext==".rtf": p.Value='writer_pdf_Export' elif ext==".xls": p.Value='calc_pdf_Export' elif ext==".tif": p.Value='draw_pdf_Export' elif ext==".tiff": p.Value='draw_pdf_Export' properties.append(p) return tuple(properties) def _ghostscript_convert_to_tiff(self, docSource): dest, source=self._get_dest_and_source_conversion_file(docSource) try: command = ' '.join([ self._ghostscriptPath + 'gswin32c.exe', '-q', '-dNOPAUSE', '-dBATCH', '-r500', '-sDEVICE=tiffg4', '-sPAPERSIZE=a4', '-sOutputFile=%s %s' % (dest, source), ]) self._execute_ghostscript(command) self.convertedTifDocList.append(dest) except OSError, e: self.logger.info(e) raise e except TypeError, (e): raise e except AttributeError, (e): raise e except: raise [/code]
[ "OpenOffice.org has a \"-headless\" parameter to run it without a GUI. I'm not sure this actually frees up all resources that would be spent on GUI. Here's how I run my server-side headless instance:\nsoffice -headless -accept=\"socket,port=1234;urp\" -display :25\n\nI can't tell what's causing the stalling problems for your Python script, but you might want to to check out PyODConverter, and see what this script does differently to maybe catch the error causing your trouble.\n", "The icky solution is to have a monitor for the OpenOffice process. If your monitor knows the PID and has privileges, it can get CPU time used every few seconds. If OO hangs in a stalled state (no more CPU), then the monitor can kill it. \nThe easiest way to handle this is to have the \"wrapper\" that's firing off the open office task watch it while it runs and kill it when it hangs. The parent process has to do a wait anyway, so it may as well monitor.\nIf OpenOffuce hangs in a loop, then it's tougher to spot. CPU usually goes through the roof, stays there, and the priority plummets to the lowest possible priority. Processing or hung? Judgement call. You have to let it hang like this for \"a while\" (pick a random duration, 432 seconds (3 dozen dozen) for instance; you'll always be second-guessing yourself.)\n" ]
[ 1, 1 ]
[]
[]
[ "java", "jython", "openoffice.org", "python" ]
stackoverflow_0000301239_java_jython_openoffice.org_python.txt
Q: Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states? I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will be written in Python, FWIW. A: You can use QGraphicsView in PyQt. Each state is a new QGraphicsItem, which is either a bitmap or a path object. You just need to provide the outlines (or bitmaps) and the positions of the states. If you have SVGs of the states, you can use them, too. There is no generally accepted canvas class for GTK+. A: If you consider Qt, consider also throwing in kdelibs dependency, then you'll have marble widget, which handles maps in neat way. If you stick only to Qt, then QGraphicsView is a framework to go. (note: kdelibs != running whole kde desktop) A: You can use Quantum GIS. QGIS is a Open Source Geographic Information System using the Qt Framework. QGIS can also be used with Python. You can either extend it with plugins written in Python or use the PyGIS Python bindings to write your own application. They have a Wiki with some good informations for developers. Maybe QGIS is to heavy for your purpose, but I add it here for completition anyway. A: If you consider Qt, consider also throwing in kdelibs dependency, then you'll have marble widget, which handles maps in neat way. Thanks for advertizing Marble. But you are incorrect: The Marble Widget doesn't depend on kdelibs at all. It just depends on Qt (>=4.3). Additionally Marble also has just received Python bindings. I think that the given problem can be solved using Marble. Would just take a few days of work at max. If you have questions about Marble, feel free to ask us on our mailing list or IRC. A: Quick tip, if you color each state differently you can identify which one to pick from the color under mouse cursor rather than doing a complex point in polygon routine.
Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states?
I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will be written in Python, FWIW.
[ "You can use QGraphicsView in PyQt. Each state is a new QGraphicsItem, which is either a bitmap or a path object. You just need to provide the outlines (or bitmaps) and the positions of the states. \nIf you have SVGs of the states, you can use them, too.\nThere is no generally accepted canvas class for GTK+.\n", "If you consider Qt, consider also throwing in kdelibs dependency, then you'll have marble widget, which handles maps in neat way.\nIf you stick only to Qt, then QGraphicsView is a framework to go.\n(note: kdelibs != running whole kde desktop)\n", "You can use Quantum GIS. QGIS is a Open Source Geographic Information System using the Qt Framework.\nQGIS can also be used with Python. You can either extend it with plugins written in Python or use the PyGIS Python bindings to write your own application.\nThey have a Wiki with some good informations for developers.\nMaybe QGIS is to heavy for your purpose, but I add it here for completition anyway. \n", "\nIf you consider Qt, consider also throwing in kdelibs dependency, \n then you'll have marble widget, which handles maps in neat way.\n\nThanks for advertizing Marble. But you are incorrect: \nThe Marble Widget doesn't depend on kdelibs at all. It just depends on Qt (>=4.3).\nAdditionally Marble also has just received Python bindings.\nI think that the given problem can be solved using Marble. Would just take a few days of work at max. If you have questions about Marble, feel free to ask us on our mailing list or IRC.\n", "Quick tip, if you color each state differently you can identify which one to pick from the color under mouse cursor rather than doing a complex point in polygon routine.\n" ]
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "desktop", "gtk", "python", "qt" ]
stackoverflow_0000112483_desktop_gtk_python_qt.txt
Q: How does Python handle classes being in separate files or are they all supposed to be in one file I'm working on framework for testing some command line utilities. I want to create some classes to hold the different types of information more easily. Python is fairly new to me so I'm not sure how you would handle this. Do you keep all your classes in one file with your main script or can you separate them into their own files and use them in your main script. What is the paradigm for how you create multiple classes and use them in a single script? Duplicate of How many python classes should I put in one file A: An answer from the duplicate question in the comments seems to answer my question. My understanding now is that you can add multiple classes to a separate file which would then be referred to as a module. Then you can import that module to use your classes. A: "What is the paradigm for how you create multiple classes and use them in a single script?" Are you asking about the import statement? A: I spread functionality out into separate files as it makes sense, using a modular approach.
How does Python handle classes being in separate files or are they all supposed to be in one file
I'm working on framework for testing some command line utilities. I want to create some classes to hold the different types of information more easily. Python is fairly new to me so I'm not sure how you would handle this. Do you keep all your classes in one file with your main script or can you separate them into their own files and use them in your main script. What is the paradigm for how you create multiple classes and use them in a single script? Duplicate of How many python classes should I put in one file
[ "An answer from the duplicate question in the comments seems to answer my question. My understanding now is that you can add multiple classes to a separate file which would then be referred to as a module. Then you can import that module to use your classes.\n", "\"What is the paradigm for how you create multiple classes and use them in a single script?\"\nAre you asking about the import statement? \n", "I spread functionality out into separate files as it makes sense, using a modular approach.\n" ]
[ 3, 2, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0000302729_oop_python.txt
Q: Can I Use Python to Make a Delete Button in a 'web page' I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list. I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory. Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button. A: You could make this even simpler by making it all happen in one main page. Instead of having a list of hyperlinks, just have the main page have one frame that loads one of the autocreated pages in it. Put a couple of buttons at the bottom - a "Keep this page" and a "Delete this page." When you click either button, the main page refreshes, this time with the next autocreated page in the frame. You could make this as a cgi script in your favorite scripting language. You can't just do this in html because an html page only does stuff client-side, and you can only delete files server-side. You will probably need as cgi args the page to show in the frame, and the last page you viewed if the button click was a "delete". A: You would have to write the web page in Python. There are many Python web frameworks out there (e.g. Django) that are easy to work with. You could convert your entire scripting framework to a web application that has a worker thread going and crawling through html pages, saving them to a particular location, indexing them for you to see and providing a delete button that calls the system's delete function on the particular file. A: Rather than having your script output static HTML files, with a little amount of work you could probably adapt your script to run as a small web application with the help of something like web.py. You would start your script and point a browser at http://localhost:8080, for instance. The web browser would be your user interface. To achieve the 'delete' functionality, all you need to do is write some Python that gets executed when a form is submitted to actually perform the deletion. A: Well I finally found an answer that achieved what I wanted-I did not want to learn a new language-Python is hard enough given my lack or experience def OnDelete(self, event): assert self.current, "invalid delete operation" try: os.remove(os.path.join(self.cwd, self.current))
Can I Use Python to Make a Delete Button in a 'web page'
I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list. I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory. Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button.
[ "You could make this even simpler by making it all happen in one main page. Instead of having a list of hyperlinks, just have the main page have one frame that loads one of the autocreated pages in it. Put a couple of buttons at the bottom - a \"Keep this page\" and a \"Delete this page.\" When you click either button, the main page refreshes, this time with the next autocreated page in the frame.\nYou could make this as a cgi script in your favorite scripting language. You can't just do this in html because an html page only does stuff client-side, and you can only delete files server-side. You will probably need as cgi args the page to show in the frame, and the last page you viewed if the button click was a \"delete\".\n", "You would have to write the web page in Python. There are many Python web frameworks out there (e.g. Django) that are easy to work with. You could convert your entire scripting framework to a web application that has a worker thread going and crawling through html pages, saving them to a particular location, indexing them for you to see and providing a delete button that calls the system's delete function on the particular file.\n", "Rather than having your script output static HTML files, with a little amount of work you could probably adapt your script to run as a small web application with the help of something like web.py.\nYou would start your script and point a browser at http://localhost:8080, for instance. The web browser would be your user interface.\nTo achieve the 'delete' functionality, all you need to do is write some Python that gets executed when a form is submitted to actually perform the deletion.\n", "Well I finally found an answer that achieved what I wanted-I did not want to learn a new language-Python is hard enough given my lack or experience\ndef OnDelete(self, event):\n assert self.current, \"invalid delete operation\"\n try:\n os.remove(os.path.join(self.cwd, self.current))\n\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "browser", "python", "web_applications" ]
stackoverflow_0000256021_browser_python_web_applications.txt
Q: information seemingly coming out of mysqldb incorrectly, python django In a latin-1 database i have '\222\222\223\225', when I try to pull this field from the django models I get back u'\u2019\u2019\u201c\u2022'. from django.db import connection (Pdb) cursor = connection.cursor() (Pdb) cursor.execute("SELECT Password from campaignusers WHERE UserID=26") (Pdb) row = cursor.fetchone() So I step into that and get into /usr/local/python2.5/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/MySQLdb/cursors.py(327)fetchone()->(u'\u2019...1c\u2022',) I can't step further into this because its an egg but it seems that the MySQL python driver is interpreting the data not as latin-1. Anyone have any clue whats going on? A: A little browsing of already-asked questions would have led you to UTF-8 latin-1 conversion issues, which was asked and answered yesterday. BTW, I couldn't remember the exact title, so I just googled on django+'\222\222\223\225' and found it. Remember, kids, Google Is Your Friend (tm). A: Django uses UTF-8, unless you define DEFAULT_CHARSET being something other. Be aware that defining other charset will require you to encode all your templates in this charset and this charset will pop from here to there, like email encoding, in sitemaps and feeds and so on. So, IMO, the best you can do is to go UTF-8, this will save you much headaches with Django (internally it's all unicode, the problems are on the borders of your app, like templates and input).
information seemingly coming out of mysqldb incorrectly, python django
In a latin-1 database i have '\222\222\223\225', when I try to pull this field from the django models I get back u'\u2019\u2019\u201c\u2022'. from django.db import connection (Pdb) cursor = connection.cursor() (Pdb) cursor.execute("SELECT Password from campaignusers WHERE UserID=26") (Pdb) row = cursor.fetchone() So I step into that and get into /usr/local/python2.5/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/MySQLdb/cursors.py(327)fetchone()->(u'\u2019...1c\u2022',) I can't step further into this because its an egg but it seems that the MySQL python driver is interpreting the data not as latin-1. Anyone have any clue whats going on?
[ "A little browsing of already-asked questions would have led you to UTF-8 latin-1 conversion issues, which was asked and answered yesterday.\nBTW, I couldn't remember the exact title, so I just googled on django+'\\222\\222\\223\\225' and found it. Remember, kids, Google Is Your Friend (tm).\n", "Django uses UTF-8, unless you define DEFAULT_CHARSET being something other. Be aware that defining other charset will require you to encode all your templates in this charset and this charset will pop from here to there, like email encoding, in sitemaps and feeds and so on. So, IMO, the best you can do is to go UTF-8, this will save you much headaches with Django (internally it's all unicode, the problems are on the borders of your app, like templates and input).\n" ]
[ 2, 0 ]
[]
[]
[ "character_encoding", "django", "mysql", "python" ]
stackoverflow_0000275541_character_encoding_django_mysql_python.txt
Q: scons : src and include dirs can someone give a scons config file which allows the following structure toplevel/ /src - .cc files /include .h files at top level I want the o and final exe. A: Here is one example of Sconscript file env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:inc', CPPDEFINES=[], LIBS=['glib-2.0']) env.Program('runme', Glob('src/*.c')) (The environment line is not really necessary for the example, but I have it to include the non standard glib header path and left it there so you can get the idea how to add extra includes and defines) The source files are in src directory and header files in inc directory. You run scons from the base directory and the output file is also generated in the same directory. A: This question: https://stackoverflow.com/questions/279860/... gives a pretty flexible scons skeleton which should serve your needs with a few tweaks to the path variables. A: env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:include', CPPDEFINES=[], LIBS=['glib-2.0']) if ARGUMENTS.get('debug', 0): env.Append(CCFLAGS = ' -g') env.Program('template', Glob('src/*.cc')) Worked a treat. Thanks.
scons : src and include dirs
can someone give a scons config file which allows the following structure toplevel/ /src - .cc files /include .h files at top level I want the o and final exe.
[ "Here is one example of Sconscript file\nenv=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:inc',\n CPPDEFINES=[],\n LIBS=['glib-2.0']) \nenv.Program('runme', Glob('src/*.c'))\n\n(The environment line is not really necessary for the example, but I have it to include the non standard glib header path and left it there so you can get the idea how to add extra includes and defines)\nThe source files are in src directory and header files in inc directory. You run scons from the base directory and the output file is also generated in the same directory.\n", "This question: https://stackoverflow.com/questions/279860/... \ngives a pretty flexible scons skeleton which should serve your needs with a few tweaks to the path variables.\n", "env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:include',\n CPPDEFINES=[],\n LIBS=['glib-2.0']) \n\nif ARGUMENTS.get('debug', 0):\n env.Append(CCFLAGS = ' -g')\n\nenv.Program('template', Glob('src/*.cc'))\n\nWorked a treat. Thanks.\n" ]
[ 7, 5, 4 ]
[]
[]
[ "python", "scons" ]
stackoverflow_0000302835_python_scons.txt
Q: Newbie Python Question about tuples I am new to Python, and I'm working on writing some database code using the cx_Oracle module. In the cx_Oracle documentation they have a code example like this: import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection.cursor() try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: error, = exc.args print >> sys.stderr, "Oracle-Error-Code:", error.code print >> sys.stderr, "Oracle-Error-Message:", error.message My question has to do with where the "error" object is created. What does the ", =" do? I tried searching Python documentation, and search engines don't work very well when you're searching for operators. :-) I know that the exc.args is a singleton tuple, but I just don't understand the ", =" syntax. If I remove the comma, I get the error message, "AttributeError: 'tuple' object has no attribute 'code'". Can someone point me to where this is documented? Thanks! EDIT: This works without having to unpack the tuple: import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection.cursor() try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: print >> sys.stderr, "Oracle-Error-Code:", exc.args[0].code print >> sys.stderr, "Oracle-Error-Message:", exc.args[0].message A: error, = exc.args This is a case of sequence unpacking. A more readable way to write the same, and the style I personally favor, is: [error] = exc.args There are two bits required to understand the previous example: When the left hand side of an assignment is a recursive sequence of names, the value of the right hand side must be a sequence with the same length, and each item of the RHS value is assigned to the corresponding name in the LHS. A one-item tuple in python is written (foo,). In most contexts, the parenthesis can be ommitted. In particular, they can be omitted next to the assignment operator. A: http://www.python.org/doc/2.5.2/tut/node7.html Look for "sequence unpacking" in section 5.3. A: The comma serves to unpack the tuple, i.e. it extracts the single item of the tuple, and binds it to error. Without the comma, you would bind the tuple itself, rather than its content.
Newbie Python Question about tuples
I am new to Python, and I'm working on writing some database code using the cx_Oracle module. In the cx_Oracle documentation they have a code example like this: import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection.cursor() try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: error, = exc.args print >> sys.stderr, "Oracle-Error-Code:", error.code print >> sys.stderr, "Oracle-Error-Message:", error.message My question has to do with where the "error" object is created. What does the ", =" do? I tried searching Python documentation, and search engines don't work very well when you're searching for operators. :-) I know that the exc.args is a singleton tuple, but I just don't understand the ", =" syntax. If I remove the comma, I get the error message, "AttributeError: 'tuple' object has no attribute 'code'". Can someone point me to where this is documented? Thanks! EDIT: This works without having to unpack the tuple: import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection.cursor() try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: print >> sys.stderr, "Oracle-Error-Code:", exc.args[0].code print >> sys.stderr, "Oracle-Error-Message:", exc.args[0].message
[ "error, = exc.args\n\nThis is a case of sequence unpacking.\nA more readable way to write the same, and the style I personally favor, is:\n[error] = exc.args\n\nThere are two bits required to understand the previous example:\n\nWhen the left hand side of an assignment is a recursive sequence of names, the value of the right hand side must be a sequence with the same length, and each item of the RHS value is assigned to the corresponding name in the LHS.\nA one-item tuple in python is written (foo,). In most contexts, the parenthesis can be ommitted. In particular, they can be omitted next to the assignment operator.\n\n", "http://www.python.org/doc/2.5.2/tut/node7.html\nLook for \"sequence unpacking\" in section 5.3.\n", "The comma serves to unpack the tuple, i.e. it extracts the single item of the tuple, and binds it to error. Without the comma, you would bind the tuple itself, rather than its content.\n" ]
[ 10, 5, 4 ]
[]
[]
[ "cx_oracle", "python", "tuples" ]
stackoverflow_0000303664_cx_oracle_python_tuples.txt
Q: Template Lib (Engine) in Python running with Jython Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok). A: Have you tried Cheetah, I don't have direct experience running it under Jython but there seem to be some people that do. A: Jinja is pretty cool and seems to work on Jython. A: Use StringTemplate, see http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf for details of why. There is nothing better, and it supports both Java and Python (and .NET, etc.).
Template Lib (Engine) in Python running with Jython
Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).
[ "Have you tried Cheetah, I don't have direct experience running it under Jython but there seem to be some people that do. \n", "Jinja is pretty cool and seems to work on Jython.\n", "Use StringTemplate, see http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf for details of why. There is nothing better, and it supports both Java and Python (and .NET, etc.).\n" ]
[ 2, 2, 1 ]
[]
[]
[ "jython", "python", "template_engine" ]
stackoverflow_0000157313_jython_python_template_engine.txt
Q: Find all nodes from an XML using cElementTree Is there a way to find all nodes in a xml tree using cElementTree? The findall method works only for specified tags. A: You can use XPath paths on the findall method: The 1.2 release supports simple element location paths. In its simplest form, a location path is one or more tag names, separated by slashes (/). You can also use an asterisk (*) instead of a tag name, to match all elements at that level. For example, */subtag returns all subtag grandchildren. An empty tag (//) is used to search on all levels of the tree, beneath the current level. The empty tag must always be followed by a tag name or an asterisk. etree.findall('.//*') A: Have you looked at node.getiterator()?
Find all nodes from an XML using cElementTree
Is there a way to find all nodes in a xml tree using cElementTree? The findall method works only for specified tags.
[ "You can use XPath paths on the findall method:\n\nThe 1.2 release supports simple\n element location paths. In its\n simplest form, a location path is one\n or more tag names, separated by\n slashes (/).\nYou can also use an asterisk (*)\n instead of a tag name, to match all\n elements at that level. For example,\n */subtag returns all subtag grandchildren.\nAn empty tag (//) is used to search on\n all levels of the tree, beneath the\n current level. The empty tag must\n always be followed by a tag name or an\n asterisk.\n\netree.findall('.//*')\n\n", "Have you looked at node.getiterator()?\n" ]
[ 3, 1 ]
[]
[]
[ "celementtree", "python", "search", "xml" ]
stackoverflow_0000304216_celementtree_python_search_xml.txt
Q: Running Django with FastCGI or with mod_python which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI? A: I've done both, and Apache/mod_python tended to be easier to work with and more stable. But these days I've jumped over to Apache/mod_wsgi, which is everything I've ever wanted and more: Easy management of daemon processes. As a result, much better process isolation (running multiple sites in the same Apache config with mod_python almost always ends in trouble -- environment variables and C extensions leak across sites when you do that). Easy code reloads (set it up right and you can just touch the .wsgi file to reload instead of restarting Apache). More predictable resource usage. With mod_python, a given Apache child process' memory use can jump around a lot. With mod_wsgi it's pretty stable: once everything's loaded, you know that's how much memory it'll use. A: lighttpd with FastCGI will be nominally faster, but really the time it takes to run your python code and any database hits it does is going to absolutely dwarf any performance benefit you get between web servers. mod_python and apache will give you a bit more flexibility feature-wise if you want to write code outside of django that does stuff like digest auth, or any fancy HTTP header getting/setting. Perhaps you want to use other builtin features of apache such as mod_rewrite. If memory is a concern, staying away form apache/mod_python will help a lot. Apache tends to use a lot of RAM, and the mod_python code that glues into all of the apache functionality occupies a lot of memory-space as well. Not to mention the multiprocess nature of apache tends to eat up more RAM, as each process grows to the size of it's most intensive request. A: Nginx with mod_wsgi A: Personally I've had it working with FastCGI for some time now (6 months or so) and the response times 'seem' quicker when loading a page that way vs mod___python. The critical reason for me though is that I couldn't see an obvious way to do multiple sites from the same apache / mod_python install whereas FastCGI was a relative no-brainer. I've not conducted any particularly thorough experiments though :-) [Edit] Speaking from experience though, setting up FastCGI can be a bit of a pain the first time around. I keep meaning to write a guide..! A: I'm using it with nginx. not sure if it's really faster, but certainly less RAM/CPU load. Also it's easier to run several Django processes and have nginx map each URL prefix to a different socket. still not taking full advantage of nginx's memcached module, but first tests show huge speed advantage. A: There's also mod_wsgi, it seems to be faster than mod_python and the daemon mode operates similar to FastCGI A: I'd recommend WSGI configurations; I keep meaning to ditch apache, but there is always some legacy app on the server that seems to require it. Additionally, the WSGI app ecology is very diverse, and it allows neat tricks such as daisy-chaining WSGI "middleware" between the server and the app. However, there are currently known issues with some apps and apache mod_wsgi, particularly some ctypes apps, so be wary if you are trying to run, say, geodjango which uses ctypes extensively. I'm currently working around those issues by going back to fastcgi myself.
Running Django with FastCGI or with mod_python
which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI?
[ "I've done both, and Apache/mod_python tended to be easier to work with and more stable. But these days I've jumped over to Apache/mod_wsgi, which is everything I've ever wanted and more:\n\nEasy management of daemon processes.\nAs a result, much better process isolation (running multiple sites in the same Apache config with mod_python almost always ends in trouble -- environment variables and C extensions leak across sites when you do that).\nEasy code reloads (set it up right and you can just touch the .wsgi file to reload instead of restarting Apache).\nMore predictable resource usage. With mod_python, a given Apache child process' memory use can jump around a lot. With mod_wsgi it's pretty stable: once everything's loaded, you know that's how much memory it'll use.\n\n", "lighttpd with FastCGI will be nominally faster, but really the time it takes to run your python code and any database hits it does is going to absolutely dwarf any performance benefit you get between web servers.\nmod_python and apache will give you a bit more flexibility feature-wise if you want to write code outside of django that does stuff like digest auth, or any fancy HTTP header getting/setting. Perhaps you want to use other builtin features of apache such as mod_rewrite.\nIf memory is a concern, staying away form apache/mod_python will help a lot. Apache tends to use a lot of RAM, and the mod_python code that glues into all of the apache functionality occupies a lot of memory-space as well. Not to mention the multiprocess nature of apache tends to eat up more RAM, as each process grows to the size of it's most intensive request.\n", "Nginx with mod_wsgi\n", "Personally I've had it working with FastCGI for some time now (6 months or so) and the response times 'seem' quicker when loading a page that way vs mod___python. The critical reason for me though is that I couldn't see an obvious way to do multiple sites from the same apache / mod_python install whereas FastCGI was a relative no-brainer.\nI've not conducted any particularly thorough experiments though :-)\n[Edit] Speaking from experience though, setting up FastCGI can be a bit of a pain the first time around. I keep meaning to write a guide..!\n", "I'm using it with nginx. not sure if it's really faster, but certainly less RAM/CPU load. Also it's easier to run several Django processes and have nginx map each URL prefix to a different socket. still not taking full advantage of nginx's memcached module, but first tests show huge speed advantage.\n", "There's also mod_wsgi, it seems to be faster than mod_python and the daemon mode operates similar to FastCGI\n", "I'd recommend WSGI configurations; I keep meaning to ditch apache, but there is always some legacy app on the server that seems to require it. Additionally, the WSGI app ecology is very diverse, and it allows neat tricks such as daisy-chaining WSGI \"middleware\" between the server and the app.\nHowever, there are currently known issues with some apps and apache mod_wsgi, particularly some ctypes apps, so be wary if you are trying to run, say, geodjango which uses ctypes extensively. I'm currently working around those issues by going back to fastcgi myself.\n" ]
[ 21, 6, 5, 2, 2, 2, 2 ]
[]
[]
[ "apache", "django", "fastcgi", "python" ]
stackoverflow_0000245237_apache_django_fastcgi_python.txt
Q: Python printing the word If any one can help me with Python code: If I input a letter, How can I print all the words start with that word? A: print [word for word in words if word.startswith(letter)] A: There are many ways of doing this, e.g.: words = ["zwei", "peanuts", "were", "walking", "down", "the", "strasse"] letter = "w" output = [x for x in words if x[0] == letter] The contents of output will be: ['were', 'walking'] Some notes: If the code needs to be fast you should put the wordlist in some kind of tree. If you need more flexibility, you should build a regular expression for matching
Python printing the word
If any one can help me with Python code: If I input a letter, How can I print all the words start with that word?
[ "print [word for word in words if word.startswith(letter)]\n\n", "There are many ways of doing this, e.g.:\nwords = [\"zwei\", \"peanuts\", \"were\", \"walking\", \"down\", \"the\", \"strasse\"]\nletter = \"w\"\noutput = [x for x in words if x[0] == letter]\n\nThe contents of output will be:\n['were', 'walking']\n\nSome notes:\n\nIf the code needs to be fast you should put the wordlist in some kind of tree.\nIf you need more flexibility, you should build a regular expression for matching\n\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000305422_python.txt
Q: How can I get a list of the running applications with GTK? How can I get a list of the running applications? I'm referring to the ones in the panel at the bottom of the screen. A: I believe what you are looking for is libwnck A: The panel you are referring to is the GNOME panel. So this is a GNOME question, not a GTK question. There is not a well-defined concept of "multi-window application" in GNOME that I know of. The panel task list is probably build by querying the window manager for the list of windows and grouping the windows by their "class" property. There are also various window manager hints that must be taken into account, for example to ignore panels and other utility windows. In your place, I would look at the source code of the taskbar applet. There is maybe some documentation somewhere that covers the status-quo, but I do know where it would be.
How can I get a list of the running applications with GTK?
How can I get a list of the running applications? I'm referring to the ones in the panel at the bottom of the screen.
[ "I believe what you are looking for is libwnck\n", "The panel you are referring to is the GNOME panel. So this is a GNOME question, not a GTK question.\nThere is not a well-defined concept of \"multi-window application\" in GNOME that I know of. The panel task list is probably build by querying the window manager for the list of windows and grouping the windows by their \"class\" property.\nThere are also various window manager hints that must be taken into account, for example to ignore panels and other utility windows. In your place, I would look at the source code of the taskbar applet. There is maybe some documentation somewhere that covers the status-quo, but I do know where it would be.\n" ]
[ 3, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0000306456_gtk_pygtk_python.txt
Q: With Python, how can I ensure that compression of a folder takes place within a particular folder? I have been able to zip the contents of my folder. But I would like the zipped file to remain in the folder that was just compressed. For example, I've zipped a folder called test in my C: drive. But I would like my "test.zip" file to be contained in C:\test. How can I do this? Thanks in advance. clarification of question with code example: Someone kindly pointed out that my question is confusing, but for a python newbie a lot of things are confusing :) - my advance apologies if this question is too basic or the answer is obvious. I don't know how I can ensure that the resulting zip file is inside the folder that has been zipped. In other words, I would like the zip process to take place in 'basedir.' That way the user does not waste time searching for it somewhere on the C drive. def zip_folder(basedir, zip_file): z = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(basedir): print "zipping files:" for fn in filenames: print fn absfn = os.path.join(dirpath, fn) z.write(absfn) z.close A: Whatever you pass as zip_file to your function will be the file that the ZipFile object will write to. So if you pass it a full path, then it will be put there. If you pass it just a filename, then it will be written to that filename under the current working path. It sounds like you just need to make sure that zip_file is an absolute path.
With Python, how can I ensure that compression of a folder takes place within a particular folder?
I have been able to zip the contents of my folder. But I would like the zipped file to remain in the folder that was just compressed. For example, I've zipped a folder called test in my C: drive. But I would like my "test.zip" file to be contained in C:\test. How can I do this? Thanks in advance. clarification of question with code example: Someone kindly pointed out that my question is confusing, but for a python newbie a lot of things are confusing :) - my advance apologies if this question is too basic or the answer is obvious. I don't know how I can ensure that the resulting zip file is inside the folder that has been zipped. In other words, I would like the zip process to take place in 'basedir.' That way the user does not waste time searching for it somewhere on the C drive. def zip_folder(basedir, zip_file): z = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(basedir): print "zipping files:" for fn in filenames: print fn absfn = os.path.join(dirpath, fn) z.write(absfn) z.close
[ "Whatever you pass as zip_file to your function will be the file that the ZipFile object will write to. So if you pass it a full path, then it will be put there. If you pass it just a filename, then it will be written to that filename under the current working path. It sounds like you just need to make sure that zip_file is an absolute path.\n" ]
[ 2 ]
[]
[]
[ "file", "python", "zip" ]
stackoverflow_0000306811_file_python_zip.txt
Q: Django foreign key access in save() function Here's my code: class Publisher(models.Model): name = models.CharField( max_length = 200, unique = True, ) url = models.URLField() def __unicode__(self): return self.name def save(self): pass class Item(models.Model): publisher = models.ForeignKey(Publisher) name = models.CharField( max_length = 200, ) code = models.CharField( max_length = 10, ) def __unicode__(self): return self.name I want to be able to access each Item from the Publisher save function. How can I do this? For instance, I'd like to append text to the code field of each Item associated with this Publisher on the save of Publisher. edit: When I try to implement the first solution, I get the error "'Publisher' object has no attribute 'item_set'". Apparently I can't access it that way. Any other clues? edit 2: I discovered that the problem occurring is that when I create a new Publisher object, I add Items inline. Therefor, when trying to save a Publisher and access the Items, they don't exist. Is there any way around this?! A: You should be able to do something like the following: def save(self, **kwargs): super(Publisher, self).save(**kwargs) for item in self.item_set.all(): item.code = "%s - whatever" % item.code I don't really like what you're doing here, this isn't a good way to relate Item to Publisher. What is it you're after in the end?
Django foreign key access in save() function
Here's my code: class Publisher(models.Model): name = models.CharField( max_length = 200, unique = True, ) url = models.URLField() def __unicode__(self): return self.name def save(self): pass class Item(models.Model): publisher = models.ForeignKey(Publisher) name = models.CharField( max_length = 200, ) code = models.CharField( max_length = 10, ) def __unicode__(self): return self.name I want to be able to access each Item from the Publisher save function. How can I do this? For instance, I'd like to append text to the code field of each Item associated with this Publisher on the save of Publisher. edit: When I try to implement the first solution, I get the error "'Publisher' object has no attribute 'item_set'". Apparently I can't access it that way. Any other clues? edit 2: I discovered that the problem occurring is that when I create a new Publisher object, I add Items inline. Therefor, when trying to save a Publisher and access the Items, they don't exist. Is there any way around this?!
[ "You should be able to do something like the following:\ndef save(self, **kwargs):\n super(Publisher, self).save(**kwargs)\n\n for item in self.item_set.all():\n item.code = \"%s - whatever\" % item.code\n\nI don't really like what you're doing here, this isn't a good way to relate Item to Publisher. What is it you're after in the end?\n" ]
[ 12 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000307038_django_django_models_python.txt
Q: The best way to invoke methods in Python class declarations? Say I am declaring a class C and a few of the declarations are very similar. I'd like to use a function f to reduce code repetition for these declarations. It's possible to just declare and use f as usual: >>> class C(object): ... def f(num): ... return '<' + str(num) + '>' ... v = f(9) ... w = f(42) ... >>> C.v '<9>' >>> C.w '<42>' >>> C.f(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method f() must be called with C instance as first argument (got int instance instead) Oops! I've inadvertently exposed f to the outside world, but it doesn't take a self argument (and can't for obvious reasons). One possibility would be to del the function after I use it: >>> class C(object): ... def f(num): ... return '<' + str(num) + '>' ... v = f(9) ... del f ... >>> C.v '<9>' >>> C.f Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'C' has no attribute 'f' But what if I want to use f again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with __) and give it the @staticmethod treatment, but invoking staticmethod objects through abnormal channels gets very funky: >>> class C(object): ... @staticmethod ... def __f(num): ... return '<' + str(num) + '>' ... v = __f.__get__(1)(9) # argument to __get__ is ignored... ... >>> C.v '<9>' I have to use the above craziness because staticmethod objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the staticmethod object before I can call it. There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this? A: Quite simply, the solution is that f does not need to be a member of the class. I am assuming that your thought-process has gone through a Javaish language filter causing the mental block. It goes a little something like this: def f(n): return '<' + str(num) + '>' class C(object): v = f(9) w = f(42) Then when you want to use f again, just use it >>> f(4) '<4>' I think the moral of the tale is "In Python, you don't have to force everything into a class". A: Extending Ali A's answer, if you really want to avoid f in the module namespace (and using a non-exported name like _f, or setting __all__ isn't sufficient), then you could achieve this by creating the class within a closure. def create_C(): def f(num): return '<' + str(num) + '>' class C(object): v = f(9) def method_using_f(self, x): return f(x*2) return C C=create_C() del create_C This way C has access to f within its definition and methods, but nothing else does (barring fairly involved introspection of its methods (C.method_using_f.im_func.func_closure)) This is probably overkill for most purposes though - documenting that f is internal by using the "_" prefix nameing convention should generally be sufficient. [Edit] One other option is to hold a reference to the pre-wrapped function object in the methods you wish to use it in. For example, by setting it as a default argument: class C(object): def f(num): return '<' + str(num) + '>' v = f(9) def method_using_f(self, x, f=f): return f(x*2) del f (Though I think the closure approach is probably better) A: I believe you are trying to do this: class C(): ... class F(): ... def __call__(self,num): ... return "<"+str(num)+">" ... f=F() ... v=f(9) >>> C.v '<9>' >>> C.f(25) '<25>' >>> Maybe there is better or more pythonic solution... "declare a function in a class, use it during its declaration, and also use it later from within the class" Sorry. Can't be done. "Can't be done" doesn't seem to get along with Python A: This is one possibility: class _C: # Do most of the function definitions in here @classmethod def f(cls): return 'boo' class C(_C): # Do the subsequent decoration in here v = _C.f() A: One option: write a better staticmethod: class staticfunc(object): def __init__(self, func): self.func = func def __call__(self, *args, **kw): return self.func(*args, **kw) def __repr__(self): return 'staticfunc(%r)' % self.func A: Let's begin from the beginning. "declare a function in a class, use it during its declaration, and also use it later from within the class" Sorry. Can't be done. "In a class" contradicts "used during declaration". In a class means created as part of the declaration. Used during declaration means it exists outside the class. Often as a meta class. However, there are other ways. It's not clear what C.w and C.v are supposed to be. Are they just strings? If so, an external function f is the best solution. The "not clutter the namespace" is a bit specious. After all, you want to use it again. It's in the same module as C. That's why Python has modules. It binds the function and class together. import myCmod myCmod.C.w myCmod.C.v myCmod.f(42) If w and v aren't simple strings, there's a really good solution that gives a lot of flexibility. Generally, for class-level ("static") variables like this, we can use other classes. It's not possible to completely achieve the desired API, but this is close. >>> class F(object): def __init__( self, num ): self.value= num self.format= "<%d>" % ( num, ) >>> class C(object): w= F(42) v= F(9) >>> C.w <__main__.F object at 0x00C58C30> >>> C.w.format '<42>' >>> C.v.format '<9>' The advantage of this is that F is a proper, first-class thing that can be extended. Not a "hidden" thing that we're trying to avoid exposing. It's a fact of life, so we might as well follow the Open/Closed principle and make it open to extension.
The best way to invoke methods in Python class declarations?
Say I am declaring a class C and a few of the declarations are very similar. I'd like to use a function f to reduce code repetition for these declarations. It's possible to just declare and use f as usual: >>> class C(object): ... def f(num): ... return '<' + str(num) + '>' ... v = f(9) ... w = f(42) ... >>> C.v '<9>' >>> C.w '<42>' >>> C.f(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method f() must be called with C instance as first argument (got int instance instead) Oops! I've inadvertently exposed f to the outside world, but it doesn't take a self argument (and can't for obvious reasons). One possibility would be to del the function after I use it: >>> class C(object): ... def f(num): ... return '<' + str(num) + '>' ... v = f(9) ... del f ... >>> C.v '<9>' >>> C.f Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'C' has no attribute 'f' But what if I want to use f again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with __) and give it the @staticmethod treatment, but invoking staticmethod objects through abnormal channels gets very funky: >>> class C(object): ... @staticmethod ... def __f(num): ... return '<' + str(num) + '>' ... v = __f.__get__(1)(9) # argument to __get__ is ignored... ... >>> C.v '<9>' I have to use the above craziness because staticmethod objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the staticmethod object before I can call it. There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this?
[ "Quite simply, the solution is that f does not need to be a member of the class. I am assuming that your thought-process has gone through a Javaish language filter causing the mental block. It goes a little something like this:\ndef f(n):\n return '<' + str(num) + '>'\n\nclass C(object):\n\n v = f(9)\n w = f(42)\n\nThen when you want to use f again, just use it\n>>> f(4)\n'<4>'\n\nI think the moral of the tale is \"In Python, you don't have to force everything into a class\". \n", "Extending Ali A's answer,\nif you really want to avoid f in the module namespace (and using a non-exported name like _f, or setting __all__ isn't sufficient), then\nyou could achieve this by creating the class within a closure.\ndef create_C():\n def f(num):\n return '<' + str(num) + '>'\n\n class C(object):\n v = f(9)\n def method_using_f(self, x): return f(x*2)\n return C\n\nC=create_C()\ndel create_C\n\nThis way C has access to f within its definition and methods, but nothing else does (barring fairly involved introspection\nof its methods (C.method_using_f.im_func.func_closure))\nThis is probably overkill for most purposes though - documenting that f is internal by using the \"_\" prefix nameing convention should\ngenerally be sufficient.\n[Edit] One other option is to hold a reference to the pre-wrapped function object in the methods you wish to use it in. For example, by setting it as a default argument:\nclass C(object):\n def f(num):\n return '<' + str(num) + '>'\n\n v = f(9)\n def method_using_f(self, x, f=f): return f(x*2)\n\n del f\n\n(Though I think the closure approach is probably better)\n", "I believe you are trying to do this:\nclass C():\n... class F():\n... def __call__(self,num):\n... return \"<\"+str(num)+\">\"\n... f=F()\n... v=f(9)\n>>> C.v\n'<9>'\n>>> C.f(25)\n'<25>'\n>>> \n\nMaybe there is better or more pythonic solution...\n\n\"declare a function in a class, use it during its declaration, and also use it later from within the class\"\nSorry. Can't be done.\n\n\"Can't be done\" doesn't seem to get along with Python\n", "This is one possibility:\nclass _C:\n # Do most of the function definitions in here\n @classmethod\n def f(cls):\n return 'boo'\n\nclass C(_C):\n # Do the subsequent decoration in here\n v = _C.f()\n\n", "One option: write a better staticmethod:\nclass staticfunc(object):\n def __init__(self, func):\n self.func = func\n def __call__(self, *args, **kw):\n return self.func(*args, **kw)\n def __repr__(self):\n return 'staticfunc(%r)' % self.func\n\n", "Let's begin from the beginning.\n\"declare a function in a class, use it during its declaration, and also use it later from within the class\"\nSorry. Can't be done. \"In a class\" contradicts \"used during declaration\".\n\nIn a class means created as part of the declaration.\nUsed during declaration means it exists outside the class. Often as a meta class. However, there are other ways.\n\nIt's not clear what C.w and C.v are supposed to be. Are they just strings? If so, an external function f is the best solution. The \"not clutter the namespace\" is a bit specious. After all, you want to use it again.\nIt's in the same module as C. That's why Python has modules. It binds the function and class together.\nimport myCmod\n\nmyCmod.C.w\nmyCmod.C.v\nmyCmod.f(42)\n\nIf w and v aren't simple strings, there's a really good solution that gives a lot of flexibility.\nGenerally, for class-level (\"static\") variables like this, we can use other classes. It's not possible to completely achieve the desired API, but this is close.\n>>> class F(object):\n def __init__( self, num ):\n self.value= num\n self.format= \"<%d>\" % ( num, )\n\n>>> class C(object):\n w= F(42)\n v= F(9)\n\n>>> C.w\n<__main__.F object at 0x00C58C30>\n>>> C.w.format\n'<42>'\n>>> C.v.format\n'<9>'\n\nThe advantage of this is that F is a proper, first-class thing that can be extended. Not a \"hidden\" thing that we're trying to avoid exposing. It's a fact of life, so we might as well follow the Open/Closed principle and make it open to extension.\n" ]
[ 14, 3, 2, 1, 1, 0 ]
[]
[]
[ "class", "declaration", "invocation", "python", "static_methods" ]
stackoverflow_0000304655_class_declaration_invocation_python_static_methods.txt
Q: Embedded Web Server in Python? Can you recommend a minimalistic python webserver that I can embedded in my Desktop Application. A: How minimalistic and for what purpose? SimpleHTTPServer comes free as part of the standard Python libraries. If you need more features, look into CherryPy or (at the top end) Twisted. A: I'm becoming a big fan of the newly released circuits library. It's a component/event framework that comes with a very nice set of packages for creating web servers & apps. Here's the simple web example from the site: from circuits.lib.web import Server, Controller class HelloWorld(Controller): def index(self): return "Hello World!" server = Server(8000) server += HelloWorld() server.run() Its WSGI support is no more complicated than that, either. Good stuff. A: If you're doing a lot of concurrent stuff, you might consider Kamaelia's HTTPServer. A: I've found web.py pretty easy to use : http://webpy.org/ A: If you want to use something from the standard library I would strongly recommend not using SimpleHTTPServer, but instead using wsgiref.simple_server. SimpleHTTPServer is awkward and a rather nonsensical way to implement a web application, and while raw WSGI isn't terribly easy (but certainly possible), you have the option to use any WSGI-based framework on top of it. Also if you use wsgiref you will have the option to change to a server like CherryPy later (note that the server in CherryPy can be used separately from the rest of the framework, and you only need one file for just the server). For a "real" web application CherryPy has several advantages over wsgiref, but for a locally hosted application it's unlikely any of them will matter. If you are making a desktop application you will need to launch a separate thread for either wsgiref or CherryPy. If that's fine, then a WSGI-based server would probably be easiest. If you don't want to launch a separate thread for the server then you most likely need to use Twisted. A: See the WSGI reference implementation. A: I made this one. It just enhances Python's SimpleHTTPServer a bit to let you define custom actions depending on the request.
Embedded Web Server in Python?
Can you recommend a minimalistic python webserver that I can embedded in my Desktop Application.
[ "How minimalistic and for what purpose? \nSimpleHTTPServer comes free as part of the standard Python libraries.\nIf you need more features, look into CherryPy or (at the top end) Twisted.\n", "I'm becoming a big fan of the newly released circuits library. It's a component/event framework that comes with a very nice set of packages for creating web servers & apps. Here's the simple web example from the site:\nfrom circuits.lib.web import Server, Controller\n\nclass HelloWorld(Controller):\n def index(self):\n return \"Hello World!\"\n\nserver = Server(8000)\nserver += HelloWorld()\nserver.run()\n\nIts WSGI support is no more complicated than that, either. Good stuff.\n", "If you're doing a lot of concurrent stuff, you might consider Kamaelia's HTTPServer.\n", "I've found web.py pretty easy to use : http://webpy.org/\n", "If you want to use something from the standard library I would strongly recommend not using SimpleHTTPServer, but instead using wsgiref.simple_server. SimpleHTTPServer is awkward and a rather nonsensical way to implement a web application, and while raw WSGI isn't terribly easy (but certainly possible), you have the option to use any WSGI-based framework on top of it. Also if you use wsgiref you will have the option to change to a server like CherryPy later (note that the server in CherryPy can be used separately from the rest of the framework, and you only need one file for just the server). For a \"real\" web application CherryPy has several advantages over wsgiref, but for a locally hosted application it's unlikely any of them will matter.\nIf you are making a desktop application you will need to launch a separate thread for either wsgiref or CherryPy. If that's fine, then a WSGI-based server would probably be easiest. If you don't want to launch a separate thread for the server then you most likely need to use Twisted.\n", "See the WSGI reference implementation.\n", "I made this one. It just enhances Python's SimpleHTTPServer a bit to let you define custom actions depending on the request.\n" ]
[ 17, 5, 4, 3, 3, 1, 0 ]
[]
[]
[ "embeddedwebserver", "python", "simplehttpserver" ]
stackoverflow_0000302615_embeddedwebserver_python_simplehttpserver.txt
Q: Why do new instances of a class share members with other instances? class Ball: a = [] def __init__(self): pass def add(self,thing): self.a.append(thing) def size(self): print len(self.a) for i in range(3): foo = Ball() foo.add(1) foo.add(2) foo.size() I would expect a return of : 2 2 2 But I get : 2 4 6 Why is this? I've found that by doing a=[] in the init, I can route around this behavior, but I'm less than clear why. A: doh I just figured out why. In the above case, the a is a class attribute, not a data attribute - those are shared by all Balls(). Commenting out the a=[] and placing it into the init block means that it's a data attribute instead. (And, I couldn't access it then with foo.a, which I shouldn't do anyhow.) It seems like the class attributes act like static attributes of the class, they're shared by all instances. Whoa. One question though : CodeCompletion sucks like this. In the foo class, I can't do self.(variable), because it's not being defined automatically - it's being defined by a function. Can I define a class variable and replace it with a data variable? A: What you probably want to do is: class Ball: def __init__(self): self.a = [] If you use just a = [], it creates a local variable in the __init__ function, which disappears when the function returns. Assigning to self.a makes it an instance variable which is what you're after. For a semi-related gotcha, see how you can change the value of default parameters for future callers. A: "Can I define a class variable and replace it with a data variable?" No. They're separate things. A class variable exists precisely once -- in the class. You could -- to finesse code completion -- start with some class variables and then delete those lines of code after you've written your class. But every time you forget to do that nothing good will happen. Better is to try a different IDE. Komodo Edit's code completions seem to be sensible. If you have so many variables with such long names that code completion is actually helpful, perhaps you should make your classes smaller or use shorter names. Seriously. I find that when you get to a place where code completion is more helpful than annoying, you've exceeded the "keep it all in my brain" complexity threshold. If the class won't fit in my brain, it's too complex.
Why do new instances of a class share members with other instances?
class Ball: a = [] def __init__(self): pass def add(self,thing): self.a.append(thing) def size(self): print len(self.a) for i in range(3): foo = Ball() foo.add(1) foo.add(2) foo.size() I would expect a return of : 2 2 2 But I get : 2 4 6 Why is this? I've found that by doing a=[] in the init, I can route around this behavior, but I'm less than clear why.
[ "doh\nI just figured out why.\nIn the above case, the a is a class attribute, not a data attribute - those are shared by all Balls(). Commenting out the a=[] and placing it into the init block means that it's a data attribute instead. (And, I couldn't access it then with foo.a, which I shouldn't do anyhow.) It seems like the class attributes act like static attributes of the class, they're shared by all instances. \nWhoa. \nOne question though : CodeCompletion sucks like this. In the foo class, I can't do self.(variable), because it's not being defined automatically - it's being defined by a function. Can I define a class variable and replace it with a data variable?\n", "What you probably want to do is:\nclass Ball:\n def __init__(self):\n self.a = []\n\nIf you use just a = [], it creates a local variable in the __init__ function, which disappears when the function returns. Assigning to self.a makes it an instance variable which is what you're after.\nFor a semi-related gotcha, see how you can change the value of default parameters for future callers.\n", "\"Can I define a class variable and replace it with a data variable?\"\nNo. They're separate things. A class variable exists precisely once -- in the class.\nYou could -- to finesse code completion -- start with some class variables and then delete those lines of code after you've written your class. But every time you forget to do that nothing good will happen.\nBetter is to try a different IDE. Komodo Edit's code completions seem to be sensible.\nIf you have so many variables with such long names that code completion is actually helpful, perhaps you should make your classes smaller or use shorter names. Seriously. \nI find that when you get to a place where code completion is more helpful than annoying, you've exceeded the \"keep it all in my brain\" complexity threshold. If the class won't fit in my brain, it's too complex.\n" ]
[ 4, 2, 1 ]
[]
[]
[ "mutable", "python", "scope" ]
stackoverflow_0000307729_mutable_python_scope.txt
Q: pygtk glade question: why isn't this simple script working? I've been writing writing a small pygtk application using glade to put together the UIs. I've created several windows already that work, but for some reason this one isn't working. I get the following traceback: Traceback (most recent call last): File "test.py", line 7, in <module> class TestClass: File "test.py", line 10, in TestClass self.wTree.signal_autoconnect(self) NameError: name 'self' is not defined Here is the contents of test.py: #!/usr/bin/env python import pygtk import gtk import gtk.glade class TestClass: def __init__(self): self.wTree = gtk.glade.XML("test.glade") self.wTree.signal_autoconnect(self) def on_TestClass_destroy(self, widget, data): gtk.main_quit() if __name__ == "__main__": window = TestClass() gtk.main() And here is the glade file, test.glade: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> <!--Generated with glade3 3.4.5 on Fri Nov 21 08:53:53 2008 --> <glade-interface> <widget class="GtkWindow" id="TestWindow"> <property name="visible">True</property> <property name="title" translatable="yes">Test Window</property> <signal name="destroy" handler="on_TestClass_destroy"/> <child> <placeholder/> </child> </widget> </glade-interface> The strange thing is that if I take out the signal_autoconnect(self) call, the window opens. But if I replace that call with "self.on_TestClass_destroy(self, None, None)" instead, it returns the same NameError exception. I really don't understand why this isn't working, as I've created several other window classes that work fine. Is the following code working for anyone here? A: That code and window and signal connection work fine here. There is a small bug though when calling the signal handler. The signal handler should not have a data argument, since only the widget is passed as an argument. def on_TestClass_destroy(self, widget): gtk.main_quit() The data argument(s) are only those provided on connect in case you need extra state for a signal handler.
pygtk glade question: why isn't this simple script working?
I've been writing writing a small pygtk application using glade to put together the UIs. I've created several windows already that work, but for some reason this one isn't working. I get the following traceback: Traceback (most recent call last): File "test.py", line 7, in <module> class TestClass: File "test.py", line 10, in TestClass self.wTree.signal_autoconnect(self) NameError: name 'self' is not defined Here is the contents of test.py: #!/usr/bin/env python import pygtk import gtk import gtk.glade class TestClass: def __init__(self): self.wTree = gtk.glade.XML("test.glade") self.wTree.signal_autoconnect(self) def on_TestClass_destroy(self, widget, data): gtk.main_quit() if __name__ == "__main__": window = TestClass() gtk.main() And here is the glade file, test.glade: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> <!--Generated with glade3 3.4.5 on Fri Nov 21 08:53:53 2008 --> <glade-interface> <widget class="GtkWindow" id="TestWindow"> <property name="visible">True</property> <property name="title" translatable="yes">Test Window</property> <signal name="destroy" handler="on_TestClass_destroy"/> <child> <placeholder/> </child> </widget> </glade-interface> The strange thing is that if I take out the signal_autoconnect(self) call, the window opens. But if I replace that call with "self.on_TestClass_destroy(self, None, None)" instead, it returns the same NameError exception. I really don't understand why this isn't working, as I've created several other window classes that work fine. Is the following code working for anyone here?
[ "That code and window and signal connection work fine here.\nThere is a small bug though when calling the signal handler. The signal handler should not have a data argument, since only the widget is passed as an argument.\ndef on_TestClass_destroy(self, widget):\n gtk.main_quit()\n\nThe data argument(s) are only those provided on connect in case you need extra state for a signal handler.\n" ]
[ 4 ]
[]
[]
[ "glade", "gtk", "pygtk", "python" ]
stackoverflow_0000308913_glade_gtk_pygtk_python.txt
Q: Python data structures overhead/performance Is there any performance advantage to using lists over dictionaries over tuples in Python? If I'm optimising for speed, is there any reason to prefer one over another? A: Rich, Lists and dicts are beasts suitable for different needs. Make sure you don't use lists for linear searches where dicts hashes are perfect, because it's way slower. Also, if you just need a list of elements to traverse, don't use dicts because it will take much more space than lists. That may sound obvious, but picking the correct data structures algorithmically has much higher performance gains that micro-optimization due to more efficient compiled code layouts, etc. If you search in a list in O(n) instead of in a dict in O(1), micro-optimizations won't save you. A: Tuples will be slightly faster to construct for a small number of elements. Although actually most of the gains will be in memory used rather than CPU cycles, since tuples require less space than lists. With that being said, the performance difference should be negligible, and in general you shouldn't worry about these kinds of micro-optimizations until you've profiled your code and identified a section of code that is a bottleneck. A: The big difference is that tuples are immutable, while lists and dictionaries are mutable data structures. This means that tuples are also faster, so if you have a collection of items that doesn't change, you should prefer them over lists. A: See the following. Speeding Up Python When should you start optimising code Is premature optimization really the root of all evil? Are tuples more efficient than lists in Python?
Python data structures overhead/performance
Is there any performance advantage to using lists over dictionaries over tuples in Python? If I'm optimising for speed, is there any reason to prefer one over another?
[ "Rich,\nLists and dicts are beasts suitable for different needs. Make sure you don't use lists for linear searches where dicts hashes are perfect, because it's way slower. Also, if you just need a list of elements to traverse, don't use dicts because it will take much more space than lists.\nThat may sound obvious, but picking the correct data structures algorithmically has much higher performance gains that micro-optimization due to more efficient compiled code layouts, etc. If you search in a list in O(n) instead of in a dict in O(1), micro-optimizations won't save you.\n", "Tuples will be slightly faster to construct for a small number of elements. Although actually most of the gains will be in memory used rather than CPU cycles, since tuples require less space than lists.\nWith that being said, the performance difference should be negligible, and in general you shouldn't worry about these kinds of micro-optimizations until you've profiled your code and identified a section of code that is a bottleneck.\n", "The big difference is that tuples are immutable, while lists and dictionaries are mutable data structures. This means that tuples are also faster, so if you have a collection of items that doesn't change, you should prefer them over lists.\n", "See the following.\n\nSpeeding Up Python\nWhen should you start optimising code\nIs premature optimization really the root of all evil?\nAre tuples more efficient than lists in Python?\n\n" ]
[ 20, 6, 2, 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0000308912_optimization_python.txt
Q: Python - Setting / Getting Environment Variables and Addrs I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if that's the only way). How would you do this? Edit: The scope of the problem is as follows: I'm trying to hack a program for class, and essentially I'm putting my shellcode into an environment variable and then overwriting one byte on the victim code with the address of my environment variable. I need to find a way to automate this in Python, so my question is two-fold: Is there a way to get the address in memory of an environment variable? Can this only be done in bash/C or can I do it purely in Python? A: For accessing and setting environment variables, read up on the os.environ dictionary. You can also use os.putenv to set an environment variable. A: The built in function id() returns a unique id for any object, which just happens to be it's memory address. http://docs.python.org/library/functions.html#id A: Pass the address itself in an environment variable, and just read it with os.getenv().
Python - Setting / Getting Environment Variables and Addrs
I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if that's the only way). How would you do this? Edit: The scope of the problem is as follows: I'm trying to hack a program for class, and essentially I'm putting my shellcode into an environment variable and then overwriting one byte on the victim code with the address of my environment variable. I need to find a way to automate this in Python, so my question is two-fold: Is there a way to get the address in memory of an environment variable? Can this only be done in bash/C or can I do it purely in Python?
[ "For accessing and setting environment variables, read up on the os.environ dictionary. You can also use os.putenv to set an environment variable.\n", "The built in function id() returns a unique id for any object, which just happens to be it's memory address. \nhttp://docs.python.org/library/functions.html#id\n", "Pass the address itself in an environment variable, and just read it with os.getenv().\n" ]
[ 4, 1, 0 ]
[]
[]
[ "environment_variables", "linux", "python" ]
stackoverflow_0000310118_environment_variables_linux_python.txt
Q: Cleaning form data in Django How can i clean and modify data from a form in django. I would like to define it on a per field basis for each model, much like using ModelForms. What I want to achieve is automatically remove leading and trailing spaces from defined fields, or turn a title (from one field) into a slug (which would be another field). A: You can define clean_FIELD_NAME() methods which can validate and alter data, as documented here: http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation
Cleaning form data in Django
How can i clean and modify data from a form in django. I would like to define it on a per field basis for each model, much like using ModelForms. What I want to achieve is automatically remove leading and trailing spaces from defined fields, or turn a title (from one field) into a slug (which would be another field).
[ "You can define clean_FIELD_NAME() methods which can validate and alter data, as documented here: http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation\n" ]
[ 12 ]
[]
[]
[ "django", "forms", "python", "slug" ]
stackoverflow_0000310931_django_forms_python_slug.txt
Q: How can I translate the following filename to a regular expression in Python? I am battling regular expressions now as I type. I would like to determine a pattern for the following example file: b410cv11_test.ext. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. Further clarification of question: I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext' A: Now that you have a human readable description of your file name, it's quite straight forward to translate it into a regular expression (at least in this case ;) must start with The caret (^) anchors a regular expression to the beginning of what you want to match, so your re has to start with this symbol. 'b', Any non-special character in your re will match literally, so you just use "b" for this part: ^b. followed by [...] digits, This depends a bit on which flavor of re you use: The most general way of expressing this is to use brackets ([]). Those mean "match any one of the characters listed within. [ASDF] for example would match either A or S or D or F, [0-9] would match anything between 0 and 9. Your re library probably has a shortcut for "any digit". In sed and awk you could use [[:digit:]] [sic!], in python and many other languages you can use \d. So now your re reads ^b\d. followed by three [...] The most simple way to express this would be to just repeat the atom three times like this: \d\d\d. Again your language might provide a shortcut: braces ({}). Sometimes you would have to escape them with a backslash (if you are using sed or awk, read about "extended regular expressions"). They also give you a way to say "at least x, but no more than y occurances of the previous atom": {x,y}. Now you have: ^b\d{3} followed by 'cv', Literal matching again, now we have ^b\d{3}cv followed by two digits, We already covered this: ^b\d{3}cv\d{2}. then an underscore, followed by 'release', followed by .'ext' Again, this should all match literally, but the dot (.) is a special character. This means you have to escape it with a backslash: ^\d{3}cv\d{2}_release\.ext Leaving out the backslash would mean that a filename like "b410cv11_test_ext" would also match, which may or may not be a problem for you. Finally, if you want to guarantee that there is nothing else following ".ext", anchor the re to the end of the thing to match, use the dollar sign ($). Thus the complete regular expression for your specific problem would be: ^b\d{3}cv\d{2}_release\.ext$ Easy. Whatever language or library you use, there has to be a reference somewhere in the documentation that will show you what the exact syntax in your case should be. Once you have learned to break down the problem into a suitable description, understanding the more advanced constructs will come to you step by step. A: To avoid confusion, read the following, in order. First, you have the glob module, which handles file name regular expressions just like the Windows and unix shells. Second, you have the fnmatch module, which just does pattern matching using the unix shell rules. Third, you have the re module, which is the complete set of regular expressions. Then ask another, more specific question. A: I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext' ^b\d{3}cv\d{2}_release\.ext$ A: Your question is a bit unclear. You say you want a regular expression, but could it be that you want a glob-style pattern you can use with commands like ls? glob expressions and regular expressions are similar in concept but different in practice (regular expressions are considerably more powerful, glob style patterns are easier for the most common cases when looking for files. Also, what do you consider to be the pattern? Certainly, * (glob) or .* (regex) will match the pattern. Also, _test.ext (glob) or ._test.ext (regexp) pattern would match, as would many other variations. Can you be more specific about the pattern? For example, you might describe it as "b, followed by digits, followed by cv, followed by digits ..." Once you can precisely explain the pattern in your native language (and that must be your first step), it's usually a fairly straight-forward task to translate that into a glob or regular expression pattern. A: if the letters are unimportant, you could try \w\d\d\d\w\w\d\d_test.ext which would match the letter/number pattern, or b\d\d\dcv\d\d_test.ext or some mix of the two. A: When working with regexes I find the Mochikit regex example to be a great help. /^b\d\d\dcv\d\d_test\.ext$/ Then use the python re (regex) module to do the match. This is of course assuming regex is really what you need and not glob as the others mentioned.
How can I translate the following filename to a regular expression in Python?
I am battling regular expressions now as I type. I would like to determine a pattern for the following example file: b410cv11_test.ext. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. Further clarification of question: I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'
[ "Now that you have a human readable description of your file name, it's quite straight forward to translate it into a regular expression (at least in this case ;)\n\nmust start with\n\nThe caret (^) anchors a regular expression to the beginning of what you want to match, so your re has to start with this symbol.\n\n'b',\n\nAny non-special character in your re will match literally, so you just use \"b\" for this part: ^b.\n\nfollowed by [...] digits,\n\nThis depends a bit on which flavor of re you use:\nThe most general way of expressing this is to use brackets ([]). Those mean \"match any one of the characters listed within. [ASDF] for example would match either A or S or D or F, [0-9] would match anything between 0 and 9.\nYour re library probably has a shortcut for \"any digit\". In sed and awk you could use [[:digit:]] [sic!], in python and many other languages you can use \\d.\nSo now your re reads ^b\\d.\n\nfollowed by three [...]\n\nThe most simple way to express this would be to just repeat the atom three times like this: \\d\\d\\d.\nAgain your language might provide a shortcut: braces ({}). Sometimes you would have to escape them with a backslash (if you are using sed or awk, read about \"extended regular expressions\"). They also give you a way to say \"at least x, but no more than y occurances of the previous atom\": {x,y}.\nNow you have: ^b\\d{3}\n\nfollowed by 'cv',\n\nLiteral matching again, now we have ^b\\d{3}cv\n\nfollowed by two digits,\n\nWe already covered this: ^b\\d{3}cv\\d{2}.\n\nthen an underscore, followed by 'release', followed by .'ext'\n\nAgain, this should all match literally, but the dot (.) is a special character. This means you have to escape it with a backslash: ^\\d{3}cv\\d{2}_release\\.ext\nLeaving out the backslash would mean that a filename like \"b410cv11_test_ext\" would also match, which may or may not be a problem for you.\nFinally, if you want to guarantee that there is nothing else following \".ext\", anchor the re to the end of the thing to match, use the dollar sign ($).\nThus the complete regular expression for your specific problem would be:\n^b\\d{3}cv\\d{2}_release\\.ext$\n\nEasy.\nWhatever language or library you use, there has to be a reference somewhere in the documentation that will show you what the exact syntax in your case should be. Once you have learned to break down the problem into a suitable description, understanding the more advanced constructs will come to you step by step.\n", "To avoid confusion, read the following, in order.\nFirst, you have the glob module, which handles file name regular expressions just like the Windows and unix shells.\nSecond, you have the fnmatch module, which just does pattern matching using the unix shell rules.\nThird, you have the re module, which is the complete set of regular expressions.\nThen ask another, more specific question.\n", "\nI would like the pattern to be as\n follows: must start with 'b', followed\n by three digits, followed by 'cv',\n followed by two digits, then an\n underscore, followed by 'release',\n followed by .'ext'\n\n^b\\d{3}cv\\d{2}_release\\.ext$\n\n", "Your question is a bit unclear. You say you want a regular expression, but could it be that you want a glob-style pattern you can use with commands like ls? glob expressions and regular expressions are similar in concept but different in practice (regular expressions are considerably more powerful, glob style patterns are easier for the most common cases when looking for files. \nAlso, what do you consider to be the pattern? Certainly, * (glob) or .* (regex) will match the pattern. Also, _test.ext (glob) or ._test.ext (regexp) pattern would match, as would many other variations. \nCan you be more specific about the pattern? For example, you might describe it as \"b, followed by digits, followed by cv, followed by digits ...\" \nOnce you can precisely explain the pattern in your native language (and that must be your first step), it's usually a fairly straight-forward task to translate that into a glob or regular expression pattern. \n", "if the letters are unimportant, you could try \\w\\d\\d\\d\\w\\w\\d\\d_test.ext which would match the letter/number pattern, or b\\d\\d\\dcv\\d\\d_test.ext or some mix of the two.\n", "When working with regexes I find the Mochikit regex example to be a great help.\n/^b\\d\\d\\dcv\\d\\d_test\\.ext$/\n\nThen use the python re (regex) module to do the match. This is of course assuming regex is really what you need and not glob as the others mentioned.\n" ]
[ 12, 4, 4, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000310199_python_regex.txt
Q: using rstrip on form.cleaned_data[i] in Django In my views.py, i have a snippit of code like this: def clean_post_data(form): for i in form.cleaned_data: form.cleaned_data[i] = form.cleaned_data[i].rstrip() def add_product(request): form = ProductForm(request.POST, request.FILES or None) image = Image.objects.all() action = "Add" if request.POST: if form.is_valid(): clean_post_data(form) form.save() action = "Added new product" return render_to_response('cms/admin/action.html', {'action' : action},context_instance=RequestContext(request)) else: action = "There was an error. Please go back and try again" return render_to_response('cms/admin/action.html', {'action' : action}, context_instance=RequestContext(request)) return render_to_response('cms/admin/editproduct.html', {'form' : form, 'action' : action, 'image' : image}, context_instance=RequestContext(request)) But when i run that, i get the following error 'list' object has no attribute 'rstrip'. What am i doing wrong. I originally had the for i in form.cleaned_data: loop directly in the view (not in another function) and it worked fine, but now when i try it i get the same error as above. http://dpaste.com/92836/ A: The clean_post_data shouldn't be a stand-alone function. It should be a method in the form, named clean. See Form and Field Validation. A: Most likely you have several elements on your form with same name. When it is submitted one of the elements returned by cleaned_data is a list If you want to skip (or do something special about) such cases you need to check for it: def clean_post_data(form): for i in form.cleaned_data: if('__iter__' in dir(form.cleaned_data[i])): print "skip this element: " + str(form.cleaned_data[i]) else: form.cleaned_data[i] = form.cleaned_data[i].rstrip()
using rstrip on form.cleaned_data[i] in Django
In my views.py, i have a snippit of code like this: def clean_post_data(form): for i in form.cleaned_data: form.cleaned_data[i] = form.cleaned_data[i].rstrip() def add_product(request): form = ProductForm(request.POST, request.FILES or None) image = Image.objects.all() action = "Add" if request.POST: if form.is_valid(): clean_post_data(form) form.save() action = "Added new product" return render_to_response('cms/admin/action.html', {'action' : action},context_instance=RequestContext(request)) else: action = "There was an error. Please go back and try again" return render_to_response('cms/admin/action.html', {'action' : action}, context_instance=RequestContext(request)) return render_to_response('cms/admin/editproduct.html', {'form' : form, 'action' : action, 'image' : image}, context_instance=RequestContext(request)) But when i run that, i get the following error 'list' object has no attribute 'rstrip'. What am i doing wrong. I originally had the for i in form.cleaned_data: loop directly in the view (not in another function) and it worked fine, but now when i try it i get the same error as above. http://dpaste.com/92836/
[ "The clean_post_data shouldn't be a stand-alone function.\nIt should be a method in the form, named clean. See Form and Field Validation.\n", "Most likely you have several elements on your form with same name. When it is submitted one of the elements returned by cleaned_data is a list\nIf you want to skip (or do something special about) such cases you need to check for it:\n\n\ndef clean_post_data(form):\n for i in form.cleaned_data:\n if('__iter__' in dir(form.cleaned_data[i])):\n print \"skip this element: \" + str(form.cleaned_data[i])\n else:\n form.cleaned_data[i] = form.cleaned_data[i].rstrip()\n\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000310833_django_python.txt
Q: Admin generic inlines for multi-table subclassed models broken --- any alternatives? Here's what I'm trying to do, and failing... I have a File model which has a generic-relation to other objects: class File(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() file = models.FileField(upload_to='files/%Y/%m/%d') # etc.... I also want to have a sub-class of File to deal with the specific case of images to be displayed in-page, rather than downloaded: class Image(File): file = models.ImageField(upload_to='files/%Y/%m/%d') All of the above works fine, including generic inlines of the File model, until I want to use a generic-inline of the Image model --- the save process fails to create the base class instance and so raises an error stating that the Image.file_ptr (the 'secret' foreign key to the base class) cannot be None. So, basically, generic inlines do not properly support multi-table inheritance at the moment. It's quite likely that I'm making this more complicated than it need be, so can anyone suggest either a fix for this problem, or a better way of achieving the same end? Please let me know if you need further clarification. A: Inheritance can be implemented two ways in a relational model. A subclass can be a new table with all the same columns as the superclass repeated. This works well when you have an abstract superclass or subclass features that override the superclass. A subclass can be just the unique columns with a join to the superclass table. This works well when you have a concrete superclass. In your case, it looks you might have the following. class FileFacts( models.Model ): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() class DownloadFile( models.Model ): facts = models.ForeignKey( FileFacts ) file = models.FileField(upload_to='files/%Y/%m/%d') class InlineImage( models.Model ): facts = models.ForeignKey( FileFacts ) file = models.ImageField(upload_to='files/%Y/%m/%d') This is my preference for handling a subclass-like model.
Admin generic inlines for multi-table subclassed models broken --- any alternatives?
Here's what I'm trying to do, and failing... I have a File model which has a generic-relation to other objects: class File(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() file = models.FileField(upload_to='files/%Y/%m/%d') # etc.... I also want to have a sub-class of File to deal with the specific case of images to be displayed in-page, rather than downloaded: class Image(File): file = models.ImageField(upload_to='files/%Y/%m/%d') All of the above works fine, including generic inlines of the File model, until I want to use a generic-inline of the Image model --- the save process fails to create the base class instance and so raises an error stating that the Image.file_ptr (the 'secret' foreign key to the base class) cannot be None. So, basically, generic inlines do not properly support multi-table inheritance at the moment. It's quite likely that I'm making this more complicated than it need be, so can anyone suggest either a fix for this problem, or a better way of achieving the same end? Please let me know if you need further clarification.
[ "Inheritance can be implemented two ways in a relational model.\nA subclass can be a new table with all the same columns as the superclass repeated. This works well when you have an abstract superclass or subclass features that override the superclass.\nA subclass can be just the unique columns with a join to the superclass table. This works well when you have a concrete superclass.\nIn your case, it looks you might have the following.\nclass FileFacts( models.Model ):\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n content_object = generic.GenericForeignKey()\n\nclass DownloadFile( models.Model ):\n facts = models.ForeignKey( FileFacts )\n file = models.FileField(upload_to='files/%Y/%m/%d')\n\nclass InlineImage( models.Model ):\n facts = models.ForeignKey( FileFacts )\n file = models.ImageField(upload_to='files/%Y/%m/%d')\n\nThis is my preference for handling a subclass-like model.\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0000311300_django_django_admin_django_models_python.txt
Q: python as a "batch" script (i.e. run commands from python) I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file. how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and asking for user input all the time. So, just running a program and printing the output won't suffice. The program has to takeover the script's input/output, pretty mcuh like running the command from a .bat file. I tried os.execl but it keeps telling me "invalid arguments", also, it doesn't find the program name (doesn't search the PATH variable); I have to give it the full path ..?! basically, in a batch script I can write: unison profile how can I achieve the same effect in python? EDIT: I found out it can be done with os.system( ... ) and since I cannot accept my own answer, I'm closing the question. EDIT: this was supposed to be a comment, but when I posted it I didn't have much points. Thanks Claudiu, that's pretty much what I want, except for a little thing: I want the function to end when the program exits, but when I try it on unison, it doesn't return control to the python script, but to the windows command line environment >>> os.execlp("unison") C:\>Usage: unison [options] or unison root1 root2 [options] or unison profilename [options] For a list of options, type "unison -help". For a tutorial on basic usage, type "unison -doc tutorial". For other documentation, type "unison -doc topics". C:\> C:\> C:\> how to get around this? A: You should create a new processess using the subprocess module. I'm not fluent in windows processes but its Popen function is cross-platform, and should be preffered to OS specific solutions. EDIT: I maintain that you should prefer the Subprocess module to os.* OS specific functions, it is cross-platform and more pythonic (just google it). You can wait for the result easily, and cleanly: import os import subprocess unison = os.path.join(os.path.curdir, "unison") p = subprocess.Popen(unison) p.wait() A: I found out that os.system does what I want, Thanks for all that tried to help. os.system("dir") runs the command just as if it was run from a batch file A: import subprocess proc = subprocess.Popen(['unison', 'profile'], stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE) proc.stdin.write('user input') print proc.stdout.read() This should help you get started. Please edit your question with more information if you want a more detailed answer! A: os.execlp should work. This will search your path for the command. Don't give it any args if they're not necessary: >>> import os >>> os.execlp("cmd") D:\Documents and Settings\Claudiu>Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. D:\Documents and Settings\Claudiu>
python as a "batch" script (i.e. run commands from python)
I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file. how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and asking for user input all the time. So, just running a program and printing the output won't suffice. The program has to takeover the script's input/output, pretty mcuh like running the command from a .bat file. I tried os.execl but it keeps telling me "invalid arguments", also, it doesn't find the program name (doesn't search the PATH variable); I have to give it the full path ..?! basically, in a batch script I can write: unison profile how can I achieve the same effect in python? EDIT: I found out it can be done with os.system( ... ) and since I cannot accept my own answer, I'm closing the question. EDIT: this was supposed to be a comment, but when I posted it I didn't have much points. Thanks Claudiu, that's pretty much what I want, except for a little thing: I want the function to end when the program exits, but when I try it on unison, it doesn't return control to the python script, but to the windows command line environment >>> os.execlp("unison") C:\>Usage: unison [options] or unison root1 root2 [options] or unison profilename [options] For a list of options, type "unison -help". For a tutorial on basic usage, type "unison -doc tutorial". For other documentation, type "unison -doc topics". C:\> C:\> C:\> how to get around this?
[ "You should create a new processess using the subprocess module.\nI'm not fluent in windows processes but its Popen function is cross-platform, and should be preffered to OS specific solutions.\nEDIT: I maintain that you should prefer the Subprocess module to os.* OS specific functions, it is cross-platform and more pythonic (just google it). You can wait for the result easily, and cleanly:\nimport os\nimport subprocess\nunison = os.path.join(os.path.curdir, \"unison\")\np = subprocess.Popen(unison)\np.wait()\n\n", "I found out that os.system does what I want, \nThanks for all that tried to help.\nos.system(\"dir\")\n\nruns the command just as if it was run from a batch file\n", "import subprocess\n\nproc = subprocess.Popen(['unison', 'profile'], stderr=subprocess.PIPE, \n stdout=subprocess.PIPE, stdin=subprocess.PIPE)\n\nproc.stdin.write('user input')\nprint proc.stdout.read()\n\nThis should help you get started. Please edit your question with more information if you want a more detailed answer!\n", "os.execlp should work. This will search your path for the command. Don't give it any args if they're not necessary:\n>>> import os\n>>> os.execlp(\"cmd\")\n\nD:\\Documents and Settings\\Claudiu>Microsoft Windows XP [Version 5.1.2600]\n(C) Copyright 1985-2001 Microsoft Corp.\n\nD:\\Documents and Settings\\Claudiu>\n\n" ]
[ 18, 7, 4, 2 ]
[]
[]
[ "batch_file", "python", "scripting" ]
stackoverflow_0000311601_batch_file_python_scripting.txt
Q: Python Input/Output, files I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string. In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, the console, whatever. Does python have a similar input/output class which can be made to represent almost any form of i/o, or at least files and memory? A: The Python way to do this is to accept an object that implements read() or write(). If you have a string, you can make this happen with StringIO: from cStringIO import StringIO s = "My very long string I want to read like a file" file_like_string = StringIO(s) data = file_like_string.read(10) Remember that Python uses duck-typing: you don't have to involve a common base class. So long as your object implements read(), it can be read like a file. A: The Pickle and cPickle modules may also be helpful to you.
Python Input/Output, files
I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string. In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, the console, whatever. Does python have a similar input/output class which can be made to represent almost any form of i/o, or at least files and memory?
[ "The Python way to do this is to accept an object that implements read() or write(). If you have a string, you can make this happen with StringIO:\nfrom cStringIO import StringIO\n\ns = \"My very long string I want to read like a file\"\nfile_like_string = StringIO(s)\ndata = file_like_string.read(10)\n\nRemember that Python uses duck-typing: you don't have to involve a common base class. So long as your object implements read(), it can be read like a file.\n", "The Pickle and cPickle modules may also be helpful to you.\n" ]
[ 10, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000310629_python.txt
Q: Public free web services for testing soap client Are there any publicly available SOAP 1.2/WSDL 2.0 compliant free web services for testing a Python based soap client library (e.g. Zolera SOAP Infrastructure)? So far, it appears to me that Google Web API may be the only option. Otherwise, how can one test a SOAP 1.2 compliant client library? A: There is a bunch on here: http://www.webservicex.net/WS/wscatlist.aspx Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints. Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
Public free web services for testing soap client
Are there any publicly available SOAP 1.2/WSDL 2.0 compliant free web services for testing a Python based soap client library (e.g. Zolera SOAP Infrastructure)? So far, it appears to me that Google Web API may be the only option. Otherwise, how can one test a SOAP 1.2 compliant client library?
[ "There is a bunch on here:\nhttp://www.webservicex.net/WS/wscatlist.aspx\nJust google for \"Free WebService\" or \"Open WebService\" and you'll find tons of open SOAP endpoints.\nRemember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.\n" ]
[ 73 ]
[]
[]
[ "python", "soap", "soappy", "web_services", "zsi" ]
stackoverflow_0000311654_python_soap_soappy_web_services_zsi.txt
Q: How do I not raise a Python exception when converting an integer-as-string to an int I have some HTML I am trying to parse. There are cases where the html attributes alone are not going to help me identify the row type (header versus data). Fortunately, if my row is a data row then it should have some values that can be converted to integers. I have figured out how to convert the unicode to an integer for those cases that it is possible to make the conversion. I am struggling to write the logic to move past the cells that the conversion will not work because the cell has content that must be treated as text. for example if rowColumn[1][3] can be converted to an integer I can do so by int(rowColumn[1][3].replace(',','').strip('$')) but I get an error if rowColumn[1][3] has text content. A: Have you looked at the try statement? try: x = int(rowColumn[1][3].replace(',','').strip('$')) except ValueError, e: x = None # rowColumn[1][3] was not an integer
How do I not raise a Python exception when converting an integer-as-string to an int
I have some HTML I am trying to parse. There are cases where the html attributes alone are not going to help me identify the row type (header versus data). Fortunately, if my row is a data row then it should have some values that can be converted to integers. I have figured out how to convert the unicode to an integer for those cases that it is possible to make the conversion. I am struggling to write the logic to move past the cells that the conversion will not work because the cell has content that must be treated as text. for example if rowColumn[1][3] can be converted to an integer I can do so by int(rowColumn[1][3].replace(',','').strip('$')) but I get an error if rowColumn[1][3] has text content.
[ "Have you looked at the try statement?\ntry:\n x = int(rowColumn[1][3].replace(',','').strip('$'))\nexcept ValueError, e:\n x = None # rowColumn[1][3] was not an integer\n\n" ]
[ 5 ]
[]
[]
[ "integer", "python", "text" ]
stackoverflow_0000311963_integer_python_text.txt
Q: How to build "Tagging" support using CouchDB? I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach? def by_tag(tag): return ''' function(doc) { if (doc.tags.length > 0) { for (var tag in doc.tags) { if (doc.tags[tag] == "%s") { emit(doc.published, doc) } } } }; ''' % tag A: Disclaimer: I didn't test this and don't know if it can perform better. Create a single perm view: function(doc) { for (var tag in doc.tags) { emit([tag, doc.published], doc) } }; And query with _view/your_view/all?startkey=['your_tag_here']&endkey=['your_tag_here', {}] Resulting JSON structure will be slightly different but you will still get the publish date sorting. A: You can define a single permanent view, as Bahadir suggests. when doing this sort of indexing, though, don't output the doc for each key. Instead, emit([tag, doc.published], null). In current release versions you'd then have to do a separate lookup for each doc, but SVN trunk now has support for specifying "include_docs=True" in the query string and CouchDB will automatically merge the docs into your view for you, without the space overhead. A: You are very much on the right track with the view. A list of thoughts though: View generation is incremental. If you're read traffic is greater than you're write traffic, then your views won't cause an issue at all. People that are concerned about this generally shouldn't be. Frame of reference, you should be worried if you're dumping hundreds of records into the view without an update. Emitting an entire document will slow things down. You should only emit what is necessary for use of the view. Not sure what the val == "%s" performance would be, but you shouldn't over think things. If there's a tag array you should emit the tags. Granted if you expect a tags array that will contain non-strings, then ignore this. A: # Works on CouchDB 0.8.0 from couchdb import Server # http://code.google.com/p/couchdb-python/ byTag = """ function(doc) { if (doc.type == 'post' && doc.tags) { doc.tags.forEach(function(tag) { emit(tag, doc); }); } } """ def findPostsByTag(self, tag): server = Server("http://localhost:1234") db = server['my_table'] return [row for row in db.query(byTag, key = tag)] The byTag map function returns the data with each unique tag in the "key", then each post with that tag in value, so when you grab key = "mytag", it will retrieve all posts with the tag "mytag". I've tested it against about 10 entries and it seems to take about 0.0025 seconds per query, not sure how efficient it is with large data sets..
How to build "Tagging" support using CouchDB?
I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach? def by_tag(tag): return ''' function(doc) { if (doc.tags.length > 0) { for (var tag in doc.tags) { if (doc.tags[tag] == "%s") { emit(doc.published, doc) } } } }; ''' % tag
[ "Disclaimer: I didn't test this and don't know if it can perform better. \nCreate a single perm view:\nfunction(doc) {\n for (var tag in doc.tags) {\n emit([tag, doc.published], doc)\n }\n};\n\nAnd query with \n_view/your_view/all?startkey=['your_tag_here']&endkey=['your_tag_here', {}]\nResulting JSON structure will be slightly different but you will still get the publish date sorting.\n", "You can define a single permanent view, as Bahadir suggests. when doing this sort of indexing, though, don't output the doc for each key. Instead, emit([tag, doc.published], null). In current release versions you'd then have to do a separate lookup for each doc, but SVN trunk now has support for specifying \"include_docs=True\" in the query string and CouchDB will automatically merge the docs into your view for you, without the space overhead.\n", "You are very much on the right track with the view. A list of thoughts though:\nView generation is incremental. If you're read traffic is greater than you're write traffic, then your views won't cause an issue at all. People that are concerned about this generally shouldn't be. Frame of reference, you should be worried if you're dumping hundreds of records into the view without an update.\nEmitting an entire document will slow things down. You should only emit what is necessary for use of the view.\nNot sure what the val == \"%s\" performance would be, but you shouldn't over think things. If there's a tag array you should emit the tags. Granted if you expect a tags array that will contain non-strings, then ignore this.\n", "# Works on CouchDB 0.8.0\nfrom couchdb import Server # http://code.google.com/p/couchdb-python/\n\nbyTag = \"\"\"\nfunction(doc) {\nif (doc.type == 'post' && doc.tags) {\n doc.tags.forEach(function(tag) {\n emit(tag, doc);\n });\n}\n}\n\"\"\"\n\ndef findPostsByTag(self, tag):\n server = Server(\"http://localhost:1234\")\n db = server['my_table']\n return [row for row in db.query(byTag, key = tag)]\n\nThe byTag map function returns the data with each unique tag in the \"key\", then each post with that tag in value, so when you grab key = \"mytag\", it will retrieve all posts with the tag \"mytag\".\nI've tested it against about 10 entries and it seems to take about 0.0025 seconds per query, not sure how efficient it is with large data sets..\n" ]
[ 7, 3, 1, 0 ]
[]
[]
[ "couchdb", "document_oriented_db", "python", "tagging" ]
stackoverflow_0000211118_couchdb_document_oriented_db_python_tagging.txt
Q: Python, optparse and file mask if __name__=='__main__': parser = OptionParser() parser.add_option("-i", "--input_file", dest="input_filename", help="Read input from FILE", metavar="FILE") (options, args) = parser.parse_args() print options result is $ python convert.py -i video_* {'input_filename': 'video_1.wmv'} there are video_[1-6].wmv in the current folder. Question is why video_* become video_1.wmv. What i'm doing wrong? A: Python has nothing to do with this -- it's the shell. Call $ python convert.py -i 'video_*' and it will pass in that wildcard. The other six values were passed in as args, not attached to the -i, exactly as if you'd run python convert.py -i video_1 video_2 video_3 video_4 video_5 video_6, and the -i only attaches to the immediate next parameter. That said, your best bet might to be just read your input filenames from args, rather than using options.input. A: Print out args and you'll see where the other files are going... They are being converted to separate arguments in argv, and optparse only takes the first one as the value for the input_filename option. A: To clarify: aprogram -e *.wmv on a Linux shell, all wildcards (*.wmv) are expanded by the shell. So aprogram actually recieves the arguments: sys.argv == ['aprogram', '-e', '1.wmv', '2.wmv', '3.wmv'] Like Charles said, you can quote the argument to get it to pass in literally: aprogram -e "*.wmv" This will pass in: sys.argv == ['aprogram', '-e', '*.wmv'] A: It isn't obvious, even if you read some of the standards (like this or this). The args part of a command line are -- almost universally -- the input files. There are only very rare odd-ball cases where an input file is specified as an option. It does happen, but it's very rare. Also, the output files are never named as args. They almost always are provided as named options. The idea is that Most programs can (and should) read from stdin. The command-line argument of - is a code for "stdin". If no arguments are given, stdin is the fallback plan. If your program opens any files, it may as well open an unlimited number of files specified on the command line. The shell facilitates this by expanding wild-cards for you. [Windows doesn't do this for you, however.] You program should never overwrite a file without an explicit command-line options, like '-o somefile' to write to a file. Note that cp, mv, rm are the big examples of programs that don't follow these standards.
Python, optparse and file mask
if __name__=='__main__': parser = OptionParser() parser.add_option("-i", "--input_file", dest="input_filename", help="Read input from FILE", metavar="FILE") (options, args) = parser.parse_args() print options result is $ python convert.py -i video_* {'input_filename': 'video_1.wmv'} there are video_[1-6].wmv in the current folder. Question is why video_* become video_1.wmv. What i'm doing wrong?
[ "Python has nothing to do with this -- it's the shell.\nCall\n$ python convert.py -i 'video_*'\n\nand it will pass in that wildcard.\nThe other six values were passed in as args, not attached to the -i, exactly as if you'd run python convert.py -i video_1 video_2 video_3 video_4 video_5 video_6, and the -i only attaches to the immediate next parameter.\nThat said, your best bet might to be just read your input filenames from args, rather than using options.input.\n", "Print out args and you'll see where the other files are going...\nThey are being converted to separate arguments in argv, and optparse only takes the first one as the value for the input_filename option.\n", "To clarify:\naprogram -e *.wmv\n\non a Linux shell, all wildcards (*.wmv) are expanded by the shell. So aprogram actually recieves the arguments:\nsys.argv == ['aprogram', '-e', '1.wmv', '2.wmv', '3.wmv']\n\nLike Charles said, you can quote the argument to get it to pass in literally:\naprogram -e \"*.wmv\"\n\nThis will pass in:\nsys.argv == ['aprogram', '-e', '*.wmv']\n\n", "It isn't obvious, even if you read some of the standards (like this or this).\nThe args part of a command line are -- almost universally -- the input files.\nThere are only very rare odd-ball cases where an input file is specified as an option. It does happen, but it's very rare.\nAlso, the output files are never named as args. They almost always are provided as named options. \nThe idea is that\n\nMost programs can (and should) read from stdin. The command-line argument of - is a code for \"stdin\". If no arguments are given, stdin is the fallback plan.\nIf your program opens any files, it may as well open an unlimited number of files specified on the command line. The shell facilitates this by expanding wild-cards for you. [Windows doesn't do this for you, however.]\nYou program should never overwrite a file without an explicit command-line options, like '-o somefile' to write to a file. \n\nNote that cp, mv, rm are the big examples of programs that don't follow these standards.\n" ]
[ 8, 2, 1, 0 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0000312673_optparse_python.txt
Q: Is it correct to inherit from built-in classes? I want to parse an Apache access.log file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now. I am going to create a class ApacheAccessLog, and the only thing I can imagine now, it will be doing is 'readline' method. Is it conventionally correct to inherit from the builtin file class in this case, so the class will behave just like an instance of the file class itself, or not? What is the best way of doing that? A: In this case I would use delegation rather than inheritance. It means that your class should contain the file object as an attribute and invoke a readline method on it. You could pass a file object in the constructor of the logger class. There are at least two reasons for this: Delegation reduces coupling, for example in place of file objects you can use any other object that implements a readline method (duck typing comes handy here). When inheriting from file the public interface of your class becomes unnecessarily broad. It includes all the methods defined on file even if these methods don't make sense in case of Apache log. A: I am coming from a Java background but I am fairly confident that the same principles will apply in Python. As a rule of thumb you should never inherit from a class whose implementation you don't understand and control unless that class has been designed specifically for inheritance. If it has been designed in this way it should describe this clearly in its documentation. The reason for this is that inheritance can potentially bind you to the implementation details of the class that you are inheriting from. To use an example from Josh Bloch's book 'Effective Java' If we were to extend the class ArrayList class in order to be able to count the number of items that were added to it during its life-time (not necessarily the number it currently contains) we may be tempted to write something like this. public class CountingList extends ArrayList { int counter = 0; public void add(Object o) { counter++; super.add(0); } public void addAll(Collection c) { count += c.size(); super.addAll(c); } // Etc. } Now this extension looks like it would accurately count the number of elements that were added to the list but in fact it may not. If ArrayList has implemented addAll by iterating over the Collection provided and calling its interface method addAll for each element then we will count each element added through the addAll method twice. Now the behaviour of our class is dependent on the implementation details of ArrayList. This is of course in addition to the disadvantage of not being able to use other implementations of List with our CountingList class. Plus the disadvantages of inheriting from a concrete class that are discussed above. It is my understanding that Python uses a similar (if not identical) method dispatch mechanism to Java and will therefore be subject to the same limitations. If someone could provide an example in Python I'm sure it would be even more useful. A: It is perfectly acceptable to inherit from a built in class. In this case I'd say you're right on the money. The log "is a" file so that tells you inheritance is ok.. General rule. Dog "is a"n animal, therefore inherit from animal. Owner "has a"n animal therefore don't inherit from animal. A: Although it is in some cases useful to inherit from builtins, the real question here is what you want to do with the output and what's your big-picture design. I would usually write a reader (that uses a file object) and spit out whatever data class I need to hold the information I just read. It's then easy to design that data class to fit in with the rest of my design. A: You should be fairly safe inheriting from a "builtin" class, as later modifications to these classes will usually be compatible with the current version. However, you should think seriously about wether you really want to tie your class to the additional functionality provided by the builtin class. As mentioned in another answer you should consider (perhaps even prefer) using delegation instead. As an example of why to avoid inheritance if you don't need it you can look at the java.util.Stack class. As it extends Vector it inherits all of the methods on Vector. Most of these methods break the contract implied by Stack, e.g. LIFO. It would have been much better to implement Stack using a Vector internally, only exposing Stack methods as the API. It would then have been easy to change the implementation to ArrayList or something else later, none of which is possible now due to inheritance. A: You seem to have found your answer that in this case delegation is the better strategy. Nevertheless, I would like to add that, excepting delegation, there is nothing wrong with extending a built-in class, particularly if your alternative, depending on the language, is "monkey patching" (see http://en.wikipedia.org/wiki/Monkey_patch)
Is it correct to inherit from built-in classes?
I want to parse an Apache access.log file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now. I am going to create a class ApacheAccessLog, and the only thing I can imagine now, it will be doing is 'readline' method. Is it conventionally correct to inherit from the builtin file class in this case, so the class will behave just like an instance of the file class itself, or not? What is the best way of doing that?
[ "In this case I would use delegation rather than inheritance. It means that your class should contain the file object as an attribute and invoke a readline method on it. You could pass a file object in the constructor of the logger class.\nThere are at least two reasons for this:\n\nDelegation reduces coupling, for example in place of file objects you can use any other object that implements a readline method (duck typing comes handy here).\nWhen inheriting from file the public interface of your class becomes unnecessarily broad. It includes all the methods defined on file even if these methods don't make sense in case of Apache log.\n\n", "I am coming from a Java background but I am fairly confident that the same principles will apply in Python. As a rule of thumb you should never inherit from a class whose implementation you don't understand and control unless that class has been designed specifically for inheritance. If it has been designed in this way it should describe this clearly in its documentation.\nThe reason for this is that inheritance can potentially bind you to the implementation details of the class that you are inheriting from.\nTo use an example from Josh Bloch's book 'Effective Java'\nIf we were to extend the class ArrayList class in order to be able to count the number of items that were added to it during its life-time (not necessarily the number it currently contains) we may be tempted to write something like this.\npublic class CountingList extends ArrayList {\n int counter = 0;\n\n public void add(Object o) {\n counter++;\n super.add(0);\n }\n\n public void addAll(Collection c) {\n count += c.size();\n super.addAll(c);\n }\n\n // Etc.\n}\n\nNow this extension looks like it would accurately count the number of elements that were added to the list but in fact it may not. If ArrayList has implemented addAll by iterating over the Collection provided and calling its interface method addAll for each element then we will count each element added through the addAll method twice. Now the behaviour of our class is dependent on the implementation details of ArrayList.\nThis is of course in addition to the disadvantage of not being able to use other implementations of List with our CountingList class. Plus the disadvantages of inheriting from a concrete class that are discussed above.\nIt is my understanding that Python uses a similar (if not identical) method dispatch mechanism to Java and will therefore be subject to the same limitations. If someone could provide an example in Python I'm sure it would be even more useful.\n", "It is perfectly acceptable to inherit from a built in class. In this case I'd say you're right on the money. \nThe log \"is a\" file so that tells you inheritance is ok.. \nGeneral rule. \nDog \"is a\"n animal, therefore inherit from animal.\nOwner \"has a\"n animal therefore don't inherit from animal. \n", "Although it is in some cases useful to inherit from builtins, the real question here is what you want to do with the output and what's your big-picture design. I would usually write a reader (that uses a file object) and spit out whatever data class I need to hold the information I just read. It's then easy to design that data class to fit in with the rest of my design.\n", "You should be fairly safe inheriting from a \"builtin\" class, as later modifications to these classes will usually be compatible with the current version. \nHowever, you should think seriously about wether you really want to tie your class to the additional functionality provided by the builtin class. As mentioned in another answer you should consider (perhaps even prefer) using delegation instead. \nAs an example of why to avoid inheritance if you don't need it you can look at the java.util.Stack class. As it extends Vector it inherits all of the methods on Vector. Most of these methods break the contract implied by Stack, e.g. LIFO. It would have been much better to implement Stack using a Vector internally, only exposing Stack methods as the API. It would then have been easy to change the implementation to ArrayList or something else later, none of which is possible now due to inheritance.\n", "You seem to have found your answer that in this case delegation is the better strategy. Nevertheless, I would like to add that, excepting delegation, there is nothing wrong with extending a built-in class, particularly if your alternative, depending on the language, is \"monkey patching\" (see http://en.wikipedia.org/wiki/Monkey_patch) \n" ]
[ 15, 6, 1, 1, 1, 0 ]
[]
[]
[ "inheritance", "oop", "python" ]
stackoverflow_0000288695_inheritance_oop_python.txt
Q: Access second result set of stored procedure with SQL or other work-around? Python\pyodbc I'm using python\pyodbc and would like to access the second result set of a stored procedure. As near as I can tell, pyodbc does not support multiple result sets. Additionally, I can't modify the stored procedure. Are there any options to access the second result set using SQL or some other work-around? Perhaps create a second stored procedure that only returns the second result set of the first? A: No need for anything fancy. Just use the cursor's nextset() method: import pyodbc db = pyodbc.connect ("") q = db.cursor () q.execute (""" SELECT TOP 5 * FROM INFORMATION_SCHEMA.TABLES SELECT TOP 10 * FROM INFORMATION_SCHEMA.COLUMNS """) tables = q.fetchall () q.nextset () columns = q.fetchall () assert len (tables) == 5 assert len (columns) == 10 A: There are a few possible methods here. If the result sets are all the same, you might be able to use the INSERT...EXEC method. Otherwise OPENQUERY might work.
Access second result set of stored procedure with SQL or other work-around? Python\pyodbc
I'm using python\pyodbc and would like to access the second result set of a stored procedure. As near as I can tell, pyodbc does not support multiple result sets. Additionally, I can't modify the stored procedure. Are there any options to access the second result set using SQL or some other work-around? Perhaps create a second stored procedure that only returns the second result set of the first?
[ "No need for anything fancy. Just use the cursor's nextset() method:\n\nimport pyodbc\n\ndb = pyodbc.connect (\"\")\nq = db.cursor ()\nq.execute (\"\"\"\nSELECT TOP 5 * FROM INFORMATION_SCHEMA.TABLES\nSELECT TOP 10 * FROM INFORMATION_SCHEMA.COLUMNS\n\"\"\")\ntables = q.fetchall ()\nq.nextset ()\ncolumns = q.fetchall ()\n\nassert len (tables) == 5\nassert len (columns) == 10\n\n\n", "There are a few possible methods here. If the result sets are all the same, you might be able to use the INSERT...EXEC method. Otherwise OPENQUERY might work.\n" ]
[ 20, 0 ]
[]
[]
[ "pyodbc", "python", "sql" ]
stackoverflow_0000273203_pyodbc_python_sql.txt
Q: Effective Keyboard Input Handling What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this: for event in pygame.event.get(): if event.type == KEYDOWN: if False: pass #make everything an elif elif rotating: pass elif event.key == K_q: elif event.key == K_e: elif event.key == K_LEFT: curpiece.shift(-1, 0) shadowpiece = curpiece.clone(); setupshadow(shadowpiece) elif event.key == K_RIGHT: curpiece.shift(1, 0) shadowpiece = curpiece.clone(); setupshadow(shadowpiece) (shortened). I don't like this, as this has to go in my main loop, and it messes with all parts of the program. This also makes it impossible to have a user config screen where they can change which key maps to which action. Is there a good pattern to do this using some form of function callbacks? A: You could create a dictionary where the keys are the input and the value is a function that handles the keypress: def handle_quit(): quit() def handle_left(): curpiece.shift(-1, 0) shadowpiece = curpiece.clone(); setupshadow(shadowpiece) def handle_right(): curpiece.shift(1, 0) shadowpiece = curpiece.clone(); setupshadow(shadowpiece) def handle_pause(): if not paused: paused = True branch = { K_q: handle_quit K_e: handle_pause K_LEFT: handle_left K_RIGHT: handle_right } for event in pygame.event.get(): if event.type == KEYDOWN: branch[event.key]() Then changing the keys is a matter of modifying keys of the dictionary. A: in addition to superjoe30's answer, you can use two levels of mapping (two dictionaries) key => command string command string => function I think this would make it easier to allow user-defined mappings. i.e. so users can map their keys to "commands" rather than "the name of a function" A: What I do nowadays is have some sort of input gathering class/function/thread which will check a list of predefined key->event bindings. Something like this: class InputHandler: def __init__ (self, eventDispatcher): self.keys = {} self.eventDispatcher = eventDispatcher def add_key_binding (self, key, event): self.keys.update((key, event,)) def gather_input (self): for event in pygame.event.get(): if event.type == KEYDOWN: event = self.keys.get(event.key, None) if not event is None: self.eventDispatcher.dispatch(event) .... inputHandler = InputHandler(EventDispatcher) inputHandler.add_key_binding(K_q, "quit_event") ... inputHandler.gather_input() .... It's basically what superjoe30 is doing, except that instead of calling callbacks directly, I add another level of separation by using an event dispatching system, so that any code that cares about the keys being pressed simply listen for that event. Also, keys can be easily bound to different events, which could be read from a config file or something and any key which is not bound to an event is simply ignored.
Effective Keyboard Input Handling
What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this: for event in pygame.event.get(): if event.type == KEYDOWN: if False: pass #make everything an elif elif rotating: pass elif event.key == K_q: elif event.key == K_e: elif event.key == K_LEFT: curpiece.shift(-1, 0) shadowpiece = curpiece.clone(); setupshadow(shadowpiece) elif event.key == K_RIGHT: curpiece.shift(1, 0) shadowpiece = curpiece.clone(); setupshadow(shadowpiece) (shortened). I don't like this, as this has to go in my main loop, and it messes with all parts of the program. This also makes it impossible to have a user config screen where they can change which key maps to which action. Is there a good pattern to do this using some form of function callbacks?
[ "You could create a dictionary where the keys are the input and the value is a function that handles the keypress:\ndef handle_quit():\n quit()\n\ndef handle_left():\n curpiece.shift(-1, 0)\n shadowpiece = curpiece.clone(); setupshadow(shadowpiece)\n\ndef handle_right():\n curpiece.shift(1, 0)\n shadowpiece = curpiece.clone(); setupshadow(shadowpiece)\n\ndef handle_pause():\n if not paused:\n paused = True\n\nbranch = {\n K_q: handle_quit\n K_e: handle_pause\n K_LEFT: handle_left\n K_RIGHT: handle_right\n}\n\nfor event in pygame.event.get():\n if event.type == KEYDOWN:\n branch[event.key]()\n\nThen changing the keys is a matter of modifying keys of the dictionary.\n", "in addition to superjoe30's answer, you can use two levels of mapping (two dictionaries)\n\nkey => command string\ncommand string => function\n\nI think this would make it easier to allow user-defined mappings. i.e. so users can map their keys to \"commands\" rather than \"the name of a function\"\n", "What I do nowadays is have some sort of input gathering class/function/thread which will check a list of predefined key->event bindings.\nSomething like this:\nclass InputHandler:\n def __init__ (self, eventDispatcher):\n self.keys = {}\n self.eventDispatcher = eventDispatcher\n def add_key_binding (self, key, event):\n self.keys.update((key, event,))\n def gather_input (self):\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n event = self.keys.get(event.key, None)\n if not event is None:\n self.eventDispatcher.dispatch(event)\n\n....\ninputHandler = InputHandler(EventDispatcher)\ninputHandler.add_key_binding(K_q, \"quit_event\")\n...\ninputHandler.gather_input()\n....\n\nIt's basically what superjoe30 is doing, except that instead of calling callbacks directly, I add another level of separation by using an event dispatching system, so that any code that cares about the keys being pressed simply listen for that event.\nAlso, keys can be easily bound to different events, which could be read from a config file or something and any key which is not bound to an event is simply ignored.\n" ]
[ 17, 3, 2 ]
[]
[]
[ "interactive", "keyboard", "python", "user_input", "user_interface" ]
stackoverflow_0000312263_interactive_keyboard_python_user_input_user_interface.txt
Q: Are there problems developing Django on Jython? The background I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks. The only decision I'm having trouble with, is whether we use Python or Jython to develop our application. Now I'm pretty familiar with Java and could possibly benefit from the libraries within the JDK. I know minimal Python, but am using this project as an opportunity to learn a new language - so the majority of work will be written in Python. The attractiveness of Jython is of course the JVM. The number of python/django enabled web-hosts is extremely minimal - whereas I'm assuming I could drop a jython/django application on a huge variety of hosts. This isn't a massive design decision, but still one I think needs to be decided. I'd really prefer jython over python for the jvm accessibility alone. Questions Does Jython have many limitations compared to regular python? Will running django on jython cause problems? How quick is the Jython team to release updates alongside Python? Will Django work as advertised on Jython (with very minimal pre-configuration)? Decision Thanks for the helpful comments. What I think I'm going to do is develop in Jython for the JVM support - but to try to only use Python code/libraries. Portability isn't a major concern so if I need a library in the JDK (not readily available in python), I'll use it. As long as Django is fully supported, I'm happy. A: Django does work on Jython, although you'll need to use the development release of Jython, since technically Jython 2.5 is still in beta. However, Django 1.0 and up should work unmodified. So as to whether you should use the regular Python implementation or Jython, I'd say it's a matter of whether you prefer having all the Java libraries available or all of the Python libraries. At this point you can expect almost everything in the Python standard library to work with Jython, but there are still plenty of third-party packages which will not work, especially C extension modules. I'd personally recommend going with regular Python, but if you've got a ton of JVM experience and want to stick with what you know, then I can respect that. As for finding Python hosting, this page might be helpful. A: I'd say that if you like Django, you'll also like Python. Don't make the (far too common) mistake of mixing past language's experience while you learn a new one. Only after mastering Python, you'll have the experience to judge if a hybrid language is better than either one. It's true that very few cheap hostings offer Django preinstalled; but it's quite probable that that will change, given that it's the most similar environment to Google's app engine. (and most GAE projects can be made to run on Django) A: I have recently started working on an open source desktop project in my spare time. So this may not apply. I came to the same the question. I decided that I should write as much of the code as possible in python (and Django) and target all the platforms CPython, Jython, and IronPython. Then, I decided that I would write plugins that would interface with libraries on different implementations (for example, different GUI libraries). Why? I decided early on that longevity of my code may depend on targeting not only CPython but also virtual machines. For today's purposes CPython is the way to go because of speed, but who knows about tomorrow. If you code is flexible enough, you may not have to decide on targeting one. The downside to this approach is that you will have more code to create and maintain. A: Django is supposed to be jython-compatible sinc version 1.0. This tutorial is a bit outdated, but from there you can see there are no special issues.
Are there problems developing Django on Jython?
The background I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks. The only decision I'm having trouble with, is whether we use Python or Jython to develop our application. Now I'm pretty familiar with Java and could possibly benefit from the libraries within the JDK. I know minimal Python, but am using this project as an opportunity to learn a new language - so the majority of work will be written in Python. The attractiveness of Jython is of course the JVM. The number of python/django enabled web-hosts is extremely minimal - whereas I'm assuming I could drop a jython/django application on a huge variety of hosts. This isn't a massive design decision, but still one I think needs to be decided. I'd really prefer jython over python for the jvm accessibility alone. Questions Does Jython have many limitations compared to regular python? Will running django on jython cause problems? How quick is the Jython team to release updates alongside Python? Will Django work as advertised on Jython (with very minimal pre-configuration)? Decision Thanks for the helpful comments. What I think I'm going to do is develop in Jython for the JVM support - but to try to only use Python code/libraries. Portability isn't a major concern so if I need a library in the JDK (not readily available in python), I'll use it. As long as Django is fully supported, I'm happy.
[ "Django does work on Jython, although you'll need to use the development release of Jython, since technically Jython 2.5 is still in beta. However, Django 1.0 and up should work unmodified.\nSo as to whether you should use the regular Python implementation or Jython, I'd say it's a matter of whether you prefer having all the Java libraries available or all of the Python libraries. At this point you can expect almost everything in the Python standard library to work with Jython, but there are still plenty of third-party packages which will not work, especially C extension modules. I'd personally recommend going with regular Python, but if you've got a ton of JVM experience and want to stick with what you know, then I can respect that.\nAs for finding Python hosting, this page might be helpful.\n", "I'd say that if you like Django, you'll also like Python. Don't make the (far too common) mistake of mixing past language's experience while you learn a new one. Only after mastering Python, you'll have the experience to judge if a hybrid language is better than either one.\nIt's true that very few cheap hostings offer Django preinstalled; but it's quite probable that that will change, given that it's the most similar environment to Google's app engine. (and most GAE projects can be made to run on Django)\n", "I have recently started working on an open source desktop project in my spare time. So this may not apply. I came to the same the question. I decided that I should write as much of the code as possible in python (and Django) and target all the platforms CPython, Jython, and IronPython.\nThen, I decided that I would write plugins that would interface with libraries on different implementations (for example, different GUI libraries).\nWhy? I decided early on that longevity of my code may depend on targeting not only CPython but also virtual machines. For today's purposes CPython is the way to go because of speed, but who knows about tomorrow. If you code is flexible enough, you may not have to decide on targeting one.\nThe downside to this approach is that you will have more code to create and maintain.\n", "Django is supposed to be jython-compatible sinc version 1.0.\nThis tutorial is a bit outdated, but from there you can see there are no special issues.\n" ]
[ 3, 3, 1, 0 ]
[]
[]
[ "django", "jvm", "jython", "python" ]
stackoverflow_0000314234_django_jvm_jython_python.txt
Q: Best way to access table instances when using SQLAlchemy's declarative syntax All the docs for SQLAlchemy give INSERT and UPDATE examples using the local table instance (e.g. tablename.update()... ) Doing this seems difficult with the declarative syntax, I need to reference Base.metadata.tables["tablename"] to get the table reference. Am I supposed to do this another way? Is there a different syntax for INSERT and UPDATE recommended when using the declarative syntax? Should I just switch to the old way? A: well it works for me: class Users(Base): __tablename__ = 'users' __table_args__ = {'autoload':True} users = Users() print users.__table__.select() ...SELECT users....... A: via the __table__ attribute on your declarative class A: There may be some confusion between table (the object) and tablename (the name of the table, a string). Using the table class attribute works fine for me.
Best way to access table instances when using SQLAlchemy's declarative syntax
All the docs for SQLAlchemy give INSERT and UPDATE examples using the local table instance (e.g. tablename.update()... ) Doing this seems difficult with the declarative syntax, I need to reference Base.metadata.tables["tablename"] to get the table reference. Am I supposed to do this another way? Is there a different syntax for INSERT and UPDATE recommended when using the declarative syntax? Should I just switch to the old way?
[ "well it works for me:\nclass Users(Base):\n __tablename__ = 'users'\n __table_args__ = {'autoload':True}\n\nusers = Users()\nprint users.__table__.select()\n\n...SELECT users.......\n", "via the __table__ attribute on your declarative class\n", "There may be some confusion between table (the object) and tablename (the name of the table, a string). Using the table class attribute works fine for me.\n" ]
[ 10, 4, 0 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0000075829_python_sql_sqlalchemy.txt
Q: Comparing multiple dictionaries in Python I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns. When the user selects multiple entries from the list control (pressing CTRL or shift while clicking), the ObjectiveListView module gives me a list of dictionaries, the dictionaries containing the data in the rows of the list control. This is exactly what I want, good! The returned list looks something like this: print MyList [{'id':1023, 'type':'Purchase', 'date':'23.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':1024, 'type':'Purchase', 'date':'24.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':23, 'type':'Purchase', 'date':'2.8.2008', 'sum':'-21,90', 'target':'Apple Store'}] All the dictionaries have the same keys, but the values change. The 'id' value is unique. Here the problems start. I want to get the common values for all the items the user selected. In the above list they would be 'sum':'-21,90' and 'target':'Apple Store'. I don't know how to properly compare the dicts in the list. One big problem is that I don't know beforehand how many dicts the list contains, since it's decided by the user. I have a vague idea that list comprehensions would be the way to go, but I only know how to compare two lists with list comprehensions, not n lists. Any help would be appreciated. A: >>> mysets = (set(x.items()) for x in MyList) >>> reduce(lambda a,b: a.intersection(b), mysets) set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')]) First, I've created a generator that will convert the list of dicts into an iterable sequence of sets of key,value pairs. You could use a list comprehension here but this way doesn't convert your entire list into yet another list, useful if you don't know how big it will be. Then I've used reduce to apply a function that finds the common values between each set. It finds the intersection of set 1 & set 2, which is itself a set, then the intersection of that set & set 3 etc. The mysets generator will happily feed each set on demand to the reduce function until its done. I believe reduce has been deprecated as a built-in in Python 3.0, but should still be available in functools. You could of course make it a one-liner by replacing mysets in the reduce with the generator expression, but that reduces the readability IMO. In practice I'd probably even go one step further and break the lambda out into its own line as well: >>> mysets = (set(x.items()) for x in MyList) >>> find_common = lambda a,b: a.intersection(b) >>> reduce(find_common, mysets) set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')]) And if you need the end result to be a dict, just wrap it like so: >>> dict(reduce(find_common, mysets)) {'sum': '-21,90', 'type': 'Purchase', 'target': 'Apple Store'} dict can accept any iterator of key,value pairs, such as the set of tuples returned at the end. A: My answer is identical to Matthew Trevor's, except for one difference: >>> mysets = (set(x.items()) for x in MyList) >>> reduce(set.intersection, mysets) set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')]) Here I use set.intersection instead of creating a new lambda. In my opinion this is more readable, as this intuitively reads as "reduce is reducing this list using the set intersection operator." This should also be much faster, as set.intersection is a built-in C function. To fully answer your question, you can extract the values using a list comprehension: >>> mysets = (set(x.items()) for x in MyList) >>> result = reduce(set.intersection, mysets) >>> values = [r[1] for r in result] >>> values ['-21,90', 'Purchase', 'Apple Store'] This would end up on one line for me. but that's entirely up to you: >>> [r[1] for r in reduce(set.intersection, (set(x.items()) for x in myList))] ['-21,90', 'Purchase', 'Apple Store'] A: First, we need a function to compute intersection of two dictionaries: def IntersectDicts( d1, d2 ) : return dict(filter(lambda (k,v) : k in d2 and d2[k] == v, d1.items())) Then we can use it to process any number of dictionaries: result = reduce(IntersectDicts, MyList) A: Since you're only looking for the common set, you can compare the keys in the first dictionary to the keys in all other dictionaries: common = {} for k in MyList[0]: for i in xrange(1,len(MyList)): if MyList[0][k] != MyList[i][k]: continue common[k] = MyList[0][k] >>> common {'sum': '-21,90', 'type': 'Purchase', 'target': 'Apple Store'} A: Sorry, yes, 'type':'Purchase' is also one of the common values.Should have logged in to edit the question.
Comparing multiple dictionaries in Python
I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns. When the user selects multiple entries from the list control (pressing CTRL or shift while clicking), the ObjectiveListView module gives me a list of dictionaries, the dictionaries containing the data in the rows of the list control. This is exactly what I want, good! The returned list looks something like this: print MyList [{'id':1023, 'type':'Purchase', 'date':'23.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':1024, 'type':'Purchase', 'date':'24.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':23, 'type':'Purchase', 'date':'2.8.2008', 'sum':'-21,90', 'target':'Apple Store'}] All the dictionaries have the same keys, but the values change. The 'id' value is unique. Here the problems start. I want to get the common values for all the items the user selected. In the above list they would be 'sum':'-21,90' and 'target':'Apple Store'. I don't know how to properly compare the dicts in the list. One big problem is that I don't know beforehand how many dicts the list contains, since it's decided by the user. I have a vague idea that list comprehensions would be the way to go, but I only know how to compare two lists with list comprehensions, not n lists. Any help would be appreciated.
[ ">>> mysets = (set(x.items()) for x in MyList)\n>>> reduce(lambda a,b: a.intersection(b), mysets)\nset([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')])\n\nFirst, I've created a generator that will convert the list of dicts into an iterable sequence of sets of key,value pairs. You could use a list comprehension here but this way doesn't convert your entire list into yet another list, useful if you don't know how big it will be.\nThen I've used reduce to apply a function that finds the common values between each set. It finds the intersection of set 1 & set 2, which is itself a set, then the intersection of that set & set 3 etc. The mysets generator will happily feed each set on demand to the reduce function until its done.\nI believe reduce has been deprecated as a built-in in Python 3.0, but should still be available in functools.\nYou could of course make it a one-liner by replacing mysets in the reduce with the generator expression, but that reduces the readability IMO. In practice I'd probably even go one step further and break the lambda out into its own line as well:\n>>> mysets = (set(x.items()) for x in MyList)\n>>> find_common = lambda a,b: a.intersection(b)\n>>> reduce(find_common, mysets)\nset([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')])\n\nAnd if you need the end result to be a dict, just wrap it like so:\n>>> dict(reduce(find_common, mysets))\n{'sum': '-21,90', 'type': 'Purchase', 'target': 'Apple Store'}\n\ndict can accept any iterator of key,value pairs, such as the set of tuples returned at the end.\n", "My answer is identical to Matthew Trevor's, except for one difference:\n>>> mysets = (set(x.items()) for x in MyList)\n>>> reduce(set.intersection, mysets)\nset([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')])\n\nHere I use set.intersection instead of creating a new lambda. In my opinion this is more readable, as this intuitively reads as \"reduce is reducing this list using the set intersection operator.\" This should also be much faster, as set.intersection is a built-in C function.\nTo fully answer your question, you can extract the values using a list comprehension:\n>>> mysets = (set(x.items()) for x in MyList)\n>>> result = reduce(set.intersection, mysets)\n>>> values = [r[1] for r in result]\n>>> values\n['-21,90', 'Purchase', 'Apple Store']\n\nThis would end up on one line for me. but that's entirely up to you:\n>>> [r[1] for r in reduce(set.intersection, (set(x.items()) for x in myList))]\n['-21,90', 'Purchase', 'Apple Store']\n\n", "First, we need a function to compute intersection of two dictionaries:\ndef IntersectDicts( d1, d2 ) :\n return dict(filter(lambda (k,v) : k in d2 and d2[k] == v, d1.items()))\n\nThen we can use it to process any number of dictionaries:\nresult = reduce(IntersectDicts, MyList)\n\n", "Since you're only looking for the common set, you can compare the keys in the first dictionary to the keys in all other dictionaries:\ncommon = {}\nfor k in MyList[0]:\n for i in xrange(1,len(MyList)):\n if MyList[0][k] != MyList[i][k]: continue\n common[k] = MyList[0][k]\n\n>>> common\n{'sum': '-21,90', 'type': 'Purchase', 'target': 'Apple Store'}\n\n", "Sorry, yes, 'type':'Purchase' is also one of the common values.Should have logged in to edit the question.\n" ]
[ 8, 8, 2, 1, 0 ]
[]
[]
[ "data_mining", "python" ]
stackoverflow_0000314583_data_mining_python.txt
Q: How do I search through a folder for the filename that matches a regular expression using Python? I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An example would be very much appreciated. Thanks in advance. A: This will find all files starting with two digits and ending in gif, you can add the files into a global list, if you wish: import re import os r = re.compile(r'\d{2}.+gif$') for root, dirs, files in os.walk('/home/vinko'): l = [os.path.join(root,x) for x in files if r.match(x)] if l: print l #Or append to a global list, whatever A: Read about the RE pattern's match method. Read all answers to How do I copy files with specific file extension to a folder in my python (version 2.5) script? Pick one that uses fnmatch. Replace fnmatch with re.match. This requires careful thought. It's not a cut-and-paste. Then, ask specific questions. A: If the pattern you have to match is simple enough to grab with filesystem wildcards, I recommend you take a look at the glob module, which exists for this exact purpose.
How do I search through a folder for the filename that matches a regular expression using Python?
I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An example would be very much appreciated. Thanks in advance.
[ "This will find all files starting with two digits and ending in gif, you can add the files into a global list, if you wish:\nimport re\nimport os\nr = re.compile(r'\\d{2}.+gif$')\nfor root, dirs, files in os.walk('/home/vinko'):\n l = [os.path.join(root,x) for x in files if r.match(x)]\n if l: print l #Or append to a global list, whatever\n\n", "\nRead about the RE pattern's match method. \nRead all answers to How do I copy files with specific file extension to a folder in my python (version 2.5) script?\nPick one that uses fnmatch. Replace fnmatch with re.match. This requires careful thought. It's not a cut-and-paste.\nThen, ask specific questions.\n\n", "If the pattern you have to match is simple enough to grab with filesystem wildcards, I recommend you take a look at the glob module, which exists for this exact purpose.\n" ]
[ 11, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000315381_python_regex.txt
Q: How can I do synchronous rpc calls I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server using the examples from twisted, but I'm having trouble with the client. c = ClientCreator(reactor, Greeter) c.connectTCP(self.host, self.port).addCallback(request) reactor.run() This works for a single call, when the data is received I'm calling reactor.stop(), but if I make any more calls the reactor won't restart. Is there something else I should be using for this? maybe a different twisted module or another framework? (I'm not including the details of how the protocol works, because the main point is that I only get one call out of this.) Addendum & Clarification: I shared a google doc with notes on what I'm doing. http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz I have a version written that uses fuse and can combine multiple local folders into the fuse mount point. The file access is already handled within a class, so I want to have servers that give me network access to the same class. After continuing to search, I suspect pyro (http://pyro.sourceforge.net/) might be what I'm really looking for (simply based on reading their home page right now) but I'm open to any suggestions. I could achieve similar results by using an nfs mount and combining it with my local folder, but I want all of the peers to have access to the same combined filesystem, so that would require every computer to bee an nfs server with a number of nfs mounts equal to the number of computers in the network. Conclusion: I have decided to use rpyc as it gave me exactly what I was looking for. A server that keeps an instance of a class that I can manipulate as if it was local. If anyone is interested I put my project up on Launchpad (http://launchpad.net/dstorage). A: For a synchronous client, Twisted probably isn't the right option. Instead, you might want to use the socket module directly. import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((self.host, self.port)) s.send(output) data = s.recv(size) s.close() The recv() call might need to be repeated until you get an empty string, but this shows the basics. Alternatively, you can rearrange your entire program to support asynchronous calls... A: If you're even considering Pyro, check out RPyC first, and re-consider XML-RPC. Regarding Twisted: try leaving the reactor up instead of stopping it, and just ClientCreator(...).connectTCP(...) each time. If you self.transport.loseConnection() in your Protocol you won't be leaving open connections. A: Why do you feel that it needs to be synchronous? If you want to ensure that only one of these is happening at a time, invoke all of the calls through a DeferredSemaphore so you can rate limit the actual invocations (to any arbitrary value). If you want to be able to run multiple streams of these at different times, but don't care about concurrency limits, then you should at least separate reactor startup and teardown from the invocations (the reactor should run throughout the entire lifetime of the process). If you just can't figure out how to express your application's logic in a reactor pattern, you can use deferToThread and write a chunk of purely synchronous code -- although I would guess this would not be necessary. A: If you are using Twisted you should probably know that: You will not be making synchronous calls to any network service The reactor can only ever be run once, so do not stop it (by calling reactor.stop()) until your application is ready to exit. I hope this answers your question. I personally believe that Twisted is exactly the correct solution for your use case, but that you need to work around your synchronicity issue. Addendum & Clarification: Part of what I don't understand is that when I call reactor.run() it seems to go into a loop that just watches for network activity. How do I continue running the rest of my program while it uses the network? if I can get past that, then I can probably work through the synchronicity issue. That is exactly what reactor.run() does. It runs a main loop which is an event reactor. It will not only wait for entwork events, but anything else you have scheduled to happen. With Twisted you will need to structure the rest of your application in a way to deal with its asynchronous nature. Perhaps if we knew what kind of application it is, we could advise.
How can I do synchronous rpc calls
I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server using the examples from twisted, but I'm having trouble with the client. c = ClientCreator(reactor, Greeter) c.connectTCP(self.host, self.port).addCallback(request) reactor.run() This works for a single call, when the data is received I'm calling reactor.stop(), but if I make any more calls the reactor won't restart. Is there something else I should be using for this? maybe a different twisted module or another framework? (I'm not including the details of how the protocol works, because the main point is that I only get one call out of this.) Addendum & Clarification: I shared a google doc with notes on what I'm doing. http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz I have a version written that uses fuse and can combine multiple local folders into the fuse mount point. The file access is already handled within a class, so I want to have servers that give me network access to the same class. After continuing to search, I suspect pyro (http://pyro.sourceforge.net/) might be what I'm really looking for (simply based on reading their home page right now) but I'm open to any suggestions. I could achieve similar results by using an nfs mount and combining it with my local folder, but I want all of the peers to have access to the same combined filesystem, so that would require every computer to bee an nfs server with a number of nfs mounts equal to the number of computers in the network. Conclusion: I have decided to use rpyc as it gave me exactly what I was looking for. A server that keeps an instance of a class that I can manipulate as if it was local. If anyone is interested I put my project up on Launchpad (http://launchpad.net/dstorage).
[ "For a synchronous client, Twisted probably isn't the right option. Instead, you might want to use the socket module directly.\nimport socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((self.host, self.port))\ns.send(output)\ndata = s.recv(size)\ns.close()\n\nThe recv() call might need to be repeated until you get an empty string, but this shows the basics.\nAlternatively, you can rearrange your entire program to support asynchronous calls...\n", "If you're even considering Pyro, check out RPyC first, and re-consider XML-RPC.\nRegarding Twisted: try leaving the reactor up instead of stopping it, and just ClientCreator(...).connectTCP(...) each time.\nIf you self.transport.loseConnection() in your Protocol you won't be leaving open connections.\n", "Why do you feel that it needs to be synchronous?\nIf you want to ensure that only one of these is happening at a time, invoke all of the calls through a DeferredSemaphore so you can rate limit the actual invocations (to any arbitrary value).\nIf you want to be able to run multiple streams of these at different times, but don't care about concurrency limits, then you should at least separate reactor startup and teardown from the invocations (the reactor should run throughout the entire lifetime of the process).\nIf you just can't figure out how to express your application's logic in a reactor pattern, you can use deferToThread and write a chunk of purely synchronous code -- although I would guess this would not be necessary.\n", "If you are using Twisted you should probably know that:\n\nYou will not be making synchronous calls to any network service\nThe reactor can only ever be run once, so do not stop it (by calling reactor.stop()) until your application is ready to exit.\n\nI hope this answers your question. I personally believe that Twisted is exactly the correct solution for your use case, but that you need to work around your synchronicity issue.\nAddendum & Clarification:\n\nPart of what I don't understand is\n that when I call reactor.run() it\n seems to go into a loop that just\n watches for network activity. How do I\n continue running the rest of my\n program while it uses the network? if\n I can get past that, then I can\n probably work through the\n synchronicity issue.\n\nThat is exactly what reactor.run() does. It runs a main loop which is an event reactor. It will not only wait for entwork events, but anything else you have scheduled to happen. With Twisted you will need to structure the rest of your application in a way to deal with its asynchronous nature. Perhaps if we knew what kind of application it is, we could advise.\n" ]
[ 2, 2, 2, 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0000281922_python_twisted.txt
Q: Running a function periodically in twisted protocol I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logic is in Protocol class and it is instantiated by the reactor as needed. I don't know how to tie it from reactor to all protocol instances... A: You would probably want to do this in the Factory for the connections. The Factory is not automatically notified of every time a connection is made and lost, so you can notify it from the Protocol. Here is a complete example of how to use twisted.internet.task.LoopingCall in conjunction with a customised basic Factory and Protocol to announce that '10 seconds has passed' to every connection every 10 seconds. from twisted.internet import reactor, protocol, task class MyProtocol(protocol.Protocol): def connectionMade(self): self.factory.clientConnectionMade(self) def connectionLost(self, reason): self.factory.clientConnectionLost(self) class MyFactory(protocol.Factory): protocol = MyProtocol def __init__(self): self.clients = [] self.lc = task.LoopingCall(self.announce) self.lc.start(10) def announce(self): for client in self.clients: client.transport.write("10 seconds has passed\n") def clientConnectionMade(self, client): self.clients.append(client) def clientConnectionLost(self, client): self.clients.remove(client) myfactory = MyFactory() reactor.listenTCP(9000, myfactory) reactor.run() A: I'd imagine the easiest way to do that is to manage a list of clients in the protocol with connectionMade and connectionLost in the client and then use a LoopingCall to ask each client to send data. That feels a little invasive, but I don't think you'd want to do it without the protocol having some control over the transmission/reception. Of course, I'd have to see your code to really know how it'd fit in well. Got a github link? :)
Running a function periodically in twisted protocol
I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logic is in Protocol class and it is instantiated by the reactor as needed. I don't know how to tie it from reactor to all protocol instances...
[ "You would probably want to do this in the Factory for the connections. The Factory is not automatically notified of every time a connection is made and lost, so you can notify it from the Protocol.\nHere is a complete example of how to use twisted.internet.task.LoopingCall in conjunction with a customised basic Factory and Protocol to announce that '10 seconds has passed' to every connection every 10 seconds.\nfrom twisted.internet import reactor, protocol, task\n\nclass MyProtocol(protocol.Protocol):\n def connectionMade(self):\n self.factory.clientConnectionMade(self)\n def connectionLost(self, reason):\n self.factory.clientConnectionLost(self)\n\nclass MyFactory(protocol.Factory):\n protocol = MyProtocol\n def __init__(self):\n self.clients = []\n self.lc = task.LoopingCall(self.announce)\n self.lc.start(10)\n\n def announce(self):\n for client in self.clients:\n client.transport.write(\"10 seconds has passed\\n\")\n\n def clientConnectionMade(self, client):\n self.clients.append(client)\n\n def clientConnectionLost(self, client):\n self.clients.remove(client)\n\nmyfactory = MyFactory()\nreactor.listenTCP(9000, myfactory)\nreactor.run()\n\n", "I'd imagine the easiest way to do that is to manage a list of clients in the protocol with connectionMade and connectionLost in the client and then use a LoopingCall to ask each client to send data.\nThat feels a little invasive, but I don't think you'd want to do it without the protocol having some control over the transmission/reception. Of course, I'd have to see your code to really know how it'd fit in well. Got a github link? :)\n" ]
[ 38, 3 ]
[]
[]
[ "protocols", "python", "tcp", "twisted" ]
stackoverflow_0000315716_protocols_python_tcp_twisted.txt
Q: Twisted FTPFileListProtocol and file names with spaces I am using Python and the Twisted framework to connect to an FTP site to perform various automated tasks. Our FTP server happens to be Pure-FTPd, if that's relevant. When connecting and calling the list method on an FTPClient, the resulting FTPFileListProtocol's files collection does not contain any directories or file names that contain a space (' '). Has anyone else seen this? Is the only solution to create a sub-class of FTPFileListProtocol and override its unknownLine method, parsing the file/directory names manually? A: Firstly, if you're performing automated tasks on a retrieived FTP listing then you should probably be looking at NLST rather than LIST as noted in RFC 959 section 4.1.3: NAME LIST (NLST) ... This command is intended to return information that can be used by a program to further process the files automatically. The Twisted documentation for LIST says: It can cope with most common file listing formats. This make me suspicious; I do not like solutions that "cope". LIST was intended for human consumption not machine processing. If your target server supports them then you should prefer MLST and MLSD as defined in RFC 3659 section 7: 7. Listings for Machine Processing (MLST and MLSD) The MLST and MLSD commands are intended to standardize the file and directory information returned by the server-FTP process. These commands differ from the LIST command in that the format of the replies is strictly defined although extensible. However, these newer commands may not be available on your target server and I don't see them in Twisted. Therefore NLST is probably your best bet. As to the nub of your problem, there are three likely causes: The processing of the returned results is incorrect (Twisted may be at fault, as you suggest, or perhaps elsewhere) The server is buggy and not sending a correct (complete) response The wrong command is being sent (unlikely with straight NLST/LIST, but some servers react differently if arguments are supplied to these commands) You can eliminate (2) and (3) and prove that the cause is (1) by looking at what is sent over the wire. If this option is not available to you as part of the Twisted API or the Pure-FTPD server logging configuration, then you may need to break out a network sniffer such as tcpdump, snoop or WireShark (assuming you're allowed to do this in your environment). Note that you will need to trace not only the control connection (port 21) but also the data connection (since that carries the results of the LIST/NLST command). WireShark is nice since it will perform the protocol-level analysis for you. Good luck. A: This is somehow expected. FTPFileListProtocol isn't able to understand every FTP output, because, well, some are wacky. As explained in the docstring: If you need different evil for a wacky FTP server, you can override either C{fileLinePattern} or C{parseDirectoryLine()}. In this case, it may be a bug: maybe you can improve fileLinePattern and makes it understand filename with spaces. If so, you're welcome to open a bug in the Twisted tracker.
Twisted FTPFileListProtocol and file names with spaces
I am using Python and the Twisted framework to connect to an FTP site to perform various automated tasks. Our FTP server happens to be Pure-FTPd, if that's relevant. When connecting and calling the list method on an FTPClient, the resulting FTPFileListProtocol's files collection does not contain any directories or file names that contain a space (' '). Has anyone else seen this? Is the only solution to create a sub-class of FTPFileListProtocol and override its unknownLine method, parsing the file/directory names manually?
[ "Firstly, if you're performing automated tasks on a retrieived FTP listing then you should probably be looking at NLST rather than LIST as noted in RFC 959 section 4.1.3:\n\n NAME LIST (NLST)\n ...\n This command is intended to return information that\n can be used by a program to further process the\n files automatically.\n\n\nThe Twisted documentation for LIST says:\n\nIt can cope with most common file listing formats.\n\nThis make me suspicious; I do not like solutions that \"cope\". LIST was intended for human consumption not machine processing.\nIf your target server supports them then you should prefer MLST and MLSD as defined in RFC 3659 section 7:\n\n7. Listings for Machine Processing (MLST and MLSD)\n\n The MLST and MLSD commands are intended to standardize the file and\n directory information returned by the server-FTP process. These\n commands differ from the LIST command in that the format of the\n replies is strictly defined although extensible.\n\n\nHowever, these newer commands may not be available on your target server and I don't see them in Twisted. Therefore NLST is probably your best bet.\nAs to the nub of your problem, there are three likely causes:\n\nThe processing of the returned results is incorrect (Twisted may be at fault, as you suggest, or perhaps elsewhere)\nThe server is buggy and not sending a correct (complete) response\nThe wrong command is being sent (unlikely with straight NLST/LIST, but some servers react differently if arguments are supplied to these commands)\n\nYou can eliminate (2) and (3) and prove that the cause is (1) by looking at what is sent over the wire. If this option is not available to you as part of the Twisted API or the Pure-FTPD server logging configuration, then you may need to break out a network sniffer such as tcpdump, snoop or WireShark (assuming you're allowed to do this in your environment). Note that you will need to trace not only the control connection (port 21) but also the data connection (since that carries the results of the LIST/NLST command). WireShark is nice since it will perform the protocol-level analysis for you.\nGood luck.\n", "This is somehow expected. FTPFileListProtocol isn't able to understand every FTP output, because, well, some are wacky. As explained in the docstring:\nIf you need different evil for a wacky FTP server, you can\noverride either C{fileLinePattern} or C{parseDirectoryLine()}.\nIn this case, it may be a bug: maybe you can improve fileLinePattern and makes it understand filename with spaces. If so, you're welcome to open a bug in the Twisted tracker.\n" ]
[ 2, 0 ]
[]
[]
[ "ftp", "python", "twisted" ]
stackoverflow_0000304152_ftp_python_twisted.txt
Q: Decimal place issues with floats and decimal.Decimal I seem to be losing a lot of precision with floats. For example I need to solve a matrix: 4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 This is the code I use to import the matrix from a text file: f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z: x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 Here is the code I use to rearrange the equations. b is a matrix of coefficients and y is the answer vector: def equations(b,y): i=0 eqn=[] row=[] while(i<len(b)): j=0 row=[] while(j<len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn However the answers I get back aren't precise to the decimal place. For example, upon rearranging the second equation from above, I should get: y=-1.2-.2x+.6z What I get is: y=-1.2-0.20000000000000001x+0.59999999999999998z This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the Decimal class but it does not work well with powers (i.e, Decimal(x)**2). Any ideas? A: IEEE floating point is binary, not decimal. There is no fixed length binary fraction that is exactly 0.1, or any multiple thereof. It is a repeating fraction, like 1/3 in decimal. Please read What Every Computer Scientist Should Know About Floating-Point Arithmetic Other options besides a Decimal class are using Common Lisp or Python 2.6 or another language with exact rationals converting the doubles to close rationals using, e.g., frap A: I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably). EDIT: What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine. >>> import decimal >>> print(decimal.Decimal("1.2") ** 2) 1.44 The module documentation explains the need for and usage of decimal.Decimal pretty clearly, you should check it out if you haven't yet. A: First, your input can be simplified a lot. You don't need to read and parse a file. You can just declare your objects in Python notation. Eval the file. b = [ [4.0, -2.0, 1.0], [1.0, +5.0, -3.0], [2.0, +2.0, +5.0], ] y = [ 11.0, -6.0, 7.0 ] Second, y=-1.2-0.20000000000000001x+0.59999999999999998z isn't unusual. There's no exact representation in binary notation for 0.2 or 0.6. Consequently, the values displayed are the decimal approximations of the original not exact representations. Those are true for just about every kind of floating-point processor there is. You can try the Python 2.6 fractions module. There's an older rational package that might help. Yes, raising floating-point numbers to powers increases the errors. Consequently, you have to be sure to avoid using the right-most positions of the floating-point number, since those bits are mostly noise. When displaying floating-point numbers, you have to appropriately round them to avoid seeing the noise bits. >>> a 0.20000000000000001 >>> "%.4f" % (a,) '0.2000' A: I'd caution against the decimal module for tasks like this. Its purpose is really more dealing with real-world decimal numbers (eg. matching human bookkeeping practices), with finite precision, not performing exact precision math. There are numbers not exactly representable in decimal just as there are in binary, and performing arithmetic in decimal is also much slower than alternatives. Instead, if you want exact results you should use rational arithmetic. These will represent numbers as a numerator/denomentator pair, so can exactly represent all rational numbers. If you're only using multiplication and division (rather than operations like square roots that can result in irrational numbers), you will never lose precision. As others have mentioned, python 2.6 will have a built-in rational type, though note that this isn't really a high-performing implementation - for speed you're better using libraries like gmpy. Just replace your calls to float() to gmpy.mpq() and your code should now give exact results (though you may want to format the results as floats for display purposes). Here's a slightly tidied version of your code to load a matrix that will use gmpy rationals instead: def read_matrix(f): b,y = [], [] for line in f: bits = line.split(",") b.append( map(gmpy.mpq, bits[:-1]) ) y.append(gmpy.mpq(bits[-1])) return b,y A: It is not an answer to your question, but related: #!/usr/bin/env python from numpy import abs, dot, loadtxt, max from numpy.linalg import solve data = loadtxt('gauss.dat', delimiter=',') a, b = data[:,:-1], data[:,-1:] x = solve(a, b) # here you may use any method you like instead of `solve` print(x) print(max(abs((dot(a, x) - b) / b))) # check solution Example: $ cat gauss.dat 4.0, 2.0, 1.0, 11.0 1.0, 5.0, 3.0, 6.0 2.0, 2.0, 5.0, 7.0 $ python loadtxt_example.py [[ 2.4] [ 0.6] [ 0.2]] 0.0 A: Also see What is a simple example of floating point error, here on SO, which has some answers. The one I give actually uses python as the example language...
Decimal place issues with floats and decimal.Decimal
I seem to be losing a lot of precision with floats. For example I need to solve a matrix: 4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 This is the code I use to import the matrix from a text file: f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z: x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 Here is the code I use to rearrange the equations. b is a matrix of coefficients and y is the answer vector: def equations(b,y): i=0 eqn=[] row=[] while(i<len(b)): j=0 row=[] while(j<len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn However the answers I get back aren't precise to the decimal place. For example, upon rearranging the second equation from above, I should get: y=-1.2-.2x+.6z What I get is: y=-1.2-0.20000000000000001x+0.59999999999999998z This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the Decimal class but it does not work well with powers (i.e, Decimal(x)**2). Any ideas?
[ "IEEE floating point is binary, not decimal. There is no fixed length binary fraction that is exactly 0.1, or any multiple thereof. It is a repeating fraction, like 1/3 in decimal.\nPlease read What Every Computer Scientist Should Know About Floating-Point Arithmetic\nOther options besides a Decimal class are \n\nusing Common Lisp or Python 2.6 or another language with exact rationals\nconverting the doubles to close rationals using, e.g., frap\n\n", "I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably).\nEDIT: What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine.\n>>> import decimal\n>>> print(decimal.Decimal(\"1.2\") ** 2)\n1.44\n\nThe module documentation explains the need for and usage of decimal.Decimal pretty clearly, you should check it out if you haven't yet.\n", "First, your input can be simplified a lot. You don't need to read and parse a file. You can just declare your objects in Python notation. Eval the file.\nb = [\n [4.0, -2.0, 1.0],\n [1.0, +5.0, -3.0],\n [2.0, +2.0, +5.0],\n]\ny = [ 11.0, -6.0, 7.0 ]\n\nSecond, y=-1.2-0.20000000000000001x+0.59999999999999998z isn't unusual. There's no exact representation in binary notation for 0.2 or 0.6. Consequently, the values displayed are the decimal approximations of the original not exact representations. Those are true for just about every kind of floating-point processor there is.\nYou can try the Python 2.6 fractions module. There's an older rational package that might help.\nYes, raising floating-point numbers to powers increases the errors. Consequently, you have to be sure to avoid using the right-most positions of the floating-point number, since those bits are mostly noise.\nWhen displaying floating-point numbers, you have to appropriately round them to avoid seeing the noise bits.\n>>> a\n0.20000000000000001\n>>> \"%.4f\" % (a,)\n'0.2000'\n\n", "I'd caution against the decimal module for tasks like this. Its purpose is really more dealing with real-world decimal numbers (eg. matching human bookkeeping practices), with finite precision, not performing exact precision math. There are numbers not exactly representable in decimal just as there are in binary, and performing arithmetic in decimal is also much slower than alternatives.\nInstead, if you want exact results you should use rational arithmetic. These will represent numbers as a numerator/denomentator pair, so can exactly represent all rational numbers. If you're only using multiplication and division (rather than operations like square roots that can result in irrational numbers), you will never lose precision.\nAs others have mentioned, python 2.6 will have a built-in rational type, though note that this isn't really a high-performing implementation - for speed you're better using libraries like gmpy. Just replace your calls to float() to gmpy.mpq() and your code should now give exact results (though you may want to format the results as floats for display purposes).\nHere's a slightly tidied version of your code to load a matrix that will use gmpy rationals instead:\ndef read_matrix(f):\n b,y = [], []\n for line in f:\n bits = line.split(\",\")\n b.append( map(gmpy.mpq, bits[:-1]) )\n y.append(gmpy.mpq(bits[-1]))\n return b,y\n\n", "It is not an answer to your question, but related:\n#!/usr/bin/env python\nfrom numpy import abs, dot, loadtxt, max\nfrom numpy.linalg import solve\n\ndata = loadtxt('gauss.dat', delimiter=',')\na, b = data[:,:-1], data[:,-1:]\nx = solve(a, b) # here you may use any method you like instead of `solve`\nprint(x)\nprint(max(abs((dot(a, x) - b) / b))) # check solution\n\nExample:\n$ cat gauss.dat\n4.0, 2.0, 1.0, 11.0\n1.0, 5.0, 3.0, 6.0 \n2.0, 2.0, 5.0, 7.0\n\n$ python loadtxt_example.py\n[[ 2.4]\n [ 0.6]\n [ 0.2]]\n0.0\n\n", "Also see What is a simple example of floating point error, here on SO, which has some answers. The one I give actually uses python as the example language...\n" ]
[ 14, 12, 4, 4, 2, 0 ]
[]
[]
[ "decimal", "floating_accuracy", "floating_point", "python" ]
stackoverflow_0000286061_decimal_floating_accuracy_floating_point_python.txt
Q: Ghostscript PDF -> TIFF throws an untrappable exception, when consuming files with asian fonts Ghostscript curls up and dies, throwing an exception to stdout which I cannot catch and log. I am pretty sure it gets sick when I give it asian fonts. Has anybody backed into this problem and solved it? A: It may be that you need to read stderr from the child process.
Ghostscript PDF -> TIFF throws an untrappable exception, when consuming files with asian fonts
Ghostscript curls up and dies, throwing an exception to stdout which I cannot catch and log. I am pretty sure it gets sick when I give it asian fonts. Has anybody backed into this problem and solved it?
[ "It may be that you need to read stderr from the child process.\n" ]
[ 1 ]
[]
[]
[ "ghostscript", "jython", "python", "tiff" ]
stackoverflow_0000316518_ghostscript_jython_python_tiff.txt
Q: Newbie Python question about strings with parameters: "%%s"? I'm trying to figure out what the following line does exactly - specifically the %%s part? cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n)) Any good mini-tutorial about string formatting and inserting variables into strings with Python? A: The %% becomes a single %. This code is essentially doing two levels of string formatting. First the %sourcedest is executed to turn your code essentially into: cursor.execute('INSERT INTO mastertickets (BLAH, FOO) VALUES (%s, %s)', (self.tkt.id, n)) then the db layer applies the parameters to the slots that are left. The double-% is needed to get the db's slots passed through the first string formatting operation safely. A: "but how should one do it instead?" Tough call. The issue is that they are plugging in metadata (specifically column names) on the fly into a SQL statement. I'm not a big fan of this kind of thing. The sourcedest variable has two column names that are going to be updated. Odds are good that there is only one (or a few few) pairs of column names that are actually used. My preference is to do this. if situation1: stmt= "INSERT INTO mastertickets (this, that) VALUES (?, ?)" elif situation2: stmt= "INSERT INTO mastertickets (foo, bar) VALUES (?, ?)" else: raise Exception( "Bad configuration -- with some explanation" ) cursor.execute( stmt, (self.tkt.id, n) ) When there's more than one valid combination of columns for this kind of thing, it indicates that the data model has merged two entities into a single table, which is a common database design problem. Since you're working with a product and a plug-in, there's not much you can do about the data model issues. A: Having the column names inserted using string formatting isn't so bad so long as they aren't user-provided. The values should be query parameters though: stmt = "INSERT INTO mastertickets (%s, %s) VALUES (?, ?)" % srcdest ... cursor.execute( stmt, (self.tkt.id, n) ) A: %% turns into a single % A: It does the same: cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (:%s, :%s)' % \ tuple(sourcedest + sourcedest), dict(zip(sourcedest, (self.tkt.id, n)))) Never do that.
Newbie Python question about strings with parameters: "%%s"?
I'm trying to figure out what the following line does exactly - specifically the %%s part? cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n)) Any good mini-tutorial about string formatting and inserting variables into strings with Python?
[ "The %% becomes a single %. This code is essentially doing two levels of string formatting. First the %sourcedest is executed to turn your code essentially into:\ncursor.execute('INSERT INTO mastertickets (BLAH, FOO) VALUES (%s, %s)', (self.tkt.id, n))\n\nthen the db layer applies the parameters to the slots that are left.\nThe double-% is needed to get the db's slots passed through the first string formatting operation safely.\n", "\"but how should one do it instead?\"\nTough call. The issue is that they are plugging in metadata (specifically column names) on the fly into a SQL statement. I'm not a big fan of this kind of thing. The sourcedest variable has two column names that are going to be updated. \nOdds are good that there is only one (or a few few) pairs of column names that are actually used. My preference is to do this.\nif situation1:\n stmt= \"INSERT INTO mastertickets (this, that) VALUES (?, ?)\"\nelif situation2:\n stmt= \"INSERT INTO mastertickets (foo, bar) VALUES (?, ?)\"\nelse:\n raise Exception( \"Bad configuration -- with some explanation\" )\ncursor.execute( stmt, (self.tkt.id, n) )\n\nWhen there's more than one valid combination of columns for this kind of thing, it indicates that the data model has merged two entities into a single table, which is a common database design problem. Since you're working with a product and a plug-in, there's not much you can do about the data model issues.\n", "Having the column names inserted using string formatting isn't so bad so long as they aren't user-provided. The values should be query parameters though:\nstmt = \"INSERT INTO mastertickets (%s, %s) VALUES (?, ?)\" % srcdest\n...\ncursor.execute( stmt, (self.tkt.id, n) )\n\n", "%% turns into a single %\n", "It does the same:\ncursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (:%s, :%s)' % \\\n tuple(sourcedest + sourcedest), dict(zip(sourcedest, (self.tkt.id, n))))\n\nNever do that.\n" ]
[ 7, 4, 3, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0000317368_python_string.txt
Q: Python: packing an ip address as a ctype.c_ulong() for use with DLL given the following code: import ctypes ip="192.168.1.1" thisdll = ctypes.cdll['aDLL'] thisdll.functionThatExpectsAnIP(ip) how can I correctly pack this for a DLL that expects it as a c_ulong datatype? I've tried using: ip_netFrmt = socket.inet_aton(ip) ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt) however, the c_ulong() method returns an error because it needs an integer. is there a way to use struct.pack to accomplish this? A: The inet_aton returns a string of bytes. This used to be the lingua franca for C-language interfaces. Here's how to unpack those bytes into a more useful value. >>> import socket >>> packed_n= socket.inet_aton("128.0.0.1") >>> import struct >>> struct.unpack( "!L", packed_n ) (2147483649L,) >>> hex(_[0]) '0x80000001L' This unpacked value can be used with ctypes. The hex thing is just to show you that the unpacked value looks a lot like an IP address. A: First a disclaimer: This is just an educated guess. an ip-address is traditionally represented as four bytes - i.e. xxx.xxx.xxx.xxx, but is really a unsigned long. So you should convert the representation 192.168.1.1 to an unsiged int. you could convert it like this. ip="192.168.1.1" ip_long = reduce(lambda x,y:x*256+int(y), ip.split('.'), 0) A: There's probably a better way, but this works: >>> ip = "192.168.1.1" >>> struct.unpack('>I', struct.pack('BBBB', *map(int, ip.split('.'))))[0] 3232235777L A: For a more thorough way of handling IPs (v6, CIDR-style stuff etc) check out how it's done in py-radix, esp. prefix_pton.
Python: packing an ip address as a ctype.c_ulong() for use with DLL
given the following code: import ctypes ip="192.168.1.1" thisdll = ctypes.cdll['aDLL'] thisdll.functionThatExpectsAnIP(ip) how can I correctly pack this for a DLL that expects it as a c_ulong datatype? I've tried using: ip_netFrmt = socket.inet_aton(ip) ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt) however, the c_ulong() method returns an error because it needs an integer. is there a way to use struct.pack to accomplish this?
[ "The inet_aton returns a string of bytes. This used to be the lingua franca for C-language interfaces.\nHere's how to unpack those bytes into a more useful value.\n>>> import socket\n>>> packed_n= socket.inet_aton(\"128.0.0.1\")\n>>> import struct\n>>> struct.unpack( \"!L\", packed_n )\n(2147483649L,)\n>>> hex(_[0])\n'0x80000001L'\n\nThis unpacked value can be used with ctypes. The hex thing is just to show you that the unpacked value looks a lot like an IP address.\n", "First a disclaimer: This is just an educated guess.\nan ip-address is traditionally represented as four bytes - i.e. xxx.xxx.xxx.xxx, but is really a unsigned long. So you should convert the representation 192.168.1.1 to an unsiged int. you could convert it like this.\nip=\"192.168.1.1\"\nip_long = reduce(lambda x,y:x*256+int(y), ip.split('.'), 0)\n\n", "There's probably a better way, but this works:\n>>> ip = \"192.168.1.1\"\n>>> struct.unpack('>I', struct.pack('BBBB', *map(int, ip.split('.'))))[0]\n3232235777L\n\n", "For a more thorough way of handling IPs (v6, CIDR-style stuff etc) check out how it's done in py-radix, esp. prefix_pton.\n" ]
[ 6, 0, 0, 0 ]
[]
[]
[ "ctypes", "dll", "ip_address", "python" ]
stackoverflow_0000317531_ctypes_dll_ip_address_python.txt
Q: Spambots are cluttering my log file [Django] I have a nice and lovely Django site up and running, but have noticed that my error.log file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like http://mysite.com/ie or http://mysite.com/~admin.php etc. Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a TemplateDoesNotExist exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly. Is there a way to turn this behavior off? Or perhaps just block the IP's doing this? A: Um, perhaps, use logrotate to rotate and compress the logs periodically, if it isn't being done already. A: If you can find a pattern in UserAgent string, you may use DISALLOWED_USER_AGENT setting. Mine is: DISALLOWED_USER_AGENTS = ( re.compile(r'Java'), re.compile(r'gigamega'), re.compile(r'litefinder'), ) See the description in Django docs. A: "Is there a way to turn this behavior off?" - the 500 is absolutely mandatory. The log entry is also mandatory. "Or perhaps just block the IP's doing this?" - don't we wish. Everyone has this problem. Just about everyone uses Apache log rotation. Everyone else either uses an OS rotation or rolls their own. A: Django should be throwing a 404, not a 500, if the URL doesn't match any entries in your URLConf. http://docs.djangoproject.com/en/dev/topics/http/urls/#handler404 You need to provide a 404 template: If you don't define your own 404 view -- and simply use the default, which is recommended -- you still have one obligation: To create a 404.html template in the root of your template directory. The default 404 view will use that template for all 404 errors. A: How about setting up a catch-all pattern as the last item in your urls file and directing it to a generic "no such page" or even your homepage? In other words, turn 500's into requests for your homepage. A: Why not fix those "bugs"? If a url pattern is not matched, then a proper error message should be shown. By adding those templates you will help the user and yourself :-) A: Yes, it should be a 404, not a 500. 500 indicates something is trying to deal with the URL and is failing in the process. You need to find and fix that. We have a similar problem. Since we are running Apache/mod_python, I chose to deal with it in .htaccess with mod_rewrite rules. I periodically look at the logs and add a few patterns to my "go to hell" list. These all rewrite to deliver a 1x1 pixel gif file. There is no tsunami of 404s to clutter up my log analysis and it puts minimal load on Django and Apache. You can't make these a**holes go away, so all you can do is minimize their impact on your system and get on with your life.
Spambots are cluttering my log file [Django]
I have a nice and lovely Django site up and running, but have noticed that my error.log file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like http://mysite.com/ie or http://mysite.com/~admin.php etc. Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a TemplateDoesNotExist exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly. Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?
[ "Um, perhaps, use logrotate to rotate and compress the logs periodically, if it isn't being done already.\n", "If you can find a pattern in UserAgent string, you may use DISALLOWED_USER_AGENT setting. Mine is:\nDISALLOWED_USER_AGENTS = (\n re.compile(r'Java'),\n re.compile(r'gigamega'),\n re.compile(r'litefinder'),\n)\n\nSee the description in Django docs.\n", "\"Is there a way to turn this behavior off?\" - the 500 is absolutely mandatory. The log entry is also mandatory. \n\"Or perhaps just block the IP's doing this?\" - don't we wish.\nEveryone has this problem. Just about everyone uses Apache log rotation. Everyone else either uses an OS rotation or rolls their own.\n", "Django should be throwing a 404, not a 500, if the URL doesn't match any entries in your URLConf.\nhttp://docs.djangoproject.com/en/dev/topics/http/urls/#handler404\nYou need to provide a 404 template:\n\nIf you don't define your own 404 view -- and simply use the default, which is recommended -- you still have one obligation: To create a 404.html template in the root of your template directory. The default 404 view will use that template for all 404 errors.\n\n", "How about setting up a catch-all pattern as the last item in your urls file and directing it to a generic \"no such page\" or even your homepage? In other words, turn 500's into requests for your homepage.\n", "Why not fix those \"bugs\"? If a url pattern is not matched, then a proper error message should be shown. By adding those templates you will help the user and yourself :-)\n", "\nYes, it should be a 404, not a 500. 500 indicates something is trying to deal with the URL and is failing in the process. You need to find and fix that.\nWe have a similar problem. Since we are running Apache/mod_python, I chose to deal with it in .htaccess with mod_rewrite rules. I periodically look at the logs and add a few patterns to my \"go to hell\" list. These all rewrite to deliver a 1x1 pixel gif file. There is no tsunami of 404s to clutter up my log analysis and it puts minimal load on Django and Apache.\n\nYou can't make these a**holes go away, so all you can do is minimize their impact on your system and get on with your life.\n" ]
[ 7, 4, 3, 3, 0, 0, 0 ]
[ "A programming solution would be to :\n\nopen the log file\nread the lines in a buffer\nreplace the lines that match the errors the bots caused\nseek to the beginning of the file\nwrite the new buffer\ntruncate the file to current pointer position\nclose\n\nVoila ! It's done !\n" ]
[ -1 ]
[ "apache", "django", "python", "spam_prevention" ]
stackoverflow_0000315363_apache_django_python_spam_prevention.txt
Q: Python: converting strings for use with ctypes.c_void_p() given a string: msg="hello world" How can I define this as a ctypes.c_void_p() data type? the following code yields a "cannot be converted to pointer" exception: data=ctypes.c_void_p(msg) data is required to be a void* type in C, because it is being passed to a DLL. I'm assuming there is a way to pack/unpack the string using the struct package, but unfortunately I am very unfamiliar with this process. A: Something like this? Using ctypes.cast? >>> import ctypes >>> p1= ctypes.c_char_p("hi mom") >>> ctypes.cast( p1, ctypes.c_void_p ) c_void_p(11133300)
Python: converting strings for use with ctypes.c_void_p()
given a string: msg="hello world" How can I define this as a ctypes.c_void_p() data type? the following code yields a "cannot be converted to pointer" exception: data=ctypes.c_void_p(msg) data is required to be a void* type in C, because it is being passed to a DLL. I'm assuming there is a way to pack/unpack the string using the struct package, but unfortunately I am very unfamiliar with this process.
[ "Something like this? Using ctypes.cast?\n>>> import ctypes\n>>> p1= ctypes.c_char_p(\"hi mom\")\n>>> ctypes.cast( p1, ctypes.c_void_p )\nc_void_p(11133300)\n\n" ]
[ 12 ]
[]
[]
[ "ctypes", "dll", "python", "types" ]
stackoverflow_0000318067_ctypes_dll_python_types.txt
Q: Python as FastCGI under windows and apache I need to run a simple request/response python module under an existing system with windows/apache/FastCGI. All the FastCGI wrappers for python I tried work for Linux only (they use socket.fromfd() and other such shticks). Is there a wrapper that runs under windows? A: You might find it easier to ditch FastCGI altogether and just run a python webserver on a localhost port. Then just use mod_rewrite to map the apache urls to the internal webserver. (I started offering FastCGI at my hosting company and to my surprise, nearly everyone ditched it in favor of just running their own web server on the ports I provided them.) A: A Django bug suggests that python-fastcgi will work for you, and its PyPI page reports that it works on Windows. A: I'd suggest mod_python or mod_wsgi.
Python as FastCGI under windows and apache
I need to run a simple request/response python module under an existing system with windows/apache/FastCGI. All the FastCGI wrappers for python I tried work for Linux only (they use socket.fromfd() and other such shticks). Is there a wrapper that runs under windows?
[ "You might find it easier to ditch FastCGI altogether and just run a python webserver on a localhost port. Then just use mod_rewrite to map the apache urls to the internal webserver.\n(I started offering FastCGI at my hosting company and to my surprise, nearly everyone ditched it in favor of just running their own web server on the ports I provided them.)\n", "A Django bug suggests that python-fastcgi will work for you, and its PyPI page reports that it works on Windows.\n", "I'd suggest mod_python or mod_wsgi.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "apache", "fastcgi", "python", "windows" ]
stackoverflow_0000312928_apache_fastcgi_python_windows.txt
Q: Does anyone know where there is a recipe for serializing data and preserving its order in the output? I am working with a set of data that I have converted to a list of dictionaries For example one item in my list is {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'} Per request The second item in my list could be: {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2006', 'actionDate': u'C20070627', 'data': u'86,000', 'rowLabel': u'Sales of Bananas'} The third item could be: {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2005', 'actionDate': u'C20070627', 'data': u'116,000', 'rowLabel': u'Sales of Cherries'} The fourth item could be: {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2006', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Sales of Cherries'} The reason I need to pickle this is because I need to find out all of the ways the columns were labeled before I consolidate the results and put them into a database. The first and second items will be one row in the results, the third and fourth would be the next line in the results (after someone decides what the uniform column header label should be) I tested pickle and was able to save and retrieve my data. However, I need to be able to preserve the order in the output. One idea I have is to add another key that would be a counter so I could retrieve my data and then sort by the counter. Is there a better way? I don't want to put this into a database because it is not permanent. I marked an answer down below. It is not what I am getting, so I need to figure out if the problem is somewhere else in my code. A: So what's wrong with pickle? If you structure your data as a list of dicts, then everything should work as you want it to (if I understand your problem). >>> import pickle >>> d1 = {1:'one', 2:'two', 3:'three'} >>> d2 = {1:'eleven', 2:'twelve', 3:'thirteen'} >>> d3 = {1:'twenty-one', 2:'twenty-two', 3:'twenty-three'} >>> data = [d1, d2, d3] >>> out = open('data.pickle', 'wb') >>> pickle.dump(data, out) >>> out.close() >>> input = open('data.pickle') >>> data2 = pickle.load(input) >>> data == data2 True A: Python does not retain order in dictionaries. However, there is the OrderedDict class in the collections module. Another option would be to use a list of tuples: [('reportDate', u'R20080501'), ('idnum', u'1078099'), ...etc] You can use the built in dict() if you need to convert this to a dictionary later. A: The Python dict is an unordered container. If you need to preserve the order of the entries, you should consider using a list of 2-tuples. Another option would be to keep an extra, ordered list of the keys. This way you can benefit from the quick, keyed access offered by the dictionary, while still being able to iterate through its values in an ordered fashion: data = {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'} dataOrder = ['reportDate', 'idnum', 'columnLabel', 'actionDate', 'data', 'rowLabel'] for key in dataOrder: print key, data[key]
Does anyone know where there is a recipe for serializing data and preserving its order in the output?
I am working with a set of data that I have converted to a list of dictionaries For example one item in my list is {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'} Per request The second item in my list could be: {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2006', 'actionDate': u'C20070627', 'data': u'86,000', 'rowLabel': u'Sales of Bananas'} The third item could be: {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2005', 'actionDate': u'C20070627', 'data': u'116,000', 'rowLabel': u'Sales of Cherries'} The fourth item could be: {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2006', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Sales of Cherries'} The reason I need to pickle this is because I need to find out all of the ways the columns were labeled before I consolidate the results and put them into a database. The first and second items will be one row in the results, the third and fourth would be the next line in the results (after someone decides what the uniform column header label should be) I tested pickle and was able to save and retrieve my data. However, I need to be able to preserve the order in the output. One idea I have is to add another key that would be a counter so I could retrieve my data and then sort by the counter. Is there a better way? I don't want to put this into a database because it is not permanent. I marked an answer down below. It is not what I am getting, so I need to figure out if the problem is somewhere else in my code.
[ "So what's wrong with pickle? If you structure your data as a list of dicts, then everything should work as you want it to (if I understand your problem).\n>>> import pickle\n>>> d1 = {1:'one', 2:'two', 3:'three'}\n>>> d2 = {1:'eleven', 2:'twelve', 3:'thirteen'}\n>>> d3 = {1:'twenty-one', 2:'twenty-two', 3:'twenty-three'}\n>>> data = [d1, d2, d3]\n>>> out = open('data.pickle', 'wb')\n>>> pickle.dump(data, out)\n>>> out.close()\n>>> input = open('data.pickle') \n>>> data2 = pickle.load(input)\n>>> data == data2\nTrue\n\n", "Python does not retain order in dictionaries.\nHowever, there is the OrderedDict class in the collections module.\nAnother option would be to use a list of tuples:\n[('reportDate', u'R20080501'), ('idnum', u'1078099'), ...etc]\n\nYou can use the built in dict() if you need to convert this to a dictionary later.\n", "The Python dict is an unordered container. If you need to preserve the order of the entries, you should consider using a list of 2-tuples.\nAnother option would be to keep an extra, ordered list of the keys. This way you can benefit from the quick, keyed access offered by the dictionary, while still being able to iterate through its values in an ordered fashion:\ndata = {'reportDate': u'R20070501', 'idnum': u'1078099', \n 'columnLabel': u'2005', 'actionDate': u'C20070627', \n 'data': u'76,000', 'rowLabel': u'Sales of Bananas'}\ndataOrder = ['reportDate', 'idnum', 'columnLabel', \n 'actionDate', 'data', 'rowLabel']\n\nfor key in dataOrder:\n print key, data[key]\n\n" ]
[ 5, 1, 1 ]
[]
[]
[ "python", "serialization" ]
stackoverflow_0000318700_python_serialization.txt
Q: Adding a dimension to every element of a numpy.array I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words: >>> my_ar = numpy.array((0,5,10)) [0, 5, 10] >>> transformed = my_fun(my_ar) # In reality, my_fun() would do something more useful array([ [ 0, 0, 0], [ 5, 10, 15], [10, 20, 30]]) >>> transformed.shape (3, 3) I've tried: def my_fun_e(val): return numpy.array((val, val*2, val*3)) my_fun = numpy.frompyfunc(my_fun_e, 1, 3) but get: my_fun(my_ar) (array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object), array([None, None, None], dtype=object), array([None, None, None], dtype=object)) and I've tried: my_fun = numpy.frompyfunc(my_fun_e, 1, 1) but get: >>> my_fun(my_ar) array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object) This is close, but not quite right -- I get an array of objects, not an array of ints. Update 3! OK. I've realized that my example was too simple beforehand -- I don't just want to replicate my data in a third dimension, I'd like to transform it at the same time. Maybe this is clearer? A: Does numpy.dstack do what you want? The first two indexes are the same as the original array, and the new third index is "depth". >>> import numpy as N >>> a = N.array([[1,2,3],[4,5,6],[7,8,9]]) >>> a array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> b = N.dstack((a,a,a)) >>> b array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]], [[7, 7, 7], [8, 8, 8], [9, 9, 9]]]) >>> b[1,1] array([5, 5, 5]) A: Use map to apply your transformation function to each element in my_ar: import numpy my_ar = numpy.array((0,5,10)) print my_ar transformed = numpy.array(map(lambda x:numpy.array((x,x*2,x*3)), my_ar)) print transformed print transformed.shape A: I propose: numpy.resize(my_ar, (3,3)).transpose() You can of course adapt the shape (my_ar.shape[0],)*2 or whatever A: Does this do what you want: tile(my_ar, (1,1,3))
Adding a dimension to every element of a numpy.array
I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words: >>> my_ar = numpy.array((0,5,10)) [0, 5, 10] >>> transformed = my_fun(my_ar) # In reality, my_fun() would do something more useful array([ [ 0, 0, 0], [ 5, 10, 15], [10, 20, 30]]) >>> transformed.shape (3, 3) I've tried: def my_fun_e(val): return numpy.array((val, val*2, val*3)) my_fun = numpy.frompyfunc(my_fun_e, 1, 3) but get: my_fun(my_ar) (array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object), array([None, None, None], dtype=object), array([None, None, None], dtype=object)) and I've tried: my_fun = numpy.frompyfunc(my_fun_e, 1, 1) but get: >>> my_fun(my_ar) array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object) This is close, but not quite right -- I get an array of objects, not an array of ints. Update 3! OK. I've realized that my example was too simple beforehand -- I don't just want to replicate my data in a third dimension, I'd like to transform it at the same time. Maybe this is clearer?
[ "Does numpy.dstack do what you want? The first two indexes are the same as the original array, and the new third index is \"depth\".\n>>> import numpy as N\n>>> a = N.array([[1,2,3],[4,5,6],[7,8,9]])\n>>> a\narray([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n>>> b = N.dstack((a,a,a))\n>>> b\narray([[[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]],\n\n [[4, 4, 4],\n [5, 5, 5],\n [6, 6, 6]],\n\n [[7, 7, 7],\n [8, 8, 8],\n [9, 9, 9]]])\n>>> b[1,1]\narray([5, 5, 5])\n\n", "Use map to apply your transformation function to each element in my_ar:\nimport numpy\n\nmy_ar = numpy.array((0,5,10))\nprint my_ar\n\ntransformed = numpy.array(map(lambda x:numpy.array((x,x*2,x*3)), my_ar))\nprint transformed\n\nprint transformed.shape\n\n", "I propose:\n numpy.resize(my_ar, (3,3)).transpose()\n\nYou can of course adapt the shape (my_ar.shape[0],)*2 or whatever\n", "Does this do what you want:\ntile(my_ar, (1,1,3))\n\n" ]
[ 7, 2, 1, 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0000310459_arrays_numpy_python.txt
Q: Problem with relative path in Python I know this is a simple, beginner-ish Python question, but I'm having trouble opening a file using a relative path. This behavior seems odd to me (coming from a non-Python background): import os, sys titles_path = os.path.normpath("../downloads/movie_titles.txt") print "Current working directory is {0}".format(os.getcwd()) print "Titles path is {0}, exists? {1}".format(movie_titles_path, os.path.exists(movie_titles_path)) titlesFile = open(movie_titles_path, 'r') print titlesFile This results in: C:\Users\Matt\Downloads\blah>testscript.py Current working directory is C:\Users\Matt\Downloads\blah Titles path is ..\downloads\movie_titles.txt, exists? False Traceback (most recent call last): File "C:\Users\Matt\Downloads\blah\testscript.py", line 27, in <module> titlesFile = open(titles_path, 'r') IOError: [Errno 2] No such file or directory: '..\\downloads\\movie_titles.txt' However, a dir command shows this file at the relative path exists: C:\Users\Matt\Downloads\blah>dir /b ..\downloads\movie_titles.txt movie_titles.txt What's going on with how Python interprets relative paths on Windows? What is the correct way to open a file with a relative path? Also, if I wrap my path in os.path.abspath(), then I get this output: Current working directory is C:\Users\Matt\Downloads\blah Titles path is C:\Users\Matt\Downloads\downloads\movie_titles.txt, exists? False Traceback (most recent call last): File "C:\Users\Matt\Downloads\blah\testscript.py", line 27, in <module> titlesFile = open(titles_path, 'r') IOError: [Errno 2] No such file or directory: 'C:\\Users\\Matt\\Downloads\\downloads\\movie_titles.txt' In this case, seems like the open() command is automatically escaping the \ characters. **Embarrassing final update: Looks like I munged a character in the pathanme :) The correct way to do this on Windows seems to be to use os.path.normpath(), as I did originally. A: normpath only returns a normalized version of that particular path. It does not actually do the work of resolving the path for you. You might want to do os.path.abspath(yourpath). Also, I'm assuming you're on IronPython. Otherwise, the standard way of expressing that string format would be: "Current working directory is %s" % os.getcwd() "Titles path is %s, exists? %s" % (movie_titles_path, os.path.exists(movie_titles_path)) (Sorry, this is only an answer to the halfway posted question. I'm puzzled about the full solution.)
Problem with relative path in Python
I know this is a simple, beginner-ish Python question, but I'm having trouble opening a file using a relative path. This behavior seems odd to me (coming from a non-Python background): import os, sys titles_path = os.path.normpath("../downloads/movie_titles.txt") print "Current working directory is {0}".format(os.getcwd()) print "Titles path is {0}, exists? {1}".format(movie_titles_path, os.path.exists(movie_titles_path)) titlesFile = open(movie_titles_path, 'r') print titlesFile This results in: C:\Users\Matt\Downloads\blah>testscript.py Current working directory is C:\Users\Matt\Downloads\blah Titles path is ..\downloads\movie_titles.txt, exists? False Traceback (most recent call last): File "C:\Users\Matt\Downloads\blah\testscript.py", line 27, in <module> titlesFile = open(titles_path, 'r') IOError: [Errno 2] No such file or directory: '..\\downloads\\movie_titles.txt' However, a dir command shows this file at the relative path exists: C:\Users\Matt\Downloads\blah>dir /b ..\downloads\movie_titles.txt movie_titles.txt What's going on with how Python interprets relative paths on Windows? What is the correct way to open a file with a relative path? Also, if I wrap my path in os.path.abspath(), then I get this output: Current working directory is C:\Users\Matt\Downloads\blah Titles path is C:\Users\Matt\Downloads\downloads\movie_titles.txt, exists? False Traceback (most recent call last): File "C:\Users\Matt\Downloads\blah\testscript.py", line 27, in <module> titlesFile = open(titles_path, 'r') IOError: [Errno 2] No such file or directory: 'C:\\Users\\Matt\\Downloads\\downloads\\movie_titles.txt' In this case, seems like the open() command is automatically escaping the \ characters. **Embarrassing final update: Looks like I munged a character in the pathanme :) The correct way to do this on Windows seems to be to use os.path.normpath(), as I did originally.
[ "normpath only returns a normalized version of that particular path. It does not actually do the work of resolving the path for you. You might want to do os.path.abspath(yourpath).\nAlso, I'm assuming you're on IronPython. Otherwise, the standard way of expressing that string format would be:\n\"Current working directory is %s\" % os.getcwd()\n\"Titles path is %s, exists? %s\" % (movie_titles_path, os.path.exists(movie_titles_path))\n\n(Sorry, this is only an answer to the halfway posted question. I'm puzzled about the full solution.)\n" ]
[ 3 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0000319037_python_windows.txt
Q: Standard C or Python libraries to compute standard deviation of normal distribution Say we have normal distribution n(x): mean=0 and \int_{-a}^{a} n(x) = P. What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that task? A: If X is normal with mean 0 and standard deviation sigma, it must hold P = Prob[ -a <= X <= a ] = Prob[ -a/sigma <= N <= a/sigma ] = 2 Prob[ 0 <= N <= a/sigma ] = 2 ( Prob[ N <= a/sigma ] - 1/2 ) where N is normal with mean 0 and standard deviation 1. Hence P/2 + 1/2 = Prob[ N <= a/sigma ] = Phi(a/sigma) Where Phi is the cumulative distribution function (cdf) of a normal variable with mean 0 and stddev 1. Now we need the inverse normal cdf (or the "percent point function"), which in Python is scipy.stats.norm.ppf(). Sample code: from scipy.stats import norm P = 0.3456 a = 3.0 a_sigma = float(norm.ppf(P/2 + 0.5)) # a/sigma sigma = a/a_sigma # Here is the standard deviation For example, we know that the probability of a N(0,1) variable falling int the interval [-1.1] is ~ 0.682 (the dark blue area in this figure). If you set P = 0.682 and a = 1.0 you obtain sigma ~ 1.0, which is indeed the standard deviation. A: The standard deviation of a mean-zero gaussian distribution with Pr(-a < X < a) = P is a/(sqrt(2)*inverseErf(P)) which is the expression you're looking for, where inverseErf is the inverse of the error function (commonly known as erf). For C, the Gnu Scientific Library (GSL) is a good resource. However it only has erf, not inverseErf, so you'd have to invert it yourself (a simple binary search would do the trick). Alternatively, here's a nice way to approximate erf and inverseErf: http://homepages.physik.uni-muenchen.de/~Winitzki/erf-approx.pdf For Python, inverseErf is available as erfinv in the SciPy library, so the following gives the standard deviation: a/(math.sqrt(2)*erfinv(P)) PS: There's some kind of bug in Stackoverflow's URL rendering and it wouldn't let me link to GSL above: http://www.gnu.org/software/gsl. It also renders wrong when I make the URL above with a pdf a proper link. A: SciPy has a stats sub-package. A: Take a look at the sciPy Project, it should have what you need.
Standard C or Python libraries to compute standard deviation of normal distribution
Say we have normal distribution n(x): mean=0 and \int_{-a}^{a} n(x) = P. What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that task?
[ "If X is normal with mean 0 and standard deviation sigma, it must hold \nP = Prob[ -a <= X <= a ] = Prob[ -a/sigma <= N <= a/sigma ]\n = 2 Prob[ 0 <= N <= a/sigma ]\n = 2 ( Prob[ N <= a/sigma ] - 1/2 )\n\nwhere N is normal with mean 0 and standard deviation 1. Hence\nP/2 + 1/2 = Prob[ N <= a/sigma ] = Phi(a/sigma)\n\nWhere Phi is the cumulative distribution function (cdf) of a normal variable with mean 0 and stddev 1. Now we need the inverse normal cdf (or the \"percent point function\"), which in Python is scipy.stats.norm.ppf(). Sample code:\nfrom scipy.stats import norm\nP = 0.3456\na = 3.0\n\na_sigma = float(norm.ppf(P/2 + 0.5)) # a/sigma\nsigma = a/a_sigma # Here is the standard deviation\n\nFor example, we know that the probability of a N(0,1) variable falling int the interval [-1.1] is ~ 0.682 (the dark blue area in this figure). If you set P = 0.682 and a = 1.0 you obtain sigma ~ 1.0, which is indeed the standard deviation. \n", "The standard deviation of a mean-zero gaussian distribution with Pr(-a < X < a) = P is\na/(sqrt(2)*inverseErf(P))\n\nwhich is the expression you're looking for, where inverseErf is the inverse of the error function (commonly known as erf).\nFor C, the Gnu Scientific Library (GSL) is a good resource. However it only has erf, not inverseErf, so you'd have to invert it yourself (a simple binary search would do the trick). Alternatively, here's a nice way to approximate erf and inverseErf: \nhttp://homepages.physik.uni-muenchen.de/~Winitzki/erf-approx.pdf\nFor Python, inverseErf is available as erfinv in the SciPy library, so the following gives the standard deviation:\na/(math.sqrt(2)*erfinv(P))\n\nPS: There's some kind of bug in Stackoverflow's URL rendering and it wouldn't let me link to GSL above: http://www.gnu.org/software/gsl.\nIt also renders wrong when I make the URL above with a pdf a proper link.\n", "SciPy has a stats sub-package.\n", "Take a look at the sciPy Project, it should have what you need.\n" ]
[ 7, 6, 3, 1 ]
[]
[]
[ "algorithm", "c", "math", "probability", "python" ]
stackoverflow_0000317963_algorithm_c_math_probability_python.txt
Q: How do you iterate over a tree? What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster? def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) Here is some test data. The first one is recursive, the second uses the generator: s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s Results: 0.416000127792 0.298999786377 Test code: import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth <= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s A: Unless your tree is really large or you have really high (real) requirements for speed, I would choose the recursive method. Easier to read, easier to code. A: Recursive function calls are not incredibly inefficient, that is an old programming myth. (If they're badly implemented, they may incur a larger overhead than necessary, but calling them "incredibly inefficient" is plain wrong.) Remember: don't optimize prematurely, and never optimize without benchmarking first. A: I can't think of any big algorithmic improvements, but a simple microoptimisation you can make is to bind frequently called methods (such as stack.append / stack.pop) to locals (this saves a dictionary lookup) def children(self): stack = [self.entities] push = stack.append pop = stack.pop while stack: for e in pop(): yield e if e.entities: push(e.entities) This gives a small (~15%) speedup by my tests (using 100 traversals of an 8-deep tree with 4 children at each node gives me the below timings:) children : 5.53942348004 children_bind: 4.77636131253 Not huge, but worth doing if speed is important. A: I'm not sure if you can reduce the overhead much on a full in-order traversal of a tree, if you use recursion the call stack will grow some, otherwise you must manually use a stack to push references of the children while visiting each node. Which way is fastest and uses less memory, depends on the expensiveness of the call stack vs. a normal stack. (I would guess the callstack is faster since it should be optimized for its use, and recursion is much easier to implement) If you don't care about the order you visit the nodes, some implementations of trees is actually stored in a dynamic array or linked list or stack wich you can traverse linearly if you don't care about the order it's traversed. But why is it important to have a fast traversal anyway? Trees are good for searching, arrays/linked lists is good for full traversal. If you often need full in-order traversal but few searches and insertions/deletions, an ordered linked list might be best, if searching is what you do most you use a tree. If the data is really massive, so that memory overhead may render recursion impossible, you should use a database. A: If you have a lot of RAM and the tree doesn't change often, you can cache the result of the call: def children(self): if self._children_cache is not None: return self._children_cache # Put your code into collectChildren() self._children_cache = self.collectChildren() return self._children_cache Whenever the tree changes, set the cache to None. In this case, using recursive calls might be more effective since the results will accumulate faster. A: I've written iterative tree-traversal code in the past: it's very ugly, and not fast, unless you know exactly how many children not only each subtree will have, but how many levels there are. A: I don't know too much about Python internals of function calls, but I really can't imagine that your code snippet is faster than recursively traversing the tree. The call stack (used for function calls, including recursive ones) is typically very fast. Going to the next object will only cost you a single function call. But in your snippet - where you use a stack object, going to the next object will cost you a stack.append (possibly allocating memory on heap), a stack.push (possibly freeing memory from heap), and a yield. The main problem with recursive calls is that you might blow the stack if your tree gets too deep. This isn't likely to happen. A: Here's a pair of small corrections. def children(self): stack = [self.entities] for e in stack: yield e if e.entities: stack.extend(e.entities) I actually think the generator, using append, isn't visiting all the nodes. I think you mean to extend the stack with all entities, not append a simple list of entities to the stack. Also, when the for loop terminates, the while loop in your original example will also terminate because there's no change to the empty stack after the for loop.
How do you iterate over a tree?
What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster? def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) Here is some test data. The first one is recursive, the second uses the generator: s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s Results: 0.416000127792 0.298999786377 Test code: import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth <= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s
[ "Unless your tree is really large or you have really high (real) requirements for speed, I would choose the recursive method. Easier to read, easier to code.\n", "Recursive function calls are not incredibly inefficient, that is an old programming myth. (If they're badly implemented, they may incur a larger overhead than necessary, but calling them \"incredibly inefficient\" is plain wrong.)\nRemember: don't optimize prematurely, and never optimize without benchmarking first.\n", "I can't think of any big algorithmic improvements, but a simple microoptimisation you can make is to bind frequently called methods (such as stack.append / stack.pop) to locals (this saves a dictionary lookup)\ndef children(self):\n stack = [self.entities]\n push = stack.append\n pop = stack.pop\n while stack: \n for e in pop():\n yield e\n if e.entities:\n push(e.entities)\n\nThis gives a small (~15%) speedup by my tests (using 100 traversals of an 8-deep tree with 4 children at each node gives me the below timings:)\nchildren : 5.53942348004\nchildren_bind: 4.77636131253\n\nNot huge, but worth doing if speed is important.\n", "I'm not sure if you can reduce the overhead much on a full in-order traversal of a tree, if you use recursion the call stack will grow some, otherwise you must manually use a stack to push references of the children while visiting each node. Which way is fastest and uses less memory, depends on the expensiveness of the call stack vs. a normal stack. (I would guess the callstack is faster since it should be optimized for its use, and recursion is much easier to implement)\nIf you don't care about the order you visit the nodes, some implementations of trees is actually stored in a dynamic array or linked list or stack wich you can traverse linearly if you don't care about the order it's traversed.\nBut why is it important to have a fast traversal anyway? Trees are good for searching, arrays/linked lists is good for full traversal. If you often need full in-order traversal but few searches and insertions/deletions, an ordered linked list might be best, if searching is what you do most you use a tree. If the data is really massive, so that memory overhead may render recursion impossible, you should use a database.\n", "If you have a lot of RAM and the tree doesn't change often, you can cache the result of the call:\ndef children(self):\n if self._children_cache is not None:\n return self._children_cache\n # Put your code into collectChildren()\n self._children_cache = self.collectChildren()\n return self._children_cache\n\nWhenever the tree changes, set the cache to None. In this case, using recursive calls might be more effective since the results will accumulate faster.\n", "I've written iterative tree-traversal code in the past: it's very ugly, and not fast, unless you know exactly how many children not only each subtree will have, but how many levels there are.\n", "I don't know too much about Python internals of function calls, but I really can't imagine that your code snippet is faster than recursively traversing the tree.\nThe call stack (used for function calls, including recursive ones) is typically very fast. Going to the next object will only cost you a single function call. But in your snippet - where you use a stack object, going to the next object will cost you a stack.append (possibly allocating memory on heap), a stack.push (possibly freeing memory from heap), and a yield.\nThe main problem with recursive calls is that you might blow the stack if your tree gets too deep. This isn't likely to happen.\n", "Here's a pair of small corrections.\ndef children(self):\n stack = [self.entities]\n for e in stack:\n yield e\n if e.entities:\n stack.extend(e.entities)\n\nI actually think the generator, using append, isn't visiting all the nodes. I think you mean to extend the stack with all entities, not append a simple list of entities to the stack.\nAlso, when the for loop terminates, the while loop in your original example will also terminate because there's no change to the empty stack after the for loop.\n" ]
[ 5, 5, 5, 4, 3, 1, 0, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0000320052_algorithm_python.txt
Q: Python type-error issue I'm writing a simple program to help generate orders for a game I'm a member of. It falls into the catergory of programmes I don't actually need. But now I've started I want it to work. It all pretty much runs smoothly but I can't figure out how to stop a type-error ocurring about half way through. Here's the code; status = 1 print "[b][u]magic[/u][/b]" while status == 1: print " " print "would you like to:" print " " print "1) add another spell" print "2) end" print " " choice = input("Choose your option: ") print " " if choice == 1: name = raw_input("What is the spell called?") level = raw_input("What level of the spell are you trying to research?") print "What tier is the spell: " print " " print "1) low" print "2) mid" print "3) high" print " " tier = input("Choose your option: ") if tier == 1: materials = 1 + (level * 1) rp = 10 + (level * 5) elif tier == 2: materials = 2 + (level * 1.5) rp = 10 + (level * 15) elif tier == 3: materials = 5 + (level * 2) rp = 60 + (level * 40) print "research ", name, "to level ", level, "--- material cost = ", materials, "and research point cost =", rp elif choice == 2: status = 0 Can anyone help? edit The error I get is; Traceback (most recent call last): File "C:\Users\Mike\Documents\python\magic orders", line 27, in <module> materials = 1 + (level * 1) TypeError: unsupported operand type(s) for +: 'int' and 'str' A: A stacktrace would've helped, but presumably the error is: materials = 1 + (level * 1) ‘level’ is a string, and you can't do arithmetic on strings. Python is a dynamically-typed language, but not a weakly-typed one. level= raw_input('blah') try: level= int(level) except ValueError: # user put something non-numeric in, tell them off In other parts of the program you are using input(), which will evaluate the entered string as Python, so for “1” will give you the number 1. But! This is super-dangerous — imagine what happens if the user types “os.remove(filename)” instead of a number. Unless the user is only you and you don't care, never use input(). It will be going away in Python 3.0 (raw_input's behaviour will be renamed input).
Python type-error issue
I'm writing a simple program to help generate orders for a game I'm a member of. It falls into the catergory of programmes I don't actually need. But now I've started I want it to work. It all pretty much runs smoothly but I can't figure out how to stop a type-error ocurring about half way through. Here's the code; status = 1 print "[b][u]magic[/u][/b]" while status == 1: print " " print "would you like to:" print " " print "1) add another spell" print "2) end" print " " choice = input("Choose your option: ") print " " if choice == 1: name = raw_input("What is the spell called?") level = raw_input("What level of the spell are you trying to research?") print "What tier is the spell: " print " " print "1) low" print "2) mid" print "3) high" print " " tier = input("Choose your option: ") if tier == 1: materials = 1 + (level * 1) rp = 10 + (level * 5) elif tier == 2: materials = 2 + (level * 1.5) rp = 10 + (level * 15) elif tier == 3: materials = 5 + (level * 2) rp = 60 + (level * 40) print "research ", name, "to level ", level, "--- material cost = ", materials, "and research point cost =", rp elif choice == 2: status = 0 Can anyone help? edit The error I get is; Traceback (most recent call last): File "C:\Users\Mike\Documents\python\magic orders", line 27, in <module> materials = 1 + (level * 1) TypeError: unsupported operand type(s) for +: 'int' and 'str'
[ "A stacktrace would've helped, but presumably the error is:\nmaterials = 1 + (level * 1)\n\n‘level’ is a string, and you can't do arithmetic on strings. Python is a dynamically-typed language, but not a weakly-typed one.\nlevel= raw_input('blah')\ntry:\n level= int(level)\nexcept ValueError:\n # user put something non-numeric in, tell them off\n\nIn other parts of the program you are using input(), which will evaluate the entered string as Python, so for “1” will give you the number 1.\nBut! This is super-dangerous — imagine what happens if the user types “os.remove(filename)” instead of a number. Unless the user is only you and you don't care, never use input(). It will be going away in Python 3.0 (raw_input's behaviour will be renamed input).\n" ]
[ 13 ]
[]
[]
[ "python", "typeerror" ]
stackoverflow_0000320827_python_typeerror.txt
Q: python - check at the end of the loop if need to run again It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like; "loop again? y/n" A: while True: func() answer = raw_input( "Loop again? " ) if answer != 'y': break A: keepLooping = True while keepLooping: # do stuff here # Prompt the user to continue q = raw_input("Keep looping? [yn]: ") if not q.startswith("y"): keepLooping = False A: There are two usual approaches, both already mentioned, which amount to: while True: do_stuff() # and eventually... break; # break out of the loop or x = True while x: do_stuff() # and eventually... x = False # set x to False to break the loop Both will work properly. From a "sound design" perspective it's best to use the second method because 1) break can have counterintuitive behavior in nested scopes in some languages; 2) the first approach is counter to the intended use of "while"; 3) your routines should always have a single point of exit A: While raw_input("loop again? y/n ") != 'n': do_stuff()
python - check at the end of the loop if need to run again
It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like; "loop again? y/n"
[ "while True:\n func()\n answer = raw_input( \"Loop again? \" )\n if answer != 'y':\n break\n\n", "keepLooping = True\nwhile keepLooping:\n # do stuff here\n\n # Prompt the user to continue\n q = raw_input(\"Keep looping? [yn]: \")\n if not q.startswith(\"y\"):\n keepLooping = False\n\n", "There are two usual approaches, both already mentioned, which amount to:\nwhile True:\n do_stuff() # and eventually...\n break; # break out of the loop\n\nor\nx = True\nwhile x:\n do_stuff() # and eventually...\n x = False # set x to False to break the loop\n\nBoth will work properly. From a \"sound design\" perspective it's best to use the second method because 1) break can have counterintuitive behavior in nested scopes in some languages; 2) the first approach is counter to the intended use of \"while\"; 3) your routines should always have a single point of exit\n", "While raw_input(\"loop again? y/n \") != 'n':\n do_stuff()\n\n" ]
[ 14, 6, 5, 1 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0000273612_loops_python.txt
Q: How do I skip processing the attachments of an email which is an attachment of a different email using jython I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file. I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments. What I want to do is skip that attached email and all its attachments. using python/jythons std email lib how can i do this? to make it clearer I need to parse an email (named ROOT email), I want to get the attachments from this email using jython. Next certain attachments are supported ie .pdf .doc etc now it just so happens that, the clients send an email (ROOT email) with another email message (CHILD email) as an attachment, and in CHILD email it has .pdf attachments and such like. What I need is: to get rid of any CHILD emails attached to the ROOT email AND the CHILD emails attachments. What happens is I walk over the whole email and it just parses every attachment, BOTH ROOT attachments and CHILD attachments as if they were ROOT attachments. I cannot have this. I am only interested in ROOT attachements that are legal ie .pdf .doc. xls .rtf .tif .tiff That should do for now, I have to run to catch a bus! thanks! A: The problem with existing suggestions is the walk method. This recursively, depth-first, walks the entire tree, including children. Look at the source of the walk method, and adapt it to skip the recursive part. A cursory reading suggests: if msg.is_multipart(): for part in msg.get_payload(): """ Process message, but do not recurse """ filename = part.get_filename() Reading the pydocs, get_payload should return a list of the top level messages, without recursing. A: What about the example named "Here’s an example of how to unpack a MIME message like the one above, into a directory of files"? It looks close from what you want. import email ... msg = email.message_from_file(fp) ... for part in msg.walk(): # multipart/* are just containers if part.get_content_maintype() == 'multipart': continue # Applications should really sanitize the given filename so that an # email message can't be used to overwrite important files filename = part.get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) ... A: Have you tried the get_payload( [i[, decode]]) method? Unlike walk it is not documented to recursively open attachments. A: I'm understanding your questions to mean "I have to check all attachments of an email, but if an attachment is also an email, I want to ignore it." Either way this answer should lead you down the right path. What I think you want is mimetypes.guess_type(). Using this method is also much better than just checking against a list of exentions. def check(self, msg): import mimetypes for part in msg.walk(): if part.get_filename() is not None: filenames = [n for n in part.getaltnames() if n] for filename in filenames: type, enc = mimetypes.guess_type(filename) if type.startswith('message'): print "This is an email and I want to ignore it." else: print "I want to keep looking at this file." Note that if this still looks through attached emails, change it to this: def check(self, msg): import mimetypes for part in msg.walk(): filename = part.get_filename() if filename is not None: type, enc = mimetypes.guess_type(filename) if type.startswith('message'): print "This is an email and I want to ignore it." else: part_filenames = [n for n in part.getaltnames() if n] for part_filename in part_filenames: print "I want to keep looking at this file." MIME types documentation
How do I skip processing the attachments of an email which is an attachment of a different email
using jython I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file. I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments. What I want to do is skip that attached email and all its attachments. using python/jythons std email lib how can i do this? to make it clearer I need to parse an email (named ROOT email), I want to get the attachments from this email using jython. Next certain attachments are supported ie .pdf .doc etc now it just so happens that, the clients send an email (ROOT email) with another email message (CHILD email) as an attachment, and in CHILD email it has .pdf attachments and such like. What I need is: to get rid of any CHILD emails attached to the ROOT email AND the CHILD emails attachments. What happens is I walk over the whole email and it just parses every attachment, BOTH ROOT attachments and CHILD attachments as if they were ROOT attachments. I cannot have this. I am only interested in ROOT attachements that are legal ie .pdf .doc. xls .rtf .tif .tiff That should do for now, I have to run to catch a bus! thanks!
[ "The problem with existing suggestions is the walk method. This recursively, depth-first, walks the entire tree, including children.\nLook at the source of the walk method, and adapt it to skip the recursive part. A cursory reading suggests:\nif msg.is_multipart():\n for part in msg.get_payload():\n \"\"\" Process message, but do not recurse \"\"\"\n filename = part.get_filename()\n\nReading the pydocs, get_payload should return a list of the top level messages, without recursing.\n", "What about the example named \"Here’s an example of how to unpack a MIME message like the one above, into a directory of files\"? It looks close from what you want.\nimport email\n...\nmsg = email.message_from_file(fp)\n...\nfor part in msg.walk():\n # multipart/* are just containers\n if part.get_content_maintype() == 'multipart':\n continue\n # Applications should really sanitize the given filename so that an\n # email message can't be used to overwrite important files\n filename = part.get_filename()\n if not filename:\n ext = mimetypes.guess_extension(part.get_content_type())\n ...\n\n", "Have you tried the get_payload( [i[, decode]]) method? Unlike walk it is not documented to recursively open attachments.\n", "I'm understanding your questions to mean \"I have to check all attachments of an email, but if an attachment is also an email, I want to ignore it.\" Either way this answer should lead you down the right path.\nWhat I think you want is mimetypes.guess_type(). Using this method is also much better than just checking against a list of exentions.\ndef check(self, msg):\n import mimetypes\n\n for part in msg.walk():\n if part.get_filename() is not None:\n filenames = [n for n in part.getaltnames() if n]\n for filename in filenames:\n type, enc = mimetypes.guess_type(filename)\n if type.startswith('message'):\n print \"This is an email and I want to ignore it.\"\n else:\n print \"I want to keep looking at this file.\"\n\nNote that if this still looks through attached emails, change it to this:\ndef check(self, msg):\n import mimetypes\n\n for part in msg.walk():\n filename = part.get_filename()\n if filename is not None:\n type, enc = mimetypes.guess_type(filename)\n if type.startswith('message'):\n print \"This is an email and I want to ignore it.\"\n else:\n part_filenames = [n for n in part.getaltnames() if n]\n for part_filename in part_filenames:\n print \"I want to keep looking at this file.\"\n\nMIME types documentation\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "attachment", "email", "jython", "python" ]
stackoverflow_0000319896_attachment_email_jython_python.txt
Q: OpenCV's Python - OS X I get the following error while building OpenCV on OS X 10.5 (intel): ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture ld: warning in .libs/_cv_la-error.o, file is not of required architecture ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture ld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture ld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture ld: warning in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libcxcore.dylib, file is not of required architecture Undefined symbols for architecture i386: "_fputs$UNIX2003", referenced from: _PySwigObject_print in _cv_la-_cv.o _PySwigPacked_print in _cv_la-_cv.o _PySwigPacked_print in _cv_la-_cv.o ld: symbol(s) not found for architecture i386 collect2: ld returned 1 exit status lipo: can't open input file: /var/folders/Sr/Srq9N4R8Hr82xeFvW3o-uk+++TI/-Tmp-//cchT0WVX.out (No such file or directory) make[4]: *** [_cv.la] Error 1 make[3]: *** [all-recursive] Error 1 make[2]: *** [all-recursive] Error 1 make[1]: *** [all-recursive] Error 1 make: *** [all] Error 2 While running ./configure --without-python everything is ok. Another strange thing is that when I used Python 2.4.5 or 2.5.1 everything has built ok, the problem occured after switching to Python Framework 2.5.2 A: It seems a little weird that it is warning about different architectures when looking for /Developer/SDKs/MacOSX10.4u.sdk while linking - can you give us some more detail about your build environment (version of XCode, GCC, Python, $PATH etc) Alternatively, won't any of the OpenCV binaries available work for you? A: /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib is just a link to /usr/local/lib after deleting files that caused the warnings I'm getting : ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture ld: warning in .libs/_cv_la-error.o, file is not of required architecture ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture ld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture ld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture ld: warning in /Users/Pietras/opencv/cxcore/src/.libs/libcxcore.dylib, file is not of required architecture Undefined symbols for architecture i386: ... ` And these files are created by make. gcc: i686-apple-darwin9-gcc-4.0.1 $PATH: /Library/Frameworks/Python.framework/Versions/Current/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/sw/bin:/sw/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/AVRMacPack/bin:/usr/X11R6/bin XCode 3 (latest) Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) - MacPython from python.org (tried to downgrade and use it instead of 2.5.2, but that doesn't work anymore...) which python /Library/Frameworks/Python.framework/Versions/Current/bin/python I didn't find any Python OpenCV binaries for OS X. I've tried to make it while setting python2.4 or 2.5 from macports as default and it compiles and installs, but when I try to import there is a bus error or Fatal Python error Interpreter not initialized (version mismatch?) and it quits. A: Ok, I kind of worked it out It needs to be compiled with python from macports or whatever. Then I need to run /System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5 (this is my previous python version) and there OpenCV just works.
OpenCV's Python - OS X
I get the following error while building OpenCV on OS X 10.5 (intel): ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture ld: warning in .libs/_cv_la-error.o, file is not of required architecture ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture ld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture ld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture ld: warning in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libcxcore.dylib, file is not of required architecture Undefined symbols for architecture i386: "_fputs$UNIX2003", referenced from: _PySwigObject_print in _cv_la-_cv.o _PySwigPacked_print in _cv_la-_cv.o _PySwigPacked_print in _cv_la-_cv.o ld: symbol(s) not found for architecture i386 collect2: ld returned 1 exit status lipo: can't open input file: /var/folders/Sr/Srq9N4R8Hr82xeFvW3o-uk+++TI/-Tmp-//cchT0WVX.out (No such file or directory) make[4]: *** [_cv.la] Error 1 make[3]: *** [all-recursive] Error 1 make[2]: *** [all-recursive] Error 1 make[1]: *** [all-recursive] Error 1 make: *** [all] Error 2 While running ./configure --without-python everything is ok. Another strange thing is that when I used Python 2.4.5 or 2.5.1 everything has built ok, the problem occured after switching to Python Framework 2.5.2
[ "It seems a little weird that it is warning about different architectures when looking for /Developer/SDKs/MacOSX10.4u.sdk while linking - can you give us some more detail about your build environment (version of XCode, GCC, Python, $PATH etc)\nAlternatively, won't any of the OpenCV binaries available work for you?\n", "/Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib is just a link to /usr/local/lib\nafter deleting files that caused the warnings I'm getting :\nld: warning in .libs/_cv_la-_cv.o, file is not of required architecture\nld: warning in .libs/_cv_la-error.o, file is not of required architecture\nld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture\nld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture\nld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture\nld: warning in /Users/Pietras/opencv/cxcore/src/.libs/libcxcore.dylib, file is not of required architecture\nUndefined symbols for architecture i386: ... `\n\nAnd these files are created by make.\ngcc: i686-apple-darwin9-gcc-4.0.1\n$PATH:\n/Library/Frameworks/Python.framework/Versions/Current/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/sw/bin:/sw/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/AVRMacPack/bin:/usr/X11R6/bin\n\nXCode 3 (latest)\nPython 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) - MacPython from python.org\n(tried to downgrade and use it instead of 2.5.2, but that doesn't work anymore...)\nwhich python\n/Library/Frameworks/Python.framework/Versions/Current/bin/python\n\nI didn't find any Python OpenCV binaries for OS X.\nI've tried to make it while setting python2.4 or 2.5 from macports as default and it compiles and installs, but when I try to import there is a bus error or Fatal Python error Interpreter not initialized (version mismatch?)\n and it quits.\n", "Ok, I kind of worked it out\nIt needs to be compiled with python from macports or whatever. Then I need to run /System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5 (this is my previous python version) and there OpenCV just works.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "macos", "opencv", "python" ]
stackoverflow_0000315803_macos_opencv_python.txt
Q: python logging into a forum I've written this to try and log onto a forum (phpBB3). import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) output = page.read() However when I run it it comes up with; Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in <module> page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) TypeError: string indices must be integers any ideas as to how to solve this? edit adding a comma between the string and the data gives this error instead Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in <module> page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login",[logindata]) File "C:\Python25\lib\urllib.py", line 84, in urlopen return opener.open(url, data) File "C:\Python25\lib\urllib.py", line 192, in open return getattr(self, name)(url, data) File "C:\Python25\lib\urllib.py", line 327, in open_http h.send(data) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "<string>", line 1, in sendall TypeError: sendall() argument 1 must be string or read-only buffer, not list edit2 I've changed the code from what it was to; import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) output = page.read() This doesn't throw any error messages, it just gives 3 blank lines. Is this because I'm trying to read from the log in page which disappears after logging in. If so how do I get it to display the index which is what should appear after hitting log in. A: Your line page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) is semantically invalid Python. Presumably you meant page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login", [logindata]) which has a comma separating the arguments. However, what you ACTUALLY want is simply page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) without trying to enclose logindata into a list and using the more up-to-date version of urlopen is the urllib2 library. A: Your URL string shouldn't be "http://www.woarl.com/board/ucp.php?mode=login"[logindata] But "http://www.woarl.com/board/ucp.php?mode=login", logindata I think, because [] is for array and it require an integer. I might be wrong cause I haven't done a lot of Python. A: How about using a comma between the string,"http:..." and the urlencoded data, [logindata]? A: If you do a type on logindata, you can see that it is a string: >>> import urllib >>> logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) >>> type(logindata) <type 'str'> Putting it in brackets ([]) puts it in a list context, which isn't what you want.
python logging into a forum
I've written this to try and log onto a forum (phpBB3). import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) output = page.read() However when I run it it comes up with; Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in <module> page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) TypeError: string indices must be integers any ideas as to how to solve this? edit adding a comma between the string and the data gives this error instead Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in <module> page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login",[logindata]) File "C:\Python25\lib\urllib.py", line 84, in urlopen return opener.open(url, data) File "C:\Python25\lib\urllib.py", line 192, in open return getattr(self, name)(url, data) File "C:\Python25\lib\urllib.py", line 327, in open_http h.send(data) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "<string>", line 1, in sendall TypeError: sendall() argument 1 must be string or read-only buffer, not list edit2 I've changed the code from what it was to; import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) output = page.read() This doesn't throw any error messages, it just gives 3 blank lines. Is this because I'm trying to read from the log in page which disappears after logging in. If so how do I get it to display the index which is what should appear after hitting log in.
[ "Your line\npage = urllib.urlopen(\"http://www.woarl.com/board/ucp.php?mode=login\"[logindata])\n\nis semantically invalid Python. Presumably you meant\npage = urllib.urlopen(\"http://www.woarl.com/board/ucp.php?mode=login\", [logindata])\n\nwhich has a comma separating the arguments. However, what you ACTUALLY want is simply\npage = urllib2.urlopen(\"http://www.woarl.com/board/ucp.php?mode=login\", logindata)\n\nwithout trying to enclose logindata into a list and using the more up-to-date version of urlopen is the urllib2 library.\n", "Your URL string shouldn't be \n\"http://www.woarl.com/board/ucp.php?mode=login\"[logindata]\n\nBut\n \"http://www.woarl.com/board/ucp.php?mode=login\", logindata\n\nI think, because [] is for array and it require an integer. I might be wrong cause I haven't done a lot of Python.\n", "How about using a comma between the string,\"http:...\" and the urlencoded data, [logindata]?\n", "If you do a type on logindata, you can see that it is a string:\n>>> import urllib\n>>> logindata = urllib.urlencode({'username': 'x', 'password': 'y'})\n>>> type(logindata)\n<type 'str'>\n\nPutting it in brackets ([]) puts it in a list context, which isn't what you want.\n" ]
[ 5, 1, 1, 1 ]
[ "This would be easier with the high-level \"mechanize\" module.\n" ]
[ -1 ]
[ "authentication", "phpbb3", "python", "typeerror" ]
stackoverflow_0000321304_authentication_phpbb3_python_typeerror.txt
Q: urllib2 data sending I've recently written this with help from SO. Now could someone please tell me how to make it actually log onto the board. It brings up everything just in a non logged in format. import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/index.php", logindata) pagesource = page.read() print pagesource A: Someone recently asked the same question you're asking. If you read through the answers to that question you'll see code examples showing you how to stay logged in while browsing a site in a Python script using only stuff in the standard library. The accepted answer might not be as useful to you as this other answer, since the accepted answer deals with a specific problem involving redirection. However, I recommend reading through all of the answers regardless. A: You probably want to look into preserving cookies from the server. Pycurl or Mechanize will make this much easier for you A: If actually look at the page, you see that the login link takes you to http://www.woarl.com/board/ucp.php?mode=login That page has the login form and submits to http://www.woarl.com/board/ucp.php?mode=login again with POST. You'll then have to extract the cookies that are probably set, and put those in a CookieJar or similar. A: You probably want to create an opener with these handlers and apply it to urllib2. With these applied your cookies are handled and you'll be redirected, if server decides it wants you somewhere else. # Create handlers cookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling redirectionHandler = urllib2.HTTPRedirectHandler() # needed for redirection (not needed for javascript redirect?) # Create opener opener = urllib2.build_opener(cookieHandler,redirectionHandler) # Install the opener urllib2.install_opener(opener)
urllib2 data sending
I've recently written this with help from SO. Now could someone please tell me how to make it actually log onto the board. It brings up everything just in a non logged in format. import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/index.php", logindata) pagesource = page.read() print pagesource
[ "Someone recently asked the same question you're asking. If you read through the answers to that question you'll see code examples showing you how to stay logged in while browsing a site in a Python script using only stuff in the standard library.\nThe accepted answer might not be as useful to you as this other answer, since the accepted answer deals with a specific problem involving redirection. However, I recommend reading through all of the answers regardless.\n", "You probably want to look into preserving cookies from the server.\nPycurl or Mechanize will make this much easier for you\n", "If actually look at the page, you see that the login link takes you to http://www.woarl.com/board/ucp.php?mode=login\nThat page has the login form and submits to http://www.woarl.com/board/ucp.php?mode=login again with POST.\nYou'll then have to extract the cookies that are probably set, and put those in a CookieJar or similar.\n", "You probably want to create an opener with these handlers and apply it to urllib2.\nWith these applied your cookies are handled and you'll be redirected, if server decides it wants you somewhere else.\n# Create handlers\ncookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling\nredirectionHandler = urllib2.HTTPRedirectHandler() # needed for redirection (not needed for javascript redirect?)\n\n# Create opener\nopener = urllib2.build_opener(cookieHandler,redirectionHandler)\n\n# Install the opener\nurllib2.install_opener(opener)\n\n" ]
[ 5, 3, 1, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0000321582_python_urllib2.txt
Q: split twice in the same expression? Imagine I have the following: inFile = "/adda/adas/sdas/hello.txt" # that instruction give me hello.txt Name = inFile.name.split("/") [-1] # that one give me the name I want - just hello Name1 = Name.split(".") [0] Is there any chance to simplify that doing the same job in just one expression? A: You can get what you want platform independently by using os.path.basename to get the last part of a path and then use os.path.splitext to get the filename without extension. from os.path import basename, splitext pathname = "/adda/adas/sdas/hello.txt" name, extension = splitext(basename(pathname)) print name # --> "hello" Using os.path.basename and os.path.splitext instead of str.split, or re.split is more proper (and therefore received more points then any other answer) because it does not break down on other platforms that use different path separators (you would be surprised how varried this can be). It also carries most points because it answers your question for "one line" precisely and is aesthetically more pleasing then your example (even though that is debatable as are all questions of taste) A: Answering the question in the topic rather than trying to analyze the example... You really want to use Florians solution if you want to split paths, but if you promise not to use this for path parsing... You can use re.split() to split using several separators by or:ing them with a '|', have a look at this: import re inFile = "/adda/adas/sdas/hello.txt" print re.split('\.|/', inFile)[-2] A: >>> inFile = "/adda/adas/sdas/hello.txt" >>> inFile.split('/')[-1] 'hello.txt' >>> inFile.split('/')[-1].split('.')[0] 'hello' A: if it is always going to be a path like the above you can use os.path.split and os.path.splitext The following example will print just the hello from os.path import split, splitext path = "/adda/adas/sdas/hello.txt" print splitext(split(path)[1])[0] For more info see https://docs.python.org/library/os.path.html A: I'm pretty sure some Regex-Ninja*, would give you a more or less sane way to do that (or as I now see others have posted: ways to write two expressions on one line...) But I'm wondering why you want to do split it with just one expression? For such a simple split, it's probably faster to do two than to create some advanced either-or logic. If you split twice it's safer too: I guess you want to separate the path, the file name and the file extension, if you split on '/' first you know the filename should be in the last array index, then you can try to split just the last index to see if you can find the file extension or not. Then you don't need to care if ther is dots in the path names. *(Any sane users of regular expressions, should not be offended. ;)
split twice in the same expression?
Imagine I have the following: inFile = "/adda/adas/sdas/hello.txt" # that instruction give me hello.txt Name = inFile.name.split("/") [-1] # that one give me the name I want - just hello Name1 = Name.split(".") [0] Is there any chance to simplify that doing the same job in just one expression?
[ "You can get what you want platform independently by using os.path.basename to get the last part of a path and then use os.path.splitext to get the filename without extension.\nfrom os.path import basename, splitext\n\npathname = \"/adda/adas/sdas/hello.txt\"\nname, extension = splitext(basename(pathname))\nprint name # --> \"hello\"\n\nUsing os.path.basename and os.path.splitext instead of str.split, or re.split is more proper (and therefore received more points then any other answer) because it does not break down on other platforms that use different path separators (you would be surprised how varried this can be).\nIt also carries most points because it answers your question for \"one line\" precisely and is aesthetically more pleasing then your example (even though that is debatable as are all questions of taste) \n", "Answering the question in the topic rather than trying to analyze the example...\nYou really want to use Florians solution if you want to split paths, but if you promise not to use this for path parsing...\nYou can use re.split() to split using several separators by or:ing them with a '|', have a look at this:\nimport re\ninFile = \"/adda/adas/sdas/hello.txt\"\nprint re.split('\\.|/', inFile)[-2]\n\n", ">>> inFile = \"/adda/adas/sdas/hello.txt\"\n>>> inFile.split('/')[-1]\n'hello.txt'\n>>> inFile.split('/')[-1].split('.')[0]\n'hello'\n\n", "if it is always going to be a path like the above you can use os.path.split and os.path.splitext \nThe following example will print just the hello\nfrom os.path import split, splitext\npath = \"/adda/adas/sdas/hello.txt\"\nprint splitext(split(path)[1])[0]\n\nFor more info see https://docs.python.org/library/os.path.html\n", "I'm pretty sure some Regex-Ninja*, would give you a more or less sane way to do that (or as I now see others have posted: ways to write two expressions on one line...)\nBut I'm wondering why you want to do split it with just one expression? \nFor such a simple split, it's probably faster to do two than to create some advanced either-or logic. If you split twice it's safer too: \nI guess you want to separate the path, the file name and the file extension, if you split on '/' first you know the filename should be in the last array index, then you can try to split just the last index to see if you can find the file extension or not. Then you don't need to care if ther is dots in the path names.\n*(Any sane users of regular expressions, should not be offended. ;)\n" ]
[ 20, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000324132_python.txt
Q: What is the equivalent of map > in Python? In C++ often do something like this: typedef map<int, vector<int> > MyIndexType; Where I then use it like this: MyIndexType myIndex; for( ... some loop ...) { myIndex[someId].push_back(someVal); } If there was no entry in the map the code will insert a new empty vector and then append to it. In Python it would look like this: myIndex = {} for (someId,someVal) in collection: try: myIndex[someId].append(someVal) except KeyError: myIndex[someId] = [someVal] The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time? A: You want to use: from collections import defaultdict myIndex = defaultdict(list) myIndex[someId].append(someVal) Standard Library defaultdict objects. Example usage from the Python documentation: >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = defaultdict(list) >>> for k, v in s: d[k].append(v) >>> d.items() [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] A: Something like this perhaps: myIndex = {} for (someId,someVal) in collection: myIndex.setdefault(someId, []).append(someVal) A: Just to complete the answer by Alastair: There is also the get equivalent of setdefault, which is called get (and not getdefault, as one might think): myIndex = {} someId = None myList = myIndex.get(someId, []) # myList is [] now A: From Python 2.5 and on you can get the behavior of setdefault or using defaultdict by implementing __missing__(k) as in note 10 here. A: How about this? It may not be performance-optimal, but I think it's the "simplest thing that could possibly work". myIndex = {} for (someId,someVal) in collection: if someId not in myIndex: myIndex[someId] = [] myIndex[someId].append(someVal)
What is the equivalent of map > in Python?
In C++ often do something like this: typedef map<int, vector<int> > MyIndexType; Where I then use it like this: MyIndexType myIndex; for( ... some loop ...) { myIndex[someId].push_back(someVal); } If there was no entry in the map the code will insert a new empty vector and then append to it. In Python it would look like this: myIndex = {} for (someId,someVal) in collection: try: myIndex[someId].append(someVal) except KeyError: myIndex[someId] = [someVal] The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time?
[ "You want to use:\nfrom collections import defaultdict\nmyIndex = defaultdict(list)\nmyIndex[someId].append(someVal)\n\nStandard Library defaultdict objects.\nExample usage from the Python documentation:\n>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]\n>>> d = defaultdict(list)\n>>> for k, v in s:\n d[k].append(v)\n\n>>> d.items()\n[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]\n\n", "Something like this perhaps:\nmyIndex = {}\nfor (someId,someVal) in collection:\n myIndex.setdefault(someId, []).append(someVal)\n\n", "Just to complete the answer by Alastair:\nThere is also the get equivalent of setdefault, which is called get (and not getdefault, as one might think):\nmyIndex = {}\nsomeId = None\nmyList = myIndex.get(someId, []) # myList is [] now\n\n", "From Python 2.5 and on you can get the behavior of setdefault or using defaultdict by implementing \n__missing__(k)\n\nas in note 10 here.\n", "How about this? It may not be performance-optimal, but I think it's the \"simplest thing that could possibly work\".\nmyIndex = {}\n\nfor (someId,someVal) in collection:\n if someId not in myIndex:\n myIndex[someId] = []\n myIndex[someId].append(someVal)\n\n" ]
[ 15, 10, 2, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0000324643_dictionary_python.txt
Q: JDBC & MSSQL seem to be truncating large fields I'm using jython 2.2.1, and jdbc 1.2 and connecting to a mssql 2000 database, writing the contents of an email to it. When I get to the body of the email which can be quite large sometimes I need to truncate the data at 5000 chars. Except mssql & jdbc gang up on me like school yard bullies, when i check the database loads of my data is missing, every time, with max chars = 256 chars. I have checked the size of the field and it is set to 5000. what gives? I am pretty sure it is related to jdbc, as the previous version used .... vb6 & odbc, without a hitch. here is some code: BODY_FIELD_DATABASE=5000 def _execute_insert(self): try: self._stmt=self._con.prepareStatement(\ "INSERT INTO EmailHdr (EntryID, MailSubject, MailFrom, MailTo, MailReceive, MailSent, AttachNo, MailBody)\ VALUES (?, ?, ?, ?, ?, ?, ?, cast(? as varchar (" + str(BODY_FIELD_DATABASE) + ")))") self._stmt.setString(1,self._emailEntryId) self._stmt.setString(2,self._subject) self._stmt.setString(3,self._fromWho) self._stmt.setString(4,self._toWho) self._stmt.setString(5,self._emailRecv) self._stmt.setString(6,self._emailSent) self._stmt.setString(7,str(int(self._attachmentCount) + 1)) self._stmt.setString(8,self._format_email_body()) self._stmt.execute() self._prepare_inserting_attachment_data() self._insert_attachment_data() except: raise def _format_email_body(self): if not self._emailBody: return " " if len(self._emailBody) > BODY_FIELD_DATABASE: return self._clean_body(self._emailBody[:BODY_FIELD_DATABASE]) else: return self._clean_body(self._emailBody) def _clean_body(self,dirty): '''used to clean =20 occurrence in email body that contains chinese characters http://en.wikipedia.org/wiki/Quoted-printable''' dirty=str(dirty) return dirty.replace(r"=20","") A: Deleted my answer - it was totally wrong. Keeping it here though so comments & conversation hang around. EDIT: As you can read in the comments, here's what happened: The data was being put into the database fine, but the MSSQL Query Manager could not display the Chinese characters.
JDBC & MSSQL seem to be truncating large fields
I'm using jython 2.2.1, and jdbc 1.2 and connecting to a mssql 2000 database, writing the contents of an email to it. When I get to the body of the email which can be quite large sometimes I need to truncate the data at 5000 chars. Except mssql & jdbc gang up on me like school yard bullies, when i check the database loads of my data is missing, every time, with max chars = 256 chars. I have checked the size of the field and it is set to 5000. what gives? I am pretty sure it is related to jdbc, as the previous version used .... vb6 & odbc, without a hitch. here is some code: BODY_FIELD_DATABASE=5000 def _execute_insert(self): try: self._stmt=self._con.prepareStatement(\ "INSERT INTO EmailHdr (EntryID, MailSubject, MailFrom, MailTo, MailReceive, MailSent, AttachNo, MailBody)\ VALUES (?, ?, ?, ?, ?, ?, ?, cast(? as varchar (" + str(BODY_FIELD_DATABASE) + ")))") self._stmt.setString(1,self._emailEntryId) self._stmt.setString(2,self._subject) self._stmt.setString(3,self._fromWho) self._stmt.setString(4,self._toWho) self._stmt.setString(5,self._emailRecv) self._stmt.setString(6,self._emailSent) self._stmt.setString(7,str(int(self._attachmentCount) + 1)) self._stmt.setString(8,self._format_email_body()) self._stmt.execute() self._prepare_inserting_attachment_data() self._insert_attachment_data() except: raise def _format_email_body(self): if not self._emailBody: return " " if len(self._emailBody) > BODY_FIELD_DATABASE: return self._clean_body(self._emailBody[:BODY_FIELD_DATABASE]) else: return self._clean_body(self._emailBody) def _clean_body(self,dirty): '''used to clean =20 occurrence in email body that contains chinese characters http://en.wikipedia.org/wiki/Quoted-printable''' dirty=str(dirty) return dirty.replace(r"=20","")
[ "Deleted my answer - it was totally wrong. Keeping it here though so comments & conversation hang around.\nEDIT:\nAs you can read in the comments, here's what happened:\nThe data was being put into the database fine, but the MSSQL Query Manager could not display the Chinese characters.\n" ]
[ 0 ]
[]
[]
[ "jdbc", "jython", "python", "sql_server" ]
stackoverflow_0000324945_jdbc_jython_python_sql_server.txt
Q: Strategies for speeding up batch ORM operations in Django One of my API calls can result in updates to a large number of objects (Django models). I'm running into performance issues with this since I'm updating each item individually, saving, and moving on to the next: for item in Something.objects.filter(x='y'): item.a="something" item.save() Sometimes my filter criterion looks like "where x in ('a','b','c',...)". It seems the official answer to this is "won't fix". I'm wondering what strategies people are using to improve performance in these scenarios. A: The ticket you linked to is for bulk creation - if you're not relying on an overridden save method or pre/post save signals to do bits of work on save, QuerySet has an update method which you can use to perform an UPDATE on the filtered rows: Something.objects.filter(x__in=['a', 'b', 'c']).update(a='something') A: You need to use transactions or create the sql statement by hand. You could also try using SQLAlchemy which supports a few great ORM features like Unit of Work (or application transaction). Django transactions: http://docs.djangoproject.com/en/dev/topics/db/transactions/?from=olddocs SQLAlchemy: http://www.sqlalchemy.org/
Strategies for speeding up batch ORM operations in Django
One of my API calls can result in updates to a large number of objects (Django models). I'm running into performance issues with this since I'm updating each item individually, saving, and moving on to the next: for item in Something.objects.filter(x='y'): item.a="something" item.save() Sometimes my filter criterion looks like "where x in ('a','b','c',...)". It seems the official answer to this is "won't fix". I'm wondering what strategies people are using to improve performance in these scenarios.
[ "The ticket you linked to is for bulk creation - if you're not relying on an overridden save method or pre/post save signals to do bits of work on save, QuerySet has an update method which you can use to perform an UPDATE on the filtered rows:\nSomething.objects.filter(x__in=['a', 'b', 'c']).update(a='something')\n\n", "You need to use transactions or create the sql statement by hand. You could also try using SQLAlchemy which supports a few great ORM features like Unit of Work (or application transaction).\nDjango transactions: http://docs.djangoproject.com/en/dev/topics/db/transactions/?from=olddocs\nSQLAlchemy: http://www.sqlalchemy.org/\n" ]
[ 15, 1 ]
[]
[]
[ "batch_file", "django", "orm", "python" ]
stackoverflow_0000324779_batch_file_django_orm_python.txt
Q: How to include output of PHP script in Python driven Plone site? I need to have the output of a PHP snippet in a Plone site. It was delivered to be a small library that has a display() function, in PHP, that outputs a line of text. But I need to put it in a Plone site. Do you have any recommendations? I was thinking a long the lines of having a display.php that just runs display() and from the Plone template to download that URL and output the content. Do you think it might work? What methods of hitting a URL, retrieve the content and outputting can I use from inside a Plone template? One important and critical constraint is that the output should be directly on the HTML and not an an iframe. This is a constraint coming from the outside, nothing technical. A: Well, use AJAX to call the PHP script (yes, you will need apache) and display the output. Adding a custom JS to plone is trivial and this abstract the technology issue. Just be sure this is not a critical feature. Some users still deactivate JS and the web page should therefor degrade itself nicely. A: Another option is to run the PHP script on the server using os.popen, then just printing the output. Quick and dirty example: import os print os.popen('php YourScript.php').read() A: Probably the easiest way: install windowz inside your site. That way you get a page with an iframe in your plone layout. Make sure the php script outputs a regular html page and configure your windowz page with that url. Done. Works great for existing in-company phonebook applications and so.
How to include output of PHP script in Python driven Plone site?
I need to have the output of a PHP snippet in a Plone site. It was delivered to be a small library that has a display() function, in PHP, that outputs a line of text. But I need to put it in a Plone site. Do you have any recommendations? I was thinking a long the lines of having a display.php that just runs display() and from the Plone template to download that URL and output the content. Do you think it might work? What methods of hitting a URL, retrieve the content and outputting can I use from inside a Plone template? One important and critical constraint is that the output should be directly on the HTML and not an an iframe. This is a constraint coming from the outside, nothing technical.
[ "Well, use AJAX to call the PHP script (yes, you will need apache) and display the output. Adding a custom JS to plone is trivial and this abstract the technology issue.\nJust be sure this is not a critical feature. Some users still deactivate JS and the web page should therefor degrade itself nicely.\n", "Another option is to run the PHP script on the server using os.popen, then just printing the output. Quick and dirty example:\nimport os\nprint os.popen('php YourScript.php').read()\n", "Probably the easiest way: install windowz inside your site. That way you get a page with an iframe in your plone layout. Make sure the php script outputs a regular html page and configure your windowz page with that url. Done.\nWorks great for existing in-company phonebook applications and so.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "php", "plone", "python" ]
stackoverflow_0000320979_php_plone_python.txt
Q: How to analyse .exe parameters inside the program? I have a program that can have a lot of parameters (we have over +30 differents options). Example: myProgram.exe -t alpha 1 -prod 1 2 -sleep 200 This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command. For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command. Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF? The code is in C# but I think the logic can be any other language too... A: (Well, since this is tagged with Python): We use Python's optparse module for this purpose. It has a much friendlier API than lots of ifs. A: Create a hash table which stores function pointers (in C# that'd be delegates) for handling each of the parameters, keyed using the parameter text. Then you just go through the command line in a loop and make calls to delegates based on what comes out of hash table lookups. A: A useful options library for C#: NDesk.Options A: The getopt function is very common for C programming. It can parse parameters for you. Here is a question (and answer) where to get it for C#: GetOpt library for C# . Especially lappies implementation looks like rather modern C# with attributes and such. A: I'd be a little uncomfortable using a command line like that. First thing I'd say is "what does the first '1' mean, and why is it different to the second '1'?" Any time I write a command line utility that accepts an argument, I consider how easy it would be for a user to learn all the options. In this case, it looks like a bit of a hard task, IMHO. Maybe refactoring how the user passes the arguments would be a good idea. There's a reason why a lot of software takes key/value type parameters (e.g. myclient.exe -server=myServerName -config=debug) It takes a lot of load off the user, and also simplifies the argument parsing once it hits your code. A: Just for fun, you can create a wrapper around the whole thing and work with strong names in your code. More work? Yes. But more fun and once you add a new command to the wrapper you can forget about it ;) public class Form1 { private void main() { MyCommandHandler CommandLineHandler = new MyCommandHandler(); CommandLineHandler.SetInput = "-t alpha 1 -prod 1 2 -sleep 200"; //now we can use strong name to work with the variables: //CommandLineHandler.prod.ProdID //CommandLineHandler.prod.ProdInstanceID //CommandLineHandler.Alpha.AlhaValue() //CommandLineHandler.Sleep.Miliseconds() if (CommandLineHandler.Alpha.AlhaValue > 255) { throw new Exception("Apha value out of bounds!"); } } } public class MyCommandHandler { private string[] values; public string SetInput { set { values = Strings.Split(value, "-"); } } //Handle Prod command public struct prodstructure { public string ProdID; public string ProdInstanceID; } public prodstructure prod { get { prodstructure ret = new prodstructure(); ret.ProdID = GetArgsForCommand("prod", 0); ret.ProdInstanceID = GetArgsForCommand("prod", 1); return ret; } } //Handle Apha command public struct Aphastructure { public int AlhaValue; } public Aphastructure Alpha { get { Aphastructure ret = new Aphastructure(); ret.AlhaValue = Convert.ToInt32(GetArgsForCommand("alpha", 0)); return ret; } } //Handle Sleep command public struct SleepStructure { public int Miliseconds; } public SleepStructure Sleep { get { SleepStructure ret = new SleepStructure(); ret.Miliseconds = Convert.ToInt32(GetArgsForCommand("sleep", 0)); return ret; } } private string GetArgsForCommand(string key, int item) { foreach (string c in values) { foreach (string cc in Strings.Split(c.Trim, " ")) { if (cc.ToLower == key.ToLower) { try { return Strings.Split(c.Trim, " ")(item + 1); } catch (Exception ex) { return ""; } } } } return ""; } } A: The answer in Java, as is so often the case, is that someone has beaten you to it and released an excellent open source library to do this. Have a look at Apache CLI. A: I dont think this is too cludging.. private void Main() { string c = "-t alpha 1 -prod 1 2 -sleep 200"; foreach (string incommand in Strings.Split(c, "-")) { HandleCommand(Strings.Split(incommand.Trim, " ")); } } public void HandleCommand(string[] c) { switch (c(0).ToLower) { case "t": Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1); break; case "prod": Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1); break; case "sleep": Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1); break; } } Of course, instead of doing exactly same thing in those switch-statements, call appropriate functions or code. A: Commonly, you can replace large if/else or switch/case constructs with a Dictionary. Where the if-criteria is the key and the code to execute is the value. For example, you could nave a Dictionary<string, ICommand> (or Dictionary<string, Type>), which you fill before you parse your command line. When you iterate over the passed in command line options, you simply look them up in the dictionary and "invoke" on the value which is the matching command (object) to execute (or alternatively use Activate.CreateInstance(/*dictionary-value*/) if you stored the type instead of a specific object instance). In C# 3.0 you could also something like Dictionary<string, System.Linq.Expressions.Expression<T>>, although this gets you pretty close to the actual if-statement - which is something you might want to have or not. YMMV. Some libraries provide you with the mere parsing of the command line arguments (like traditionally getopt() et al did) or can provide the whole package, including the invokation of actions upon the presence of specific command line arguments.
How to analyse .exe parameters inside the program?
I have a program that can have a lot of parameters (we have over +30 differents options). Example: myProgram.exe -t alpha 1 -prod 1 2 -sleep 200 This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command. For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command. Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF? The code is in C# but I think the logic can be any other language too...
[ "(Well, since this is tagged with Python):\nWe use Python's optparse module for this purpose. It has a much friendlier API than lots of ifs.\n", "Create a hash table which stores function pointers (in C# that'd be delegates) for handling each of the parameters, keyed using the parameter text. Then you just go through the command line in a loop and make calls to delegates based on what comes out of hash table lookups.\n", "A useful options library for C#: NDesk.Options\n", "The getopt function is very common for C programming. It can parse parameters for you. Here is a question (and answer) where to get it for C#: GetOpt library for C# .\nEspecially lappies implementation looks like rather modern C# with attributes and such.\n", "I'd be a little uncomfortable using a command line like that. First thing I'd say is \"what does the first '1' mean, and why is it different to the second '1'?\"\nAny time I write a command line utility that accepts an argument, I consider how easy it would be for a user to learn all the options. In this case, it looks like a bit of a hard task, IMHO.\nMaybe refactoring how the user passes the arguments would be a good idea. There's a reason why a lot of software takes key/value type parameters (e.g. myclient.exe -server=myServerName -config=debug) It takes a lot of load off the user, and also simplifies the argument parsing once it hits your code.\n", "Just for fun, you can create a wrapper around the whole thing and work with strong names in your code.\nMore work? Yes. But more fun and once you add a new command to the wrapper you can forget about it ;)\npublic class Form1 \n{ \n\nprivate void main() \n{ \n MyCommandHandler CommandLineHandler = new MyCommandHandler(); \n CommandLineHandler.SetInput = \"-t alpha 1 -prod 1 2 -sleep 200\"; \n\n //now we can use strong name to work with the variables: \n //CommandLineHandler.prod.ProdID \n //CommandLineHandler.prod.ProdInstanceID \n //CommandLineHandler.Alpha.AlhaValue() \n //CommandLineHandler.Sleep.Miliseconds() \n if (CommandLineHandler.Alpha.AlhaValue > 255) { \n throw new Exception(\"Apha value out of bounds!\"); \n } \n\n} \n} \n\npublic class MyCommandHandler \n{ \nprivate string[] values; \npublic string SetInput { \n set { values = Strings.Split(value, \"-\"); } \n} \n\n//Handle Prod command \npublic struct prodstructure \n{ \n public string ProdID; \n public string ProdInstanceID; \n} \npublic prodstructure prod { \n get { \n prodstructure ret = new prodstructure(); \n ret.ProdID = GetArgsForCommand(\"prod\", 0); \n ret.ProdInstanceID = GetArgsForCommand(\"prod\", 1); \n return ret; \n } \n} \n\n//Handle Apha command \npublic struct Aphastructure \n{ \n public int AlhaValue; \n} \npublic Aphastructure Alpha { \n get { \n Aphastructure ret = new Aphastructure(); \n ret.AlhaValue = Convert.ToInt32(GetArgsForCommand(\"alpha\", 0)); \n return ret; \n } \n} \n\n\n//Handle Sleep command \npublic struct SleepStructure \n{ \n public int Miliseconds; \n} \npublic SleepStructure Sleep { \n get { \n SleepStructure ret = new SleepStructure(); \n ret.Miliseconds = Convert.ToInt32(GetArgsForCommand(\"sleep\", 0)); \n return ret; \n } \n} \n\n\nprivate string GetArgsForCommand(string key, int item) \n{ \n foreach (string c in values) { \n foreach (string cc in Strings.Split(c.Trim, \" \")) { \n if (cc.ToLower == key.ToLower) { \n try { \n return Strings.Split(c.Trim, \" \")(item + 1); \n } \n catch (Exception ex) { \n return \"\"; \n } \n } \n } \n } \n return \"\"; \n} \n} \n\n", "The answer in Java, as is so often the case, is that someone has beaten you to it and released an excellent open source library to do this. Have a look at Apache CLI.\n", "I dont think this is too cludging.. \nprivate void Main() \n{ \nstring c = \"-t alpha 1 -prod 1 2 -sleep 200\"; \n\nforeach (string incommand in Strings.Split(c, \"-\")) { \n HandleCommand(Strings.Split(incommand.Trim, \" \")); \n} \n} \n\n\npublic void HandleCommand(string[] c) \n{ \nswitch (c(0).ToLower) { \n case \"t\": \n Interaction.MsgBox(\"Command:\" + c(0) + \" params: \" + c.Length - 1); \n break; \n case \"prod\": \n Interaction.MsgBox(\"Command:\" + c(0) + \" params: \" + c.Length - 1); \n break; \n case \"sleep\": \n Interaction.MsgBox(\"Command:\" + c(0) + \" params: \" + c.Length - 1); \n break; \n} \n} \n\nOf course, instead of doing exactly same thing in those switch-statements, call appropriate functions or code.\n", "Commonly, you can replace large if/else or switch/case constructs with a Dictionary. Where the if-criteria is the key and the code to execute is the value.\nFor example, you could nave a Dictionary<string, ICommand> (or Dictionary<string, Type>), which you fill before you parse your command line.\nWhen you iterate over the passed in command line options, you simply look them up in the dictionary and \"invoke\" on the value which is the matching command (object) to execute (or alternatively use Activate.CreateInstance(/*dictionary-value*/) if you stored the type instead of a specific object instance).\nIn C# 3.0 you could also something like Dictionary<string, System.Linq.Expressions.Expression<T>>, although this gets you pretty close to the actual if-statement - which is something you might want to have or not. YMMV.\nSome libraries provide you with the mere parsing of the command line arguments (like traditionally getopt() et al did) or can provide the whole package, including the invokation of actions upon the presence of specific command line arguments.\n" ]
[ 6, 5, 5, 4, 1, 1, 1, 0, 0 ]
[]
[]
[ ".net", "c#", "java", "python" ]
stackoverflow_0000323866_.net_c#_java_python.txt
Q: Problem with Boolean Expression with a string value from a lIst I have the following problem: # line is a line from a file that contains ["baa","beee","0"] line = TcsLine.split(",") NumPFCs = eval(line[2]) if NumPFCs==0: print line I want to print all the lines from the file if the second position of the list has a value == 0. I print the lines but after that the following happens: Traceback (most recent call last): ['baaa', 'beee', '0', '\n'] BUT after I have the next ERROR ilation.py", line 141, in ? getZeroPFcs() ilation.py", line 110, in getZeroPFcs NumPFCs = eval(line[2]) File "<string>", line 0 Can you please help me? thanks What0s A: Let me explain a little what you do here. If you write: NumPFCs = eval(line[2]) the order of evaluation is: take the second character of the string line, i.e. a quote '"' eval this quote as a python expression, which is an error. If you write it instead as: NumPFCs = eval(line)[2] then the order of evaluation is: eval the line, producing a python list take the second element of that list, which is a one-character string: "0" a string cannot be compared with a number; this is an error too. In your terms, you want to do the following: NumPFCs = eval(eval(line)[2]) or, slightly better, compare NumPFCs to a string: if NumPFCs == "0": but the ways this could go wrong are almost innumerable. You should forget about eval and try to use other methods: string splitting, regular expressions etc. Others have already provided some suggestions, and I'm sure more will follow. A: Your question is kind of hard to read, but using eval there is definitely not a good idea. Either just do a direct string comparison: line=TcsLine.split(",") if line[2] == "0": print line or use int line=TcsLine.split(",") if int(line[2]) == 0: print line Either way, your bad data will fail you. I'd also recomment reading PEP 8. A: There are a few issues I see in your code segment: you make an assumption that list always has at least 3 elements eval will raise exception if containing string isn't valid python you say you want second element, but you access the 3rd element. This is a safer way to do this line=TcsLine.split(",") if len(line) >=3 and line[2].rfind("0") != -1: print line A: I'd recommend using a regular expression to capture all of the variants of how 0 can be specified: with double-quotes, without any quotes, with single quotes, with extra whitespace outside the quotes, with whitespace inside the quotes, how you want the square brackets handled, etc. A: There are many ways of skinning a cat, as it were :) Before we begin though, don't use eval on strings that are not yours so if the string has ever left your program; i.e. it has stayed in a file, sent over a network, someone can send in something nasty. And if someone can, you can be sure someone will. And you might want to look over your data format. Putting strings like ["baa","beee","0", "\n"] in a file does not make much sense to me. The first and simplest way would be to just strip away the stuff you don't need and to a string comparison. This would work as long as the '0'-string always looks the same and you're not really after the integer value 0, only the character pattern: TcsLine = '["baa","beee","0"]' line = TcsLine.strip('[]').split(",") if line[2] == '"0"': print line The second way would be to similar to the first except that we cast the numeric string to an integer, yielding the integer value you were looking for (but printing 'line' without all the quotation marks): TcsLine = '["baa","beee","0"]' line = [e.strip('"') for e in TcsLine.strip('[]').split(",")] NumPFCs = int(line[2]) if NumPFCs==0: print line Could it be that the string is actually a json array? Then I would probably go get simplejson to parse it properly if I were running Python<2.6 or just import json on Python>=2.6. Then cast the resulting '0'-string to an integer as in the previous example. TcsLine = '["baa","beee","0"]' #import json # for >= Python2.6 import simplejson as json # for <Python2.6 line = json.loads(TcsLine) NumPFCs = int(line[2]) if NumPFCs==0: print line
Problem with Boolean Expression with a string value from a lIst
I have the following problem: # line is a line from a file that contains ["baa","beee","0"] line = TcsLine.split(",") NumPFCs = eval(line[2]) if NumPFCs==0: print line I want to print all the lines from the file if the second position of the list has a value == 0. I print the lines but after that the following happens: Traceback (most recent call last): ['baaa', 'beee', '0', '\n'] BUT after I have the next ERROR ilation.py", line 141, in ? getZeroPFcs() ilation.py", line 110, in getZeroPFcs NumPFCs = eval(line[2]) File "<string>", line 0 Can you please help me? thanks What0s
[ "Let me explain a little what you do here.\nIf you write:\nNumPFCs = eval(line[2])\n\nthe order of evaluation is:\n\ntake the second character of the string line, i.e. a quote '\"'\neval this quote as a python expression, which is an error.\n\nIf you write it instead as:\nNumPFCs = eval(line)[2]\n\nthen the order of evaluation is:\n\neval the line, producing a python list\ntake the second element of that list, which is a one-character string: \"0\"\na string cannot be compared with a number; this is an error too.\n\nIn your terms, you want to do the following:\nNumPFCs = eval(eval(line)[2])\n\nor, slightly better, compare NumPFCs to a string:\nif NumPFCs == \"0\":\n\nbut the ways this could go wrong are almost innumerable. You should forget about eval and try to use other methods: string splitting, regular expressions etc. Others have already provided some suggestions, and I'm sure more will follow.\n", "Your question is kind of hard to read, but using eval there is definitely not a good idea. Either just do a direct string comparison:\nline=TcsLine.split(\",\")\nif line[2] == \"0\":\n print line\n\nor use int\nline=TcsLine.split(\",\")\nif int(line[2]) == 0:\n print line\n\nEither way, your bad data will fail you.\nI'd also recomment reading PEP 8.\n", "There are a few issues I see in your code segment:\n\nyou make an assumption that list always has at least 3 elements\neval will raise exception if containing string isn't valid python\nyou say you want second element, but you access the 3rd element.\n\nThis is a safer way to do this\nline=TcsLine.split(\",\")\nif len(line) >=3 and line[2].rfind(\"0\") != -1:\n print line\n\n", "I'd recommend using a regular expression to capture all of the variants of how 0 can be specified: with double-quotes, without any quotes, with single quotes, with extra whitespace outside the quotes, with whitespace inside the quotes, how you want the square brackets handled, etc.\n", "There are many ways of skinning a cat, as it were :)\nBefore we begin though, don't use eval on strings that are not yours so if the string has ever left your program; i.e. it has stayed in a file, sent over a network, someone can send in something nasty. And if someone can, you can be sure someone will.\nAnd you might want to look over your data format. Putting strings like [\"baa\",\"beee\",\"0\", \"\\n\"] in a file does not make much sense to me.\nThe first and simplest way would be to just strip away the stuff you don't need and to a string comparison. This would work as long as the '0'-string always looks the same and you're not really after the integer value 0, only the character pattern:\nTcsLine = '[\"baa\",\"beee\",\"0\"]'\n\nline = TcsLine.strip('[]').split(\",\")\nif line[2] == '\"0\"':\n print line\n\n\nThe second way would be to similar to the first except that we cast the numeric string to an integer, yielding the integer value you were looking for (but printing 'line' without all the quotation marks):\nTcsLine = '[\"baa\",\"beee\",\"0\"]'\n\nline = [e.strip('\"') for e in TcsLine.strip('[]').split(\",\")]\nNumPFCs = int(line[2])\nif NumPFCs==0:\n print line\n\n\nCould it be that the string is actually a json array? Then I would probably go get simplejson to parse it properly if I were running Python<2.6 or just import json on Python>=2.6. Then cast the resulting '0'-string to an integer as in the previous example.\nTcsLine = '[\"baa\",\"beee\",\"0\"]'\n\n#import json # for >= Python2.6\nimport simplejson as json # for <Python2.6\n\nline = json.loads(TcsLine)\nNumPFCs = int(line[2])\nif NumPFCs==0:\n print line\n\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000324506_python.txt
Q: Python 2.5.2 and Solaris 8 (gcc 3.4.2) build issues I'm trying to build python 2.5.2 on Solaris 8 using gcc 3.4.2. I can't see any immediate errors in the ./configure step but, once built and i enter the python shell doing an import time errors with : Python 2.5.2 (r252:60911, Nov 21 2008, 18:45:42) [GCC 3.4.2] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import time Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named time What am i doing wrong? From what i can see with a cursory google is that there might be an error with libstdc++.so, but i can't find any hard details. Any suggestions would be most welcome. Many thanks, Al. A: The time module is not built by default in Python, if you build from a source distribution you need to explicitly enable all the modules you want to compile. Open up Modules/Setup.dist in the python source tree and comment out the line which says: #time timemodule.c To enable the build of time module. Also remember that you need to recompile Python for this to take an effect.
Python 2.5.2 and Solaris 8 (gcc 3.4.2) build issues
I'm trying to build python 2.5.2 on Solaris 8 using gcc 3.4.2. I can't see any immediate errors in the ./configure step but, once built and i enter the python shell doing an import time errors with : Python 2.5.2 (r252:60911, Nov 21 2008, 18:45:42) [GCC 3.4.2] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import time Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named time What am i doing wrong? From what i can see with a cursory google is that there might be an error with libstdc++.so, but i can't find any hard details. Any suggestions would be most welcome. Many thanks, Al.
[ "The time module is not built by default in Python, if you build from a source distribution you need to explicitly enable all the modules you want to compile. \nOpen up Modules/Setup.dist in the python source tree and comment out the line which says:\n\n#time timemodule.c\n\nTo enable the build of time module. Also remember that you need to recompile Python for this to take an effect.\n" ]
[ 2 ]
[]
[]
[ "build_process", "environment_variables", "gcc", "python", "solaris" ]
stackoverflow_0000314749_build_process_environment_variables_gcc_python_solaris.txt
Q: Packaging a Python library I have a few Munin plugins which report stats from an Autonomy database. They all use a small library which scrapes the XML status output for the relevant numbers. I'm trying to bundle the library and plugins into a Puppet-installable RPM. The actual RPM-building should be straightforward; once I have a distutils-produced distfile I can make it into an RPM based on a .spec file pinched from the Dag or EPEL repos [1]. It's the distutils bit I'm unsure of -- in fact I'm not even sure my library is correctly written for packaging. Here's how it works: idol7stats.py: import datetime import os import stat import sys import time import urllib import xml.sax class IDOL7Stats: cache_dir = '/tmp' def __init__(self, host, port): self.host = host self.port = port # ... def collect(self): self.data = self.__parseXML(self.__getXML()) def total_slots(self): return self.data['Service:Documents:TotalSlots'] Plugin code: from idol7stats import IDOL7Stats a = IDOL7Stats('db.example.com', 23113) a.collect() print a.total_slots() I guess I want idol7stats.py to wind up in /usr/lib/python2.4/site-packages/idol7stats, or something else in Python's search path. What distutils magic do I need? This: from distutils.core import setup setup(name = 'idol7stats', author = 'Me', author_email = 'me@example.com', version = '0.1', py_modules = ['idol7stats']) almost works, except the code goes in /usr/lib/python2.4/site-packages/idol7stats.py, not a subdirectory. I expect this is down to my not understanding the difference between modules/packages/other containers in Python. So, what's the rub? [1] Yeah, I could just plonk the library in /usr/lib/python2.4/site-packages using RPM but I want to know how to package Python code. A: You need to create a package to do what you want. You'd need a directory named idol7stats containing a file called __init__.py and any other library modules to package. Also, this will affect your scripts' imports; if you put idol7stats.py in a package called idol7stats, then your scripts need to "import idol7stats.idol7stats". To avoid that, you could just rename idol7stats.py to idol7stats/__init__.py, or you could put this line into idol7stats/__init__.py to "massage" the imports into the way you expect them: from idol7stats.idol7stats import *
Packaging a Python library
I have a few Munin plugins which report stats from an Autonomy database. They all use a small library which scrapes the XML status output for the relevant numbers. I'm trying to bundle the library and plugins into a Puppet-installable RPM. The actual RPM-building should be straightforward; once I have a distutils-produced distfile I can make it into an RPM based on a .spec file pinched from the Dag or EPEL repos [1]. It's the distutils bit I'm unsure of -- in fact I'm not even sure my library is correctly written for packaging. Here's how it works: idol7stats.py: import datetime import os import stat import sys import time import urllib import xml.sax class IDOL7Stats: cache_dir = '/tmp' def __init__(self, host, port): self.host = host self.port = port # ... def collect(self): self.data = self.__parseXML(self.__getXML()) def total_slots(self): return self.data['Service:Documents:TotalSlots'] Plugin code: from idol7stats import IDOL7Stats a = IDOL7Stats('db.example.com', 23113) a.collect() print a.total_slots() I guess I want idol7stats.py to wind up in /usr/lib/python2.4/site-packages/idol7stats, or something else in Python's search path. What distutils magic do I need? This: from distutils.core import setup setup(name = 'idol7stats', author = 'Me', author_email = 'me@example.com', version = '0.1', py_modules = ['idol7stats']) almost works, except the code goes in /usr/lib/python2.4/site-packages/idol7stats.py, not a subdirectory. I expect this is down to my not understanding the difference between modules/packages/other containers in Python. So, what's the rub? [1] Yeah, I could just plonk the library in /usr/lib/python2.4/site-packages using RPM but I want to know how to package Python code.
[ "You need to create a package to do what you want. You'd need a directory named idol7stats containing a file called __init__.py and any other library modules to package. Also, this will affect your scripts' imports; if you put idol7stats.py in a package called idol7stats, then your scripts need to \"import idol7stats.idol7stats\".\nTo avoid that, you could just rename idol7stats.py to idol7stats/__init__.py, or you could put this line into idol7stats/__init__.py to \"massage\" the imports into the way you expect them:\nfrom idol7stats.idol7stats import *\n\n" ]
[ 2 ]
[]
[]
[ "distutils", "packaging", "python" ]
stackoverflow_0000326254_distutils_packaging_python.txt
Q: How can I dynamically get the set of classes from the current python module? I have a python module that defines a number of classes: class A(object): def __call__(self): print "ran a" class B(object): def __call__(self): print "ran b" class C(object): def __call__(self): print "ran c" From within the module, how might I add an attribute that gives me all of the classes? dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from within the module. From outside of the module, I can simply use getattr(mod, 'A'), but I don't have a self kind of module from within the module itself. This seems pretty obvious. Can someone tell me what I'm missing? A: import sys getattr(sys.modules[__name__], 'A') A: You can smash this into one for statement, but that'd have messy code duplication. import sys import types this_module = sys.modules[__name__] [x for x in [getattr(this_module, x) for x in dir(this_module)] if type(x) == types.ClassType] A: classes = [x for x in globals().values() if isinstance(x, type)]
How can I dynamically get the set of classes from the current python module?
I have a python module that defines a number of classes: class A(object): def __call__(self): print "ran a" class B(object): def __call__(self): print "ran b" class C(object): def __call__(self): print "ran c" From within the module, how might I add an attribute that gives me all of the classes? dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from within the module. From outside of the module, I can simply use getattr(mod, 'A'), but I don't have a self kind of module from within the module itself. This seems pretty obvious. Can someone tell me what I'm missing?
[ "import sys\ngetattr(sys.modules[__name__], 'A')\n\n", "You can smash this into one for statement, but that'd have messy code duplication.\nimport sys\nimport types\nthis_module = sys.modules[__name__]\n[x for x in\n [getattr(this_module, x) for x in dir(this_module)]\n if type(x) == types.ClassType]\n\n", "\nclasses = [x for x in globals().values() if isinstance(x, type)]\n\n" ]
[ 10, 6, 3 ]
[]
[]
[ "metaprogramming", "python", "reflection" ]
stackoverflow_0000326770_metaprogramming_python_reflection.txt
Q: Best language choice for a spam detection service I have around 20 or so active blogs that get quite a bit of spam. As I hate CAPCHA the alternative is very smart spam filtering. I want to build a simple REST api like spam checking service which I would use in all my blogs. That way I can consolidate IP blocks and offload spam detection to 3rd party such as Akisment, Mollom, Defensio and sometime in the future write my own spam detection to really get my head into some very interesting spam detection algorithms. My language of choice is PHP, I consider myself quite proficient and I can really dig in deep and come out with a solution. This project, I feel, can be used as a good exercise to learn another language. The big 2 that come to mind are Python and Ruby on Rails as everyone talks about them like its the next coming of our savior. Since this is mostly just an API and has no admin or public facing anything, seems like basic Python running a simple http server seems like the way to go. Am I missing anything? What would you, the great community, recommend? I would love to hear your language, book and best practices recommendations. This has to scale and I want to write it with that in mind. Right now I'd probably be able to use 3rd party's free plans, but soon enough I'd have to expand the whole thing to actually think on its own. For now I think I'll just store everything in a MySQL database until I can do some real analysis on it. Thanks! A: My first question - why don't you just use one of those three services you listed? It seems they do exactly what you want. Sorry for being cynical, but I doubt that you working alone could in a reasonable amount of time beat the software engineers designing the algorithms used at those websites, especially considering their source of income depends on how well they do it. Then again, you might just be smarter than they are =P. I'm not one to judge. In any case, I'd recommend python, for the reasons you stated - you won't need a fancy public interface, so python's lack of excellence in this area won't matter. Python is also good for doing text processing, and it has great built-in bindings for using databases (sqlite, for example; you can, of course, install MySQL if you feel it is necessary). Downsides: it might get a bit slow, depending on how sophisticated your algorithms get. A: Python has some advantages. There are several HTTP server frameworks in Python. Look at the WSGI reference implementation, and learn how to use the WSGI standard to handle web requests. It's very clean and extensible. It takes a little bit of study to see that WSGI is all about adding details to the request until you reach a stage in the processing where it's time to formulate a reply. MIME email parsing is pretty straightforward. After that, you'll be using site blacklisting and content filtering for your spam detection. A site blacklist can be a big, fancy RDBMS. Or it can be simple pickled Python Set of domain names and IP addresses. I recommend a simple pickled set object that lives in memory. It's fast. You can have your RESTful service reload this set from a source file on receipt of some GET request that forces a refresh. Text filtering is just hard. I'd start with SpamBayes. A: I humbly recommend Lua, not only because it's a great, fast language, already integrated with web servers, but also because you can then exploit OSBF-Lua, an existing spam filter that has won spam-filtering competitions for several years in a row. Fidelis Assis and I have put in a lot of work trying to generalize the model beyond email, and we'd be delighted to work with you on integrating it with your app, which is what Lua was designed for. As for scaling, in training mode we process hundreds of emails per second on a 2006 machine, so that should work out pretty well even for a busy web site. We'd need to work with you on classifying stuff without mail headers, but I've been pushing in that direction already. For more info please write nr@cs.tufts.edu. (Yes, I want people to send me spam. It's for research!) A: I'd have to recommend Akismet for it's ease-of-use and high accuracy. With only a WordPress.com API key and an API call, you can determine if a given blob of text from a user is spammy. I've been using the Akismet plugin for WordPress, which uses the same API, and have had stellar results with it for the last year or so. Zend Framework has a great Akismet PHP class you can use independent of the rest of the framework, which should make integration pretty straightforward. Documentation is quite thorough, as well.
Best language choice for a spam detection service
I have around 20 or so active blogs that get quite a bit of spam. As I hate CAPCHA the alternative is very smart spam filtering. I want to build a simple REST api like spam checking service which I would use in all my blogs. That way I can consolidate IP blocks and offload spam detection to 3rd party such as Akisment, Mollom, Defensio and sometime in the future write my own spam detection to really get my head into some very interesting spam detection algorithms. My language of choice is PHP, I consider myself quite proficient and I can really dig in deep and come out with a solution. This project, I feel, can be used as a good exercise to learn another language. The big 2 that come to mind are Python and Ruby on Rails as everyone talks about them like its the next coming of our savior. Since this is mostly just an API and has no admin or public facing anything, seems like basic Python running a simple http server seems like the way to go. Am I missing anything? What would you, the great community, recommend? I would love to hear your language, book and best practices recommendations. This has to scale and I want to write it with that in mind. Right now I'd probably be able to use 3rd party's free plans, but soon enough I'd have to expand the whole thing to actually think on its own. For now I think I'll just store everything in a MySQL database until I can do some real analysis on it. Thanks!
[ "My first question - why don't you just use one of those three services you listed? It seems they do exactly what you want. Sorry for being cynical, but I doubt that you working alone could in a reasonable amount of time beat the software engineers designing the algorithms used at those websites, especially considering their source of income depends on how well they do it.\nThen again, you might just be smarter than they are =P. I'm not one to judge. In any case, I'd recommend python, for the reasons you stated - you won't need a fancy public interface, so python's lack of excellence in this area won't matter. Python is also good for doing text processing, and it has great built-in bindings for using databases (sqlite, for example; you can, of course, install MySQL if you feel it is necessary). \nDownsides: it might get a bit slow, depending on how sophisticated your algorithms get.\n", "Python has some advantages.\n\nThere are several HTTP server frameworks in Python. Look at the WSGI reference implementation, and learn how to use the WSGI standard to handle web requests. It's very clean and extensible. It takes a little bit of study to see that WSGI is all about adding details to the request until you reach a stage in the processing where it's time to formulate a reply. \nMIME email parsing is pretty straightforward.\nAfter that, you'll be using site blacklisting and content filtering for your spam detection. \n\nA site blacklist can be a big, fancy RDBMS. Or it can be simple pickled Python Set of domain names and IP addresses. I recommend a simple pickled set object that lives in memory. It's fast. You can have your RESTful service reload this set from a source file on receipt of some GET request that forces a refresh.\nText filtering is just hard. I'd start with SpamBayes.\n\n\n", "I humbly recommend Lua, not only because it's a great, fast language, already integrated with web servers, but also because you can then exploit OSBF-Lua, an existing spam filter that has won spam-filtering competitions for several years in a row. Fidelis Assis and I have put in a lot of work trying to generalize the model beyond email, and we'd be delighted to work with you on integrating it with your app, which is what Lua was designed for.\nAs for scaling, in training mode we process hundreds of emails per second on a 2006 machine, so that should work out pretty well even for a busy web site.\nWe'd need to work with you on classifying stuff without mail headers, but I've been pushing in that direction already. For more info please write nr@cs.tufts.edu. (Yes, I want people to send me spam. It's for research!)\n", "I'd have to recommend Akismet for it's ease-of-use and high accuracy. With only a WordPress.com API key and an API call, you can determine if a given blob of text from a user is spammy. I've been using the Akismet plugin for WordPress, which uses the same API, and have had stellar results with it for the last year or so.\nZend Framework has a great Akismet PHP class you can use independent of the rest of the framework, which should make integration pretty straightforward. Documentation is quite thorough, as well.\n" ]
[ 9, 2, 1, 1 ]
[]
[]
[ "mysql", "php", "python", "ruby", "spam_prevention" ]
stackoverflow_0000326401_mysql_php_python_ruby_spam_prevention.txt
Q: using curses with raw_input in python In my python linux console application I use curses to handle displaying of data. At the same time I'd like to have an input line to enter commands, pretty much in good ol' irssi-style. With default curses getch() I'd have to do a lot of coding just to get the basic funcionality of raw_input function - arrow keys to move cursor / browse through the input history. Is there a simple way to get such behavior working with curses, as it captures input events and I can't just use functions that read sys.stdin. A: Use curses.textpad http://www.python.org/doc/2.4.1/lib/module-curses.textpad.html
using curses with raw_input in python
In my python linux console application I use curses to handle displaying of data. At the same time I'd like to have an input line to enter commands, pretty much in good ol' irssi-style. With default curses getch() I'd have to do a lot of coding just to get the basic funcionality of raw_input function - arrow keys to move cursor / browse through the input history. Is there a simple way to get such behavior working with curses, as it captures input events and I can't just use functions that read sys.stdin.
[ "Use curses.textpad\nhttp://www.python.org/doc/2.4.1/lib/module-curses.textpad.html\n" ]
[ 1 ]
[]
[]
[ "console_application", "ncurses", "python" ]
stackoverflow_0000326922_console_application_ncurses_python.txt
Q: How do you create a simple Google Talk Client using the Twisted Words Python library? I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk. Has anybody had any luck with this? Would you mind documenting a brief tutorial? As a simple task, I'd like to create a client/bot that tracks the Online time of my various Google Talk accounts so that I can get an aggregate number. I figure I could friend the bot in each account and then use the XMPP presence information to keep track of the times that I can then aggregate. Thanks. A: wokkel is the future of twisted words. metajack wrote a really nice blog post on getting started. If you want a nice, functional sample project to start with, check out my whatsup bot. A: I have written a simple Jabber bot (and thus Google talk bot) using the xmpppy library, which works well. The examples on xmpppy should get you started (specifically bot.py) As for something actually implemented in twisted.Words: Here is a simple tutorial on creating a bot that prints every received message to the local terminal (and a version that replies with the revere of the received message). To track the online time of various accounts, you would add a callback for "presences" (going online/offline/away etc are "presence changes", in Jabber terminology) For a more complete system, pownce-jabber-bot uses twisted.words and wokkel for the jabber interface. The powncebot/__init__.py file seems like a good place to start - it's seems pretty simple. A: I was looking building an XMPP client in python a while ago. I haven't gotten around to working on the project I was looking at it for. I didn't see anything that used twisted but are a couple XMPP libraries I found. https://launchpad.net/python-xmpp/ http://xmpppy.sourceforge.net/ http://pyxmpp.jajcus.net/ I also found a python program, under the GPL, that acts multi-point conference system using XMPP. http://coders.meta.net.nz/~perry/jabber/confbot.php
How do you create a simple Google Talk Client using the Twisted Words Python library?
I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk. Has anybody had any luck with this? Would you mind documenting a brief tutorial? As a simple task, I'd like to create a client/bot that tracks the Online time of my various Google Talk accounts so that I can get an aggregate number. I figure I could friend the bot in each account and then use the XMPP presence information to keep track of the times that I can then aggregate. Thanks.
[ "wokkel is the future of twisted words. metajack wrote a really nice blog post on getting started.\nIf you want a nice, functional sample project to start with, check out my whatsup bot.\n", "I have written a simple Jabber bot (and thus Google talk bot) using the xmpppy library, which works well. The examples on xmpppy should get you started (specifically bot.py)\nAs for something actually implemented in twisted.Words:\nHere is a simple tutorial on creating a bot that prints every received message to the local terminal (and a version that replies with the revere of the received message). To track the online time of various accounts, you would add a callback for \"presences\" (going online/offline/away etc are \"presence changes\", in Jabber terminology)\nFor a more complete system, pownce-jabber-bot uses twisted.words and wokkel for the jabber interface.\nThe powncebot/__init__.py file seems like a good place to start - it's seems pretty simple.\n", "I was looking building an XMPP client in python a while ago. I haven't gotten around to working on the project I was looking at it for. I didn't see anything that used twisted but are a couple XMPP libraries I found.\n\nhttps://launchpad.net/python-xmpp/\nhttp://xmpppy.sourceforge.net/\nhttp://pyxmpp.jajcus.net/\n\nI also found a python program, under the GPL, that acts multi-point conference system using XMPP.\nhttp://coders.meta.net.nz/~perry/jabber/confbot.php\n" ]
[ 14, 7, 2 ]
[ "As the Twisted libs seem to be out of date, you have two choices:\nImplement your own XMPP-handler or look for another library.\nI would suggest working with the raw XML; XMPP is not that complicated and you are bound to learn something.\n" ]
[ -2 ]
[ "google_talk", "python", "twisted", "xmpp" ]
stackoverflow_0000227279_google_talk_python_twisted_xmpp.txt
Q: How to call python2.5 function from x86asm/x64asm? I'll have couple of python functions I must interface with from the assembly code. The solution doesn't need to be a complete solution because I'm not going to interface with python code for too long. Anyway, I chewed it a bit: What does a python object look like in memory? How can I call a python function? How can I pass python objects as python objects for ctypes interface? Could ctypes interface make my work easier in any alternative way? A: You will want to read and understand Extending and Embedding the Python Interpreter and the Python/C API Reference Manual. This describes how to interface with Python from C. Everything you can do in C you can equivalently do in assembly code too, but you're on your own for this as it is not directly described from a Python perspective. A: It's certainly doable, but you'd have a much easier time reading the C API docs and writing a go-between function in C. Come to think of it, C is highly recommended, since it may be hard to tell which of the routines you're calling might be implemented as preprocessor macros.
How to call python2.5 function from x86asm/x64asm?
I'll have couple of python functions I must interface with from the assembly code. The solution doesn't need to be a complete solution because I'm not going to interface with python code for too long. Anyway, I chewed it a bit: What does a python object look like in memory? How can I call a python function? How can I pass python objects as python objects for ctypes interface? Could ctypes interface make my work easier in any alternative way?
[ "You will want to read and understand Extending and Embedding the Python Interpreter and the Python/C API Reference Manual. This describes how to interface with Python from C. Everything you can do in C you can equivalently do in assembly code too, but you're on your own for this as it is not directly described from a Python perspective.\n", "It's certainly doable, but you'd have a much easier time reading the C API docs and writing a go-between function in C.\nCome to think of it, C is highly recommended, since it may be hard to tell which of the routines you're calling might be implemented as preprocessor macros.\n" ]
[ 3, 1 ]
[]
[]
[ "assembly", "python" ]
stackoverflow_0000319232_assembly_python.txt
Q: how to draw lines on a picture background in pygame I would like to draw lines (of arbitrary position and length) onto a surface in pygame, which itself is an image loaded from a file on disk. Can anyone point me to some example code that does this? A: This should do what you're asking for: # load the image image = pygame.image.load("some_image.png") # draw a yellow line on the image pygame.draw.line(image, (255, 255, 0), (0, 0), (100, 100)) Typically you don't draw to the original image, since you'll have to reload the image to get the original back (or create a copy of it before you start drawing onto it). Perhaps what you actually need is something more like this: # initialize pygame and screen import pygame pygame.init() screen = pygame.display.set_mode((720, 576)) # Draw the image to the screen screen.blit(image, (0, 0)) # Draw a line on top of the image on the screen pygame.draw.line(screen, (255, 255, 255), (0, 0), (50, 50)) A: Help on module pygame.draw in pygame: NAME pygame.draw - pygame module for drawing shapes FILE d:\program files\python25\lib\site-packages\pygame\draw.pyd FUNCTIONS aaline(...) pygame.draw.aaline(Surface, color, startpos, endpos, blend=1): return Rect draw fine antialiased lines aalines(...) pygame.draw.aalines(Surface, color, closed, pointlist, blend=1): return Rect arc(...) pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1): return Rect draw a partial section of an ellipse circle(...) pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect draw a circle around a point ellipse(...) pygame.draw.ellipse(Surface, color, Rect, width=0): return Rect draw a round shape inside a rectangle line(...) pygame.draw.line(Surface, color, start_pos, end_pos, width=1): return Rect draw a straight line segment lines(...) pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect draw multiple contiguous line segments polygon(...) pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect draw a shape with any number of sides rect(...) pygame.draw.rect(Surface, color, Rect, width=0): return Rect draw a rectangle shape
how to draw lines on a picture background in pygame
I would like to draw lines (of arbitrary position and length) onto a surface in pygame, which itself is an image loaded from a file on disk. Can anyone point me to some example code that does this?
[ "This should do what you're asking for:\n# load the image\nimage = pygame.image.load(\"some_image.png\")\n\n# draw a yellow line on the image\npygame.draw.line(image, (255, 255, 0), (0, 0), (100, 100))\n\nTypically you don't draw to the original image, since you'll have to reload the image to get the original back (or create a copy of it before you start drawing onto it). Perhaps what you actually need is something more like this:\n# initialize pygame and screen\nimport pygame\npygame.init()\nscreen = pygame.display.set_mode((720, 576))\n\n# Draw the image to the screen\nscreen.blit(image, (0, 0))\n\n# Draw a line on top of the image on the screen\npygame.draw.line(screen, (255, 255, 255), (0, 0), (50, 50))\n\n", "Help on module pygame.draw in pygame:\nNAME\n pygame.draw - pygame module for drawing shapes\nFILE\n d:\\program files\\python25\\lib\\site-packages\\pygame\\draw.pyd\nFUNCTIONS\n aaline(...)\n pygame.draw.aaline(Surface, color, startpos, endpos, blend=1): return Rect\n draw fine antialiased lines\naalines(...)\n pygame.draw.aalines(Surface, color, closed, pointlist, blend=1): return Rect\n\narc(...)\n pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1): return Rect\n draw a partial section of an ellipse\n\ncircle(...)\n pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect\n draw a circle around a point\n\nellipse(...)\n pygame.draw.ellipse(Surface, color, Rect, width=0): return Rect\n draw a round shape inside a rectangle\n\nline(...)\n pygame.draw.line(Surface, color, start_pos, end_pos, width=1): return Rect\n draw a straight line segment\n\nlines(...)\n pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect\n draw multiple contiguous line segments\n\npolygon(...)\n pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect\n draw a shape with any number of sides\n\nrect(...)\n pygame.draw.rect(Surface, color, Rect, width=0): return Rect\n draw a rectangle shape\n\n" ]
[ 3, 0 ]
[]
[]
[ "drawing", "pygame", "python" ]
stackoverflow_0000327896_drawing_pygame_python.txt
Q: Is there a library similar to pyparsing in Java? I need to quickly build a parser for a very simplified version of a html-like markup language in Java. In python, I would use pyparsing library to do this. Is there something similar for Java? Please, don't suggest libraries already out there for html parsing, my application is a school assignment which will demonstrate walking a tree of objects and serializing to text using visitor pattern, so I'm not thinking in real world terms here. Basically all I need here is tags, attributes and text nodes. A: Another good parser generator is ANTLR, that might be what you're looking for. A: May be overkill for your use, but javacc is an excellent industrial-strength parser generator. I've used this program/library several times, its reliable and worth learning, particularly if you are going to work with languages and compilers. Here's the description of the program from the website listed above: Java Compiler Compiler [tm] (JavaCC [tm]) is the most popular parser generator for use with Java [tm] applications. A parser generator is a tool that reads a grammar specification and converts it to a Java program that can recognize matches to the grammar. In addition to the parser generator itself, JavaCC provides other standard capabilities related to parser generation such as tree building (via a tool called JJTree included with JavaCC), actions, debugging, etc. A: A quick search for parser generators in Java yields JParsec. I've never used it - but it's inspired by a Haskell library, so by definition it must be good:-) A: I like JParsec (which I just discovered thanks to Torsten) because it doesn't generate code... :-) Perhaps less efficient, but enough for small tasks. I found a similar library, JTopas. There is a good list of parser (generators or not) at Java Source. A: There are quite a number choices for stringhandling in java. Maybe the very basic java.util.Scanner and java.util.StringTokenizer Classes are helpfull for you? Another good choice is maybe the org.apache.commons.lang.text library. http://commons.apache.org/lang/apidocs/org/apache/commons/lang/text/package-summary.html
Is there a library similar to pyparsing in Java?
I need to quickly build a parser for a very simplified version of a html-like markup language in Java. In python, I would use pyparsing library to do this. Is there something similar for Java? Please, don't suggest libraries already out there for html parsing, my application is a school assignment which will demonstrate walking a tree of objects and serializing to text using visitor pattern, so I'm not thinking in real world terms here. Basically all I need here is tags, attributes and text nodes.
[ "Another good parser generator is ANTLR, that might be what you're looking for.\n", "May be overkill for your use, but javacc is an excellent industrial-strength parser generator. I've used this program/library several times, its reliable and worth learning, particularly if you are going to work with languages and compilers. Here's the description of the program from the website listed above:\n\nJava Compiler Compiler [tm] (JavaCC [tm]) is the most popular parser generator for use with Java [tm] applications. A parser generator is a tool that reads a grammar specification and converts it to a Java program that can recognize matches to the grammar. In addition to the parser generator itself, JavaCC provides other standard capabilities related to parser generation such as tree building (via a tool called JJTree included with JavaCC), actions, debugging, etc.\n\n", "A quick search for parser generators in Java yields JParsec. I've never used it - but it's inspired by a Haskell library, so by definition it must be good:-)\n", "I like JParsec (which I just discovered thanks to Torsten) because it doesn't generate code... :-) Perhaps less efficient, but enough for small tasks.\nI found a similar library, JTopas.\nThere is a good list of parser (generators or not) at Java Source.\n", "There are quite a number choices for stringhandling in java. \nMaybe the very basic java.util.Scanner and java.util.StringTokenizer Classes are helpfull for you?\nAnother good choice is maybe the org.apache.commons.lang.text library.\nhttp://commons.apache.org/lang/apidocs/org/apache/commons/lang/text/package-summary.html\n" ]
[ 8, 3, 3, 2, 1 ]
[]
[]
[ "java", "parsing", "pyparsing", "python" ]
stackoverflow_0000327569_java_parsing_pyparsing_python.txt
Q: wxpython: Updating a dict or other appropriate data type from wx.lib.sheet.CSheet object If I have a notebook with three spreadsheet widgets, what is the best way to have changes to the spreadsheet update a dictionary (or maybe an sqlite file?). Do all wx grid objects come with a built in dictionary related to the SetNumberRows and SetNumberCols? Basically I am looking for guidance on how to work with the user-input data from a spreadsheet widget, as in this example adapted from the tutorial on python.org: class ExSheet(wx.lib.sheet.CSheet): def __init__(self, parent): sheet.CSheet.__init__(self, parent) self.SetLabelBackgroundColour('#CCFF66') self.SetNumberRows(50) self.SetNumberCols(50) class Notebook(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM) self.sheet1 = ExSheet(nb) self.sheet2 = ExSheet(nb) self.sheet3 = ExSheet(nb) nb.AddPage(self.sheet1, "Sheet1") nb.AddPage(self.sheet2, "Sheet2") nb.AddPage(self.sheet3, "Sheet3") self.sheet1.SetFocus() self.StatusBar() A: Use a wxGrid with a wxGridTableBase instead Here is a simple example: import wx, wx.grid class GridData(wx.grid.PyGridTableBase): _cols = "a b c".split() _data = [ "1 2 3".split(), "4 5 6".split(), "7 8 9".split() ] def GetColLabelValue(self, col): return self._cols[col] def GetNumberRows(self): return len(self._data) def GetNumberCols(self): return len(self._cols) def GetValue(self, row, col): return self._data[row][col] def SetValue(self, row, col, val): self._data[row][col] = val class Test(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.data = GridData() grid = wx.grid.Grid(self) grid.SetTable(self.data) self.Bind(wx.EVT_CLOSE, self.OnClose) self.Show() def OnClose(self, event): print self.data._data event.Skip() app = wx.PySimpleApp() app.TopWindow = Test() app.MainLoop()
wxpython: Updating a dict or other appropriate data type from wx.lib.sheet.CSheet object
If I have a notebook with three spreadsheet widgets, what is the best way to have changes to the spreadsheet update a dictionary (or maybe an sqlite file?). Do all wx grid objects come with a built in dictionary related to the SetNumberRows and SetNumberCols? Basically I am looking for guidance on how to work with the user-input data from a spreadsheet widget, as in this example adapted from the tutorial on python.org: class ExSheet(wx.lib.sheet.CSheet): def __init__(self, parent): sheet.CSheet.__init__(self, parent) self.SetLabelBackgroundColour('#CCFF66') self.SetNumberRows(50) self.SetNumberCols(50) class Notebook(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM) self.sheet1 = ExSheet(nb) self.sheet2 = ExSheet(nb) self.sheet3 = ExSheet(nb) nb.AddPage(self.sheet1, "Sheet1") nb.AddPage(self.sheet2, "Sheet2") nb.AddPage(self.sheet3, "Sheet3") self.sheet1.SetFocus() self.StatusBar()
[ "Use a wxGrid with a wxGridTableBase instead\nHere is a simple example:\nimport wx, wx.grid\n\nclass GridData(wx.grid.PyGridTableBase):\n _cols = \"a b c\".split()\n _data = [\n \"1 2 3\".split(),\n \"4 5 6\".split(),\n \"7 8 9\".split()\n ]\n\n def GetColLabelValue(self, col):\n return self._cols[col]\n\n def GetNumberRows(self):\n return len(self._data)\n\n def GetNumberCols(self):\n return len(self._cols)\n\n def GetValue(self, row, col):\n return self._data[row][col]\n\n def SetValue(self, row, col, val):\n self._data[row][col] = val\n\nclass Test(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n self.data = GridData()\n grid = wx.grid.Grid(self)\n grid.SetTable(self.data)\n self.Bind(wx.EVT_CLOSE, self.OnClose)\n self.Show()\n\n def OnClose(self, event):\n print self.data._data\n event.Skip()\n\napp = wx.PySimpleApp()\napp.TopWindow = Test()\napp.MainLoop()\n\n" ]
[ 4 ]
[]
[]
[ "python", "spreadsheet", "wxpython", "wxwidgets" ]
stackoverflow_0000328003_python_spreadsheet_wxpython_wxwidgets.txt
Q: Scripting language choice for initial performance I have a small lightweight application that is used as part of a larger solution. Currently it is written in C but I am looking to rewrite it using a cross-platform scripting language. The solution needs to run on Windows, Linux, Solaris, AIX and HP-UX. The existing C application works fine but I want to have a single script I can maintain for all platforms. At the same time, I do not want to lose a lot of performance but am willing to lose some. Startup cost of the script is very important. This script can be called anywhere from every minute to many times per second. As a consequence, keeping it's memory and startup time low are important. So basically I'm looking for the best scripting languages that is: Cross platform. Capable of XML parsing and HTTP Posts. Low memory and low startup time. Possible choices include but are not limited to: bash/ksh + curl, Perl, Python and Ruby. What would you recommend for this type of a scenario? A: Lua is a scripting language that meets your criteria. It's certainly the fastest and lowest memory scripting language available. A: Because of your requirement for fast startup time and a calling frequency greater than 1Hz I'd recommend either staying with C and figuring out how to make it portable (not always as easy as a few ifdefs) or exploring the possibility of turning it into a service daemon that is always running. Of course this depends on how Python can have lower startup times if you compile the module and run the .pyc file, but it is still generally considered slow. Perl, in my experience, in the fastest of the scripting languages so you might have good luck with a perl daemon. You could also look at cross platform frameworks like gtk, wxWidgets and Qt. While they are targeted at GUIs they do have low level cross platform data types and network libraries that could make the job of using a fast C based application easier. A: "called anywhere from every minute to many times per second. As a consequence, keeping it's memory and startup time low are important." This doesn't sound like a script to me at all. This sounds like a server handling requests that arrive from every minute to several times a second. If it's a server, handling requests, start-up time doesn't mean as much as responsiveness. In which case, Python might work out well, and still keep performance up. Rather than restarting, you're just processing another request. You get to keep as much state as you need to optimize performance. A: When written properly, C should be platform independant and would only need a recompile for those different platforms. You might have to jump through some #ifdef hoops for the headers (not all systems use the same headers), but most normal (non-win32 API) calls are very portable. For web access (which I presume you need as you mention bash+curl), you could take a look at libcurl, it's available for all the platforms you mentioned, and shouldn't be that hard to work with. With execution time and memory cost in mind, I doubt you could go any faster than properly written C with any scripting language as you would lose at least some time on interpreting the script... A: I concur with Lua: it is super-portable, it has XML libraries, either native or by binding C libraries like Expat, it has a good socket library (LuaSocket) plus, for complex stuff, some cURL bindings, and is well known for being very lightweight (often embedded in low memory devices), very fast (one of the fastest scripting languages), and powerful. And very easy to code! It is coded in pure Ansi C, and lot of people claim it has one of the best C biding API (calling C routines from Lua, calling Lua code from C...). A: If Low memory and low startup time are truly important you might want to consider doing the work to keep the C code cross platform, however I have found this is rarely necessary. Personally I would use Ruby or Python for this type of job, they both make it very easy to make clear understandable code that others can maintain (or you can maintain after not looking at it for 6 months). If you have the control to do so I would also suggest getting the latest version of the interpreter, as both Ruby and Python have made notable improvements around performance recently. It is a bit of a personal thing. Programming Ruby makes me happy, C code does not (nor bash scripting for anything non-trivial). A: As others have suggested, daemonizing your script might be a good idea; that would reduce the startup time to virtually zero. Either have a small C wrapper that connects to your daemon and transmits the request back and forth, or have the daemon handle requests directly. It's not clear if this is intended to handle HTTP requests; if so, Perl has a good HTTP server module, bindings to several different C-based XML parsers, and blazing fast string support. (If you don't want to daemonize, it has a good, full-featured CGI module; if you have full control over the server it's running on, you could also use mod_perl to implement your script as an Apache handler.) Ruby's strings are a little slower, but there are some really good backgrounding tools available for it. I'm not as familiar with Python, I'm afraid, so I can't really make any recommendations about it. In general, though, I don't think you're as startup-time-constrained as you think you are. If the script is really being called several times a second, any decent interpreter on any decent operating system will be cached in memory, as will the source code of your script and its modules. Result: the startup times won't be as bad as you might think. Dagny:~ brent$ time perl -MCGI -e0 real 0m0.610s user 0m0.036s sys 0m0.022s Dagny:~ brent$ time perl -MCGI -e0 real 0m0.026s user 0m0.020s sys 0m0.006s (The parameters to the Perl interpreter load the rather large CGI module and then execute the line of code '0;'.) A: Python is good. I would also check out The Computer Languages Benchmarks Game website: http://shootout.alioth.debian.org/ It might be worth spending a bit of time understanding the benchmarks (including numbers for startup times and memory usage). Lots of languages are compared such as Perl, Python, Lua and Ruby. You can also compare these languages against benchmarks in C. A: I agree with others in that you should probably try to make this a more portable C app instead of porting it over to something else since any scripting language is going to introduce significant overhead from a startup perspective, have a much larger memory footprint, and will probably be much slower. In my experience, Python is the most efficient of the three, followed by Perl and then Ruby with the difference between Perl and Ruby being particularly large in certain areas. If you really want to try porting this to a scripting language, I would put together a prototype in the language you are most comfortable with and see if it comes close to your requirements. If you don't have a preference, start with Python as it is easy to learn and use and if it is too slow with Python, Perl and Ruby probably won't be able to do any better. A: Remember that if you choose Python, you can also extend it in C if the performance isn't great. Heck, you could probably even use some of the code you have right now. Just recompile it and wrap it using pyrex. You can also do this fairly easily in Ruby, and in Perl (albeit with some more difficulty). Don't ask me about ways to do this though. A: Can you instead have it be a long-running process and answer http or rpc requests? This would satisfy the latency requirements in almost any scenario, but I don't know if that would break your memory footprint constraints. A: At first sight, it's sounds like over engineering, as a rule of thumb I suggest fixing only when things are broken. You have an already working application. Apparently you want to want to call the feature provided from few more several sources. It looks like the description of a service to me (maybe easier to maintain). Finally you also mentioned that this is part of a larger solution, then you may want to reuse the language, facilities of the larger solutions. From the description you gave (xml+http) it seems quite an usual application that can be written in any generalist language (maybe a web container in java?). Some libraries can help you to make your code portable: Boost, Qt more details may trigger more ideas :) A: Port your app to Ruby. If your app is too slow, profile it and rewrite the those parts in C.
Scripting language choice for initial performance
I have a small lightweight application that is used as part of a larger solution. Currently it is written in C but I am looking to rewrite it using a cross-platform scripting language. The solution needs to run on Windows, Linux, Solaris, AIX and HP-UX. The existing C application works fine but I want to have a single script I can maintain for all platforms. At the same time, I do not want to lose a lot of performance but am willing to lose some. Startup cost of the script is very important. This script can be called anywhere from every minute to many times per second. As a consequence, keeping it's memory and startup time low are important. So basically I'm looking for the best scripting languages that is: Cross platform. Capable of XML parsing and HTTP Posts. Low memory and low startup time. Possible choices include but are not limited to: bash/ksh + curl, Perl, Python and Ruby. What would you recommend for this type of a scenario?
[ "Lua is a scripting language that meets your criteria. It's certainly the fastest and lowest memory scripting language available.\n", "Because of your requirement for fast startup time and a calling frequency greater than 1Hz I'd recommend either staying with C and figuring out how to make it portable (not always as easy as a few ifdefs) or exploring the possibility of turning it into a service daemon that is always running. Of course this depends on how \nPython can have lower startup times if you compile the module and run the .pyc file, but it is still generally considered slow. Perl, in my experience, in the fastest of the scripting languages so you might have good luck with a perl daemon.\nYou could also look at cross platform frameworks like gtk, wxWidgets and Qt. While they are targeted at GUIs they do have low level cross platform data types and network libraries that could make the job of using a fast C based application easier.\n", "\"called anywhere from every minute to many times per second. As a consequence, keeping it's memory and startup time low are important.\"\nThis doesn't sound like a script to me at all.\nThis sounds like a server handling requests that arrive from every minute to several times a second.\nIf it's a server, handling requests, start-up time doesn't mean as much as responsiveness. In which case, Python might work out well, and still keep performance up.\nRather than restarting, you're just processing another request. You get to keep as much state as you need to optimize performance.\n", "When written properly, C should be platform independant and would only need a recompile for those different platforms. You might have to jump through some #ifdef hoops for the headers (not all systems use the same headers), but most normal (non-win32 API) calls are very portable.\nFor web access (which I presume you need as you mention bash+curl), you could take a look at libcurl, it's available for all the platforms you mentioned, and shouldn't be that hard to work with.\nWith execution time and memory cost in mind, I doubt you could go any faster than properly written C with any scripting language as you would lose at least some time on interpreting the script...\n", "I concur with Lua: it is super-portable, it has XML libraries, either native or by binding C libraries like Expat, it has a good socket library (LuaSocket) plus, for complex stuff, some cURL bindings, and is well known for being very lightweight (often embedded in low memory devices), very fast (one of the fastest scripting languages), and powerful. And very easy to code!\nIt is coded in pure Ansi C, and lot of people claim it has one of the best C biding API (calling C routines from Lua, calling Lua code from C...).\n", "If Low memory and low startup time are truly important you might want to consider doing the work to keep the C code cross platform, however I have found this is rarely necessary.\nPersonally I would use Ruby or Python for this type of job, they both make it very easy to make clear understandable code that others can maintain (or you can maintain after not looking at it for 6 months). If you have the control to do so I would also suggest getting the latest version of the interpreter, as both Ruby and Python have made notable improvements around performance recently.\nIt is a bit of a personal thing. Programming Ruby makes me happy, C code does not (nor bash scripting for anything non-trivial).\n", "As others have suggested, daemonizing your script might be a good idea; that would reduce the startup time to virtually zero. Either have a small C wrapper that connects to your daemon and transmits the request back and forth, or have the daemon handle requests directly.\nIt's not clear if this is intended to handle HTTP requests; if so, Perl has a good HTTP server module, bindings to several different C-based XML parsers, and blazing fast string support. (If you don't want to daemonize, it has a good, full-featured CGI module; if you have full control over the server it's running on, you could also use mod_perl to implement your script as an Apache handler.) Ruby's strings are a little slower, but there are some really good backgrounding tools available for it. I'm not as familiar with Python, I'm afraid, so I can't really make any recommendations about it.\nIn general, though, I don't think you're as startup-time-constrained as you think you are. If the script is really being called several times a second, any decent interpreter on any decent operating system will be cached in memory, as will the source code of your script and its modules. Result: the startup times won't be as bad as you might think.\nDagny:~ brent$ time perl -MCGI -e0\n\nreal 0m0.610s\nuser 0m0.036s\nsys 0m0.022s\nDagny:~ brent$ time perl -MCGI -e0\n\nreal 0m0.026s\nuser 0m0.020s\nsys 0m0.006s\n\n(The parameters to the Perl interpreter load the rather large CGI module and then execute the line of code '0;'.)\n", "Python is good. I would also check out The Computer Languages Benchmarks Game website:\nhttp://shootout.alioth.debian.org/\nIt might be worth spending a bit of time understanding the benchmarks (including numbers for startup times and memory usage). Lots of languages are compared such as Perl, Python, Lua and Ruby. You can also compare these languages against benchmarks in C.\n", "I agree with others in that you should probably try to make this a more portable C app instead of porting it over to something else since any scripting language is going to introduce significant overhead from a startup perspective, have a much larger memory footprint, and will probably be much slower.\nIn my experience, Python is the most efficient of the three, followed by Perl and then Ruby with the difference between Perl and Ruby being particularly large in certain areas. If you really want to try porting this to a scripting language, I would put together a prototype in the language you are most comfortable with and see if it comes close to your requirements. If you don't have a preference, start with Python as it is easy to learn and use and if it is too slow with Python, Perl and Ruby probably won't be able to do any better.\n", "Remember that if you choose Python, you can also extend it in C if the performance isn't great. Heck, you could probably even use some of the code you have right now. Just recompile it and wrap it using pyrex.\nYou can also do this fairly easily in Ruby, and in Perl (albeit with some more difficulty). Don't ask me about ways to do this though.\n", "Can you instead have it be a long-running process and answer http or rpc requests?\nThis would satisfy the latency requirements in almost any scenario, but I don't know if that would break your memory footprint constraints.\n", "At first sight, it's sounds like over engineering, as a rule of thumb I suggest fixing only when things are broken.\nYou have an already working application. Apparently you want to want to call the feature provided from few more several sources. It looks like the description of a service to me (maybe easier to maintain). \nFinally you also mentioned that this is part of a larger solution, then you may want to reuse the language, facilities of the larger solutions. From the description you gave (xml+http) it seems quite an usual application that can be written in any generalist language (maybe a web container in java?).\nSome libraries can help you to make your code portable:\nBoost, \nQt\nmore details may trigger more ideas :) \n", "Port your app to Ruby. If your app is too slow, profile it and rewrite the those parts in C.\n" ]
[ 23, 9, 6, 5, 4, 3, 3, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "bash", "perl", "python", "ruby", "scripting_language" ]
stackoverflow_0000328041_bash_perl_python_ruby_scripting_language.txt
Q: storing unbound python functions in a class object I'm trying to do the following in python: In a file called foo.py: # simple function that does something: def myFunction(a,b,c): print "call to myFunction:",a,b,c # class used to store some data: class data: fn = None # assign function to the class for storage. data.fn = myFunction And then in a file called bar.py: import foo d = foo.data d.fn(1,2,3) However, I get the following error: TypeError: unbound method f() must be called with data instance as first argument (got int instance instead) This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition. So the question is: How can I store a function in a class object without the function becoming bound to that class? A: data.fn = staticmethod(myFunction) should do the trick. A: What you can do is: d = foo.data() d.fn = myFunction d.fn(1,2,3) Which may not be exactly what you want, but does work. A: Thanks to Andre for the answer - so simple! For those of you who care, perhaps I should have included the entire context of the problem. Here it is anyway: In my application, users are able to write plugins in python. They must define a function with a well-defined parameter list, but I didn't want to impose any naming conventions on them. So, as long as users write a function with the correct number of parameters and types, all they have to do is something like this (remember, this is the plugin code): # this is my custom code - all plugins are called with a modified sys.path, so this # imports some magic python code that defines the functions used below. from specialPluginHelperModule import * # define the function that does all the work in this plugin: def mySpecialFn(paramA, paramB, paramC): # do some work here with the parameters above: pass # set the above function: setPluginFunction(mySpecialFn) The call to setPluginFunction takes the function object and sets it in a hidden class object (along with other plugin-configuration related stuff, this example has been simplified somewhat). When the main application wants to run the function, I use the runpy module to run the plugin code, and then extract the class object mentioned above - this gives me the configuration data and the plugin function so I can run it cleanly (without polluting my namespace). This entire process is repeated multiple times for different plugins over the same input, and seems to work very well for me.
storing unbound python functions in a class object
I'm trying to do the following in python: In a file called foo.py: # simple function that does something: def myFunction(a,b,c): print "call to myFunction:",a,b,c # class used to store some data: class data: fn = None # assign function to the class for storage. data.fn = myFunction And then in a file called bar.py: import foo d = foo.data d.fn(1,2,3) However, I get the following error: TypeError: unbound method f() must be called with data instance as first argument (got int instance instead) This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition. So the question is: How can I store a function in a class object without the function becoming bound to that class?
[ "data.fn = staticmethod(myFunction)\n\nshould do the trick.\n", "What you can do is:\nd = foo.data()\nd.fn = myFunction\n\nd.fn(1,2,3)\n\nWhich may not be exactly what you want, but does work.\n", "Thanks to Andre for the answer - so simple!\nFor those of you who care, perhaps I should have included the entire context of the problem. Here it is anyway:\nIn my application, users are able to write plugins in python. They must define a function with a well-defined parameter list, but I didn't want to impose any naming conventions on them.\nSo, as long as users write a function with the correct number of parameters and types, all they have to do is something like this (remember, this is the plugin code):\n# this is my custom code - all plugins are called with a modified sys.path, so this\n# imports some magic python code that defines the functions used below.\nfrom specialPluginHelperModule import *\n\n# define the function that does all the work in this plugin:\ndef mySpecialFn(paramA, paramB, paramC):\n # do some work here with the parameters above:\n pass\n\n# set the above function:\nsetPluginFunction(mySpecialFn)\n\nThe call to setPluginFunction takes the function object and sets it in a hidden class object (along with other plugin-configuration related stuff, this example has been simplified somewhat). When the main application wants to run the function, I use the runpy module to run the plugin code, and then extract the class object mentioned above - this gives me the configuration data and the plugin function so I can run it cleanly (without polluting my namespace).\nThis entire process is repeated multiple times for different plugins over the same input, and seems to work very well for me.\n" ]
[ 27, 1, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0000327483_function_python.txt
Q: Monitoring a displays state in python? How can I tell when Windows is changing a monitors power state? A: It seems that, when Windows wants to start the screen saver or turn the monitor off, it will send a WM_SYSCOMMAND to the topmost window with a wParam of SC_SCREENSAVE (to start the screen saver) or a wParam of SC_MONITORPOWER and a lParam of 1 or 2 (to turn the monitor off). This message will then be passed to DefWindowProc, which will actually do the action. So, if your window happens to be the topmost one, you can intercept these events and ignore them (or do anything else you want before passing them to DefWindowProc). On Windows Vista, there seems to be a more intuitive, and more reliable, way to know the monitor power state. You call RegisterPowerSettingNotification to tell the system to send your window a WM_POWERBROADCAST message with a wParam of PBT_POWERSETTINGCHANGE and a lParam pointing to a POWERBROADCAST_SETTING structure. I cannot test either of them since I currently do not have any computer with Windows nearby. I hope, however, they point you in the right direction. References: The Old New Thing : Fumbling around in the dark and stumbling across the wrong solution Recursive hook ... - borland.public.delphi.nativeapi.win32 | Google Groups Registering for Power Events (Windows)
Monitoring a displays state in python?
How can I tell when Windows is changing a monitors power state?
[ "It seems that, when Windows wants to start the screen saver or turn the monitor off, it will send a WM_SYSCOMMAND to the topmost window with a wParam of SC_SCREENSAVE (to start the screen saver) or a wParam of SC_MONITORPOWER and a lParam of 1 or 2 (to turn the monitor off). This message will then be passed to DefWindowProc, which will actually do the action. So, if your window happens to be the topmost one, you can intercept these events and ignore them (or do anything else you want before passing them to DefWindowProc).\nOn Windows Vista, there seems to be a more intuitive, and more reliable, way to know the monitor power state. You call RegisterPowerSettingNotification to tell the system to send your window a WM_POWERBROADCAST message with a wParam of PBT_POWERSETTINGCHANGE and a lParam pointing to a POWERBROADCAST_SETTING structure.\nI cannot test either of them since I currently do not have any computer with Windows nearby. I hope, however, they point you in the right direction.\nReferences:\n\nThe Old New Thing : Fumbling around in the dark and stumbling across the wrong solution\nRecursive hook ... - borland.public.delphi.nativeapi.win32 | Google Groups\nRegistering for Power Events (Windows)\n\n" ]
[ 7 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0000328490_python_winapi.txt
Q: python curses.ascii depending on locale? The curses.ascii module has some nice functions defined, that allow for example to recognize which characters are printable (curses.ascii.isprint(ch)). But, diffrent character codes can be printable depending on which locale setting is being used. For example, there are certain polish characters: >>> ord('a') 97 >>> ord('ą') 177 >>> I'm wondering, is there a better way to tell if a number represents printable character then the one used in curses.ascii module: def isprint(c): return _ctoi(c) >= 32 and _ctoi(c) <= 126 which is kind of locale-unfriendly. A: If you convert the character to a unicode then you can use unicodedata: >>> unicodedata.category(u'ą')[0] in 'LNPS' True A: Well, it is called curses.ascii, so using ASCII rules for what's printable should not be a surprise. If you are using an ISO 8-bit code, or you are operating from a known code page, you will need rules that correspond to what the actual codes and their displays are. I think using unicode characters and standard Unicode classifications is fine. That just might not deal with what the curses and console arrangement are actually going to display properly. There also needs to be some consideration for what is acceptable and unacceptable for the application, even if displayable.
python curses.ascii depending on locale?
The curses.ascii module has some nice functions defined, that allow for example to recognize which characters are printable (curses.ascii.isprint(ch)). But, diffrent character codes can be printable depending on which locale setting is being used. For example, there are certain polish characters: >>> ord('a') 97 >>> ord('ą') 177 >>> I'm wondering, is there a better way to tell if a number represents printable character then the one used in curses.ascii module: def isprint(c): return _ctoi(c) >= 32 and _ctoi(c) <= 126 which is kind of locale-unfriendly.
[ "If you convert the character to a unicode then you can use unicodedata:\n>>> unicodedata.category(u'ą')[0] in 'LNPS'\nTrue\n\n", "Well, it is called curses.ascii, so using ASCII rules for what's printable should not be a surprise. If you are using an ISO 8-bit code, or you are operating from a known code page, you will need rules that correspond to what the actual codes and their displays are.\nI think using unicode characters and standard Unicode classifications is fine. That just might not deal with what the curses and console arrangement are actually going to display properly. \nThere also needs to be some consideration for what is acceptable and unacceptable for the application, even if displayable.\n" ]
[ 4, 2 ]
[]
[]
[ "locale", "ncurses", "python" ]
stackoverflow_0000328793_locale_ncurses_python.txt
Q: In Python, is there a concise way to use a list comprehension with multiple iterators? Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following Haskell code: [(i,j) | i <- [1,2], j <- [1..4]] which yields [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] Can I obtain a similar behavior in Python in a concise way? A: Are you asking about this? [ (i,j) for i in range(1,3) for j in range(1,5) ] A: Cartesian product is in the itertools module (in 2.6). >>> import itertools >>> list(itertools.product(range(1, 3), range(1, 5))) [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)] A: Fun fact about the nested comprehension: it mimics nested "for" loops, so the inner ones can use values from outer ones. This isn't useful in the cartesian product case, but good to know. For example: [ (i,j) for i in range(10) for j in range(i) ] generates all pairs (i,j) where 0>=i>j>10. A: This seems to do what you describe: [[a,b] for a in range(1,3) for b in range(1,5)] UPDATE: Drat! Should have reloaded the page to see S.Lott's answer before posting. Hmmm... what to do for a little value-add? Perhaps a short testimony to the usefulness of interactive mode with Python. I come most recently from a background with Perl so with issues like this I find it very helpful to type "python" at the command line and drop into interactive mode and just a)start trying things, and b)refine the niceties by hitting up-arrow and adjusting my previous attempt until I get what I want. Any time I'm hazy on some keyword, help is at hand. Just type: help("some_keyword"), read the brief summary, then hit "Q" and I'm back on line in direct conversation with the python interpreter. Recommended if you are a beginner and not using it.
In Python, is there a concise way to use a list comprehension with multiple iterators?
Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following Haskell code: [(i,j) | i <- [1,2], j <- [1..4]] which yields [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] Can I obtain a similar behavior in Python in a concise way?
[ "Are you asking about this?\n[ (i,j) for i in range(1,3) for j in range(1,5) ]\n\n", "Cartesian product is in the itertools module (in 2.6).\n>>> import itertools\n>>> list(itertools.product(range(1, 3), range(1, 5)))\n[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)]\n\n", "Fun fact about the nested comprehension: it mimics nested \"for\" loops, so the inner ones can use values from outer ones. This isn't useful in the cartesian product case, but good to know. For example:\n[ (i,j) for i in range(10) for j in range(i) ] \n\ngenerates all pairs (i,j) where 0>=i>j>10.\n", "This seems to do what you describe:\n[[a,b] for a in range(1,3) for b in range(1,5)]\nUPDATE: Drat! Should have reloaded the page to see S.Lott's answer before posting. Hmmm... what to do for a little value-add? Perhaps a short testimony to the usefulness of interactive mode with Python. \nI come most recently from a background with Perl so with issues like this I find it very helpful to type \"python\" at the command line and drop into interactive mode and just a)start trying things, and b)refine the niceties by hitting up-arrow and adjusting my previous attempt until I get what I want. Any time I'm hazy on some keyword, help is at hand. Just type: help(\"some_keyword\"), read the brief summary, then hit \"Q\" and I'm back on line in direct conversation with the python interpreter. \nRecommended if you are a beginner and not using it.\n" ]
[ 21, 8, 5, 2 ]
[]
[]
[ "iterator", "list_comprehension", "python" ]
stackoverflow_0000329886_iterator_list_comprehension_python.txt