content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: apache + mod_wsgi + aspell-python on OS X 10.5.8 I have a website that processes user submitted documents in a variety of ways, one of which is to do a spell check on a part of each document. When I set this website up on a Mac Mini (yes, I realize that's a pretty weak piece of equipment for a website, but it's i...
apache + mod_wsgi + aspell-python on OS X 10.5.8
I have a website that processes user submitted documents in a variety of ways, one of which is to do a spell check on a part of each document. When I set this website up on a Mac Mini (yes, I realize that's a pretty weak piece of equipment for a website, but it's internal and no one outside the office sees it), I reme...
[ "If your upgrade was only from one patch revision of 10.5 to later patch revision of 10.5, then you shouldn't have seen any change in behaviour in respect of requirement for 32 bit vs 64 bit. If it broke now, it should have broke before as it has always behave same for 10.5 and didn't change in a patch revision.\nT...
[ 1 ]
[]
[]
[ "apache", "aspell", "django", "mod_wsgi", "python" ]
stackoverflow_0001925425_apache_aspell_django_mod_wsgi_python.txt
Q: How can I do python/ruby/javascript style generators in actionscript? I want to use coroutines in actionscript to implement a state machine. I'd like to be able to do something like the following function stateMachine():void { sendBytes(0xFFFF); var receiveBytes:ByteArray = yield() sendBytes(receiveBytes)...
How can I do python/ruby/javascript style generators in actionscript?
I want to use coroutines in actionscript to implement a state machine. I'd like to be able to do something like the following function stateMachine():void { sendBytes(0xFFFF); var receiveBytes:ByteArray = yield() sendBytes(receiveBytes); } stateMachine.send( Socket.read() ) like in this blog entry
[ "As far as I know, Actionscript doesn't have coroutines, continuations or anything that will give you the relevant behavior (call a function without pushing a stack frame). You can fake it using static variables and a switch, but that defeats the purpose of using coroutines for state machines. Also, without tail ca...
[ 2, 1 ]
[]
[]
[ "actionscript", "coroutine", "generator", "python" ]
stackoverflow_0001918817_actionscript_coroutine_generator_python.txt
Q: Handling an exception in another thread What is the "correct" way of detecting and handling an exception in another thread in Python, when the code in that other thread is not under your control? For instance, say you set a function that requires 2 parameters as the target of the threading.Thread object, but at ru...
Handling an exception in another thread
What is the "correct" way of detecting and handling an exception in another thread in Python, when the code in that other thread is not under your control? For instance, say you set a function that requires 2 parameters as the target of the threading.Thread object, but at runtime attempt to pass it 3. The Thread module...
[ "I think you can only decorate your target function or subclass threading.Thread to take care of exceptions. \ndef safer( func ):\n def safer(*args,**kwargs):\n try:\n return func(*args,**kwargs)\n except Exception,e:\n print \"Couldn't call\", func\n # do_stuff( e ...
[ 3 ]
[]
[]
[ "exception", "multithreading", "python" ]
stackoverflow_0001925635_exception_multithreading_python.txt
Q: Python programming on Eclipse with Pydev I need major help getting started! I managed to create a new project, and add python.exe as the interpreter. But when the project is created it's blank. How do I start programming? Ugh. A: Create PyDev project Add "Source Folder" under the project Add "Modules" to the "So...
Python programming on Eclipse with Pydev
I need major help getting started! I managed to create a new project, and add python.exe as the interpreter. But when the project is created it's blank. How do I start programming? Ugh.
[ "\nCreate PyDev project\nAdd \"Source Folder\" under the project\nAdd \"Modules\" to the \"Source Folder\"\nGet coding :-)\n\n", "Open a new text file and start writing code?\n", "You need to make sure you create a Pydev project. If you don't already have a Python interpreter installed, you'll need to get one (...
[ 4, 2, 1 ]
[]
[]
[ "eclipse", "ide", "pydev", "python" ]
stackoverflow_0001925750_eclipse_ide_pydev_python.txt
Q: Read a formatted date in Python 2.3? I had never worked with the datetime module in Python 2.3, and I have a very silly problem. I need to read a date in the format '10-JUL-2010' then subtract a day (I would use timedelta), and return the string '09-JUL-2010 00:00:00 ET' of course, this is for hundreds of date...
Read a formatted date in Python 2.3?
I had never worked with the datetime module in Python 2.3, and I have a very silly problem. I need to read a date in the format '10-JUL-2010' then subtract a day (I would use timedelta), and return the string '09-JUL-2010 00:00:00 ET' of course, this is for hundreds of dates. While it should be trivial, I cannot fi...
[ "You're looking for datetime.datetime.strptime(), but the documentation is awful for that function, it's effectively the reverse operation of datetime.datetime.strftime().\nThe format string you're looking for is: '%d-%b-%Y'\nSee: http://www.python.org/doc/2.3.5/lib/node211.html and http://www.python.org/doc/2.3.5/...
[ 3, 2, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0001925678_datetime_python.txt
Q: Eclipse (with Pydev) keeps throwing SyntaxError My code: print "Hello World!" I even tried adding a semicolon behind, but everytime I save and run (as Python run) it says: File "E:\Software\Eclipse\Workspace\Python1\src\main.py", line 1 print "Hello World!"; SyntaxError: invalid syntax I have no idea why. A: ...
Eclipse (with Pydev) keeps throwing SyntaxError
My code: print "Hello World!" I even tried adding a semicolon behind, but everytime I save and run (as Python run) it says: File "E:\Software\Eclipse\Workspace\Python1\src\main.py", line 1 print "Hello World!"; SyntaxError: invalid syntax I have no idea why.
[ "What version of Python are you using? Python 2.X has print as a keyword, but Python 3.X only has print() as a function - you'd need to use print(\"Hello, World!\") instead.\n", "This is kind of a longshot but - if you're running python 3.0 that is invalid syntax. Try \nprint(\"Hello World!\") \n\nto see if this...
[ 35, 4, 1 ]
[]
[]
[ "eclipse", "pydev", "python", "syntax" ]
stackoverflow_0001925852_eclipse_pydev_python_syntax.txt
Q: Specifying chars in python I need a functions that iterates over all the lines in the file. Here's what I have so far: def LineFeed(file): ret = "" for byte in file: ret = ret + str(byte) if str(byte) == '\r': yield ret ret = "" All the lines in the file end with \...
Specifying chars in python
I need a functions that iterates over all the lines in the file. Here's what I have so far: def LineFeed(file): ret = "" for byte in file: ret = ret + str(byte) if str(byte) == '\r': yield ret ret = "" All the lines in the file end with \r (not \n), and I'm reading it i...
[ "I think that you are confused with what \"for x in file\" does. Assuming you got your handle like \"file = open(file_name)\", byte in this case will be an entire line, not a single character. So you are only calling yield when the entire line consists of a single carriage return. Try changing \"byte\" to \"line...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "binaryfiles", "python" ]
stackoverflow_0001925043_binaryfiles_python.txt
Q: this python script can be shortened/optimized, how? I'm not used to doing things the python way yet, but I'm almost certain the following script can be condensed. I'm not looking for speed optimization here, I'm looking for more readable code. Make it slower for all I care, but what are some ways to make this look...
this python script can be shortened/optimized, how?
I'm not used to doing things the python way yet, but I'm almost certain the following script can be condensed. I'm not looking for speed optimization here, I'm looking for more readable code. Make it slower for all I care, but what are some ways to make this look more Python-esque. I'm simply reading in a csv file fill...
[ "This part:\nmultis = '%s, '*23\nmultis = multis[:-2]\n\nshould be\nmultis = ', '.join(['%s'] * 23)\n\nziplist is not used, so you can just remove the line that sets it.\n (row[0], row[1], row[2], row[3], row[4], row[5], row[6],\n row[7], row[8], row[9], row[10], row[11], row[12],\n ...
[ 7, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001925999_python.txt
Q: How to get the LAN IP that a socket is sending (linux) I need some code to get the address of the socket i just created (to filter out packets originating from localhost on a multicast network) this: socket.gethostbyname(socket.gethostname()) works on mac but it returns only the localhost IP in linux... is there a...
How to get the LAN IP that a socket is sending (linux)
I need some code to get the address of the socket i just created (to filter out packets originating from localhost on a multicast network) this: socket.gethostbyname(socket.gethostname()) works on mac but it returns only the localhost IP in linux... is there anyway to get the LAN address thanks --edit-- is it possible ...
[ "Looks like you're looking for the getsockname method of socket objects.\n", "quick answer - socket.getpeername() (provided that socket is a socket object, not a module)\n(playing around in python/ipython/idle/... interactive shell is very helpful)\n.. or if I read you question carefully, maybe socket.getsockname...
[ 1, 0 ]
[]
[]
[ "ip_address", "python", "sockets" ]
stackoverflow_0001925974_ip_address_python_sockets.txt
Q: Transitioning from desktop app written in C++ to a web-based app We have a mature Windows desktop application written in C++. The application's GUI sits on top of a windows DLL that does most of the work for the GUI (it's kind of the engine). It, too, is written in C++. We are considering transitioning the Wind...
Transitioning from desktop app written in C++ to a web-based app
We have a mature Windows desktop application written in C++. The application's GUI sits on top of a windows DLL that does most of the work for the GUI (it's kind of the engine). It, too, is written in C++. We are considering transitioning the Windows app to be a web-based app for various reasons. What I would like ...
[ "\nSee also Can a huge existing\n application be ported to the web?\n How?\n\nSorry there are no good solutions, just less bad ones....\nFirstly as you already develop for windows I am assuming that you are used to using the Microsoft development tools, I would not give the same answer for a desktop application t...
[ 10, 4, 2, 1 ]
[]
[]
[ "c#", "c++", "dll", "python", "web_based" ]
stackoverflow_0001900868_c#_c++_dll_python_web_based.txt
Q: Python programming general questions I heard that Python is easy and powerful, but I don't know if I'm on the right track to learn it. I learn from online tutorials, I know basic maths calculation and printing strings, but how long will it take to develop something useful? I don't really know the exact uses of Pyt...
Python programming general questions
I heard that Python is easy and powerful, but I don't know if I'm on the right track to learn it. I learn from online tutorials, I know basic maths calculation and printing strings, but how long will it take to develop something useful? I don't really know the exact uses of Python, though.
[ "I'm not exactly sure what you're looking for, but I think one or more of the following may be the next step you're looking for. \nPerhaps you would like to use a variety of different protocols for a networking program, you could check out Twisted. \nOr perhaps if you would like to make a web application or blog ...
[ 8, 4, 3, 3, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001926019_python.txt
Q: How should I perform cleanup at the end of a repoze.bfg response? Example code for the repoze.bfg web framework performs post-response cleanup by adding a __del__ method to an object attached to the request's environ. Is there a better way to clean up database connections, etc. after the response has been complete...
How should I perform cleanup at the end of a repoze.bfg response?
Example code for the repoze.bfg web framework performs post-response cleanup by adding a __del__ method to an object attached to the request's environ. Is there a better way to clean up database connections, etc. after the response has been completely sent to the client?
[ "Since you are dealing with repoze.bfg, best you use their documented way of doing things as it is going to be compatible with their framework and how they manage the request lifecycle. That said, if you want the generic WSGI way of doing it, it is documented in:\nhttp://code.google.com/p/modwsgi/wiki/RegisteringCl...
[ 1 ]
[]
[]
[ "python", "repoze.bfg", "wsgi" ]
stackoverflow_0001926169_python_repoze.bfg_wsgi.txt
Q: python import a method that depends on a imported class So if I have 2 files that look like this: File 1 import class1 import method1 def method2(something): result = method1(classname=class1) File 2 def method1(classname): some_result = classname.resultfinder return some_result Will this work? I me...
python import a method that depends on a imported class
So if I have 2 files that look like this: File 1 import class1 import method1 def method2(something): result = method1(classname=class1) File 2 def method1(classname): some_result = classname.resultfinder return some_result Will this work? I mean, since I am not importing class1 in the file where method1...
[ "What happened when you tried it?\nNote that your import of method1 is wrong. Apart from that --- yes, you do not need to import everything. Do you think the standard library imports your stuff whenever you use it? ;-)\n", "I think that should be fine - imagine having to import every possible type that could be p...
[ 2, 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0001924906_import_python.txt
Q: How do I parse a string representing a nested list into an actual list? Say I have a string representing some nested lists and I want to convert it into the real thing. I could do this, I think: exec "myList = ['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']" But in an environment where users might be supply...
How do I parse a string representing a nested list into an actual list?
Say I have a string representing some nested lists and I want to convert it into the real thing. I could do this, I think: exec "myList = ['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']" But in an environment where users might be supplying the string to execute this could/would be a bad idea. Does anybody have a...
[ ">>> import ast\n>>> mylist = ast.literal_eval(\"['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']\")\n>>> mylist\n['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']\n\nast.literal_eval:\n\nSafely evaluate an expression node or\n a string containing a Python\n expression. The string or node\n provided may...
[ 29 ]
[]
[]
[ "exec", "nested_lists", "parsing", "python", "string" ]
stackoverflow_0001926741_exec_nested_lists_parsing_python_string.txt
Q: Searching a file This is in reference to a question I posted yesterday Searching a file in 3 different ways I just require help now on two things, searching a file and and printing the line a search result is found on and all the lines after it to the end of the file. Lastly i need help on coding were i search a f...
Searching a file
This is in reference to a question I posted yesterday Searching a file in 3 different ways I just require help now on two things, searching a file and and printing the line a search result is found on and all the lines after it to the end of the file. Lastly i need help on coding were i search a file and print the line...
[ "for the first part\nfor line in open(\"file\"):\n line=line.rstrip()\n if \"search\" in line:\n f=1\n if f: print line\n\nfor the second part\ncontext=3\nsearch=\"myword\"\nf=open(\"file\")\nd={}\nfor n,line in enumerate(f):\n d[n%context]=line.rstrip()\n if search in line:\n for i in ...
[ 2 ]
[]
[]
[ "file", "python", "search" ]
stackoverflow_0001927276_file_python_search.txt
Q: Python script running in linux I am having trouble trying to get this script to work. When I debug this code it will not read into the class or functions. The code will not execute properly. Has anyone know the problem here, Thanks #!/home/build/test/Python-2.6.4 import os, subprocess class mks_function: sandb...
Python script running in linux
I am having trouble trying to get this script to work. When I debug this code it will not read into the class or functions. The code will not execute properly. Has anyone know the problem here, Thanks #!/home/build/test/Python-2.6.4 import os, subprocess class mks_function: sandbox="new_sandbox" def mks_create_sa...
[ "Few things to check your code\n\ncall should be subprocess.call\nbetter use full path when you call for example, /usr/bin/si createsandbox, you can check with which si in shell\ninstead of concatenating the commands \"si createsandbox\" + \"--no ...\", please use list [\"/usr/bin/si\",\"createsandbox --no ...\"]\n...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001927375_python.txt
Q: XML-RPC method parameter data typing in Python I have built an XML-RPC interface in Python and I need to enforce some stricter typing. For example, passing string '10' instead of int 10. I can clean this up with some type casting and a little exception handling, but I am wondering if there is any other way of fo...
XML-RPC method parameter data typing in Python
I have built an XML-RPC interface in Python and I need to enforce some stricter typing. For example, passing string '10' instead of int 10. I can clean this up with some type casting and a little exception handling, but I am wondering if there is any other way of forcing type integrity such as something XML-RPC speci...
[ "It's always going to be converted to a string anyway, so why do you care what's being passed in? If you use \"%s\" % number or even just str(number), then it doesn't matter whether number is a string or an int.\n", "XML-RPC methods (at least in xmlrpclib) are dispatched to Python functions or method, so you have...
[ 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001925487_django_python.txt
Q: strategies for finding duplicate mailing addresses I'm trying to come up with a method of finding duplicate addresses, based on a similarity score. Consider these duplicate addresses: addr_1 = '# 3 FAIRMONT LINK SOUTH' addr_2 = '3 FAIRMONT LINK S' addr_3 = '5703 - 48TH AVE' adrr_4 = '5703- 48 AVENUE' I'm plannin...
strategies for finding duplicate mailing addresses
I'm trying to come up with a method of finding duplicate addresses, based on a similarity score. Consider these duplicate addresses: addr_1 = '# 3 FAIRMONT LINK SOUTH' addr_2 = '3 FAIRMONT LINK S' addr_3 = '5703 - 48TH AVE' adrr_4 = '5703- 48 AVENUE' I'm planning on applying some string transformation to make long wo...
[ "Removing spaces, commas and dashes will be ambiguous . It will be better to replace them with a single space.\nTake for example this address\n56 5th avenue\n\nAnd this\n5, 65th avenue\n\nwith your method both of them will be:\n565THAV\n\nWhat you can do is write a good address shortening algorithm and then use str...
[ 2, 2, 2, 1, 1, 0 ]
[]
[]
[ "duplicates", "mailing", "python", "similarity", "street_address" ]
stackoverflow_0001369289_duplicates_mailing_python_similarity_street_address.txt
Q: Embeddable Workflow/BPM Library For Python? Let's say you are building a Python-based web app that requires some workflow management such as that in jBPM or Windows Workflow Foundation. Is there a library that offers this in the Python world? A: Oh yes, tons. But most of them depend on a specific framework. DCWo...
Embeddable Workflow/BPM Library For Python?
Let's say you are building a Python-based web app that requires some workflow management such as that in jBPM or Windows Workflow Foundation. Is there a library that offers this in the Python world?
[ "Oh yes, tons. But most of them depend on a specific framework. DCWorkflow is integrated with Zopes CMF, for example. hurry.workflow is for Zope 3, etc. SpiffWorkflow presumes sql-alchemy, etc. This is because you need to have something to apply the workflow to, and that means you need to make some basic assumption...
[ 3, 1 ]
[]
[]
[ "business_process_management", "python", "workflow" ]
stackoverflow_0001493550_business_process_management_python_workflow.txt
Q: Python - Tkinter - Padding woes I have a scrollbar widget that ALWAYS hides the last 15 px under the resize button, is there an option to stop this happening on mac or a padding "under" the widget option?\ thanks! A: No, there isn't an option. You need to adjust your padding so that the scrollbar doesn't extend ...
Python - Tkinter - Padding woes
I have a scrollbar widget that ALWAYS hides the last 15 px under the resize button, is there an option to stop this happening on mac or a padding "under" the widget option?\ thanks!
[ "No, there isn't an option. You need to adjust your padding so that the scrollbar doesn't extend all the way to the bottom of the window. Perhaps the easiest way is to add a statusbar that extends across the bottom of the window. \n", "Or, you could also try switching to the place() layout manager.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0001927475_python_tkinter_user_interface.txt
Q: Why is (python|ruby) interpreted? What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we woul...
Why is (python|ruby) interpreted?
What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains. So...
[ "Several reasons:\n\nfaster development loop, write-test vs write-compile-link-test\neasier to arrange for dynamic behavior (reflection, metaprogramming)\nmakes the whole system portable (just recompile the underlying C code and you are good to go on a new platform)\n\nThink of what would happen if the system was n...
[ 32, 16, 8, 6, 5, 5, 2, 2, 2, 1, 1, 1 ]
[]
[]
[ "compiler_construction", "python", "ruby" ]
stackoverflow_0001805148_compiler_construction_python_ruby.txt
Q: How to use python, PyLab, NumPy, etc for my Physics lab class over excel I took a scientific programming course this semester that I really enjoyed and experimented with a lot. We used python, and all the related modules. I am taking a physics lab next semester and I just wanted to hear from some of you how pyth...
How to use python, PyLab, NumPy, etc for my Physics lab class over excel
I took a scientific programming course this semester that I really enjoyed and experimented with a lot. We used python, and all the related modules. I am taking a physics lab next semester and I just wanted to hear from some of you how python can help me in ways that excel can't or in ways that are better than excel'...
[ "The paper Python all a scientist needs comes to mind. I hope you can make the needed transformations from Biology to Physics.\n", "Scipy will also be useful to you, as it includes many more advanced analysis tools. For example, Scipy includes a linear regression, and gets more interesting from there. Along wit...
[ 1, 1, 0, 0 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0001912743_matplotlib_numpy_python.txt
Q: Calling a method on class A depending on type of parameter class Class1(object): ... class Class2(object): ... class Class3(object): ... class A(object): def _methA(parm1, parm2) ... def _methB(parm1, parm2) ... def _methC(parm1, parm2) ... def manager(parm...
Calling a method on class A depending on type of parameter
class Class1(object): ... class Class2(object): ... class Class3(object): ... class A(object): def _methA(parm1, parm2) ... def _methB(parm1, parm2) ... def _methC(parm1, parm2) ... def manager(parm1, method, params) ... if parm1.__class__.__name...
[ "That's one of many wrong ways to implement polymorphism. You should never look at class names. Looking at class names should bother you because it means that you haven't delegated the responsibility correctly.\nMove each method into the appropriate class.\nclass Class1(object):\n def method( self, theA, param...
[ 5, 1, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0001928806_oop_python.txt
Q: cross platform usb module for python? I was interested in doing some cross platform work with a usb device in python, any tips or recommendations on modules that can do this type of thing? I've looked around SF and googlecode without a lot of luck. thanks! ct A: PyUSB is what you are looking for. it is a wrapper...
cross platform usb module for python?
I was interested in doing some cross platform work with a usb device in python, any tips or recommendations on modules that can do this type of thing? I've looked around SF and googlecode without a lot of luck. thanks! ct
[ "PyUSB is what you are looking for. it is a wrapper around libusb which works on linux and was ported on Windows. \n" ]
[ 5 ]
[]
[]
[ "python", "usb" ]
stackoverflow_0001928936_python_usb.txt
Q: How do I plug a new templating language into repoze.bfg? What do I need to implement to add a new templating language to repoze.bfg? Will the framework send my plugin absolute paths or package relative paths, or both depending? A: The package at http://svn.repoze.org/repoze.bfg.jinja2/trunk/repoze/bfg/jinja2/ pr...
How do I plug a new templating language into repoze.bfg?
What do I need to implement to add a new templating language to repoze.bfg? Will the framework send my plugin absolute paths or package relative paths, or both depending?
[ "The package at http://svn.repoze.org/repoze.bfg.jinja2/trunk/repoze/bfg/jinja2/ provides add-on Jinja2 bindings for BFG. Basically, you do create a package like that, then allow folks to wire it into their systems.\nThere are two levels of integration. The first is just an import-level integration that would al...
[ 2 ]
[]
[]
[ "python", "repoze.bfg" ]
stackoverflow_0001926199_python_repoze.bfg.txt
Q: Nested dot lookups in Django templates According to The Django Book, Django's templating system supports nested dot lookups: Dot lookups can be nested multiple levels deep. For instance, the following example uses {{ person.name.upper }}, which translates into a dictionary lookup (person['name']), then a method c...
Nested dot lookups in Django templates
According to The Django Book, Django's templating system supports nested dot lookups: Dot lookups can be nested multiple levels deep. For instance, the following example uses {{ person.name.upper }}, which translates into a dictionary lookup (person['name']), then a method call (upper()): '{{ person.name.upper }} is ...
[ "I think the problem is that you are expecting ndx to be evaluated when that simply never happens. Have you tried this:\n{{ test.0.bar }}\n\nI think that will do what you're looking for.\n\nAre there goblins with this approach...?\n\nSort of, but they aren't the ones you're talking about, and I don't think it's be...
[ 9, 4, 1, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0001929109_django_django_templates_python.txt
Q: python-config ldflags on mac I have a problem with python-config --ldflags on OS X 10.6.2. Using my non-system python.org python install: robin-mbp:~ robince$ which python /Library/Frameworks/Python.framework/Versions/2.5/bin/python robin-mbp:~ robince$ python-config --ldflags -L/Library/Frameworks/Python.framewor...
python-config ldflags on mac
I have a problem with python-config --ldflags on OS X 10.6.2. Using my non-system python.org python install: robin-mbp:~ robince$ which python /Library/Frameworks/Python.framework/Versions/2.5/bin/python robin-mbp:~ robince$ python-config --ldflags -L/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/confi...
[ "Sorry to answer my own question but I got an amazingly prompt reply on the pythonmac-sig mailing list where I also asked. It is a bug with current python: http://bugs.python.org/issue7541\nSuggested workaround:\n\nThe easiest workaround is to open a\n terminal window and execute the\n following commands:\ncd\n ...
[ 2 ]
[]
[]
[ "ld", "linker", "macos", "python" ]
stackoverflow_0001929180_ld_linker_macos_python.txt
Q: Searching for text in a file hi there got a couple of probs, say in my text file i have: abase abased abasement abasements abases This coding below is meant to find a word in a file and print all the lines to the end of the file. But it doesnt it only prints out my search term and not the rest of the file. searc...
Searching for text in a file
hi there got a couple of probs, say in my text file i have: abase abased abasement abasements abases This coding below is meant to find a word in a file and print all the lines to the end of the file. But it doesnt it only prints out my search term and not the rest of the file. search_term = r'\b%s\b' % search_term ...
[ "For the first part of the question, unindent your if f: print line,. Otherwise, you're only trying to print when the regex matches.\nIt's not clear to me what your question is in the second part. I see what you're trying to do, and your code, but you've not indicated how it misbehaves.\n", "For the first part th...
[ 1, 1 ]
[]
[]
[ "file", "python", "search" ]
stackoverflow_0001929432_file_python_search.txt
Q: Reading the same file multiple times in Python I need to download a zip archive of text files, dispatch each text file in the archive to other handlers for processing, and finally write the unzipped text file to disk. I have the following code. It uses multiple open/close on the same file, which does not seem eleg...
Reading the same file multiple times in Python
I need to download a zip archive of text files, dispatch each text file in the archive to other handlers for processing, and finally write the unzipped text file to disk. I have the following code. It uses multiple open/close on the same file, which does not seem elegant. How do I make it more elegant and efficient? zi...
[ "Your answer is in your example code. Just use StringIO to buffer the logfile:\nzipped = urllib.urlopen('www.abc.com/xyz.zip')\nbuf = cStringIO.StringIO(zipped.read())\nzipped.close()\nunzipped = zipfile.ZipFile(buf, 'r')\nfor f_info in unzipped.infolist():\n logfile = unzipped.open(f_info)\n # Here's where we ...
[ 5, 1, 1 ]
[]
[]
[ "file_io", "python", "unzip", "zip" ]
stackoverflow_0001929662_file_io_python_unzip_zip.txt
Q: Serializing resultset returned from mysqldb in python Can anyone please help me in serializing resultset returned using mysqldb in python? I get typeerror: datetime.date(2007, 11, 15) is not JSON serializable What is the best way to do serialize into Json object in python? I am using json.dumps(resultset) to seria...
Serializing resultset returned from mysqldb in python
Can anyone please help me in serializing resultset returned using mysqldb in python? I get typeerror: datetime.date(2007, 11, 15) is not JSON serializable What is the best way to do serialize into Json object in python? I am using json.dumps(resultset) to serialize resultset...
[ "Set the \"default\" function passed to json.dump:\n>>> d=datetime.datetime.now()\n>>> json.dumps(d,default=str)\n'\"2009-12-18 14:22:21.405095\"'\n\n", "You can use rfc3339 strings instead:\n json.dump(datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))\n\nSee: JSON datetime between Python and JavaScript\n", "Seria...
[ 3, 1, 0 ]
[]
[]
[ "django", "json", "mysql", "python" ]
stackoverflow_0001899110_django_json_mysql_python.txt
Q: Best python XMPP / Jabber client library? What are your experiences with Python Jabber / XMPP client libraries? What do you recommend? A: It depends what license you can use. Some popular libraries are GPL which can cause serious issues if you need to use it for work, especially if you need to keep proprietary ...
Best python XMPP / Jabber client library?
What are your experiences with Python Jabber / XMPP client libraries? What do you recommend?
[ "It depends what license you can use. Some popular libraries are GPL which can cause serious issues if you need to use it for work, especially if you need to keep proprietary extensions. The LGPL libraries are a little less popular, I think, but you have more flexibility with what you can use them for.\nI'd once ...
[ 76, 7 ]
[]
[]
[ "chat", "google_talk", "python", "xmpp" ]
stackoverflow_0001901828_chat_google_talk_python_xmpp.txt
Q: Prevent RegEx Hang on Large Matches This is a great regular expression for dates... However it hangs indefinitely on this one page I tried... I wanted to try this page ( http://pleac.sourceforge.net/pleac_python/datesandtimes.html ) for the fact that it does have lots of dates on it and I want to grab all of them....
Prevent RegEx Hang on Large Matches
This is a great regular expression for dates... However it hangs indefinitely on this one page I tried... I wanted to try this page ( http://pleac.sourceforge.net/pleac_python/datesandtimes.html ) for the fact that it does have lots of dates on it and I want to grab all of them. I don't understand why it is hanging whe...
[ "You should read Mastering Regular Expressions. The problem is:\n(?:[\\d]*[\\,\\.\\ \\-]+)*\n\nwhich takes exponential time. Try using:\n(?:[\\d,. \\-]*[,. \\-])?\n\nwhich should match the same things but take linear time. Having checked your example, this does indeed speed things up.\nYou also appear to have accid...
[ 5, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001930135_python_regex.txt
Q: PyCrypto with Py2exe Can you use PyCrypto with py2exe? Can you use any arbitrary library for that matter with py2exe? Thanks, Chris A: I have yet to find anything that py2exe can't actually handle, though from time to time it has lagged developments in Python itself. (For example, for a while it had trouble wit...
PyCrypto with Py2exe
Can you use PyCrypto with py2exe? Can you use any arbitrary library for that matter with py2exe? Thanks, Chris
[ "I have yet to find anything that py2exe can't actually handle, though from time to time it has lagged developments in Python itself. (For example, for a while it had trouble with the new absolute imports stuff, though I believe that's been resolved. It also wasn't so good with eggs, but I don't know if that has ...
[ 1 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0001930539_py2exe_python.txt
Q: Robocopy error code 6 ''The handle is invalid' I have written a python script that uses subprocess to call robocopy to sync log files from a remote host. Like so: program = 'Robocopy' options = ['/S'] args.append(program) args.append(options) args.append('\\\\%s\%s' % (hostname, source_path)) args.append(local_pa...
Robocopy error code 6 ''The handle is invalid'
I have written a python script that uses subprocess to call robocopy to sync log files from a remote host. Like so: program = 'Robocopy' options = ['/S'] args.append(program) args.append(options) args.append('\\\\%s\%s' % (hostname, source_path)) args.append(local_path) proc = subprocess.Popen(args=args, shell=True, s...
[ "Google searches for \"robocopy handle is invalid\" suggest you might find success by using the /b option for \"backup mode\".\nEven if that doesn't work, I'd suggest adding code to output the filenames as they are being copied (or log it), and once you've identified the specific failing file, you may well also rea...
[ 1 ]
[]
[]
[ "python", "robocopy", "subprocess" ]
stackoverflow_0001928855_python_robocopy_subprocess.txt
Q: Some other filter I have a problem. I've got a string which looks like "var1,var2" and table in database which contains some records looks like "var1, var3", "var3", "var2,var3" an I want to filter them by splitting first string. When any of my string-variable fits to database-variable django will display them. So...
Some other filter
I have a problem. I've got a string which looks like "var1,var2" and table in database which contains some records looks like "var1, var3", "var3", "var2,var3" an I want to filter them by splitting first string. When any of my string-variable fits to database-variable django will display them. So, when I have string-va...
[ "I htink that what you want is OR lookups. Try this:\nvar_string = 'var1,var2'\nvars = var_string.split(',')\n\nresult = MyModel.objects.none()\n\nfor var in vars:\n result |= MyModel.objects.filter(name__icontains=var.strip())\n\nreturn result\n\nYou might want to put this in a Manager for reusability. But person...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001930120_django_python.txt
Q: In python (django) how can I stop access to a global dictionary data structure when it's being updated? In django when updating a global dictionary data structure I want to lock access to it by different request. I am planning to have a wrapper function to update and access and synchronize it. Coming from Java bac...
In python (django) how can I stop access to a global dictionary data structure when it's being updated?
In django when updating a global dictionary data structure I want to lock access to it by different request. I am planning to have a wrapper function to update and access and synchronize it. Coming from Java background! Any pointers?
[ "Extending the LockableDict example somewhat, to make it a little more robust you can use the real Lock:\nclass LockableDict(dict):\n def __init__(self, *args, **kwargs):\n from threading import Lock\n self.lock = Lock()\n dict.__init__(self, *args, **kwargs)\n\n @property\n def locked...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001927887_django_python.txt
Q: show html with pyqt4 print "hellp world" :) i want to ask you if exist a function or class hwo can show the html code like the browser's jobe thx A: There is QtWebKit Module within Qt. It incorporates webkit rendering engine. Whereas you can get access to Qt classes using python binding, you can use Qt official ...
show html with pyqt4
print "hellp world" :) i want to ask you if exist a function or class hwo can show the html code like the browser's jobe thx
[ "There is QtWebKit Module within Qt. It incorporates webkit rendering engine. Whereas you can get access to Qt classes using python binding, you can use Qt official manual as help. Qt designer is also included into pyqt - you can try using it to design your application's GUI (I'm almost sure you'll be able to find ...
[ 1 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0001930866_pyqt4_python.txt
Q: Python - assign lists within nest to variable I am new to python and would appreciate a little help. How does one do the following: Having converted each line within a file to a nested list, e.g. [['line 1', 'a'], ['line 2','b']] how do I flatten the list so that each line is associated with a variable. Assume th...
Python - assign lists within nest to variable
I am new to python and would appreciate a little help. How does one do the following: Having converted each line within a file to a nested list, e.g. [['line 1', 'a'], ['line 2','b']] how do I flatten the list so that each line is associated with a variable. Assume that the first member in each list, i.e. i[:][0], is ...
[ "# Answer to question 1 - just use the built-in functionality of lists.\n#\n# There is no need to use variables when lists let you do so much more\n# in a quick and organised fashion.\nlines = []\nfor line in open_file:\n lines.append(line)\n\nSince Li0liQ already answered questions 2 and 3, I'd just like to ad...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "list", "loops", "python", "variables" ]
stackoverflow_0001931380_list_loops_python_variables.txt
Q: How to change the max_length in a django subclass? I have the following model in django: class Node(models.Model): name = models.CharField(max_length=255) And this subclass of the above model: class Thingy(Node): name = models.CharField(max_length=100) otherstuff = models.CharField(max_length=25...
How to change the max_length in a django subclass?
I have the following model in django: class Node(models.Model): name = models.CharField(max_length=255) And this subclass of the above model: class Thingy(Node): name = models.CharField(max_length=100) otherstuff = models.CharField(max_length=255) The problem with this setup is that while everything...
[ "Your implementation is totally wrong, that is not how you suppose to write parent and child class. either define name in parent class or child class, if you define it in a parent class then you can't define again in the child because new field will be created instead. so if you want to change max_length in the chi...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001931404_django_python.txt
Q: Under what circumstances do Python unittests fail to run? I have a standalone Django app that I'm working on right now. You can see the code at Github. In one of the edits, I introduced an error that caused the source tree to be deleted. I reset to an earlier revision, and suddenly my unittests stopped working. I'...
Under what circumstances do Python unittests fail to run?
I have a standalone Django app that I'm working on right now. You can see the code at Github. In one of the edits, I introduced an error that caused the source tree to be deleted. I reset to an earlier revision, and suddenly my unittests stopped working. I've tried bisecting from an earlier revision, but it turned out ...
[ "Problem solved. Turns out it was a Django-specific problem. I had a models.py file in my app that wasn't part of git repo for some strange reason. Once the source tree was removed, and code from repo restored, the models.py was no longer there, so tests wouldn't run... Silly mistake.\n" ]
[ 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0001931567_python_unit_testing.txt
Q: Accessing python httplib2 over a network share in windows 7 I am trying to run python from a network share on windows 7. The network share is T: >t:\python-2.6.1\python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more in...
Accessing python httplib2 over a network share in windows 7
I am trying to run python from a network share on windows 7. The network share is T: >t:\python-2.6.1\python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import httplib2 httplib2\__init__.py:29: Deprecati...
[ "Peter, \nWhen I copy python-2.6.1 from the network share to my local drive it works fine. It also works fine on my windows XP machine using the same network share.\n" ]
[ 1 ]
[]
[]
[ "httplib2", "python", "windows_7" ]
stackoverflow_0001931353_httplib2_python_windows_7.txt
Q: Python - ignore lines in a file How does one ignore lines in a file? Example: If you know that the first lines in a file will begin with say, a or b and the remainder of lines end with c, how does one parse the file so that lines beginning a or b are ignored and lines ending c are converted to a nested list? What ...
Python - ignore lines in a file
How does one ignore lines in a file? Example: If you know that the first lines in a file will begin with say, a or b and the remainder of lines end with c, how does one parse the file so that lines beginning a or b are ignored and lines ending c are converted to a nested list? What I have so far: fname = raw_input('Ent...
[ "startswith can take a tuple of strings to match, so you can do this:\n[line.strip().split() for line in z if not line.startswith(('a', 'b'))]\n\nThis will work even if a and b are words or sentences not just characters.\nIf there can be cases where lines don't start with a or b but also don't end with c you can ex...
[ 9, 3, 2, 1, 0, 0 ]
[]
[]
[ "file", "line", "loops", "python" ]
stackoverflow_0001931527_file_line_loops_python.txt
Q: Django 1.1 date-based generic view problem - archive_year, archive_month, archive_day I'm on my first Django blog and when trying to get the posts by year, month and day, using the built-in generic view from Django, but I don't get proper results. (Sorry for my non-professional first question.. if someone knows wh...
Django 1.1 date-based generic view problem - archive_year, archive_month, archive_day
I'm on my first Django blog and when trying to get the posts by year, month and day, using the built-in generic view from Django, but I don't get proper results. (Sorry for my non-professional first question.. if someone knows what is the appropriate question, please let me know) Well, I think it's better to show you m...
[ "The month information is stored in the context variable date_list, not pub_date.\nFrom the django docs for archive_year:\n\nTemplate context:\nIn addition to extra_context, the\n template's context will be:\n\ndate_list: A list of datetime.date objects representing all\n months that have objects available in\n ...
[ 2 ]
[]
[]
[ "django", "django_templates", "html", "python" ]
stackoverflow_0001931708_django_django_templates_html_python.txt
Q: What is the use of strings like "-*- Mode: Python -*-" found at the top of some python files? Here are the top few lines (all comments) from a python application. What do the first two comment lines indicate? Are they special markers for another app? # -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Istanbul...
What is the use of strings like "-*- Mode: Python -*-" found at the top of some python files?
Here are the top few lines (all comments) from a python application. What do the first two comment lines indicate? Are they special markers for another app? # -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Istanbul - A desktop recorder # Copyright (C) 2005 Zaheer Abbas Merali (zaheerabbas at merali dot org) # Po...
[ "The first line is an emacs thing (although it may also be a vi thing). It basically tells it that it should use python-mode to read the file. You'll usually see this if the file ends in an extension other than .py.\nAs mentioned, the second line deals with spacings.\n", "Its define tab size 4 spaces to text ed...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001931781_python.txt
Q: What's a good general way to look SQLAlchemy transactions, complete with authenticated user, etc? I'm using SQLAlchemy's declarative extension. I'd like all changes to tables logs, including changes in many-to-many relationships (mapping tables). Each table should have a separate "log" table with a similar schema,...
What's a good general way to look SQLAlchemy transactions, complete with authenticated user, etc?
I'm using SQLAlchemy's declarative extension. I'd like all changes to tables logs, including changes in many-to-many relationships (mapping tables). Each table should have a separate "log" table with a similar schema, but additional columns specifying when the change was made, who made the change, etc. My programming m...
[ "There are too many questions in one, so they that full answers to all them won't fit StackOverflow answer format. I'll try to describe hints in short, so ask separate question for them if it's not enough.\nAssigning user and description to transaction\nThe most popular way to do so is assigning user (and other inf...
[ 6, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0001862029_python_sqlalchemy.txt
Q: PyTables problem - different results when iterating over subset of table I am new to PyTables, and am looking at using it to process data generated from an agent-based modeling simulation and stored in HDF5. I'm working with a 39 MB test file, and am experiencing some strangeness. Here's the layout of the table:...
PyTables problem - different results when iterating over subset of table
I am new to PyTables, and am looking at using it to process data generated from an agent-based modeling simulation and stored in HDF5. I'm working with a 39 MB test file, and am experiencing some strangeness. Here's the layout of the table: /example/agt_coords (Table(2000000,)) '' description := { "agent": In...
[ "This is a very common point of confusion when iterating over Table object,\nWhen you iterate over a Table the type of item you get is not the data at the item, but an accessor to the table at the current row. So with\n[x for x in coords if x['agent'] == 1]\n\nyou create a list of row accessors that all point to t...
[ 7 ]
[]
[]
[ "numpy", "pytables", "python" ]
stackoverflow_0001929973_numpy_pytables_python.txt
Q: Python - Check Order of Lines in File How does one check the order of lines in a file? Example file: a b c d e f b c d e f g 1 2 3 4 5 0 Requirements: All lines beginning a, must precede lines beginning b. There is no limit on number of lines beginning a. Lines beginning a, may or may not be present. Lines conta...
Python - Check Order of Lines in File
How does one check the order of lines in a file? Example file: a b c d e f b c d e f g 1 2 3 4 5 0 Requirements: All lines beginning a, must precede lines beginning b. There is no limit on number of lines beginning a. Lines beginning a, may or may not be present. Lines containing integers, must follow lines beginning...
[ "A straightforward iterative method. This defines a function to determine a linetype from 1 to 3. Then we iterate over the lines in the file. An unknown line type or a linetype less than any previous one will raise an exception.\ndef linetype(line):\n if line.startswith(\"a\"):\n return 1\n if line....
[ 4, 2, 0, 0 ]
[]
[]
[ "file", "lines", "python" ]
stackoverflow_0001931802_file_lines_python.txt
Q: packaging cryptography software and distributing I'm developing a python GUI application and plan on calling external program packaged with my program to do some encryption. I noticed from sites like OpenSSL that talk about export laws regarding cryptography software. If I can't package binary forms of the cryptog...
packaging cryptography software and distributing
I'm developing a python GUI application and plan on calling external program packaged with my program to do some encryption. I noticed from sites like OpenSSL that talk about export laws regarding cryptography software. If I can't package binary forms of the cryptography software with my application, how can I work aro...
[ "You need to pick your target audiences with care, especially when you are dancing around with ITAR -- the International Traffic in Arms Regulations. Identify the countries you can legally export your product to and then, at the very least, say that people from other countries can't download it. You may have to do ...
[ 5, 0 ]
[]
[]
[ "aes", "cryptography", "itar", "python" ]
stackoverflow_0001932200_aes_cryptography_itar_python.txt
Q: Printing Lines in a File So here's the problem I have, I can find the Search Term in my file but at the moment I can only print out the line that the Search Term is in. (Thanks to Questions posted by people earlier =)). But I cannot print out all the lines to the end of the file after the Search Term. Here is the...
Printing Lines in a File
So here's the problem I have, I can find the Search Term in my file but at the moment I can only print out the line that the Search Term is in. (Thanks to Questions posted by people earlier =)). But I cannot print out all the lines to the end of the file after the Search Term. Here is the coding I have so far:- search...
[ "It can be much improved if you first compile the regex:\nsearch_term_regex = re.compile(r'\\b%s\\b' % search_term)\n\nfound = False\nfor line in open(f):\n if not found:\n found = bool(search_term_regex.findall(line))\n if found:\n print line,\n\nThen you're not repeating the print line. \n", ...
[ 1, 0 ]
[]
[]
[ "printing", "python", "text" ]
stackoverflow_0001932491_printing_python_text.txt
Q: python post large files to django I am trying to find the best way (most efficient way) to post large files from a python application to a Django server. If I rely on raw_post_data on the Django side then all the content needs to be in RAM before I can read it which doesn't seem efficient at all if the file receiv...
python post large files to django
I am trying to find the best way (most efficient way) to post large files from a python application to a Django server. If I rely on raw_post_data on the Django side then all the content needs to be in RAM before I can read it which doesn't seem efficient at all if the file received is 100s of megs. Is it better to use...
[ "I think only files less than 2.5MB are stored in the memory, any file that is larger than 2.5MB is streamed or written to temporary file in temp directory..\nreference:\nhttp://simonwillison.net/2008/Jul/1/uploads/ and here http://docs.djangoproject.com/en/dev/topics/http/file-uploads/\n", "If you really want to...
[ 6, 2 ]
[]
[]
[ "django", "post", "python", "upload" ]
stackoverflow_0001931673_django_post_python_upload.txt
Q: Offline access to MoinMoin wiki using Google Gears How to add offline access functionality to MoinMoin wiki? As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would b...
Offline access to MoinMoin wiki using Google Gears
How to add offline access functionality to MoinMoin wiki? As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update wiki content while ...
[ "If you have the freedom to change the wiki software, I might suggest looking at ikiwiki. You can set it up so the pages are backed by a real VCS such as Git, in which case you can clone the whole wiki and read and even update it offline.\n", "By using Gears with the Firefox Greasemonkey plugin, you can inject Ge...
[ 2, 2, 1, 1 ]
[ "Have a look at MoinMoin Desktop Edition.\n" ]
[ -1 ]
[ "google_gears", "moinmoin", "offline", "python", "wiki" ]
stackoverflow_0000176955_google_gears_moinmoin_offline_python_wiki.txt
Q: How to use InterWiki links in moinmoin? We use a number of diffrent web services in our company, wiki(moinmoin), bugtracker (internally), requestracker (customer connection), subversion. Is there a way to parse the wikipages so that if I write "... in Bug1234 you could ..." Bug1234 woud be renderd as a link to htt...
How to use InterWiki links in moinmoin?
We use a number of diffrent web services in our company, wiki(moinmoin), bugtracker (internally), requestracker (customer connection), subversion. Is there a way to parse the wikipages so that if I write "... in Bug1234 you could ..." Bug1234 woud be renderd as a link to http://mybugtracker/bug1234
[ "check out the interwiki page in moinmoin, (most wikis have them) we use trac for example and you can set up different link paths to point to your different web resources. So in our Trac you can go [[SSGWiki:Some Topic]] and it will point to another internal wiki.\n", "add to the file data/intermap.txt (create i...
[ 3, 0 ]
[ "I finally found the solution. \n\"Add the site to data/intermap.txt\" found at:\nhttp://moinmo.in/MoinMoinQuestions#MoinMoinQuestions.2BAC8-Administration.Howtoaddnewinterwikisites.3F\n" ]
[ -1 ]
[ "moinmoin", "python", "wiki" ]
stackoverflow_0000343769_moinmoin_python_wiki.txt
Q: General questions regarding Python language I'm a newbie to programming and I've decided to start with Python. Just curious though, is it enough/recommended to learn Python from online tutorials or from books? I want to go further than simple "Hello World!" programs. I'm not sure if books will actually teach you h...
General questions regarding Python language
I'm a newbie to programming and I've decided to start with Python. Just curious though, is it enough/recommended to learn Python from online tutorials or from books? I want to go further than simple "Hello World!" programs. I'm not sure if books will actually teach you how to make more advanced programs. One example is...
[ "Well, I learnt all my Python from online sources (not just tutorials, but reference documentation, blog posts and other texts). It's certainly possible, although some people prefer the \"guided\" way a book teaches you, particularly people new to programming (at that point I had already been programming for years)...
[ 4, 2, 2, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001932643_python.txt
Q: How do I generate multi-word terms recursively? Say I have a string of words: 'a b c d e f'. I want to generate a list of multi-word terms from this string. Word order matters. The term 'f e d' shouldn't be generated from the above example. Edit: Also, words should not be skipped. 'a c', or 'b d f' shouldn't be ...
How do I generate multi-word terms recursively?
Say I have a string of words: 'a b c d e f'. I want to generate a list of multi-word terms from this string. Word order matters. The term 'f e d' shouldn't be generated from the above example. Edit: Also, words should not be skipped. 'a c', or 'b d f' shouldn't be generated. What I have right now: doc = 'a b c d e f'...
[ "This isn't recursive, but I think it does what you want. \ndoc = 'a b c d e f'\nwords = doc.split(None)\nmax = 3 \n\n\nfor index in xrange(len(words)): \n for n in xrange(max):\n if index + n < len(words): \n print ' '.join(words[index:index+n+1]) \n\nAnd here's a recur...
[ 11, 3, 3, 1 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0000702760_python_recursion.txt
Q: make python replace un-encodable chars with a string by default I want to make python ignore chars it can't encode, by simply replacing them with the string "<could not encode>". E.g, assuming the default encoding is ascii, the command '%s is the word'%'ébác' would yield '<could not encode>b<could not encode>c is...
make python replace un-encodable chars with a string by default
I want to make python ignore chars it can't encode, by simply replacing them with the string "<could not encode>". E.g, assuming the default encoding is ascii, the command '%s is the word'%'ébác' would yield '<could not encode>b<could not encode>c is the word' Is there any way to make this the default behavior, acros...
[ "The str.encode function takes an optional argument defining the error handling:\nstr.encode([encoding[, errors]])\n\nFrom the docs:\n\nReturn an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for erro...
[ 11, 5 ]
[]
[]
[ "encode", "python", "replace" ]
stackoverflow_0001933184_encode_python_replace.txt
Q: I want to display name in front of field instead of ..whatdoyoucallitanyway.. I have this model: class Kaart(models.Model): name = models.CharField(max_length=200, name="Kaardi peakiri", help_text="Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)", blank=False, null=False) url = models.CharField(ma...
I want to display name in front of field instead of
..whatdoyoucallitanyway.. I have this model: class Kaart(models.Model): name = models.CharField(max_length=200, name="Kaardi peakiri", help_text="Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)", blank=False, null=False) url = models.CharField(max_length=200, blank=False, null=False, name="Asukoha URL"...
[ "You need to use verbose_name instead of name in your model.\nname = models.CharField(max_length=200, verbose_name=\"Kaardi peakiri\", help_text=\"Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)\", blank=False, null=False)\n\nSee the docs. There is no option called name.\n", "According to the documentati...
[ 22, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0001933299_django_django_forms_python.txt
Q: Programmable transparent forward proxy I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings. I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed ...
Programmable transparent forward proxy
I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings. I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in Ruby and Python that allow you to inspect...
[ "Squid and Apache both have mechanisms to call external scripts for allow/deny decisions per-request. This allows you to use either for their proxy engines, but call your external script per request for processing of arbitrary complexity. Your code only has to manage the business logic, not the heavy lifting.\n...
[ 3, 2, 2, 0 ]
[]
[]
[ "apache", "perl", "proxy", "python", "ruby" ]
stackoverflow_0001933217_apache_perl_proxy_python_ruby.txt
Q: Python - specify which function in file to use on command line Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line? Example: python prog.py -x <<<filname>>> Where -x tells python...
Python - specify which function in file to use on command line
Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line? Example: python prog.py -x <<<filname>>> Where -x tells python to go to a particular for loop and then execute the function called...
[ "The Python idiom for the main entry point:\nif __name__ == '__main__':\n main()\n\nReplace main() by whatever function should go first ...\n(more on if name ...: http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm)\nIf you want to specify the function to run via command line argument, just check these ar...
[ 10, 9, 4, 1, 0 ]
[]
[]
[ "command_line", "function", "python" ]
stackoverflow_0001933400_command_line_function_python.txt
Q: Deepcopy a simple Python object I have an object which defines a __deepcopy__ method. I would like a function that will deepcopy it not by the method given by it, but in the default way that objects of the class object are copied. How could I do that? I think I could try to code it but there are probably many "got...
Deepcopy a simple Python object
I have an object which defines a __deepcopy__ method. I would like a function that will deepcopy it not by the method given by it, but in the default way that objects of the class object are copied. How could I do that? I think I could try to code it but there are probably many "gotchas" I won't be thinking of. The rea...
[ "You basically need to override the existing __deepcopy__ method, which means temporarily setting the object's class to something different -- whether that's acceptable essentially depends on whether the \"__deepcopy__ override\" needs to affect only one, \"top-level\" object (in which case the kludge's probably O...
[ 4 ]
[]
[]
[ "deep_copy", "python" ]
stackoverflow_0001933621_deep_copy_python.txt
Q: How to refactor this python code block to be more efficient This code block works - it loops through a file that has a repeating number of sets of data and extracts out each of the 5 pieces of information for each set. But I I know that the current factoring is not as efficient as it can be since it is looping t...
How to refactor this python code block to be more efficient
This code block works - it loops through a file that has a repeating number of sets of data and extracts out each of the 5 pieces of information for each set. But I I know that the current factoring is not as efficient as it can be since it is looping through each key for each line found. Wondering if some python gu...
[ "Though this doesn't answer your question (other answers are getting at that) something that has helped me a lot in doing things similar to what you're doing are List Comprehensions. They allow you to build lists in a concise and (I think) easy to read way. \nFor instance, the below code builds a 2-dimenstional arr...
[ 2, 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001933564_python.txt
Q: How do you clone a class in Python? I have a class A and i want a class B with exactly the same capabilities. I cannot or do not want to inherit from B, such as doing class B(A):pass Still i want B to be identical to A, yet have a different i: id(A) != id(B) Watch out, i am not talking about instances but classes ...
How do you clone a class in Python?
I have a class A and i want a class B with exactly the same capabilities. I cannot or do not want to inherit from B, such as doing class B(A):pass Still i want B to be identical to A, yet have a different i: id(A) != id(B) Watch out, i am not talking about instances but classes to be cloned.
[ "I'm pretty sure whatever you are trying to do can be solved in a better way, but here is something that gives you a clone of the class with a new id:\ndef c():\n class Clone(object):\n pass\n\n return Clone\n\nc1 = c()\nc2 = c()\nprint id(c1)\nprint id(c2)\n\ngives:\n4303713312\n4303831072\n\n", "I ...
[ 14, 9, 0 ]
[ "You can clone the class via inheritance. Otherwise you are just passing around a reference to the class itself (rather than a reference to an instance of the class). Why would you want to duplicate the class anyway? It's obvious why you would want to create multiple instances of the class, but I can't fathom wh...
[ -1 ]
[ "python" ]
stackoverflow_0001933784_python.txt
Q: How to load remote javascript into a SpiderMonkey context? I have a server which will be serving up javascript files, I need to grab it and execute some of it's functions using SpiderMonkey in python. How can I do this? A: hope the following example helps: >>> import urllib2 >>> import spidermonkey >>> js = spid...
How to load remote javascript into a SpiderMonkey context?
I have a server which will be serving up javascript files, I need to grab it and execute some of it's functions using SpiderMonkey in python. How can I do this?
[ "hope the following example helps:\n>>> import urllib2\n>>> import spidermonkey\n>>> js = spidermonkey.Runtime()\n>>> js_ctx = js.new_context()\n>>> script = urllib2.urlopen('http://etherhack.co.uk/hashing/whirlpool/js/whirlpool.js').read()\n>>> js_ctx.eval_script(script)\n>>> js_ctx.eval_script('var s = \"abc\"')\...
[ 1 ]
[]
[]
[ "http", "javascript", "python", "spidermonkey" ]
stackoverflow_0001931688_http_javascript_python_spidermonkey.txt
Q: help with python urllib2 import error In my script, I've imported urrlib2 and the script was working fine. After reboot, I get the following error: File "demo.py", line 2, in <module> import urllib2 File "/usr/lib/python2.6/urllib2.py", line 92, in <module> import httplib File "/usr/lib/python2.6/htt...
help with python urllib2 import error
In my script, I've imported urrlib2 and the script was working fine. After reboot, I get the following error: File "demo.py", line 2, in <module> import urllib2 File "/usr/lib/python2.6/urllib2.py", line 92, in <module> import httplib File "/usr/lib/python2.6/httplib.py", line 78, in <module> import m...
[ "The usual answer is that you've got a file called random.py in the current directory when the script is running. tempfile would be accidentally importing that random and not the stdlib random module.\n", "Check that random is the stdlib's module and not some arbitrary module with the same name from sys.path.\n>>...
[ 5, 0 ]
[]
[]
[ "import", "python", "urllib2" ]
stackoverflow_0001933928_import_python_urllib2.txt
Q: A pythonic way how to find if a value is between two values in a list Having a sorted list and some random value, I would like to find in which range the value is. List goes like this: [0, 5, 10, 15, 20] And value is, say 8. The standard way would be to either go from start until we hit value that is bigger than o...
A pythonic way how to find if a value is between two values in a list
Having a sorted list and some random value, I would like to find in which range the value is. List goes like this: [0, 5, 10, 15, 20] And value is, say 8. The standard way would be to either go from start until we hit value that is bigger than ours (like in the example below), or to perform binary search. grid = [0, 5...
[ ">>> import bisect\n>>> grid = [0, 5, 10, 15, 20]\n>>> value = 8\n>>> bisect.bisect(grid, value)\n2\n\nEdit:\nbisect — Array bisection algorithm\n", "for min, max in zip(grid, grid[1:]): # [(0, 5), (5, 10), (10, 15), (15, 20), (20, 25)]\n if max <= value < min: #previously: if value in xrange(min, max):\n ret...
[ 20, 1 ]
[]
[]
[ "grid", "list", "python", "range", "snapping" ]
stackoverflow_0001933919_grid_list_python_range_snapping.txt
Q: python - urrlib2 request https site - getting 400 error using the following snip of code to access a url with a post. i can get it using wget and the following: wget --post-data 'p_calling_proc=bwckschd.p_disp_dyn_sched&p_term=201010' https://spectrumssb2.memphis.edu/pls/PROD/bwckgens.p_proc_term_date for some re...
python - urrlib2 request https site - getting 400 error
using the following snip of code to access a url with a post. i can get it using wget and the following: wget --post-data 'p_calling_proc=bwckschd.p_disp_dyn_sched&p_term=201010' https://spectrumssb2.memphis.edu/pls/PROD/bwckgens.p_proc_term_date for some reason, i'm having an issue with my python text, in that i get ...
[ "Try not encoding the query string. The &'s and ='s in the POST data don't need to be urlencoded. If the web app on the remote end does not expect the %xx encoding in the query string, it won't be able to parse it. \nHere's curl's HTTP request headers:\nPOST / HTTP/1.1\nUser-Agent: curl/7.19.4 (universal-apple-dar...
[ 1, 0 ]
[]
[]
[ "https", "parsing", "python", "request", "urllib2" ]
stackoverflow_0001934284_https_parsing_python_request_urllib2.txt
Q: Editing the XML texts from a XML file using Python I have an XML file which contains some data as given. <?xml version="1.0" encoding="UTF-8" ?> - <ParameterData> <CreationInfo date="10/28/2009 03:05:14 PM" user="manoj" /> - <ParameterList count="85"> - <Parameter name="Spec 2 Included" type="boolean" mode="bo...
Editing the XML texts from a XML file using Python
I have an XML file which contains some data as given. <?xml version="1.0" encoding="UTF-8" ?> - <ParameterData> <CreationInfo date="10/28/2009 03:05:14 PM" user="manoj" /> - <ParameterList count="85"> - <Parameter name="Spec 2 Included" type="boolean" mode="both"> <Value>n/a</Value> <Result>n/a</Result> </P...
[ "You can convert your data text into python dictionary by regular expression\ndata=\"\"\"Spec 2 Included : TRUE\nSpec 2 Label: 19-Flat2-HS3\nSpec 3 Included : FALSE\nSpec 3 Label: 4-1-Bead1-HS3\"\"\"\n\n#data=open(\"data.txt\").read()\n\nimport re\n\ndata=dict(re.findall('(Spec \\d+ (?:Included|Label))\\s*:\\s*(\\S...
[ 6, 5, 1, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001926512_python_xml.txt
Q: Python: incorporating index from for loop as part of a list name How does one generate a set of lists that incorporate the index from a for loop in the list name: for j in range(10): li"j" = [] How can the index 'j' be part of the name, so the lists are li0, li1, li2, ... Thanks! A: You can make li a diction...
Python: incorporating index from for loop as part of a list name
How does one generate a set of lists that incorporate the index from a for loop in the list name: for j in range(10): li"j" = [] How can the index 'j' be part of the name, so the lists are li0, li1, li2, ... Thanks!
[ "You can make li a dictionary:\nli = {}\nfor j in range(10):\n li[j] = []\n\n", "If you do this simply to initialize lists to use them later, you should instead use one multi-dimensional list or even better tuple to do this:\nli = tuple( [] for i in range( 10 ) )\nli[0].append( 'foo' )\nli[5].append( 'bar' )\n...
[ 11, 3, 0 ]
[]
[]
[ "for_loop", "indexing", "list", "python" ]
stackoverflow_0001934344_for_loop_indexing_list_python.txt
Q: Why should exec() and eval() be avoided? I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. So, hopefully, one will be presented here. Why should we (at least, generally) not use exec() and eval()? EDIT: I see that people are assuming...
Why should exec() and eval() be avoided?
I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. So, hopefully, one will be presented here. Why should we (at least, generally) not use exec() and eval()? EDIT: I see that people are assuming that this question pertains to web servers – ...
[ "There are often clearer, more direct ways to get the same effect. If you build a complex string and pass it to exec, the code is difficult to follow, and difficult to test. \nExample: I wrote code that read in string keys and values and set corresponding fields in an object. It looked like this: \nfor key, val in ...
[ 32, 17, 13, 12, 9, 6, 5, 5, 4, 3, 3 ]
[]
[]
[ "python", "python_exec" ]
stackoverflow_0001933451_python_python_exec.txt
Q: Item assignment to bytes object? GAHH, code not working is bad code indeed! in RemoveRETNs toOutput[currentLoc - 0x00400000] = b'\xCC' TypeError: 'bytes' object does not support item assignment How can I fix this? inputFile = 'original.exe' outputFile = 'output.txt' patchedFile = 'original_patched.exe' d...
Item assignment to bytes object?
GAHH, code not working is bad code indeed! in RemoveRETNs toOutput[currentLoc - 0x00400000] = b'\xCC' TypeError: 'bytes' object does not support item assignment How can I fix this? inputFile = 'original.exe' outputFile = 'output.txt' patchedFile = 'original_patched.exe' def GetFileContents(filename): f = ...
[ "Change the return statement of GetFileContents into\nreturn bytearray(fileContents)\n\nand the rest should work. You need to use bytearray rather than bytes simply because the former is mutable (read/write), the latter (which is what you're using now) is immutable (read-only).\n", "Bytestrings (and strings in g...
[ 43, 8 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001934624_python_python_3.x.txt
Q: Combine matrix in numpy Suppose I have three "sheets" of matrix a,b and c, each with the same mnp dimension. And I want to combine them to get a new mnp*3 matrix whose (i,j,k) element is (a[i,j,k],b[i,j,k],c[i,j,k]). Which command should I use ? The dstack command seems not work here. Thanks. A: Another one line...
Combine matrix in numpy
Suppose I have three "sheets" of matrix a,b and c, each with the same mnp dimension. And I want to combine them to get a new mnp*3 matrix whose (i,j,k) element is (a[i,j,k],b[i,j,k],c[i,j,k]). Which command should I use ? The dstack command seems not work here. Thanks.
[ "Another one liner would be:\nresult = numpy.array( (a,b,c) ).transpose( (1,2,3,0) )\n\nor a more self-descriptive method:\nresult = empty( (m,n,p,3) )\nresult[:,:,:,0] = a\nresult[:,:,:,1] = b\nresult[:,:,:,2] = c\n\n", "I think what you want is:\nnp.concatenate([np.expand_dims(x, -1) for x in (a, b, c)], axis=3...
[ 4, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001934683_numpy_python.txt
Q: web framework compatible with python 3.1 and py-postgresql I have started learning Python by writing a small application using Python 3.1 and py-PostgreSQL. Now I want to turn it into a web application. But it seems that most frameworks such as web-py, Django, zope are still based on Python 2.x. Unfortunately, py-...
web framework compatible with python 3.1 and py-postgresql
I have started learning Python by writing a small application using Python 3.1 and py-PostgreSQL. Now I want to turn it into a web application. But it seems that most frameworks such as web-py, Django, zope are still based on Python 2.x. Unfortunately, py-PostgreSQL is incompatible with Python 2.x. Do I have to rewrite...
[ "Update: this answer is out of date in 2011.\nUnless you are interested in blazing a new trail while trying to learn Python at all, I'd recommend converting your project to Python 2.x. Hopefully your code doesn't use too many py-postgresql features not found in the widely supported DB-API interface.\nYou should loo...
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "python_3.x", "web_applications", "wsgi" ]
stackoverflow_0001423000_python_python_3.x_web_applications_wsgi.txt
Q: numpy to matlab interface with mlabwrap I am looking for a simple way to visualize some of my data in numpy, and I discovered the mlabwrap package which looks really promising. I am trying to create a simple plot with the ability to be updated as the data changes. Here is the matlab code that I am trying to dupli...
numpy to matlab interface with mlabwrap
I am looking for a simple way to visualize some of my data in numpy, and I discovered the mlabwrap package which looks really promising. I am trying to create a simple plot with the ability to be updated as the data changes. Here is the matlab code that I am trying to duplicate >> h = plot([1,2,3], [1,2,3], '-o'); >> ...
[ "Maybe mlab is mad that you're not saving matlab's return value for that set() call...\nI don't have this installed, what does someval = mlab.set(h,'XData') give?\nedit: you could also try using nout... mlab.set(h,'XData',[0,0,0],nout=0)\n", "Since set takes no output arguments, we need to tell mlabwrap that no o...
[ 6, 5 ]
[]
[]
[ "interface", "matlab", "mlabwrap", "python" ]
stackoverflow_0001934740_interface_matlab_mlabwrap_python.txt
Q: pyfacebook stream.publish not publishing all details Trying to publish a stream to facebook using py facebook. The stream publishes a single attachment perfectly i.e media or name or href , e.t.c But when it comes to appending all the attachments in one line it breaks down and just publishes the message. attachm...
pyfacebook stream.publish not publishing all details
Trying to publish a stream to facebook using py facebook. The stream publishes a single attachment perfectly i.e media or name or href , e.t.c But when it comes to appending all the attachments in one line it breaks down and just publishes the message. attachment = [media,description] etc does not work. message = "T...
[ "You haven't really given enough information to know what is causing the first issue (the only code you pasted doesn't include the pyfacebook call and has a syntax error from indentation).\nabout the second issue, python and pyfacebook can deal with facebook's server api only. If you want a popup displayed to your ...
[ 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0001929495_facebook_python.txt
Q: fb:promt-permission gives me a link, I need a direct popup I'm using Django/Python , I need to ask the user for permission to let me put feeds ( ideally oneliners which was not working so I thought to use full streams) into the user profile. Would you like to receive email from our application? This is giving me ...
fb:promt-permission gives me a link, I need a direct popup
I'm using Django/Python , I need to ask the user for permission to let me put feeds ( ideally oneliners which was not working so I thought to use full streams) into the user profile. Would you like to receive email from our application? This is giving me a hyper link which I click and it shows me the permission box. W...
[ "use the javascript FB.Connect.showPermissionDialog method.\nit takes an optional callback function to which it passes whether the permission was allowed or not, so you could call FB.Connect.streamPublish in that callback if the permission was granted.\n" ]
[ 1 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0001928098_django_facebook_python.txt
Q: File searching: TypeError Im trying to search a file where the the line containing the search term is found and printed along with a number of lines before and after the search term defined by the user. The coding i have so far is: f = open(f, 'r') d = {} for n, line in enumerate(f): d[n%numb] = line.rstrip()...
File searching: TypeError
Im trying to search a file where the the line containing the search term is found and printed along with a number of lines before and after the search term defined by the user. The coding i have so far is: f = open(f, 'r') d = {} for n, line in enumerate(f): d[n%numb] = line.rstrip() if search_term in line: ...
[ "You haven't specified what numb is, but I'm guessing it's something like:\nnumb = sys.argv[1]\n\nThe sys.argv is an array of strings, rather than integers. Try converting the string to an integer:\nnumb = int(sys.argv[1])\n\n", "n % numb can have different meanings, depending on the type of n and numb. If they ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001935465_python.txt
Q: __del__ method being called in python when it is not expected I am new to python and have been working through the examples in Swaroop CH's "A Byte of Python". I am seeing some behavior with the __del__ method that is puzzling me. Basically, if I run the following script (in Python 2.6.2) class Person4: ''...
__del__ method being called in python when it is not expected
I am new to python and have been working through the examples in Swaroop CH's "A Byte of Python". I am seeing some behavior with the __del__ method that is puzzling me. Basically, if I run the following script (in Python 2.6.2) class Person4: '''Represents a person''' population = 0 def __init__(self, ...
[ "There are a couple of things going on here. When your Person4 class is instantiated, it initialises its population class variable to 0. From your interactive console, you appear to be running your \"test1.py\" file multiple times. The second time you run it, the Person4 class is declared again which makes it techn...
[ 19, 8 ]
[]
[]
[ "del", "object_lifetime", "python" ]
stackoverflow_0001935153_del_object_lifetime_python.txt
Q: pyfacebook and javascript query I'm using pyfacebook on the backend and javascript on the client side. Now if I want to pass a variable to the javascript from pyfacebook. how would I go about doing that, any ideas? A: You can't pass a variable directly, as JavaScript is running on the client (browser), and Pytho...
pyfacebook and javascript query
I'm using pyfacebook on the backend and javascript on the client side. Now if I want to pass a variable to the javascript from pyfacebook. how would I go about doing that, any ideas?
[ "You can't pass a variable directly, as JavaScript is running on the client (browser), and Python is running on the server.\nYou could make a XHR (AJAX) request from JavaScript to the server which would then return your values back to JS (JSON could be used here).\nOr you could put a hidden field to your markup tha...
[ 1 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0001935636_javascript_python.txt
Q: Xpath builder in Python I'm building relatively complicated xpath expressions in Python, in order to pass them to selenium. However, its pretty easy to make a mistake, so I'm looking for a library that allows me to build the expressions without messing about with strings. For example, instead of writing locator='/...
Xpath builder in Python
I'm building relatively complicated xpath expressions in Python, in order to pass them to selenium. However, its pretty easy to make a mistake, so I'm looking for a library that allows me to build the expressions without messing about with strings. For example, instead of writing locator='//ul[@class="comment-contents"...
[ "though this is not exactly what you want.. you can use css selector\n...\nimport lxml.cssselect\ncsssel = 'div[class=\"main\"]'\nselobj = lxml.cssselect.CSSSelector(csssel)\nelements = selobj(documenttree)\n\ngenerated XPath expression is in selobj.path\n>>> selobj.path\nu\"descendant-or-self::div[@class = 'main']...
[ 1, 0 ]
[]
[]
[ "python", "selenium", "xml", "xpath" ]
stackoverflow_0001934720_python_selenium_xml_xpath.txt
Q: What are the major differences between Python and PHP? I know PHP a little. But Python is totally new for me. I only know it's something "similar", right? Or wrong? What are the differences I should know? A: This page on the Python wiki highlights the main differences and the common elements between Python and P...
What are the major differences between Python and PHP?
I know PHP a little. But Python is totally new for me. I only know it's something "similar", right? Or wrong? What are the differences I should know?
[ "This page on the Python wiki highlights the main\ndifferences and the common elements between Python and PHP:\n\nCompared as Languages\nWhat strengths does PHP have that Python doesn't?\n\nthe 'switch' statement and 'do ... while' construct.\nincrement and decrement and assignment operators (assignment is a statem...
[ 18, 16, 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0001936085_php_python.txt
Q: Excluding last element in 0-based indexing Once when I was reading some python docs I came across a reference to an article that explained why programming languages with 0-based indexing should always exclude the last element during operations like slicing: >> a = [1, 2, 3] >> a[0:1] [1] #and not [1,2] Unfortuna...
Excluding last element in 0-based indexing
Once when I was reading some python docs I came across a reference to an article that explained why programming languages with 0-based indexing should always exclude the last element during operations like slicing: >> a = [1, 2, 3] >> a[0:1] [1] #and not [1,2] Unfortunately I did not bookmark it. Does anyone know whi...
[ "Could it be this note from E. W. Dijkstra?\n", "No, but there are at least two good reasons:\n\na[m:n] gives you n-m elements, making it easy to compute how many elements you are requesting.\nWith inclusive end-points, it's awkward to request an empty slice (a[3:2]? yuck).\n\nEdit: I just thought of another Pyth...
[ 8, 5, 3, 1, 1, 0 ]
[]
[]
[ "arrays", "programming_languages", "python" ]
stackoverflow_0001935990_arrays_programming_languages_python.txt
Q: Sub-classing float type in Python, fails to catch exception in __init__() On Python 2.5 I need to use float numbers with a modified __str__() method. Also I need to know when the constructor fails. Why I can't catch exceptions raised from float.__init__()? What is the best way to consult the numeric value of my de...
Sub-classing float type in Python, fails to catch exception in __init__()
On Python 2.5 I need to use float numbers with a modified __str__() method. Also I need to know when the constructor fails. Why I can't catch exceptions raised from float.__init__()? What is the best way to consult the numeric value of my derived float object? In my code I'm using float(self). class My_Number(float): ...
[ "float is immutable, therefore its __init__, the initializer, is basically a no-op -- nothing substantial can happen there, because the self object cannot be altered (if it's actually an instance of float rather than of a subclass -- but of course float's own __init__ must operate on that assumption;-).\nTherefore,...
[ 23, 8 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0001936457_exception_handling_python.txt
Q: operator overloading in python Possible Duplicates: Python: defining my own operators? Rules of thumb for when to use operator overloading in python Is it possible to overload operators in Python? If so, can one define new operators, such as ++ and <<? A: As other answers have mentioned, you can indeed overloa...
operator overloading in python
Possible Duplicates: Python: defining my own operators? Rules of thumb for when to use operator overloading in python Is it possible to overload operators in Python? If so, can one define new operators, such as ++ and <<?
[ "As other answers have mentioned, you can indeed overload operators (by definining special methods in the class you're writing, i.e., methods whose names start and end with two underscores). All the details are here.\nTo complete the answers to you questions: you cannot define new operators; but << is not a new op...
[ 72, 6, 4 ]
[]
[]
[ "operator_overloading", "python" ]
stackoverflow_0001936135_operator_overloading_python.txt
Q: How do you listen to notifications from iTunes on a Mac (Using the NSDistributedNotificationCenter) Looking for help/tutorials/sample code of using python to listen to distributed notifications from applications on a mac. I know the py-objc lib is the bridge between python and mac/cocoa classes, and the Foundation...
How do you listen to notifications from iTunes on a Mac (Using the NSDistributedNotificationCenter)
Looking for help/tutorials/sample code of using python to listen to distributed notifications from applications on a mac. I know the py-objc lib is the bridge between python and mac/cocoa classes, and the Foundation library can be used to add observers, but looking for examples or tutorials on how to use this to monito...
[ "If anyone comes by to this question, i figured out how to listen, the code below works. However accessing attributes do not seem to work like standard python attribute access. \nUpdate: you do not access attributes as you would in python i.e (.x), the code has been updated below, it now generates a dict called s...
[ 11, 4 ]
[]
[]
[ "macos", "notifications", "pyobjc", "python" ]
stackoverflow_0001933107_macos_notifications_pyobjc_python.txt
Q: wxPython - DatePickerCtrl seems to ignore SetValue() I'm trying to pre-populate a wxPython DatePicker with a value using the following code: month, day, year = runData[2][0:8].split('/') displayDate = wx.DateTimeFromDMY(int(day), int(month) - 1, int(year)) self.datePicker.SetValue(displayDate) Here are the printe...
wxPython - DatePickerCtrl seems to ignore SetValue()
I'm trying to pre-populate a wxPython DatePicker with a value using the following code: month, day, year = runData[2][0:8].split('/') displayDate = wx.DateTimeFromDMY(int(day), int(month) - 1, int(year)) self.datePicker.SetValue(displayDate) Here are the printed values: runData[2] = 12/16/09 00:00 month, day, year = ...
[ "Have you tried making year 2009 instead of 9?\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001936074_python_wxpython.txt
Q: Setting an alias to a Django "plug-in" app is there some pythonic way to load a django app trough an alias name? This I think would be one way to make an app more "pluggable-friendly". there is a pattern used in settings.py: INSTALLED_APPS = ('... ','...', ) where INSTALLED_APPS is a tuple containing names of app...
Setting an alias to a Django "plug-in" app
is there some pythonic way to load a django app trough an alias name? This I think would be one way to make an app more "pluggable-friendly". there is a pattern used in settings.py: INSTALLED_APPS = ('... ','...', ) where INSTALLED_APPS is a tuple containing names of apps. That's fine, but I don't want to put in certa...
[ "Set\nLOGIN_APP_NAME = 'drupal_login' # or 'mediawiki_login', or whatever\n\nearly enough in settings.py, then put LOGIN_APP_NAME (without any quotes around it!) in your INSTALLED_APPS instead of the name of the actual app.\nIf you need more complex functionality involved in determining what app to use, how about p...
[ 4, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001934188_django_python.txt
Q: How can I run all unit tests of Jinja2? I want to run the unittests of Jinja2 whenever I change something to make sure I'm not breaking something. There's a package full of unit tests. Basically it's a folder full of Python files with the name "test_xxxxxx.py" How do I run all of these tests in one command? A: I...
How can I run all unit tests of Jinja2?
I want to run the unittests of Jinja2 whenever I change something to make sure I'm not breaking something. There's a package full of unit tests. Basically it's a folder full of Python files with the name "test_xxxxxx.py" How do I run all of these tests in one command?
[ "It looks like Jinja uses the py.test testing tool. If so you can run all tests by just running py.test from within the tests subdirectory.\n", "You could also take a look at nose too. It's supposed to be a py.test evolution.\n", "Watch out for \"test.py\" in the Jinja2 package! -- Those are not unit tests! Th...
[ 1, 0, 0 ]
[ "Try to 'walk' through the directories and import all from files like \"test_xxxxxx.py\", then call unittest.main()\n" ]
[ -1 ]
[ "jinja2", "python", "unit_testing" ]
stackoverflow_0000665093_jinja2_python_unit_testing.txt
Q: How to run installed python script? I used distutils to install my python package, with this setup.py : import distutils.core args = { 'name' : 'plugh', 'version' : '1.0', 'scripts' : [ "scripts/plugh" ], 'packages': [ "plugh" ], } d = distutils.core.setup( ...
How to run installed python script?
I used distutils to install my python package, with this setup.py : import distutils.core args = { 'name' : 'plugh', 'version' : '1.0', 'scripts' : [ "scripts/plugh" ], 'packages': [ "plugh" ], } d = distutils.core.setup( **args ) On linux/mac, it works as expec...
[ "windows uses the extension of the file to determine how it will run.\nName your file plugh.py and use plugh.py on the prompt to call it.\n", "\nIf you use ActivePython, it will already add the C:\\PythonXY\\Scripts directory to your %PATH% (ActivePython 2.6 additionally adds PEP 370's %APPDATA%\\Python\\Scripts ...
[ 6, 5 ]
[]
[]
[ "distutils", "packaging", "python", "windows" ]
stackoverflow_0001829524_distutils_packaging_python_windows.txt
Q: Python send cmd on socket I have a simple question about Python: I have another Python script listening on a port on a Linux machine. I have made it so I can send a request to it, and it will inform another system that it is alive and listening. My problem is that I don't know how to send this request from another...
Python send cmd on socket
I have a simple question about Python: I have another Python script listening on a port on a Linux machine. I have made it so I can send a request to it, and it will inform another system that it is alive and listening. My problem is that I don't know how to send this request from another python script running on the s...
[ "It looks like you are doing an HTTP request, rather than an ICMP ping.\nurllib2, built-in to Python, can help you do that.\nYou'll need to override the timeout so you aren't hanging too long. Straight from that article, above, here is some example code for you to tweak with your desired time-out and URL.\nimport s...
[ 4, 2, 0, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0001935939_python_sockets.txt
Q: Sprox form with Turbogears, using Mako, only displays plain text I'm generating a Sprox form with Turbogears 2.1 and trying to display it in a Mako template. Here is my code: To define the form: class NewUserForm(AddRecordForm): __model__ = User newuserform = NewUserForm(DBSession) The controller defini...
Sprox form with Turbogears, using Mako, only displays plain text
I'm generating a Sprox form with Turbogears 2.1 and trying to display it in a Mako template. Here is my code: To define the form: class NewUserForm(AddRecordForm): __model__ = User newuserform = NewUserForm(DBSession) The controller definition that assigns the form and calls the template: @expose('limelight....
[ "Figured it out. I have to pass the variable through the the 'n' mako filter to remove any automatic filters mako applies to the html generated. So:\n${tmpl_context.register_form(value=value) | n}\n" ]
[ 3 ]
[]
[]
[ "forms", "mako", "python", "sprox", "turbogears" ]
stackoverflow_0001919833_forms_mako_python_sprox_turbogears.txt
Q: Interactive Python script output stored in some file How do I perform logging of all activities that are done by a Python script and all scripts that are called from it? I had several Bash scripts but now wrote a Python script which call all of these Bash scripts. I would like to have all output produced from thes...
Interactive Python script output stored in some file
How do I perform logging of all activities that are done by a Python script and all scripts that are called from it? I had several Bash scripts but now wrote a Python script which call all of these Bash scripts. I would like to have all output produced from these scripts stored in some file. The script is interactive P...
[ "Making Python's own prints go to both the terminal and a file is not hard:\n>>> import sys\n>>> class tee(object):\n... def __init__(self, fn='/tmp/foo.txt'):\n... self.o = sys.stdout\n... self.f = open(fn, 'w')\n... def write(self, s):\n... self.o.write(s)\n... self.f.write(s)\n... \n>>> sys.s...
[ 7, 1, 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0001936996_logging_python.txt
Q: Why does this code behave differently in Python3.1 than in Python2.6? I'm very new to programming so I apologize in advance if my question is too silly. #!/usr/bin/python2.6 import subprocess, time p=subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) for i in 'abcd': p.stdin.writ...
Why does this code behave differently in Python3.1 than in Python2.6?
I'm very new to programming so I apologize in advance if my question is too silly. #!/usr/bin/python2.6 import subprocess, time p=subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) for i in 'abcd': p.stdin.write(str.encode(i+'\n')) output=p.stdout.readline() print(output) ...
[ "Appears to be a difference in buffering. Adding a p.stdin.flush() call solved the problem. (See the comments above).\nCommunity wiki as I deserve no credits for this answer, but some answer needs to be marked accepted.\n[@Geo Pop: Please \"accept\" this question, as it apparently is correct.]\n" ]
[ 3 ]
[]
[]
[ "popen", "python", "stdin", "stdout", "subprocess" ]
stackoverflow_0001936725_popen_python_stdin_stdout_subprocess.txt
Q: Python Service File Caching Apache Race Condition I am writing a python service (pyamf) through which a user can access images. All images are stored on a central server. The python services will be running on satellite machines which have network access to server. The service should work as follows: check loca...
Python Service File Caching Apache Race Condition
I am writing a python service (pyamf) through which a user can access images. All images are stored on a central server. The python services will be running on satellite machines which have network access to server. The service should work as follows: check locally to see if the file exists, if so, use it. check loc...
[ "I'm guessing its either a threaded or a forked apache, but the effect would be the same since they are accessing a remote resource.\nThis problem is sometimes called the \"dog pile\" problem and its one of the issues addressed by the Beaker caching library (http://beaker.groovie.org). It provides a system bywhic...
[ 1 ]
[]
[]
[ "apache", "python", "race_condition", "service" ]
stackoverflow_0001937018_apache_python_race_condition_service.txt
Q: Word game server in Python, design pros and cons? I'd like to get busy with a winter programming project and am contemplating writing an online word game (with a server load of up to, say, 500 users simultaneously). I would prefer it to be platform independent. I intend to use Python, which I have some experience ...
Word game server in Python, design pros and cons?
I'd like to get busy with a winter programming project and am contemplating writing an online word game (with a server load of up to, say, 500 users simultaneously). I would prefer it to be platform independent. I intend to use Python, which I have some experience with. For user data storage, after previous experience ...
[ "I would go for Python + Django. It makes web application developments pretty easy.\n", "\nIs it worth starting with Python 3, or is it still too poorly supported with ports of modules from previous versions?\n\ndepends on which modules do you want to use. twisted is a \"swiss knife\" for the network programming ...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001937286_python.txt
Q: Is there a better way to serve the results of an expensive, blocking python process over HTTP? We have a web service which serves small, arbitrary segments of a fixed inventory of larger MP3 files. The MP3 files are generated on-the-fly by a python application. The model is, make a GET request to a URL specifying...
Is there a better way to serve the results of an expensive, blocking python process over HTTP?
We have a web service which serves small, arbitrary segments of a fixed inventory of larger MP3 files. The MP3 files are generated on-the-fly by a python application. The model is, make a GET request to a URL specifying which segments you want, get an audio/mpeg stream in response. This is an expensive process. We're...
[ "Have you tried Spawning? It is a WSGI server with a flexible assortment of threading modes.\n", "You might consider a queuing system with AJAX notification methods.\nWhenever there is a request for your expensive resource, and that resource needs to be generated, add that request to the queue (if it's not alread...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "http", "mod_wsgi", "python", "tornado" ]
stackoverflow_0001929681_http_mod_wsgi_python_tornado.txt
Q: How does one add default (hidden) values to form templates in Django? Given a Django.db models class: class P(models.Model): type = models.ForeignKey(Type) # Type is another models.Model class name = models.CharField() where one wishes to create a new P with a specified type, i.e. how does one make "type" t...
How does one add default (hidden) values to form templates in Django?
Given a Django.db models class: class P(models.Model): type = models.ForeignKey(Type) # Type is another models.Model class name = models.CharField() where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given likeso: h...
[ "The widget django.forms.widgets.HiddenInput will render your field as hidden.\nIn most cases, I think you'll find that any hidden form value could also be specified as a url parameter instead. In other words:\n<form action=\"new/{{your_hidden_value}}\" method=\"post\">\n....\n</form>\n\nand in urls.py:\n^/new/(?P...
[ 8, 5, 2 ]
[]
[]
[ "django", "django_templates", "django_urls", "python" ]
stackoverflow_0000271244_django_django_templates_django_urls_python.txt
Q: Importing Excel sheets, including formulae, into Django I have an Excel spreadsheet with calculations I would like to use in a Django web application. I do not need to present the spreadsheet as it appears in Excel. I only want to use the formulae embedded in it. What is the best way to do this? A: You can contr...
Importing Excel sheets, including formulae, into Django
I have an Excel spreadsheet with calculations I would like to use in a Django web application. I do not need to present the spreadsheet as it appears in Excel. I only want to use the formulae embedded in it. What is the best way to do this?
[ "You can control Excel with Python via COM. See this thread: Driving Excel from Python in Windows\nIt might be a challenge to get this to work reliably as part of a Django app.\n", "In addition to the COM solution, xlrd is cross-platform. That might be more suitable, since I believe Linux is still the most common...
[ 4, 1, 0, 0 ]
[]
[]
[ "django", "excel", "python" ]
stackoverflow_0001883098_django_excel_python.txt
Q: How to iterate over a string using a buffer (python) I'm trying to find some code that, given a string, will allow me to iterate over each line using the for loop construct, but with the added requirement that separate for loop constructs will not reset the iteration back to the beginning. At the moment I have sLi...
How to iterate over a string using a buffer (python)
I'm trying to find some code that, given a string, will allow me to iterate over each line using the for loop construct, but with the added requirement that separate for loop constructs will not reset the iteration back to the beginning. At the moment I have sList = [line for line in theString.split(os.linesep)] for li...
[ "Just use a generator expression (genexp) instead of the list comprehension (listcomp) you're now using - i.e.:\nsList = (line for line in theString.split(os.linesep))\n\nthat's all -- if you're otherwise happy with your code (splitting by os.linesep, even though normal text I/O in Python will already have translat...
[ 13, 2, 0, 0 ]
[]
[]
[ "buffer", "iteration", "python", "string" ]
stackoverflow_0001937519_buffer_iteration_python_string.txt
Q: Regular Expression to split on specific character ONLY if that character is not in a pair After finding the fastest string replace algorithm in this thread, I've been trying to modify one of them to suit my needs, particularly this one by gnibbler. I will explain the problem again here, and what issue I am having....
Regular Expression to split on specific character ONLY if that character is not in a pair
After finding the fastest string replace algorithm in this thread, I've been trying to modify one of them to suit my needs, particularly this one by gnibbler. I will explain the problem again here, and what issue I am having. Say I have a string that looks like this: str = "The &yquick &cbrown &bfox &Yjumps over the &u...
[ "You could use a negative lookbehind (assuming the regex engine in question supports it) to only match ampersands that do not follow another ampersand.\n/(?<!&)&/\n\n", "Maybe loop while (q = str.find('&', p)) != -1, then append the left side (p + 2 to q - 1) and the replacement value.\n", "I think this does th...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "regex", "replace", "string" ]
stackoverflow_0001936837_python_regex_replace_string.txt
Q: PyQt 4 UI freezes The following programm should just count up and int and displays its value in a label. But after a while the GUI stops working, while the loop continous. from PyQt4 import QtGui,QtCore import sys class main_window(QtGui.QWidget): def __init__(self,parent=None): #Layout ...
PyQt 4 UI freezes
The following programm should just count up and int and displays its value in a label. But after a while the GUI stops working, while the loop continous. from PyQt4 import QtGui,QtCore import sys class main_window(QtGui.QWidget): def __init__(self,parent=None): #Layout QtGui.QWidget.__init__...
[ "You're not letting Qt's event loop run, so the GUI is not responding. Also, repaint() is not needed, the QLabel.setText() will repaint the label. All it does is queue up an extra paint event, but this never gets processed. \nWhat you need to do is replace self.repaint() with QtGui.QApplication.processEvents(). Thi...
[ 7, 5, 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0001936868_pyqt_pyqt4_python_qt.txt
Q: python django string rendering issue I'm trying to render a string into a javascript ( which usually works fine for me ) here's my code HTML: THE USER NAME IS : {{name}} has added app {{has_added_app}} JAVA SCRIPT: <script> <!-- var userName = {{name}} The html version works the javascript fails wh...
python django string rendering issue
I'm trying to render a string into a javascript ( which usually works fine for me ) here's my code HTML: THE USER NAME IS : {{name}} has added app {{has_added_app}} JAVA SCRIPT: <script> <!-- var userName = {{name}} The html version works the javascript fails when I have tried the same rendering in java...
[ "var userName = {{name}}\n\nComes out when you view the HTML source as:\nvar userName = Bob\n\nWhich is an obvious mistake: missing quotes. But, simply putting quotes around it:\nvar userName = '{{name}}';\n\nisn't good enough for the general case. What if the string contains a quote character, or a backslash, or a...
[ 8, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001937682_django_python.txt