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: Regular Expressions: Print last in group I wrote a script to find a certain string and print a certain occurrence. This worked very well until the groups become an indeterminate length and I simply need to print the last one. I was curious for the found2.group and found3.group if there was a way to simply only pri...
Regular Expressions: Print last in group
I wrote a script to find a certain string and print a certain occurrence. This worked very well until the groups become an indeterminate length and I simply need to print the last one. I was curious for the found2.group and found3.group if there was a way to simply only print the last result. f = open ("CompTime.csv","...
[ "I believe that re.match only looks for first occurence, you can use re.findall(pattern, string) instead:\n>>> re.findall('-[a-zA-Z]', 'ls -A -H -B -b .')\n['-A', '-H', '-B', '-b']\n\nThen you can just access it like any other list:\n>>> re.findall('-[a-zA-Z]', 'ls -A -H -B -b .')[-1]\n'-b'\n\n" ]
[ 2 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0008158345_parsing_python_regex.txt
Q: minimizing the calculation time (ie: "print" slows it down) I have simple fibonacci(n) function that returns the n-th value. The main() code is as follows: def main(): # Programming 101, basic recursion start = time.clock() for i in range(36): print fibonacci(i) end = time.clock() print "Time elapsed...
minimizing the calculation time (ie: "print" slows it down)
I have simple fibonacci(n) function that returns the n-th value. The main() code is as follows: def main(): # Programming 101, basic recursion start = time.clock() for i in range(36): print fibonacci(i) end = time.clock() print "Time elapsed = ", end - start, "seconds" # Basic tweak no.1 start2 = time....
[ "Save you data by appending it in a list. Then print it in one shot as you did in your second example. This is a common idiom in python. Often you use something like:\nprint '\\n'.join(milistofdatastrings)\n\nYou have a collection of scipy performance tips here. I also like this compedium of numpy functions and exa...
[ 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0008157581_algorithm_python.txt
Q: Twisted async request processing How can I do async request processing in Twisted like in Node.js? I wrote sample with Twisted, but my app still waited an answer from long operation(I emulate this with time.sleep). Also I don't understand how can I use reactor.callLater correct. This is my sample of twisted app. ...
Twisted async request processing
How can I do async request processing in Twisted like in Node.js? I wrote sample with Twisted, but my app still waited an answer from long operation(I emulate this with time.sleep). Also I don't understand how can I use reactor.callLater correct. This is my sample of twisted app. from twisted.web import server from tw...
[ "You're already doing it... sort of.\nYour problem here is that time.sleep() is a blocking call, and will therefore make your whole server stop.\nIf you're using that as a stand-in for something that does network I/O (like urllib), the best option is usually to do the I/O with Twisted (like twisted.web.client.getPa...
[ 4 ]
[]
[]
[ "python", "twisted", "twisted.internet", "twisted.web" ]
stackoverflow_0008148048_python_twisted_twisted.internet_twisted.web.txt
Q: Fair semaphore in python Is it possible to have a fair semaphore in python, one that guarantees that blocking threads are unblocked in the order they call acquire()? A: You might have to build one from other moving parts. For example, create a Queue.Queue() to which each listener posts a brand-new Event() on whi...
Fair semaphore in python
Is it possible to have a fair semaphore in python, one that guarantees that blocking threads are unblocked in the order they call acquire()?
[ "You might have to build one from other moving parts. For example, create a Queue.Queue() to which each listener posts a brand-new Event() on which it then waits. When it is time to wake up one of the waiting threads, pop off the item on the queue that has been waiting longest — it will be one of those event object...
[ 6, 0 ]
[]
[]
[ "python", "semaphore", "synchronization" ]
stackoverflow_0008158442_python_semaphore_synchronization.txt
Q: Unexpected Text Widget behavior in loop Please refer the code below: I am able to print the two print statements (at #1 and #2) on real time basis(line by line). However the text widget appears only after the execution of the subprocess csh script. When I am able to print the values received from stdout of subproc...
Unexpected Text Widget behavior in loop
Please refer the code below: I am able to print the two print statements (at #1 and #2) on real time basis(line by line). However the text widget appears only after the execution of the subprocess csh script. When I am able to print the values received from stdout of subprocess, why is it not displayed on text widget? ...
[ "The problem is that events must be being serviced in order for the display to update. This is fundamental to the way that Tk (and hence Tkinter) works. The easiest method in Python is probably to put the reading from the subprocess in its own thread that then sends each line in a message to the main GUI thread for...
[ 0 ]
[]
[]
[ "python", "subprocess", "tk_toolkit", "tkinter", "widget" ]
stackoverflow_0008149326_python_subprocess_tk_toolkit_tkinter_widget.txt
Q: Create two immutable objects with the same value in Python Is it possible in Python to create two immutable objects with the same value? So that you understand what I mean, here are some examples: >>> a = 13 >>> b = 13 >>> a is b True >>> a = 13 >>> b = 26/2 >>> a is b True >>> a = 13 >>> b = int.__new__(int, 1...
Create two immutable objects with the same value in Python
Is it possible in Python to create two immutable objects with the same value? So that you understand what I mean, here are some examples: >>> a = 13 >>> b = 13 >>> a is b True >>> a = 13 >>> b = 26/2 >>> a is b True >>> a = 13 >>> b = int.__new__(int, 13) >>> a is b True >>> a = 13 >>> b = int("13") >>> a is b T...
[ "Sure, just choose a value that is too large to be cached:\n>>> a = 256\n>>> b = 256\n>>> a is b\nTrue\n>>> a = 257\n>>> b = 257\n>>> a is b\nFalse\n>>> a = \"hey\"\n>>> b = \"hey\"\n>>> a is b\nTrue\n>>> a = \"hey!\"\n>>> b = \"hey!\"\n>>> a is b\nFalse\n\nOnly small integers and short strings will be cached (and ...
[ 5 ]
[]
[]
[ "immutability", "python" ]
stackoverflow_0008158837_immutability_python.txt
Q: Python argument to provide less-like limiting functionality Any idea if there is a clean way to make optparse bypass/handle a generic -XXX option ? My case is an application for which i want to provide a less like option to limit the application s output entries to the number defined after - e.g. myapp.py list -10...
Python argument to provide less-like limiting functionality
Any idea if there is a clean way to make optparse bypass/handle a generic -XXX option ? My case is an application for which i want to provide a less like option to limit the application s output entries to the number defined after - e.g. myapp.py list -10 i guess i could overwrite sys.argv dict to avoid optparse from ...
[ "In argparse, you can define an optional positional integer argument. Negative values will then look to the user like giving an option:\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('limit', type=int, nargs='?')\nargs = parser.parse_args()\nif args.limit is not None:\n print \"Limitin...
[ 0 ]
[]
[]
[ "command_line_arguments", "optparse", "python" ]
stackoverflow_0008157472_command_line_arguments_optparse_python.txt
Q: Python Django UnboundLocalError while calling a different function Not long ago I started programming Python with Django. Sometimes I get strange errors and have no clue, why. So, let's beginn with one of these errors. I have a View with two functions. Example: def view_post(request, slug): """ Shows a sin...
Python Django UnboundLocalError while calling a different function
Not long ago I started programming Python with Django. Sometimes I get strange errors and have no clue, why. So, let's beginn with one of these errors. I have a View with two functions. Example: def view_post(request, slug): """ Shows a single post """ posts = Post.objects(slug = slug).limit(1) for ...
[ "The problem is the indentation\ndef view(request):\n ...\n def new(request):\n ...\n\nIs different for python of:\ndef view(request):\n ...\n\ndef new(request):\n ...\n\nYou should be sure use spaces for indentation and python recommends 4 spaces instead of tab\nUpdate:\nThe problem is in urls:\...
[ 3, 1 ]
[]
[]
[ "django", "python", "urlconf" ]
stackoverflow_0008158937_django_python_urlconf.txt
Q: 'Cannot request session' when using impacket's SMB client against a Windows machine i am running on fedora 15 ( python 2.7 ) i've tried the imapcket.smb against windows 2000 sp4 (frensh) , windows xp sp2 (frensh) , windows xp sp3 (frensh) and it worked perfectly , but when i use it against windows 7 (frensh) x64 i...
'Cannot request session' when using impacket's SMB client against a Windows machine
i am running on fedora 15 ( python 2.7 ) i've tried the imapcket.smb against windows 2000 sp4 (frensh) , windows xp sp2 (frensh) , windows xp sp3 (frensh) and it worked perfectly , but when i use it against windows 7 (frensh) x64 it didn't work . from my python : >>> import impacket.smb as smb >>> session = smb.SMB ( '...
[ "*SMBSERVER is a NetBios alias that would allow to establish a SMB over NetBIOS (port 139) connection against a target Windows machine without knowing the real NetBIOS server name of the target. Since Vista on, that alias has been deprecated.\nSo you have two choices:\n\nsession = smb.SMB ( '<TARGET NETBIOS NAME>' ...
[ 2 ]
[]
[]
[ "impacket", "linux", "python", "smb" ]
stackoverflow_0007711845_impacket_linux_python_smb.txt
Q: Tail -f log on server, process data, then serve to client via twisted Goal: Show data from server in wxPython GUI on client Newcomer to Twisted. I have a wxPython GUI running on a Windows 7 client, and I have a program running on an Ubuntu server that produces a log. My current attempt is to tail -f the log, pip...
Tail -f log on server, process data, then serve to client via twisted
Goal: Show data from server in wxPython GUI on client Newcomer to Twisted. I have a wxPython GUI running on a Windows 7 client, and I have a program running on an Ubuntu server that produces a log. My current attempt is to tail -f the log, pipe the output to a twisted server, then serve any data that meets my regex c...
[ "You've got a few different easily separated goals you're trying to achieve here. First, I'll talk about watching the log file.\nYour generator has a couple problems. One of them is big - it calls time.sleep(0.1). The sleep function blocks for the amount of time passed to it. While it is blocking, the thread wh...
[ 7 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0008157197_python_twisted.txt
Q: CherryPy + Jinja, where to initialize Environment I'm writing an application in python using CherryPy and Jinja as the template system. May be needed to say that i'm a beginner with these tools. The problem I'm facing now is I cannot figure where to initialize Jinja's Environment class. Currently I have applicat...
CherryPy + Jinja, where to initialize Environment
I'm writing an application in python using CherryPy and Jinja as the template system. May be needed to say that i'm a beginner with these tools. The problem I'm facing now is I cannot figure where to initialize Jinja's Environment class. Currently I have application.py (entry point, sets up Environment and starts ser...
[ "You shouldn't really repeat yourself. If I were you I would create a new python module templates.py and put all the jinja environment configuration / creation there. Afterwards you can simply import that environment wherever you need it (e.g. from templates import jinjaenv). In this case you keep things simple and...
[ 0 ]
[]
[]
[ "cherrypy", "jinja2", "python" ]
stackoverflow_0008159576_cherrypy_jinja2_python.txt
Q: Convert date, datetime to timestamp How can I produce a timestamp to millisecond accuracy from a date or datetime in Python? There are an overwhelming number of methods and ways of doing this, and I'm wondering which is the most Pythonic way. A: The following has worked for my purposes: To datetime from millise...
Convert date, datetime to timestamp
How can I produce a timestamp to millisecond accuracy from a date or datetime in Python? There are an overwhelming number of methods and ways of doing this, and I'm wondering which is the most Pythonic way.
[ "The following has worked for my purposes:\nTo datetime from millisecond timestamp\nimport datetime\ntimestamp #=> 1317912250955\ndt = datetime.datetime.fromtimestamp(time/1000.0)\ndt #=> datetime.datetime(2011, 10, 6, 10, 44, 10, 955000)\n\nFrom datetime to millisecond timestamp\nimport time\ndt #=> datetime.datet...
[ 11, 2, 0 ]
[]
[]
[ "datetime", "python", "python_3.x" ]
stackoverflow_0002755573_datetime_python_python_3.x.txt
Q: How do I debug error 500's served up by the DJango test server? I'm trying to debug my DJango Paypal IPN integration but I'm struggling. The Django dev server reports a 500 error to the console (but no other details) and the IPN test tool reports a 500 error but no other details. I've tried disabling the DEBUG mod...
How do I debug error 500's served up by the DJango test server?
I'm trying to debug my DJango Paypal IPN integration but I'm struggling. The Django dev server reports a 500 error to the console (but no other details) and the IPN test tool reports a 500 error but no other details. I've tried disabling the DEBUG mode to try and get it to send me emails but despite setting up the EMAI...
[ "Another thing to try is to launch a simple SMTP server on your machine.\npython -m smtpd -n -c DebuggingServer localhost:1025\n\nWhich will output on your console all emails headers and body.\nMake sure localhost and the port 1025 correpond to what you have in your settings.py, respectively in EMAIL_HOST and EMAIL...
[ 2, 1, 0 ]
[]
[]
[ "django", "internal_server_error", "paypal_ipn", "python" ]
stackoverflow_0008159414_django_internal_server_error_paypal_ipn_python.txt
Q: How can I read zip files from Google Storage in App Engine? An application creates a zip file and stores it to Google Storage. I am working on the web server side which is responsible for grabbing the zip file extract the contents etc. The web service is written in Python App Engine. So far I have set the credenti...
How can I read zip files from Google Storage in App Engine?
An application creates a zip file and stores it to Google Storage. I am working on the web server side which is responsible for grabbing the zip file extract the contents etc. The web service is written in Python App Engine. So far I have set the credentials and by following the tutorials I am able to list buckets cont...
[ "There's now an API that lets you manipulate objects in Google Storage directly. Using that, you can get a file-like object for the zipfile, and simply pass that to the zipfile module.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_storage", "python", "zip" ]
stackoverflow_0008151929_google_app_engine_google_cloud_storage_python_zip.txt
Q: Using quickly (python+gtk by Canonical), how do I pass self.ui items around when using multiprocessing I've been toying with Quickly (the Canonical created program for rapid development of Python + GTK applications), and I'd like this particular app I'm starting to develop to wait until at least one interface is "...
Using quickly (python+gtk by Canonical), how do I pass self.ui items around when using multiprocessing
I've been toying with Quickly (the Canonical created program for rapid development of Python + GTK applications), and I'd like this particular app I'm starting to develop to wait until at least one interface is "up" and has a default route allocated to it by DHCP. Here's my code thus far: import gettext import subproce...
[ "I would use the threading module rather than the multiprocessing one: http://docs.python.org/library/threading.html\nThe reason for this is that a new thread will execute in the same context as the main program so it will be a lot easier to exchange data while a sub-process will have a different context. The way t...
[ 2 ]
[]
[]
[ "canonical_quickly", "python", "ubuntu" ]
stackoverflow_0008159635_canonical_quickly_python_ubuntu.txt
Q: Specifying an index in QTableView with PyQt I have a table and I want to see the data at a specific coordinate- say Row 2, Column 5. I create a QPoint object with those values set, but when that gets translated into a QModelIndex object, I get Row 0 and Column 1. Here's the code: myQPoint = QPoint() myQPoi...
Specifying an index in QTableView with PyQt
I have a table and I want to see the data at a specific coordinate- say Row 2, Column 5. I create a QPoint object with those values set, but when that gets translated into a QModelIndex object, I get Row 0 and Column 1. Here's the code: myQPoint = QPoint() myQPoint.setX(2) myQPoint.setY(5) myIndex = sel...
[ "If you want to get the contents of an index at a specified column and row, use QTableView.model().index(row, column).data().\nQTableView.model(row, column) returns a QModelIndex object ( http://doc.qt.nokia.com/latest/qmodelindex.html ), which then has a QModelIndex.data(role) method. You can specifiy which role y...
[ 5, 2 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0008157688_pyqt_python.txt
Q: Elegant mechanism to determine smallest magnitude number but preserve sign in Python I have a Pythonic need to determine the minimum number in terms of absolute value, but preserve its sign. Below is the code I use to do this now. Is there a more elegant mechanism either mathematically or pythonically? This fu...
Elegant mechanism to determine smallest magnitude number but preserve sign in Python
I have a Pythonic need to determine the minimum number in terms of absolute value, but preserve its sign. Below is the code I use to do this now. Is there a more elegant mechanism either mathematically or pythonically? This function is one of the most used functions in my application, so it would be nice if it were...
[ "You can use the key named parameter of min:\n>>> min(-5, -10, 10, -2, -1, key=abs)\n-1\n\nSee also: documentation for the built-in function min.\n" ]
[ 16 ]
[]
[]
[ "math", "python" ]
stackoverflow_0008160214_math_python.txt
Q: Twisted web service - sql connection drops I am working on a web service with Twisted that is responsible for calling up several packages I had previously used on the command line. The routines these packages handle were being prototyped on their own but now are ready to be integrated into our webservice. In shor...
Twisted web service - sql connection drops
I am working on a web service with Twisted that is responsible for calling up several packages I had previously used on the command line. The routines these packages handle were being prototyped on their own but now are ready to be integrated into our webservice. In short, I have several different modules that all cre...
[ "i was developing a piece of software with twisted where i had to utilize a constant MySQL database connection. i did run into this problem and digging through the twisted documentation extensively and posting a few questions i was unable to find a proper solution.There is a boolean parameter you can pass when you ...
[ 2 ]
[]
[]
[ "mysql_connect", "python", "twisted", "web_services" ]
stackoverflow_0008159528_mysql_connect_python_twisted_web_services.txt
Q: python easy_install fails with "assembler for architecture ppc not installed" on Mac OS X bash-3.2$ sudo easy_install appscript Password: Searching for appscript Reading http://pypi.python.org/simple/appscript/ Reading http://appscript.sourceforge.net Best match: appscript 1.0.0 Downloading http://pypi...
python easy_install fails with "assembler for architecture ppc not installed" on Mac OS X
bash-3.2$ sudo easy_install appscript Password: Searching for appscript Reading http://pypi.python.org/simple/appscript/ Reading http://appscript.sourceforge.net Best match: appscript 1.0.0 Downloading http://pypi.python.org/packages/source/a/appscript/appscript-1.0.0.tar.gz#md5=6619b637037ea0f391f45870c13a...
[ "This happened for me after having upgraded to XCode 4; I haven't had time to figure out what went wrong during the upgrade (or whether this is the intended behaviour), but the following workaround works for me:\nsudo env ARCHFLAGS=\"-arch i386\" easy_install whatever\n\nThe ARCHFLAGS trick works with setup.py as w...
[ 77, 15, 1, 0 ]
[]
[]
[ "installation", "macos", "powerpc", "python", "xcode" ]
stackoverflow_0005256397_installation_macos_powerpc_python_xcode.txt
Q: dynamically create a function with a specific name I've read several articles on closures and what not but im attempting to create a specific named function from app.conf import html_helpers # html_helpers = ['img','js','meta'] def _makefunc(val): def result(): # Make this name of function? return va...
dynamically create a function with a specific name
I've read several articles on closures and what not but im attempting to create a specific named function from app.conf import html_helpers # html_helpers = ['img','js','meta'] def _makefunc(val): def result(): # Make this name of function? return val() return result def _load_func_from_module(module...
[ "I think functools.wraps should do what you want:\nfrom functools import wraps\n\ndef _makefunc(val):\n @wraps(val)\n def result():\n return val()\n return result\n\n>>> somefunc = _makefunc(list)\n>>> somefunc()\n[]\n>>> somefunc.__name__\n'list'\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008160537_python.txt
Q: python naming convention for plugins, i.e. non-top-level packages I'm wondering if there is naming convention for non-top-level python packages, i.e. so called plugins or extensions. According to PyPI the plugins, mostly, named with dash(-) or dot(.) e.g.: most django plugins named with dash while plone/zope and m...
python naming convention for plugins, i.e. non-top-level packages
I'm wondering if there is naming convention for non-top-level python packages, i.e. so called plugins or extensions. According to PyPI the plugins, mostly, named with dash(-) or dot(.) e.g.: most django plugins named with dash while plone/zope and many others prefer the dot, WTF? :) Thanks!
[ "I don't know of any such convention, but if there was one it would most probably be frameworkName-extensionName. It's the one I've seen used most often.\nPyPI's package index shows a mix of both. Stick to the existing convention whenever possible i.e. if you're developing a Django resusable app, use hyphen (-); fo...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008159313_python.txt
Q: twisted.web.resource.Resource with twisted.web.template.Element example I want to use twisted.web templates together twisted.web resources. But I just don't get, how to make them work together. I tried using, flatten(request, MyElement(), request.write), but it ends up throwing an exception: Request.write called ...
twisted.web.resource.Resource with twisted.web.template.Element example
I want to use twisted.web templates together twisted.web resources. But I just don't get, how to make them work together. I tried using, flatten(request, MyElement(), request.write), but it ends up throwing an exception: Request.write called on a request after Request.finish was called. Could someone provide me a very...
[ "It sounds like you forgot to return NOT_DONE_YET from your render() method, and therefore finish() was called for you immediately. Something like the following should be somewhere in Twisted itself, to help with exactly this problem:\nfrom twisted.web.resource import Resource\nfrom twisted.web.template import fla...
[ 5 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0008160061_python_twisted.txt
Q: Error setting status to empathy with dbus I'm getting error when I try setting status to empathy with dbus using python, this is the code I've got from different sources ## getting status from clementine music player import dbus # Clementine lives on the Session bus session_bus = dbus.SessionBus() # Get Clement...
Error setting status to empathy with dbus
I'm getting error when I try setting status to empathy with dbus using python, this is the code I've got from different sources ## getting status from clementine music player import dbus # Clementine lives on the Session bus session_bus = dbus.SessionBus() # Get Clementine's player object, and then get an interface ...
[ "Try this to update the status of Empathy with the current track playing in Clementine:\nimport dbus\nsession_bus = dbus.SessionBus()\nplayer = session_bus.get_object('org.mpris.clementine', '/Player')\niface = dbus.Interface(player, dbus_interface='org.freedesktop.MediaPlayer')\nmetadata = iface.GetMetadata()\nsta...
[ 4, 1 ]
[]
[]
[ "dbus", "python", "ubuntu" ]
stackoverflow_0007671763_dbus_python_ubuntu.txt
Q: Python basic on classes I have defined a class to process a file but get the following error when I try to instantiate the class and pass the filename. Let me know what would be the problem? >>> class fileprocess: ... def pread(self,filename): ... print filename ... f = open(filename,'w') ... ...
Python basic on classes
I have defined a class to process a file but get the following error when I try to instantiate the class and pass the filename. Let me know what would be the problem? >>> class fileprocess: ... def pread(self,filename): ... print filename ... f = open(filename,'w') ... print f >>> x = fileproces...
[ "x = fileprocess does not mean x is an instance of fileprocess. It means x is now an alias for the fileprocess class.\nYou need to create an instance, using the ().\nx = fileprocess()\nx.pread('c:/test.txt')\n\nIn addition, based on your original code, you could use x to create class instances.\nx = fileprocess\nf ...
[ 7, 3, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0008159525_class_python.txt
Q: Python: Return tuple or list? I have a method that returns either a list or a tuple. What is the most pythonic way of denoting the return type in the argument? def names(self, section, as_type=()): return type(as_type)(([m[0] for m in self.items(section)])) A: The pythonic way would be not to care about the ...
Python: Return tuple or list?
I have a method that returns either a list or a tuple. What is the most pythonic way of denoting the return type in the argument? def names(self, section, as_type=()): return type(as_type)(([m[0] for m in self.items(section)]))
[ "The pythonic way would be not to care about the type at all. Return a tuple, and if the calling function needs a list, then let it call list() on the result. Or vice versa, whichever makes more sense as a default type.\nEven better, have it return a generator expression:\ndef names(self, section):\n return (m[0...
[ 33, 6, 5 ]
[]
[]
[ "python" ]
stackoverflow_0008159107_python.txt
Q: Why do I get rows of zeros in my 2D fft? I am trying to replicate the results from a paper. "Two-dimensional Fourier Transform (2D-FT) in space and time along sections of constant latitude (east-west) and longitude (north-south) were used to characterize the spectrum of the simulated flux variability south of 40de...
Why do I get rows of zeros in my 2D fft?
I am trying to replicate the results from a paper. "Two-dimensional Fourier Transform (2D-FT) in space and time along sections of constant latitude (east-west) and longitude (north-south) were used to characterize the spectrum of the simulated flux variability south of 40degS." - Lenton et al(2006) The figures publishe...
[ "Consider the following example:\nIn [59]: from scipy import absolute, fft\n\nIn [60]: absolute(fft([1,2,3,4]))\nOut[60]: array([ 10. , 2.82842712, 2. , 2.82842712])\n\nIn [61]: absolute(fft([1,2,3,4, 1,2,3,4]))\nOut[61]: \narray([ 20. , 0. , 5.65685425, 0. ,\n ...
[ 3 ]
[]
[]
[ "fft", "image_processing", "numpy", "python", "signal_processing" ]
stackoverflow_0008151531_fft_image_processing_numpy_python_signal_processing.txt
Q: reST to Latex to PDF I was able to generate the latex output from reST using make latex command of Sphinx/Python. It generated the required latex files under latex directory. I am not sure on what I need to do for creating the PDF from latex. Can someone help me on what should i do next. A: There's an explanatio...
reST to Latex to PDF
I was able to generate the latex output from reST using make latex command of Sphinx/Python. It generated the required latex files under latex directory. I am not sure on what I need to do for creating the PDF from latex. Can someone help me on what should i do next.
[ "There's an explanation of how to do it here.\nShort story: use pdflatex. All your images must be in .eps format.\nYou can get pdflatex here. Edit: looks like it's a site for only pdftex. \nI seem to recall MiXTeX has the whole toolchain for windows users. And it comes with all the binaries, including pdflatex.\...
[ 2 ]
[]
[]
[ "pdflatex", "python", "python_sphinx", "restructuredtext" ]
stackoverflow_0008161186_pdflatex_python_python_sphinx_restructuredtext.txt
Q: unremovable text in tkinter here is some code: from Tkinter import * class Main(object): def __init__(self): self.console = Text(root, relief='groove', cursor='arrow', spacing1=3) self.console.insert(INSERT, '>>> ') self.console.focus_set() self.scroll = Scrollbar(root, cursor...
unremovable text in tkinter
here is some code: from Tkinter import * class Main(object): def __init__(self): self.console = Text(root, relief='groove', cursor='arrow', spacing1=3) self.console.insert(INSERT, '>>> ') self.console.focus_set() self.scroll = Scrollbar(root, cursor='arrow', command=self.console.yv...
[ "There is no built in way to do this. You will have to set up a collection of bindings that override the default behavior, and that's not a particularly easy thing to do. It's possible, though, since you have complete control over all bindings (ie: no behavior is hard-coded in the widget where it can't be changed)\...
[ 3, 3, 1 ]
[]
[]
[ "python", "text", "tk_toolkit", "tkinter" ]
stackoverflow_0007725009_python_text_tk_toolkit_tkinter.txt
Q: How to do fuzzy string search without a heavy database? I have a mapping of catalog numbers to product names: 35 cozy comforter 35 warm blanket 67 pillow and need a search that would find misspelled, mixed names like "warm cmfrter". We have code using edit-distance (difflib), but it probably won't scale to the...
How to do fuzzy string search without a heavy database?
I have a mapping of catalog numbers to product names: 35 cozy comforter 35 warm blanket 67 pillow and need a search that would find misspelled, mixed names like "warm cmfrter". We have code using edit-distance (difflib), but it probably won't scale to the 18000 names. I achieved something similar with Lucene, but a...
[ "Apparently the only way to make fuzzy comparisons fast is to do less of them ;)\nInstead of writing another n-gram search or improving the one in Whoosh we now keep a word index, retrieve all entries that have at least one (correctly spelled) word in common with the query, and use difflib to rank those. Works well...
[ 4, 3, 2, 1, 1, 1 ]
[]
[]
[ "database", "full_text_search", "fuzzy_search", "python" ]
stackoverflow_0000834570_database_full_text_search_fuzzy_search_python.txt
Q: Python 3.2.1: TypeError, Number of Arguments, Etc I have searched for the problem I am having, but have seen different variations of it that don't help me much (I am fairly new to Python; taking it as part of an introduction to programming at a university). The Problem: I keep getting a TypeError talking about the...
Python 3.2.1: TypeError, Number of Arguments, Etc
I have searched for the problem I am having, but have seen different variations of it that don't help me much (I am fairly new to Python; taking it as part of an introduction to programming at a university). The Problem: I keep getting a TypeError talking about the number of arguments, but I (with my so far limited kno...
[ "It's hard to tell because you've provided so much code, but I believe what's going on is this:\nwP = [Point(bX - (10 * bS) + 5, bS + 80), Point(bX - (10 * bS) + 105, bS + 120)]\n\nThis makes wP a list of two elements. Even though it contains two things, it's still a single object.\ngoWest = Rectangle(wP)\n\nI'm gu...
[ 5 ]
[]
[]
[ "arguments", "python", "typeerror" ]
stackoverflow_0008161669_arguments_python_typeerror.txt
Q: Get attribute of complex element using lxml I have a simple file XML like below: <brandName type="http://example.com/codes/bmw#" abbrev="BMW" value="BMW" />BMW</brandName> <maxspeed> <value>250</value> <unit type="http://example.com/codes/units#" value="miles per hour" abbrev="mph" /> ...
Get attribute of complex element using lxml
I have a simple file XML like below: <brandName type="http://example.com/codes/bmw#" abbrev="BMW" value="BMW" />BMW</brandName> <maxspeed> <value>250</value> <unit type="http://example.com/codes/units#" value="miles per hour" abbrev="mph" /> </maxspeed> I want to parse it using lxml and...
[ "import lxml.etree as ET\ncontent='''\n<Car xmlns=\"http://example.com/vocab/xml/cars#\">\n <brandName type=\"http://example.com/codes/bmw#\" abbrev=\"BMW\" value=\"BMW\" >BMW</brandName>\n <maxspeed>\n <value>250</value>\n <unit type=\"http://example.com/codes/units#\" value=\"miles per hour\" abbrev=\"m...
[ 0, 0 ]
[]
[]
[ "elementtree", "lxml", "python" ]
stackoverflow_0008161530_elementtree_lxml_python.txt
Q: Python list comprehension and list.remove() The list signals_by_date stores tuples and each tuple contains 15 numbers. For each tuple within signals_by_date, I want to remove numbers that don't satisfy certain criteria. For some reason, no matter what constraints I put in the list comprehension, I'm always left wi...
Python list comprehension and list.remove()
The list signals_by_date stores tuples and each tuple contains 15 numbers. For each tuple within signals_by_date, I want to remove numbers that don't satisfy certain criteria. For some reason, no matter what constraints I put in the list comprehension, I'm always left with 7 numbers in each tuple. In the code example b...
[ "The last line should read:\nsignals_by_date[i] = [v for v in signals_by_date[i] if v >= 3]\n\n", "Presumably, as you remove each item you're shifting the items in the list such that you skip seeing every second one.\nIn general, I believe list comprehensions are intended to accrue new lists from existing ones ra...
[ 3, 1 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0008162147_list_list_comprehension_python.txt
Q: Python - Locating the closest timestamp I have a Python datetime timestamp and a large dict (index) where keys are timestamps and the values are some other information I'm interested in. I need to find the datetime (the key) in index that is closest to timestamp, as efficiently as possible. At the moment I'm doin...
Python - Locating the closest timestamp
I have a Python datetime timestamp and a large dict (index) where keys are timestamps and the values are some other information I'm interested in. I need to find the datetime (the key) in index that is closest to timestamp, as efficiently as possible. At the moment I'm doing something like: for timestamp in timestamps...
[ "Dictionaries aren't organized for efficient near miss searches. They are designed for exact matches (using a hash table).\nYou may be better-off maintaining a separate, fast-searchable ordered structure.\nA simple way to start off is to use the bisect module for fast O(log N) searches but slower O(n) insertions:\...
[ 26, 4, 2 ]
[]
[]
[ "algorithm", "python", "search", "timestamp" ]
stackoverflow_0008162379_algorithm_python_search_timestamp.txt
Q: Good algorithm to find themes in tweets ranked by follower counts? I'm new to data mining and experimenting a bit. Let's say I have N twitter users and what I want to find is the overall theme they're writing about (based on tweets). Then I want to give higher weight to each theme if that user has higher followers...
Good algorithm to find themes in tweets ranked by follower counts?
I'm new to data mining and experimenting a bit. Let's say I have N twitter users and what I want to find is the overall theme they're writing about (based on tweets). Then I want to give higher weight to each theme if that user has higher followers. Then I want to merge all themes if there're similar enough but still r...
[ "Generally speaking : R has some packages specifically directed at text mining and datamining, offering a wide range of techniques. I have no knowledge of that kind of packages in Python, but that doesn't mean they don't exist. I just wouldn't implement it all myself, it's a bit more complicated than it looks at fi...
[ 4, 0 ]
[]
[]
[ "algorithm", "cluster_analysis", "data_mining", "python", "r" ]
stackoverflow_0004607295_algorithm_cluster_analysis_data_mining_python_r.txt
Q: How do you get the current URL for a Python uwsgi app? I'm using this uwsgi app: http://projects.unbit.it/uwsgi/wiki def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return "Hello World" I'd like to know what my current URL is, for example: localhost:9090/some/pat...
How do you get the current URL for a Python uwsgi app?
I'm using this uwsgi app: http://projects.unbit.it/uwsgi/wiki def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return "Hello World" I'd like to know what my current URL is, for example: localhost:9090/some/path/here?a=b&c=d For some reason this isn't in the docs. Am I...
[ "It's all in env, and wsgiref.util can help you get to it. And none of it is specific to uWSGI, which is just a WSGI container.\n", "Most (if not all) servers is based on Apache (grandaddy). The environment is standardized. \nTry: env['HTTP_HOST'], env['PATH_INFO'], env['HOST_NAME'], env['REQUEST_METHOD'], env['...
[ 3, 1 ]
[]
[]
[ "python", "uwsgi" ]
stackoverflow_0008162631_python_uwsgi.txt
Q: OpenCV 2.2 python bindings for machine learning part I'm interesting in getting the connection from Python to machine learning part of OpenCV 2.2. OpenCV 2.2 already includes python bindings but only to the computer vision (cv) part of it and not to the machine learning (ml) part. Where could I get some third part...
OpenCV 2.2 python bindings for machine learning part
I'm interesting in getting the connection from Python to machine learning part of OpenCV 2.2. OpenCV 2.2 already includes python bindings but only to the computer vision (cv) part of it and not to the machine learning (ml) part. Where could I get some third party bindings to also have access to the machine learning par...
[ "The pyopencv project is early in development, but provides access to most of the functionality, including the C++ and machine learning classes. It currently supports OpenCV 2.1.\nThe ctypes-opencv bindings have the same problem you ran into, inability to wrap the C++ classes in the machine learning library.\n", ...
[ 1, 0, 0 ]
[]
[]
[ "machine_learning", "opencv", "python" ]
stackoverflow_0005577164_machine_learning_opencv_python.txt
Q: python logging specific level only I'm logging events in my python code uing the python logging module. I have 2 logging files I wish to log too, one to contain user information and the other a more detailed log file for devs. I've set the the two logging files to the levels I want (usr.log = INFO and dev.log = ER...
python logging specific level only
I'm logging events in my python code uing the python logging module. I have 2 logging files I wish to log too, one to contain user information and the other a more detailed log file for devs. I've set the the two logging files to the levels I want (usr.log = INFO and dev.log = ERROR) but cant work out how to restrict t...
[ "I am in general agreement with David, but I think more needs to be said. To paraphrase The Princess Bride - I do not think this code means what you think it means. Your code has:\nlogger1 = logging.getLogger('')\n...\nlogger2 = logging.getLogger('')\n\nwhich means that logger1 and logger2 are the same logger, so w...
[ 71, 8 ]
[]
[]
[ "python" ]
stackoverflow_0008162419_python.txt
Q: How can I use Python 2.6 in Ubuntu 11.10? The default version of Python on Ubuntu 11.10 is 2.7, but I'm looking for 2.6. How do I make it default and where is the executable located? I type which python2.6 but it returns nothing, yet I did have a python2.6 folder under /usr/lib/python2.6. But it doesn't look like ...
How can I use Python 2.6 in Ubuntu 11.10?
The default version of Python on Ubuntu 11.10 is 2.7, but I'm looking for 2.6. How do I make it default and where is the executable located? I type which python2.6 but it returns nothing, yet I did have a python2.6 folder under /usr/lib/python2.6. But it doesn't look like the python2.7 which is at the same path /usr/li...
[ "You can install the package python2.6 (apt-get install python2.6). At this point, the default version of Python will still be 2.7. You can change this via\nln -s /usr/bin/python2.6 /usr/bin/python\n\nNote that there's a decent chance this could cause problems with your system. Several scripts assume the default ve...
[ 7, 4 ]
[]
[]
[ "pydev", "python", "ubuntu" ]
stackoverflow_0008163018_pydev_python_ubuntu.txt
Q: Separated web server and application server? I am developing web service. My system is like this: Client request --> Web Server(Apache) --> Application Server(Python) I used WSGI for communicating between Apache and Python. My question how can I separated the web server and app server. At the moment, I have to r...
Separated web server and application server?
I am developing web service. My system is like this: Client request --> Web Server(Apache) --> Application Server(Python) I used WSGI for communicating between Apache and Python. My question how can I separated the web server and app server. At the moment, I have to run them on the same server.
[ "WSGI is not a network protocol, so you will have to run a web server in front of your application even if it only acts as a WSGI container. Proxy connections from your main web server to the WSGI container with mod_proxy.\n", "+1 for Ignacio's answer. \nAlso note that separating a WSGI app from a server will l...
[ 3, 1 ]
[]
[]
[ "apache", "python", "wsgi" ]
stackoverflow_0008163418_apache_python_wsgi.txt
Q: Ordering in django model I have django model class TestResult(models.Model): chemical_name = char(50) value =char(50) unit = choices(UNIT_CHOICES) method = choices(METHOD_CHOICES) CSUSNormal = char(50) CSUSCaution = char(50) In admin page this model consist of 180 records. Now i want to ...
Ordering in django model
I have django model class TestResult(models.Model): chemical_name = char(50) value =char(50) unit = choices(UNIT_CHOICES) method = choices(METHOD_CHOICES) CSUSNormal = char(50) CSUSCaution = char(50) In admin page this model consist of 180 records. Now i want to apply ordering for these recor...
[ "Meta.ordering\n", "\nclass TestResult(models.Model):\n\n chemical_name = models.CharField(max_length=50)\n value =models.CharField(max_length=50)\n unit = models.CharField(choices=UNIT_CHOICES)\n method = models.CharField(METHOD_CHOICES)\n CSUSNormal = models.CharField(max_length=50)\n CSUSCaut...
[ 3, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008163667_django_python.txt
Q: How to render django form field in template I want to make a page with a list of users and checkboxes that signal if a user is selected, which will apply some action to selected users. I created a form class which looks like this: #in forms.py class UserSelectionForm(forms.Form): """form for selecting users"""...
How to render django form field in template
I want to make a page with a list of users and checkboxes that signal if a user is selected, which will apply some action to selected users. I created a form class which looks like this: #in forms.py class UserSelectionForm(forms.Form): """form for selecting users""" def __init__(self, userlist, *args, **kwargs...
[ "You're making the template far too complicated. Add a label to each field when you create it in the form's __init__ method.\nfor f in userlist:\n self.fields[str(f.id)] = forms.BooleanField(label=f.username, initial=False)\n\nThen just loop over the fields in the form and don't worry about the userlist anymore....
[ 13, 8 ]
[]
[]
[ "django", "django_forms", "django_template_filters", "django_templates", "python" ]
stackoverflow_0008157509_django_django_forms_django_template_filters_django_templates_python.txt
Q: Run the some code whenever I upload the project on to the app engine server I've built an appeninge project so, how can I run some piece of code on the appserver only once, i.e when ever I upload the whole project on to the server. How should I achieve this task??? A: There isn't an official way to discover if ...
Run the some code whenever I upload the project on to the app engine server
I've built an appeninge project so, how can I run some piece of code on the appserver only once, i.e when ever I upload the whole project on to the server. How should I achieve this task???
[ "There isn't an official way to discover if your application has been modified altought each time you upload your application it gets a unique version number {app version.(some unique number)} but since there isn't a document API on how to get it I wound't take a risk and use it.\nWhat you need todo is to have a sc...
[ 0 ]
[]
[]
[ "appserver", "google_app_engine", "python" ]
stackoverflow_0008163669_appserver_google_app_engine_python.txt
Q: How to save a python script directly from python shell? Currently, I am working on python interactive shell version 6. When i start python shell, i use to code some line. but i don't know how to store what i code. So, is there any command or or keyword to save my session on python shell as like .py A: Maybe you...
How to save a python script directly from python shell?
Currently, I am working on python interactive shell version 6. When i start python shell, i use to code some line. but i don't know how to store what i code. So, is there any command or or keyword to save my session on python shell as like .py
[ "Maybe you mean ipython? For this shell, all your input is stored in the In dictionary. Here's an example session log how to write input lines 2-3 into the script myscript.py:\nPython 2.7.1 |EPD 7.0-2 (32-bit)| (r271:86832, Nov 29 2010, 13:52:51) \nType \"copyright\", \"credits\" or \"license\" for more information...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008113090_python.txt
Q: How to access pop-up window with PAMIE I want to know how to change windows using PAMIE. I am using this to log on to a website with a password, and then click through some links and screens. After I log in the next screen is a new window and can't get to that window. from PAM30 import PAMIE ie1 = PAMIE() websit...
How to access pop-up window with PAMIE
I want to know how to change windows using PAMIE. I am using this to log on to a website with a password, and then click through some links and screens. After I log in the next screen is a new window and can't get to that window. from PAM30 import PAMIE ie1 = PAMIE() website = "my website" ie1.navigate(website) ie1.s...
[ "I dont know about PAMIE, but I have done something like what you describe with IEC.\nThis snippet opens an url, clicks a link to open a popup and the graps that popup to do some stuff. After that the popup is closed.\nie = IEC.IEController()\nie.Navigate(url)\nie.PollWhileBusy()\n\nwhile True:\n\n time.sleep(sl...
[ 0 ]
[]
[]
[ "pamie", "python" ]
stackoverflow_0008118845_pamie_python.txt
Q: Creating a subprocess in python I am trying to use th subprocess module along with the Popen class to create and run a process. Up until now, I always succeeded calling any program I wanted. Now I am trying to call paraview (version 3.8.1) with a python script attached to it as a parameter like so: paraview --scri...
Creating a subprocess in python
I am trying to use th subprocess module along with the Popen class to create and run a process. Up until now, I always succeeded calling any program I wanted. Now I am trying to call paraview (version 3.8.1) with a python script attached to it as a parameter like so: paraview --script=script.py If I run this command f...
[ "There are 2 things which are strage:\n\nNormally, this call shouldn't work at all. As you have shell=False, you would need to use a sequence as 1st parameter:\np = subprocess.Popen((\"paraview\", \"--script=script.py\"), bufsize=-1)\n\n(shell=False is the default.)\nYou seem to mix several Python versions:\n/home/...
[ 3, 1 ]
[]
[]
[ "paraview", "popen", "python", "subprocess" ]
stackoverflow_0008164125_paraview_popen_python_subprocess.txt
Q: Fitting a scikits.learn.hmm.GaussianHMM to variable length training sequences I'd like to fit a scikits.learn.hmm.GaussianHMM to training sequences of different length. The fit method, however, prevents using sequences of different length by doing obs = np.asanyarray(obs) which only works on a list of equally sh...
Fitting a scikits.learn.hmm.GaussianHMM to variable length training sequences
I'd like to fit a scikits.learn.hmm.GaussianHMM to training sequences of different length. The fit method, however, prevents using sequences of different length by doing obs = np.asanyarray(obs) which only works on a list of equally shaped arrays. Does anyone have a hint on how to proceed?
[ "You may do re-sampling to \"reshape\" a given input to the desired length.\n" ]
[ 7 ]
[]
[]
[ "hidden_markov_models", "python", "scikit_learn", "scikits" ]
stackoverflow_0004575041_hidden_markov_models_python_scikit_learn_scikits.txt
Q: How to make a custom element im gst-python i have quite a lot of experience with python and gst-python, but no experience with plain gstreamer. does anyone know (well, someone on earth probably does but...) how to create a custom element? i got as far as class MyElement(Element): by intuition, but i have no idea w...
How to make a custom element im gst-python
i have quite a lot of experience with python and gst-python, but no experience with plain gstreamer. does anyone know (well, someone on earth probably does but...) how to create a custom element? i got as far as class MyElement(Element): by intuition, but i have no idea what next... simply what i was hoping for was a "...
[ "If you're creating a source element, you probably want to subclass gst.BaseSrc. Then, IIRC, the main thing you need to do is implement the do_create() virtual method. Don't forget to gobject.type_register() your class; you may also need to set the time format using set_format().\nI second the recommendation to loo...
[ 0 ]
[]
[]
[ "gstreamer", "python" ]
stackoverflow_0005382305_gstreamer_python.txt
Q: Python copy file from remote machine to local machine I want to copy file from remote machine (Ex: 1.1.1.1) present in some directory to my local machine. Please let me know how to do it. If you can put any example that would be very grateful. Thanks in advance. I am using windows machine remote as well as local....
Python copy file from remote machine to local machine
I want to copy file from remote machine (Ex: 1.1.1.1) present in some directory to my local machine. Please let me know how to do it. If you can put any example that would be very grateful. Thanks in advance. I am using windows machine remote as well as local.
[ "The tool I use for copying to/from remote machines is fabric. \n", "Set up password less SSH between the 2 machines and do unlimited file transfers.. or use pexpect module to enter password when asked in your script\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008164172_python.txt
Q: Python freeze.py generated bin doesn't run I need to run a Python 2.7 script into a client critical machine, so I have permission to install nothing, and when I say nothing I mean nothing even into local dirs, so the solution I found is to pass him the script as a binary created with the batteries-included tool "f...
Python freeze.py generated bin doesn't run
I need to run a Python 2.7 script into a client critical machine, so I have permission to install nothing, and when I say nothing I mean nothing even into local dirs, so the solution I found is to pass him the script as a binary created with the batteries-included tool "freeze.py" http://wiki.python.org/moin/Freeze , a...
[ "I patched Python-2.7.2/Tools/freeze/makefreeze.py from the source package like this:\n--- orig/Python-2.7.2/Tools/freeze/makefreeze.py 2011-06-11 17:46:28.000000000 +0200\n+++ 2.7.2/Python-2.7.2/Tools/freeze/makefreeze.py 2011-11-15 18:18:33.632177119 +0100\n@@ -23,6 +23,7 @@\n \"\"\" + ((not __debug__ and \"...
[ 3 ]
[]
[]
[ "binary", "freeze", "python", "shared_libraries" ]
stackoverflow_0006486414_binary_freeze_python_shared_libraries.txt
Q: Unable to lazy reverse when using django-localeurl I'm using djangio-localeurl to provide locale switching based on my URLs. It works fine pretty much apart from a little hiccup. In some of my class-based views, I have been using a lazy reverse function else I get errors about missing URL patterns. This was someth...
Unable to lazy reverse when using django-localeurl
I'm using djangio-localeurl to provide locale switching based on my URLs. It works fine pretty much apart from a little hiccup. In some of my class-based views, I have been using a lazy reverse function else I get errors about missing URL patterns. This was something due to the order in which files were imported. One e...
[ "It was an error in lazy_reverse function it seems. I've not modified my lazy_reverse function to return unicode instead of str. Here's what it looks like:\nfrom django.utils.functional import lazy\nfrom django.core.urlresolvers import reverse\n\nreverse_lazy = lazy(reverse, unicode) \n\n" ]
[ 2 ]
[]
[]
[ "django", "django_localeurl", "python" ]
stackoverflow_0008132893_django_django_localeurl_python.txt
Q: Text to XML in python I'm trying to convert text into xml format. And I'm using LXML Library. But I'm getting error message. Please help me. Thank you import re from lxml import etree import urllib,urllib2 def get_movie_info(movie_id): URL = "http://www.raaga.com/a/rss.asp?%s"%(movie_id) f = urllib.urlope...
Text to XML in python
I'm trying to convert text into xml format. And I'm using LXML Library. But I'm getting error message. Please help me. Thank you import re from lxml import etree import urllib,urllib2 def get_movie_info(movie_id): URL = "http://www.raaga.com/a/rss.asp?%s"%(movie_id) f = urllib.urlopen(URL) movie_info = f.r...
[ "It works fine for me without this string:\nrss = \"\".join([ line.strip() for line in movie_info ])\n\nSomething like this:\nmi_tree = etree.fromstring(movie_info)\n\n" ]
[ 0 ]
[]
[]
[ "python", "url", "xml" ]
stackoverflow_0008164704_python_url_xml.txt
Q: Should structures in python be filled with zeros before being used in WinAPI calls? I want to use the WinAPI (CreateProcessA) in python with the help of ctypes. In order to call the function correctly, I should make some structure (e.g. STARTUPINFO, PROCESSINFORMATION) beforehand. I know that when you want to use...
Should structures in python be filled with zeros before being used in WinAPI calls?
I want to use the WinAPI (CreateProcessA) in python with the help of ctypes. In order to call the function correctly, I should make some structure (e.g. STARTUPINFO, PROCESSINFORMATION) beforehand. I know that when you want to use a structure in a WinAPI, you should use ZeroMemory to fill the structure with zeros. Sho...
[ "It depends. I don't think there is any single blanket requirement. Let us consider the two examples you give, in the context of CreateProcess.\nlpStartupInfo\nThis parameter is marked with the annotation __in. This means that the information is being passed from the caller to CreateProcess. In that case it is the...
[ 3, 0 ]
[]
[]
[ "ctypes", "python", "structure", "winapi" ]
stackoverflow_0008163837_ctypes_python_structure_winapi.txt
Q: Site packages in Python So I have two sitepackage folders: Under: /Library/Python/2.6/site-packages Under: /Library/Python/2.6/site-packages /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages Every time I do sudo easy_install module, Python installs it in (1). Every time I try to impor...
Site packages in Python
So I have two sitepackage folders: Under: /Library/Python/2.6/site-packages Under: /Library/Python/2.6/site-packages /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages Every time I do sudo easy_install module, Python installs it in (1). Every time I try to import it from (1), Python can't f...
[ "Add /Library/Python/2.6/site-packages to your PYTHONPATH.\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0008164875_python.txt
Q: Creating procedural MPEG-4 video with pygst I hope to find how to create MPEG-4 video file with pygst (other frameworks can be suggested). The question has three parts How to feed generated video data in pygst pipeline from Python frame buffer How to save this stream to MPEG-4 file How to mix this stream with MP3...
Creating procedural MPEG-4 video with pygst
I hope to find how to create MPEG-4 video file with pygst (other frameworks can be suggested). The question has three parts How to feed generated video data in pygst pipeline from Python frame buffer How to save this stream to MPEG-4 file How to mix this stream with MP3 audio source Pseudo-code below: for frame in r...
[ "You would probably want to create an appsink element, then for each frame create a new GstBuffer and push it into the pipeline with gst_app_src_push_buffer().\nThis is some example code, It does not work - ffmpeg complains about the frame length(?), but I think you get the point, and some hints.\nimport os\n\nos.p...
[ 2 ]
[]
[]
[ "gstreamer", "mpeg_4", "python", "python_gstreamer", "video" ]
stackoverflow_0007152611_gstreamer_mpeg_4_python_python_gstreamer_video.txt
Q: How do I get more locations? I am trying to get some locations in New York using FourSquare API using the following API call: https://api.foursquare.com/v2/venues/search?ll=40.7,-74&limit=50 What I don't understand is that if the call imposes a limit of 50 search results (which is the maximum), how can I get mor...
How do I get more locations?
I am trying to get some locations in New York using FourSquare API using the following API call: https://api.foursquare.com/v2/venues/search?ll=40.7,-74&limit=50 What I don't understand is that if the call imposes a limit of 50 search results (which is the maximum), how can I get more locations? When using Facebook A...
[ "The API docs here can help.\nFoursquare searching is very closely linked to the location 'point' (the 'll' param on the query) that you provide. The simple answer is that to find more venues within a given area, you need to simply query again with a different location 'point' within that area.\nTwo queries, both a...
[ 2, 1 ]
[]
[]
[ "foursquare", "http", "javascript", "python" ]
stackoverflow_0007303309_foursquare_http_javascript_python.txt
Q: Error when using argv I'm learning Python using Learn Python The Hard Way. It is very good and efficient but at one point I had a crash. I've searched the web but could not find an answer. Here is my question: One of the exercises tell to do this: from sys import argv script, filename = argv and then it proceed...
Error when using argv
I'm learning Python using Learn Python The Hard Way. It is very good and efficient but at one point I had a crash. I've searched the web but could not find an answer. Here is my question: One of the exercises tell to do this: from sys import argv script, filename = argv and then it proceeds to doing things that I do...
[ "script, filename = argv\n\nThis is unpacking the sequence argv. The first element goes into script, and the second element goes into filename. In general, this can be done with any iterable, as long as there exactly as many variables on the left-hand-side as are items in the iterable on the right-hand-side.\nThe c...
[ 2, 1, 1 ]
[]
[]
[ "argv", "python", "syntax_error" ]
stackoverflow_0008165086_argv_python_syntax_error.txt
Q: Accessing C++ typedef in Python using SWIG I have a C++ API I'm trying to wrap in Python. I want to call a wrapped C++ function myfunc taking as an argument the following C++ typedef /* my_header.h */ namespace my_namespace { typedef std::vector<Foo> Bar } where Foo is a C++ class. I managed to wrap the function...
Accessing C++ typedef in Python using SWIG
I have a C++ API I'm trying to wrap in Python. I want to call a wrapped C++ function myfunc taking as an argument the following C++ typedef /* my_header.h */ namespace my_namespace { typedef std::vector<Foo> Bar } where Foo is a C++ class. I managed to wrap the function and the underlying class Foo, but I don't know ...
[ "I solved it.\nSeems like the problem was I had to tell SWIG about the typedef already present in the %{ %} braces in the interface file, i.e.\n/* my_interface.i */\n\n%{\n#include \"my_header.h\"\ntypedef my_namespace::Bar Bar;\n%}\n\ntypedef my_namespace::Bar Bar;\n%include \"my_header.h\"\n\nAlthough I'm not 100...
[ 2 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0008155224_c++_python_swig.txt
Q: Boost.Python and C++ std::vector of pointers I'm using Boost.Python to create a wrapper for my C++ library, and I'm having some troubles, googling all the day did not produc any results. For example, I have the following code: class Base { public: virtual void func() = 0; }; class Derived : public Base { publ...
Boost.Python and C++ std::vector of pointers
I'm using Boost.Python to create a wrapper for my C++ library, and I'm having some troubles, googling all the day did not produc any results. For example, I have the following code: class Base { public: virtual void func() = 0; }; class Derived : public Base { public: virtual void func() { cout << ...
[ "You can fix this by registering Base* as a type that can be used to point to a BaseWrapper*:\nclass_<BaseWrapper, noncopyable, Base*>(\"Base\")\n .def(\"func\", pure_virtual(&Base::func));\n\nBut it seems that this means that Base can't have a pure virtual function...\n" ]
[ 3 ]
[]
[]
[ "boost", "pointers", "python", "vector" ]
stackoverflow_0008164745_boost_pointers_python_vector.txt
Q: using django with https using apache I am using Apache 2.2.21 with mod_wsgi on a machine running arch linux. I want to use django with https ability. I have also installed python2.7 and python 3.2. The django.wsdi file of the project is given below. When I try to access a sample file with https but without using d...
using django with https using apache
I am using Apache 2.2.21 with mod_wsgi on a machine running arch linux. I want to use django with https ability. I have also installed python2.7 and python 3.2. The django.wsdi file of the project is given below. When I try to access a sample file with https but without using django it works fine. When I try to get a f...
[ "Install a version of mod_wsgi compiled against Python 2.7. The mod_wsgi module can only be bound to one Python version at a time and what is uses cannot be changed dynamically, instead only being able to be set at compile time.\nIf you actually want to use different Python versions at different times, you will not...
[ 0 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0008164996_apache_django_mod_wsgi_python.txt
Q: How to pass a function and its arguments through a wrapper function in R? Similar to *args and *kwargs in python I want to write a wrapper function in R. I should take a function and its arguments. Do something, and then call the function with the supplied arguments. I know how to do it in python, but I search for...
How to pass a function and its arguments through a wrapper function in R? Similar to *args and *kwargs in python
I want to write a wrapper function in R. I should take a function and its arguments. Do something, and then call the function with the supplied arguments. I know how to do it in python, but I search for an implementation in R. In python I would write: def wrapper(func, *args, **kwargs): #do something here retur...
[ "wrapper <- function(func, ...) {\n func(...)\n}\n\n" ]
[ 12 ]
[]
[]
[ "argument_passing", "python", "r" ]
stackoverflow_0008165837_argument_passing_python_r.txt
Q: aix 6.1: python: ImportError: No module named _md5 I am trying to set up python environment on AIX 6.1 TL7, python-2.7.1-1.aix6.1.ppc.rpm installation was successful, however when I try to use BaseHttpServer I am getting following error: ImportError: No module named _md5 Please advise Thank You, m. A: I work...
aix 6.1: python: ImportError: No module named _md5
I am trying to set up python environment on AIX 6.1 TL7, python-2.7.1-1.aix6.1.ppc.rpm installation was successful, however when I try to use BaseHttpServer I am getting following error: ImportError: No module named _md5 Please advise Thank You, m.
[ "I worked it around by extracting md5.so from hashlib.a. fortunately dynamic library was in the archive. \n" ]
[ 1 ]
[]
[]
[ "aix", "import", "python" ]
stackoverflow_0008080885_aix_import_python.txt
Q: Python imports across modules and global variables I have a question which seems to be rather fundamental but I can't seem to find any help on this anywhere. file_a.py >> from xyz import XYZ class A: . . . file_b.py >> import file_a from file_a import A class B(A): def __init__(self): A....
Python imports across modules and global variables
I have a question which seems to be rather fundamental but I can't seem to find any help on this anywhere. file_a.py >> from xyz import XYZ class A: . . . file_b.py >> import file_a from file_a import A class B(A): def __init__(self): A.__init__(self) def someMethod(self): XYZ.do...
[ "\nIs my understanding wrong?\n\nYes, because the line from file_a import A import only class A into the namespace of file_b. The namespace of file_a is left alone. If it were not like this, there would be little sense in having both syntax:\nimport modulename\nfrom modulename import something\n\nas if your thinkin...
[ 5, 4, 3, 1 ]
[]
[]
[ "import", "python", "python_module" ]
stackoverflow_0008165703_import_python_python_module.txt
Q: Android JetCreator deepcopy error I’m trying to use the JetCreator python application that comes with the Android SDK to create sound files for Android. I get an error trying to play a midi segment using the provided JetCreator demo that come with the Android SDK android-sdk-r12-windows.zip. It tried it with Win...
Android JetCreator deepcopy error
I’m trying to use the JetCreator python application that comes with the Android SDK to create sound files for Android. I get an error trying to play a midi segment using the provided JetCreator demo that come with the Android SDK android-sdk-r12-windows.zip. It tried it with Windows XP and Windows 7. First I installe...
[ "So I'm not sure if you're still looking for an answer to this, but when I saw that you were having the same error with the same version of Python and WXPython as I was using I figured it must have something to do with the fact that the version the program was built with is no longer supported as it's from 2008. It...
[ 1 ]
[]
[]
[ "android", "python" ]
stackoverflow_0007949272_android_python.txt
Q: Printing Attribute Values in python-amara I'm trying to parse an xml file with using python-amara. doc = amara.parse('h.xml') assert doc.xml_type == tree.entity.xml_type m = doc.xml_children[0] print m When I do this it gives amara.tree.element at 0x94c864c: name u'HOP', 0 namespaces, 0 attributes, 93 childre...
Printing Attribute Values in python-amara
I'm trying to parse an xml file with using python-amara. doc = amara.parse('h.xml') assert doc.xml_type == tree.entity.xml_type m = doc.xml_children[0] print m When I do this it gives amara.tree.element at 0x94c864c: name u'HOP', 0 namespaces, 0 attributes, 93 children However when I try this : print doc.HOP.A.D ...
[ "To access elements in a way you are trying to do it, you must use \nfrom amara import bindery\ndoc = bindery.parse('h.xml')\n\ninstead of \ndoc = amara.parse('h.xml')\n\n" ]
[ 1 ]
[]
[]
[ "amara", "python", "xml_parsing" ]
stackoverflow_0003727633_amara_python_xml_parsing.txt
Q: Redirecting traffic to other webserver Here is my setup: I have a Python webserver (written myself) that listens on port 80 and also have the Transmission-daemon (bittorrent client) that provides a webUI on port 9101. (running on Linux) I can access both webservers locally without problems, but now would like to a...
Redirecting traffic to other webserver
Here is my setup: I have a Python webserver (written myself) that listens on port 80 and also have the Transmission-daemon (bittorrent client) that provides a webUI on port 9101. (running on Linux) I can access both webservers locally without problems, but now would like to access them externally also. My issue is that...
[ "I found my answer: a reverse proxy. It will take care of the routing to the correct port based on the URL. I now just have to select the right one there are so many (NginX, pound, lighttd etc...)\nThanks anyway.\n", "Return an http response with status code 300, see this\n" ]
[ 2, 0 ]
[]
[]
[ "linux", "python", "redirect", "transmission", "webserver" ]
stackoverflow_0008149701_linux_python_redirect_transmission_webserver.txt
Q: python sqlite3 sum each type I have a table (foos) which is a list of Foos, one row per type of Foo. A second table (items) is a list in which each row is the type of Foo and an amount (and other information). For example, Foo3, 45.2 and Foo2, 12.34. I'd like to determine the total of the amounts for each type o...
python sqlite3 sum each type
I have a table (foos) which is a list of Foos, one row per type of Foo. A second table (items) is a list in which each row is the type of Foo and an amount (and other information). For example, Foo3, 45.2 and Foo2, 12.34. I'd like to determine the total of the amounts for each type of Foo. This is my existing code, b...
[ "SELECT foo_type, SUM(amount)\nFROM items\nGROUP BY foo_type\n\ngives you within one query already each foo_type and the corresponding sum. You can build a dictionary from it and use it to expand data from the first query.\nOr put everything into one query:\ncursor.execute(\"SELECT foo_type, SUM(amount) \"\n ...
[ 4 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0008166990_python_sqlite.txt
Q: How to input data from a web page to Python script most efficiently How can I most easily input data from a web page and pass it to a Python script? I've been reading here and on other forums a lot about Python in connection with php or cgi, or even Tornado, Django, etc but I am quite puzzled what is the best solu...
How to input data from a web page to Python script most efficiently
How can I most easily input data from a web page and pass it to a Python script? I've been reading here and on other forums a lot about Python in connection with php or cgi, or even Tornado, Django, etc but I am quite puzzled what is the best solution for me. I have a Python script that grabs data from the web, generat...
[ "I now managed it with the exec() command.\n<html>\n<body>\n\n<form action=\"test.php\" method=\"get\">\n<input type=\"text\" name=\"name\" />\n<input type=\"submit\" />\n</form>\n\n</body>\n</html> \n\ntest.php:\n<?php\nexec(\"python mypythonscript.py \".$name, $output);\n?>\n\n", "To get a value from the form y...
[ 3, 1, 0 ]
[]
[]
[ "cgi", "forms", "php", "python", "web" ]
stackoverflow_0008137056_cgi_forms_php_python_web.txt
Q: Python Telnetlib and connecting timeout I am trying to make a script, which connects to a server by telnet. I am using python and telnetlib. I have problems getting timeout to work. I want to use the optional timeout when connecting to host, so that I get an exception if the host isn't online. I have read the pyth...
Python Telnetlib and connecting timeout
I am trying to make a script, which connects to a server by telnet. I am using python and telnetlib. I have problems getting timeout to work. I want to use the optional timeout when connecting to host, so that I get an exception if the host isn't online. I have read the python telnetlib documentation but I have no idea...
[ "You probably aren't using python 2.6 or above. Quote from the docs:\n\nChanged in version 2.6: timeout was added.\n\n" ]
[ 4 ]
[]
[]
[ "python", "telnetlib", "timeout" ]
stackoverflow_0008167453_python_telnetlib_timeout.txt
Q: Reportlab: dynamic color for table column (color stored in django model) in reportlab I have django model called TestResults models.py Class TestResults(models) chemical_name charfield value floatfield unit charfield method charfield normal_limit charfield caution_limit charfield color c...
Reportlab: dynamic color for table column (color stored in django model) in reportlab
I have django model called TestResults models.py Class TestResults(models) chemical_name charfield value floatfield unit charfield method charfield normal_limit charfield caution_limit charfield color charfield Now, The below code will generate the table for oils, which has following fields....
[ "Maybe I'm missing something, but this seems really easy.\nIn your objects, store the color you want in a variable like color as a valid ReportLab color specification (e.g. string of hex color value). Then when you build your report, if you want to set the background color, just set it for all the cells in the col...
[ 2 ]
[]
[]
[ "python", "reportlab" ]
stackoverflow_0008156280_python_reportlab.txt
Q: QWebView undersampled SVG rendering I'd like to use QWebView for an SVG thumbnailing job because it supports filters (unlike QSvgRender which only supports SVG Tiny 1.2). It seems to work quite well except for font rendering but that can be tweaked using fontconfig package. The problem is that it seems to be unde...
QWebView undersampled SVG rendering
I'd like to use QWebView for an SVG thumbnailing job because it supports filters (unlike QSvgRender which only supports SVG Tiny 1.2). It seems to work quite well except for font rendering but that can be tweaked using fontconfig package. The problem is that it seems to be undersampling elements with filters. Element...
[ "Try rendering using QWebPage (the non-GUI renderer), see if that helps. I can't see any setting that would affect the rendering.\nCode would be something like this (not checked):\nQWebPage page\nQWebFrame frame = page.mainFrame()\nframe.load(url)\nframe.render(painter)\n\n" ]
[ 1 ]
[]
[]
[ "pyqt", "python", "qt", "svg", "webkit" ]
stackoverflow_0006002621_pyqt_python_qt_svg_webkit.txt
Q: I have a cPickle error and does not know what he means maybe anyone know what this means? I use a process communication RMC for which the code may be found below: HOST = '' # local host PORT = 50000 SERVER_ADDRESS = HOST, PORT # set up server socket s = socket.socket() s.bind(SERVER_AD...
I have a cPickle error and does not know what he means maybe anyone know what this means?
I use a process communication RMC for which the code may be found below: HOST = '' # local host PORT = 50000 SERVER_ADDRESS = HOST, PORT # set up server socket s = socket.socket() s.bind(SERVER_ADDRESS) s.listen(1) while True: conn, addr = s.accept() connFile = conn...
[ "When you transform your socket in a file-like object (connFile = conn.makefile()), everything you had in your socket is available in your file. When you do cPickle.load(connFile) the first time, everything that is in your socket/file is loaded by pickle, so on the second call, there isn't anything to unpickle, tha...
[ 3 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0008166722_pickle_python.txt
Q: Python sys.maxint, sys.maxunicode on Linux and windows On 64-bit Debian Linux 6: Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.maxint 9223372036854775807 >>> sys.maxunicode 1114111 On 64-bit Wind...
Python sys.maxint, sys.maxunicode on Linux and windows
On 64-bit Debian Linux 6: Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.maxint 9223372036854775807 >>> sys.maxunicode 1114111 On 64-bit Windows 7: Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC...
[ "I don't know what your question is, but sys.maxunicode is not wrong on Windows.\nSee the docs:\n\nsys.maxunicode\nAn integer giving the largest supported code point for a Unicode character. The value of this depends on the configuration option that\n specifies whether Unicode characters are stored as UCS-2 or UC...
[ 4, 1 ]
[]
[]
[ "linux", "python", "unicode", "windows" ]
stackoverflow_0008164832_linux_python_unicode_windows.txt
Q: Nullable DecimalField returns 'This value must be a decimal number' when blank I have a field in my model that's of type DecimalField. Even though I have blank=True and null=True in the options, when my model goes through form validation and that field is blank, I get an error 'This value must be a decimal number....
Nullable DecimalField returns 'This value must be a decimal number' when blank
I have a field in my model that's of type DecimalField. Even though I have blank=True and null=True in the options, when my model goes through form validation and that field is blank, I get an error 'This value must be a decimal number.' Can DecimalFields not be null? I could set a default of 0 for this field but I'd r...
[ "Your forms.CharField will return an empty string, not None (Python's NULL). Therefore it tries to set the column to '' (empty string), not NULL.\nYou should probably use a django.forms.DecimalField in the form. See https://docs.djangoproject.com/en/dev/ref/forms/fields/#decimalfield\n" ]
[ 9 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0008114192_django_django_models_python.txt
Q: Python file to read in binary and write in xml I have a binary file which was created by a VBA file (I don't work with VBA or binary at all) but I need to get Python to read this binary file (which includes a list of inputs for a calculation) and then write these values into an xml file. If I know the order of the...
Python file to read in binary and write in xml
I have a binary file which was created by a VBA file (I don't work with VBA or binary at all) but I need to get Python to read this binary file (which includes a list of inputs for a calculation) and then write these values into an xml file. If I know the order of the inputs into the file that is created, is it possibl...
[ "Python is probably not the best tool, I would recommend VBA as it is going to be best suited to reading that file. Then, create your xml file as output.\n", "If you have the VBA code that made the file you should be able to copy the data structure in python and then deserialize it.\n" ]
[ 0, 0 ]
[]
[]
[ "binary", "python", "xml" ]
stackoverflow_0008168482_binary_python_xml.txt
Q: Mocking file objects or iterables in python Which way is proper for mocking and testing code that iters object returned by open(), using mock library? whitelist_data.py: WHITELIST_FILE = "testdata.txt" format_str = lambda s: s.rstrip().lstrip('www.') whitelist = None with open(WHITELIST_FILE) as whitelist_data: ...
Mocking file objects or iterables in python
Which way is proper for mocking and testing code that iters object returned by open(), using mock library? whitelist_data.py: WHITELIST_FILE = "testdata.txt" format_str = lambda s: s.rstrip().lstrip('www.') whitelist = None with open(WHITELIST_FILE) as whitelist_data: whitelist = set(format_str(line) for line in ...
[ "You're looking for a MagicMock. This supports iteration.\nIn mock 0.80beta4, patch returns a MagicMock. So this simple example works:\nimport mock\n\ndef foo():\n for line in open('myfile'):\n print line\n\n@mock.patch('__builtin__.open')\ndef test_foo(open_mock):\n foo()\n assert open_mock.calle...
[ 16 ]
[]
[]
[ "mocking", "python", "python_mock", "tdd" ]
stackoverflow_0008166633_mocking_python_python_mock_tdd.txt
Q: How to launch a file with its default application using Python for WIN32, WIN64 and MAC OSX? Possible Duplicate: Open document with default application in Python I want python code to launch a file with its default application e.g. a .txt file with notepad(when notepad is set as the default application to open ....
How to launch a file with its default application using Python for WIN32, WIN64 and MAC OSX?
Possible Duplicate: Open document with default application in Python I want python code to launch a file with its default application e.g. a .txt file with notepad(when notepad is set as the default application to open .txt files) I want to do this for WIN 32 bit, WIN 64 bit and MAC OS X Please help me out
[ "Well it might seem awkward but following works quite well under Win Xp:\nimport webbrowser\n\nwebbrowser.open(\"myFile.txt\")\n\n", "I don't know about OS X, but an os.system call with the file name as an argument works on Windows.\nAlso take a look at this answer.\n" ]
[ 0, 0 ]
[]
[]
[ "launch", "python" ]
stackoverflow_0008167004_launch_python.txt
Q: Extend python's dict functionality to user created classes Is it possible to add dict functionality to user created classes? ie: class Foo(object): def __init__(self, x, y): self.x self.y def __dict__(self): return {'x': self.x, 'y': self.y} f = Foo() dict(f) <-- throws TypeError: ite...
Extend python's dict functionality to user created classes
Is it possible to add dict functionality to user created classes? ie: class Foo(object): def __init__(self, x, y): self.x self.y def __dict__(self): return {'x': self.x, 'y': self.y} f = Foo() dict(f) <-- throws TypeError: iteration over non-sequence
[ "The dict constructor expects either a mapping or an iterable of key/value pairs as a parameter, so your class needs to either implement the mapping protocol or be iterable.\nHere's an example how to got about the latter approach:\nclass Foo(object):\n def __init__(self, x, y):\n self.x = x\n self.y ...
[ 3 ]
[]
[]
[ "dictionary", "extend", "map", "python" ]
stackoverflow_0008168957_dictionary_extend_map_python.txt
Q: Notebook widgets do not display properly unless we resize the window in wxPython? im having a little issue with NoteBook switching. When I switch notebook tabs, I will need to resize to make the wigdets display properly. I tried using self.Refresh() but that does not seem to do anything. If you have trouble unders...
Notebook widgets do not display properly unless we resize the window in wxPython?
im having a little issue with NoteBook switching. When I switch notebook tabs, I will need to resize to make the wigdets display properly. I tried using self.Refresh() but that does not seem to do anything. If you have trouble understanding me, please run the following code, then switch tabs and resize, you will notice...
[ "Just change the self.Refresh() to self.Layout(). Worked for me on Windows 7 anyway.\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008161569_python_wxpython.txt
Q: Pythonic way of checking if several elements are in a list I have this piece of code in Python: if 'a' in my_list and 'b' in my_list and 'c' in my_list: # do something print my_list Is there a more pythonic way of doing this? Something like (invalid python code follows): if ('a', 'b', 'c') individual_in m...
Pythonic way of checking if several elements are in a list
I have this piece of code in Python: if 'a' in my_list and 'b' in my_list and 'c' in my_list: # do something print my_list Is there a more pythonic way of doing this? Something like (invalid python code follows): if ('a', 'b', 'c') individual_in my_list: # do something print my_list
[ "if set(\"abc\").issubset(my_list):\n # whatever\n\n", "The simplest form:\nif all(x in mylist for x in 'abc'):\n pass\n\nOften when you have a lot of items in those lists it is better to use a data structure that can look up items without having to compare each of them, like a set.\n", "You can use set o...
[ 13, 10, 3 ]
[]
[]
[ "list", "python" ]
stackoverflow_0008169074_list_python.txt
Q: Python - Append Help - String & list Another append question... This is my code: def s(xs,n,m): t = [] while n < m: n += 2 t.append(xs[n]) return t When I evaluate the following: x = s('African', 0, 3) Why does it return this?: ['r', 'c'] A: while n < m: n += 2 # at this point n...
Python - Append Help - String & list
Another append question... This is my code: def s(xs,n,m): t = [] while n < m: n += 2 t.append(xs[n]) return t When I evaluate the following: x = s('African', 0, 3) Why does it return this?: ['r', 'c']
[ "while n < m:\n n += 2 # at this point n = 2 because you've passed 0\n t.append(xs[n]) # you append r to t since xs[2] = r\n\nbut n < m still, so next iteration:\nwhile n < m:\n n += 2 # at this point n = 4\n t.append(xs[n]) # you append c to t since xs[4] = c\n\nnow n > m, so the function returns ['r',...
[ 3, 2 ]
[]
[]
[ "append", "python" ]
stackoverflow_0008169249_append_python.txt
Q: How to speed up debugging of python programs in PyDev in Eclipse (esspecially Google App Engine) How it possible to speed up debugging in PyDev in Eclipse for Google App Engine programs? How to speed up code execution? How to speed up application reloading? Please share your experience or suggestions. A: How o...
How to speed up debugging of python programs in PyDev in Eclipse (esspecially Google App Engine)
How it possible to speed up debugging in PyDev in Eclipse for Google App Engine programs? How to speed up code execution? How to speed up application reloading? Please share your experience or suggestions.
[ "How often do you need to reload the application?, the dev server will update all your code and configuration changes without need to reload.\n" ]
[ 0 ]
[]
[]
[ "debugging", "google_app_engine", "optimization", "pydev", "python" ]
stackoverflow_0008169561_debugging_google_app_engine_optimization_pydev_python.txt
Q: Decoding MIME (HTML+Attachments) I'm planning to write an application that should handle incoming mails. Basically it will act more like a ticketing system than a webmail, so I'm only interested in receiving emails, and not sending them. I have made a simple prototype that downloads mails and displays the text wit...
Decoding MIME (HTML+Attachments)
I'm planning to write an application that should handle incoming mails. Basically it will act more like a ticketing system than a webmail, so I'm only interested in receiving emails, and not sending them. I have made a simple prototype that downloads mails and displays the text with downloadable attachments in a web pa...
[ "There are several email-handling packages in the Python standard library. I haven't worked with them very much, so I'm not sure whether they do quite what you intend, but if you haven't already I would suggest taking a look at e.g. the email package.\nIf you're looking for something higher-level than that, I'm sur...
[ 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "java", "perl", "php", "python", "ruby" ]
stackoverflow_0002795893_java_perl_php_python_ruby.txt
Q: Extract artist and music From text (regex) I have written following regex But its not working. Can you please help me? thank you :-) track_desc = '''<img src="http://images.raaga.com/catalog/cd/A/A0000102.jpg" align="right" border="0" width="100" height="100" vspace="4" hspace="4" /> <p> <...
Extract artist and music From text (regex)
I have written following regex But its not working. Can you please help me? thank you :-) track_desc = '''<img src="http://images.raaga.com/catalog/cd/A/A0000102.jpg" align="right" border="0" width="100" height="100" vspace="4" hspace="4" /> <p> </p> <p> Artist(s) David: <br/> ...
[ "You were ignoring the whitespace:\n<p>[\\s\\n\\r]*Artist\\(s\\)[\\s\\n\\r]*(.*?)[\\s\\n\\r]*:[\\s\\n\\r]*<br/>[\\s\\n\\r]*Music:[\\s\\n\\r]*(.*?)<br/>[\\s\\n\\r]*</p>\n\nOutput is:\n[1] => \"David\"\n[2] => \"Ramana Gogula\"\n\n(note that your regex didn't match the Artists(s) and Music: prefixes either)\n\nHoweve...
[ 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008169461_python_regex.txt
Q: Pygame + Opengl + Frustum not displaying anything I'm trying to set up a simple 3d view with pygame and opengl, using frustum to set up the projection matrix. Here is my initialization code: def initgl(self): glClearColor(0.0,0.0,0.0,0.0) glViewport(0,0,640,480) glMatrixMode(GL_PROJECTION) glLoadId...
Pygame + Opengl + Frustum not displaying anything
I'm trying to set up a simple 3d view with pygame and opengl, using frustum to set up the projection matrix. Here is my initialization code: def initgl(self): glClearColor(0.0,0.0,0.0,0.0) glViewport(0,0,640,480) glMatrixMode(GL_PROJECTION) glLoadIdentity() glFrustum(0,640,480,0,.1,1000.) glMatr...
[ "I've never used glFrustum (the whole matrix stack is deprecated since OpenGL3.3, btw) but since the 5th parameter seems to be the near plane, your geometry is simply behind it !\nIn other words, all vertices already being in world space (since you're not setting a model view matrix) and having a Z of 0.0, they are...
[ 1, 1 ]
[]
[]
[ "opengl", "pygame", "python" ]
stackoverflow_0008161477_opengl_pygame_python.txt
Q: What is wrong with this setInterval() code of javascript? Hi I am working on an application in Django. I have multiple threads running and I need to check the status of the threads periodically. So I used setInterval() but I want to stop it when I have exception in thread. But it is not stopping and keeps on calli...
What is wrong with this setInterval() code of javascript?
Hi I am working on an application in Django. I have multiple threads running and I need to check the status of the threads periodically. So I used setInterval() but I want to stop it when I have exception in thread. But it is not stopping and keeps on calling the URL. Here is my code: function checkThreadsStatus(){ ...
[ "What if you define your var g_progress_intv before your setInterval? But it should be working as you got it, there's nothing wrong with your definition. \nDEMO: http://jsfiddle.net/fH6c9/2/\nfunction checkThreadsStatus(){\n var g_progress_intv;\n g_progress_intv = setInterval(function() {\n\nInstead of your ...
[ 0, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0008169873_javascript_python.txt
Q: Model Creation by SQLAlchemy database reflection I am currently working on a pyramid system that uses sqlalchemy. This system will include a model (let's call it Base) that is stored in a database table. This model should be extensible by the user on runtime. Basically, the user should be able to subclass the Base...
Model Creation by SQLAlchemy database reflection
I am currently working on a pyramid system that uses sqlalchemy. This system will include a model (let's call it Base) that is stored in a database table. This model should be extensible by the user on runtime. Basically, the user should be able to subclass the Base and create a new model (let's call this one 'Child')....
[ "This doesn't seem to have much to do with \"database reflection\", but rather dynamic table creation. This is a pretty dangerous operation and generally frowned upon.\nYou should try to think about how to model the possible structure your users would want to add to the Base and design your schema around that. Some...
[ 4, 2, 1, 1 ]
[]
[]
[ "pyramid", "python", "reflection", "sqlalchemy" ]
stackoverflow_0008122078_pyramid_python_reflection_sqlalchemy.txt
Q: Reusing patch objects in matplotlib without them moving position I want to automatically generate a series of plots which are clipped to patches. If I try and reuse a patch object, it moves position across the canvas. This script (based on an answer to a previous question by Yann) demonstrates what is happening. ...
Reusing patch objects in matplotlib without them moving position
I want to automatically generate a series of plots which are clipped to patches. If I try and reuse a patch object, it moves position across the canvas. This script (based on an answer to a previous question by Yann) demonstrates what is happening. import pylab as plt import scipy as sp import matplotlib.patches as p...
[ "The problem can be avoided by using the same axes for each plot, with ax.cla() called to clear the plot after each iteration.\nimport pylab as plt\nimport scipy as sp\nimport matplotlib.patches as patches\n\nsp.random.seed(100)\npatch = patches.Circle((.75,.75),radius=.25,fc='none')\n\nfig = plt.figure()\nax = fig...
[ 2, 2 ]
[]
[]
[ "canvas", "figure", "matplotlib", "patch", "python" ]
stackoverflow_0008166294_canvas_figure_matplotlib_patch_python.txt
Q: SQLAlchemy Query not returning all of large text field First up, here's a little bit about my environment: Using MSSMS as my database management tool. Using Django 1.3 Using SQLAlchemy I have a text field in the database with no max length. There is text in it that is 890591 characters long. When I retrieve this...
SQLAlchemy Query not returning all of large text field
First up, here's a little bit about my environment: Using MSSMS as my database management tool. Using Django 1.3 Using SQLAlchemy I have a text field in the database with no max length. There is text in it that is 890591 characters long. When I retrieve this field using SQLAlchemy it is truncated to 64512 characters....
[ "I know little of *nix connectivity to SQL Server, but simple googling suggests that the issue is related to FreeTDS configuration:\n\nA related question on SO: Data ended at 64512 characters - MSSQL // PHP // OPENSuSE // APACHE2.\nAnother Q&A extracted from here:\n\n\nMy text data are being truncated or are causin...
[ 4 ]
[]
[]
[ "django", "python", "sql", "sqlalchemy" ]
stackoverflow_0008160564_django_python_sql_sqlalchemy.txt
Q: Speed up this interpolation in python I have an image processing problem I'm currently solving in python, using numpy and scipy. Briefly, I have an image that I want to apply many local contractions to. My prototype code is working, and the final images look great. However, processing time has become a serious bot...
Speed up this interpolation in python
I have an image processing problem I'm currently solving in python, using numpy and scipy. Briefly, I have an image that I want to apply many local contractions to. My prototype code is working, and the final images look great. However, processing time has become a serious bottleneck in our application. Can you help me...
[ "I'm pretty sure that, as you said, the bulk of the calculation time happens in interpolate.map_coordinates(…), which gets called once for every iteration on center_points, here 10,000 times. Generally, working with the numpy/scipy stack, you want the repetitive task over a large array to happen in native Numpy/Sci...
[ 3 ]
[]
[]
[ "interpolation", "numpy", "optimization", "python", "scipy" ]
stackoverflow_0008158953_interpolation_numpy_optimization_python_scipy.txt
Q: XML quoting in Python How to quote XML to get the string with quoted control characters in python? Source string: <root namespace="value" id="guid"> <child name="child1">Content</child> </root> Result string: <root namespace=\"value\" id=\"guid\">\n <child name=\"child1\">Content<\/child><\/root> A: You ...
XML quoting in Python
How to quote XML to get the string with quoted control characters in python? Source string: <root namespace="value" id="guid"> <child name="child1">Content</child> </root> Result string: <root namespace=\"value\" id=\"guid\">\n <child name=\"child1\">Content<\/child><\/root>
[ "You can find information about how to escape/unscape xml entities in the python.org wiki. In particular, there's a section about quoting attributes with xml.sax.saxutils.quoteattr which seems to be what you're looking for.\n" ]
[ 0 ]
[]
[]
[ "python", "quoting", "xml" ]
stackoverflow_0006691996_python_quoting_xml.txt
Q: Strip string after third occurrence of character python I want to strip all characters after a third character, say - for instance. I found this code online and it works but I'm having trouble learning how it works and wanted to ask so I can understand it fully. def indexList(s, item, i=0): """ Return an ...
Strip string after third occurrence of character python
I want to strip all characters after a third character, say - for instance. I found this code online and it works but I'm having trouble learning how it works and wanted to ask so I can understand it fully. def indexList(s, item, i=0): """ Return an index list of all occurrances of 'item' in string/list 's'. ...
[ "Here is a way:\ndef trunc_at(s, d, n=3):\n \"Returns s truncated at the n'th (3rd by default) occurrence of the delimiter, d.\"\n return d.join(s.split(d, n)[:n])\n\nprint trunc_at(\"115Z2113-3-777-55789ABC7777\", \"-\")\n\nHow it works:\n\nThe string s is split into a list at each occurrence of the delimite...
[ 28, 11, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008170982_python.txt
Q: How do I avoid naming clashes within Python's module system? In my Django project I have an app called profile, which mostly contains my profile.models.UserProfile class for additional information on User objects (may seem familiar to Django folks). Now I've put some initialization code into profile/__init__.py (s...
How do I avoid naming clashes within Python's module system?
In my Django project I have an app called profile, which mostly contains my profile.models.UserProfile class for additional information on User objects (may seem familiar to Django folks). Now I've put some initialization code into profile/__init__.py (some signals) and have ran into a problem: Django tells me that a t...
[ "You should never import your own modules in the form import mymodule (relative imports). Instead you should always use import myproject.mymodule instead (absolute imports). This avoids all name clashes.\n" ]
[ 5 ]
[]
[]
[ "django", "python", "python_import", "python_module" ]
stackoverflow_0008171225_django_python_python_import_python_module.txt
Q: Python socket dictionary with select For some reason I cannot match select sockets to my dictionary of sockets. The below code creates a dictionary of sockets (which is does) then when someone connects accept (which it doesn't). It finds 's' in 'L', but then cannot socket.error: [Errno 22] Invalid argument listeni...
Python socket dictionary with select
For some reason I cannot match select sockets to my dictionary of sockets. The below code creates a dictionary of sockets (which is does) then when someone connects accept (which it doesn't). It finds 's' in 'L', but then cannot socket.error: [Errno 22] Invalid argument listening = {} L = [] for link in links: try:...
[ "I think the problem is that when you add the append client socket to (input), you are also adding it to (L). This happens because input and L are both pointing to the same list object. Then, when the newly-connected-client-socket sends you some data, you try to call accept() on the client socket, but of course t...
[ 0, 0 ]
[]
[]
[ "dictionary", "python", "sockets" ]
stackoverflow_0008101430_dictionary_python_sockets.txt
Q: python lxml - modify attributes from lxml import objectify, etree root = etree.fromstring('''<?xml version="1.0" encoding="ISO-8859-1" ?> <scenario> <init> <send channel="channel-Gy"> <command name="CER"> <avp name="Origin-Host" value="router1dev"></avp> <avp name="Origin-Realm...
python lxml - modify attributes
from lxml import objectify, etree root = etree.fromstring('''<?xml version="1.0" encoding="ISO-8859-1" ?> <scenario> <init> <send channel="channel-Gy"> <command name="CER"> <avp name="Origin-Host" value="router1dev"></avp> <avp name="Origin-Realm" value="realm.dev"></avp> ...
[ "import lxml.etree as et\n\ntree = et.fromstring('''\n... your xml ...\n''')\n\nfor host_ip in tree.xpath(\"/scenario/init/send/command[@name='CER']/avp[@name='Host-IP-Address']\"):\n host_ip.attrib['value'] = 'foo'\n\nprint et.tostring(tree)\n\n", "You could try this:\nr = etree.fromstring('...')\n\nelement =...
[ 43, 8 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0008171146_lxml_python_xml.txt
Q: Importing a module from an upper directory within a package when the package is imported from another place I have a project that I am having problems with. kreveik. |-- classes | |-- baseclasses.py | |-- family.py | |-- __init__.py | `-- network.py |-- family | |-- __init__.py | `-- killer.py `-- gene...
Importing a module from an upper directory within a package when the package is imported from another place
I have a project that I am having problems with. kreveik. |-- classes | |-- baseclasses.py | |-- family.py | |-- __init__.py | `-- network.py |-- family | |-- __init__.py | `-- killer.py `-- genetic `-- __init__.py This is the relevant part of the project. The traceback explains me what I was trying to...
[ "You must also reference the enclosing package when importing from a sub-package.\nIn this example, in network.py, use\nfrom kreivik.classes import *\n\n" ]
[ 1 ]
[]
[]
[ "packaging", "python" ]
stackoverflow_0008171445_packaging_python.txt
Q: subtraction operator python I want to reduce the number of "the" words from a by 2. But this code doesn't seem to run. I cannot understand why the multiplication operator works but the subtraction operator doesn't. b = "the" a = b * 5 print a a -= (b * 2) print a output the the the the the the Traceback (most...
subtraction operator python
I want to reduce the number of "the" words from a by 2. But this code doesn't seem to run. I cannot understand why the multiplication operator works but the subtraction operator doesn't. b = "the" a = b * 5 print a a -= (b * 2) print a output the the the the the the Traceback (most recent call last): a -= (b ...
[ "b = \"the\"\na = b * 5\nprint a\n\na = a[:-2*len(b)]\nprint a\n\n# returns: thethethe\n\nI am not substracting (you cannot really do it with strings), I am removing twice the length of b from the end of a, ignoring its real value.\n", "To reduce the number of \"the\" by 2 in you word, try with the replace method...
[ 4, 3, 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008168194_python.txt
Q: Replacing text with variables I have to send out letters to certain clients and I have a standard letter that I need to use. I want to replace some of the text inside the body of the message with variables. Here is my maturity_letter models.py class MaturityLetter(models.Model): default = models.BooleanField(defa...
Replacing text with variables
I have to send out letters to certain clients and I have a standard letter that I need to use. I want to replace some of the text inside the body of the message with variables. Here is my maturity_letter models.py class MaturityLetter(models.Model): default = models.BooleanField(default=False, blank=True) body = model...
[ "use format strings:\n>>> print \"today is %(date)s, im %(age)d years old!\" % {\"date\":\"my birthday!\",\"age\":100}\ntoday is my birthday!, im 100 years old!\n\n", "I think this is the best way to do it. First, you have a file with your template, something like:\nDear {{primary-firstname}},\nAN IMPORTANT REMIN...
[ 4, 2, 0 ]
[ "You can use regular expression substitution with a callback. The advantage of this over a simple string replace or using django's template engine is that you also know when undefined variables are used (since you might not want to send out letters/emails like that :)\nimport re\n\nbody = \"\"\"\nDear [primary-firs...
[ -1 ]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0008156503_django_django_models_django_views_python.txt
Q: Python Imaging Library errors with libjpeg I have a centos 5 and am trying to get Python Imaging library up and going. I installed libjpeg, libjpeg-devel, etc and am still not able to upload jpeg images to my django site. I have reinstalled PIL several times. Through PIP, through easy_install2.6 and building m...
Python Imaging Library errors with libjpeg
I have a centos 5 and am trying to get Python Imaging library up and going. I installed libjpeg, libjpeg-devel, etc and am still not able to upload jpeg images to my django site. I have reinstalled PIL several times. Through PIP, through easy_install2.6 and building manually. Each time it shows JPEG support avail...
[ "Make sure you don't have a different version libjpeg installed which is being used. To check it, try\nlsof | grep libjpeg\n\n", "I had the same issues and documented my installation step by step. It's quite a long one: you can find it on my blog.\nIt will help you with the following:\n\nA working copy\nDjango\nP...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "libjpeg", "python", "python_imaging_library" ]
stackoverflow_0006880930_django_libjpeg_python_python_imaging_library.txt
Q: validating an array of regex string on a string I have an array of regex to apply on a string. regexString = "'\d{2,}';'..'" regexPatterns = regexString.split(";") regexPatterns = ["'\d{2,}'","'..'"] How can I efficiently use that list and only match if all the regex find a match? A: You could use the built-in ...
validating an array of regex string on a string
I have an array of regex to apply on a string. regexString = "'\d{2,}';'..'" regexPatterns = regexString.split(";") regexPatterns = ["'\d{2,}'","'..'"] How can I efficiently use that list and only match if all the regex find a match?
[ "You could use the built-in all() function:\nisgood = all(re.search(regex, s) for regex in regexPatterns)\n\n" ]
[ 3 ]
[]
[]
[ "django", "python", "regex" ]
stackoverflow_0008172179_django_python_regex.txt
Q: How do I read the last modified file that contains a certain string? I want to find the last modified file that contains a string using python. I have many files in my directory so comparing dates is not appealing. I am looking for a way to search the file by modified data until I hit a file containing the string ...
How do I read the last modified file that contains a certain string?
I want to find the last modified file that contains a string using python. I have many files in my directory so comparing dates is not appealing. I am looking for a way to search the file by modified data until I hit a file containing the string I want. Or if there is a better way to do this that would be great.
[ "To search for the last modified file in the current directory that contains the string search_string, you can use this code:\nfiles = os.listdir(\".\")\nfiles.sort(key=os.path.getmtime, reverse=True)\nfor name in files:\n with open(name) as f:\n if search_string in f.read():\n print name\n ...
[ 4 ]
[]
[]
[ "python", "readfile" ]
stackoverflow_0008172336_python_readfile.txt