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: wxPython: how to make taskbar icon respond to left-click Using wxPython, I created a taskbar icon and menu. Everything works fine (in Windows at least) upon right-click of the icon: i.e., the menu is displayed, and automatically hidden when you click somewhere else, like on Windows' taskbar. Now I do want to have ...
wxPython: how to make taskbar icon respond to left-click
Using wxPython, I created a taskbar icon and menu. Everything works fine (in Windows at least) upon right-click of the icon: i.e., the menu is displayed, and automatically hidden when you click somewhere else, like on Windows' taskbar. Now I do want to have the menu appear when the icon is left-clicked as well. So I in...
[ "Ah, I've discovered what went wrong. In the statement\nself.PopupMenu(self.tbicon.CreatePopupMenu())\n\nI had bound the popup menu to the frame, instead of to the taskbar icon.\nBy changing it to:\nself.tbicon.PopupMenu(self.tbicon.CreatePopupMenu())\n\nall is working well now.\nThanks for all remarks\n", "I thi...
[ 4, 0 ]
[]
[]
[ "python", "taskbar", "wxpython" ]
stackoverflow_0003235408_python_taskbar_wxpython.txt
Q: How can I use python to load a browser session that posts values to a url? I have a python script that takes a number of variables. I also have a html page that can receive post values. How can I start a browser from python and point it to the html page I have above and send those post variables to the html url? T...
How can I use python to load a browser session that posts values to a url?
I have a python script that takes a number of variables. I also have a html page that can receive post values. How can I start a browser from python and point it to the html page I have above and send those post variables to the html url? The problem I have is that if I use urllib/urllib2 to do the post, it doesn't loa...
[ "Do the values have to be supplied via HTTP POST? Could you supply the parameters as part of the URL and use a GET instead?\ne.g. Build a URL similar to the following:\nhttp://somehost/somefile.html?param1=value1&param2=value2&...\n", "\"... it doesn't load the browser window.\"\nSorry, I don't fully understand ...
[ 0, 0, 0 ]
[]
[]
[ "html", "php", "post", "python" ]
stackoverflow_0003263350_html_php_post_python.txt
Q: Python API C++ : "Static variable" for a Type Object I have a small question about static variable and TypeObjects. I use the API C to wrap a c++ object (let's call it Acpp) that has a static variable called x. Let's call my TypeObject A_Object : typedef struct { PyObject_HEAD Acpp* a; } A_Object; The TypeObj...
Python API C++ : "Static variable" for a Type Object
I have a small question about static variable and TypeObjects. I use the API C to wrap a c++ object (let's call it Acpp) that has a static variable called x. Let's call my TypeObject A_Object : typedef struct { PyObject_HEAD Acpp* a; } A_Object; The TypeObject is attached to my python module "myMod" as "A". I have...
[ "Essentially, what you're trying to do is define a \"static property\". That is, you want a function to be called when you get/set an attribute of the class.\nWith that in mind, you might find this thread interesting. It only talks about Python-level solutions to this problem, not C extension types, but it covers...
[ 1, 0 ]
[]
[]
[ "api", "c++", "python", "static", "wrapper" ]
stackoverflow_0003265592_api_c++_python_static_wrapper.txt
Q: HTML form data to recursive json dict I would like to convert flat form data to recursive JSON data in python or javascript. This JSON data can later be interpreted by a template engine (google for tempest, it has django like syntax). There are plenty examples to convert flat data to recursive data, but the proble...
HTML form data to recursive json dict
I would like to convert flat form data to recursive JSON data in python or javascript. This JSON data can later be interpreted by a template engine (google for tempest, it has django like syntax). There are plenty examples to convert flat data to recursive data, but the problem is it can't be a dict or list only. I tri...
[ "Well, if you know the format will be consistent then something like this will work:\ndef add_data(node, name, value):\n if '-' not in name:\n node[name] = value\n else:\n key = name[:name.index('-')]\n node_index = int(name[len(key) + 1:name.index('.')])\n node.setdefault(key, [])...
[ 1 ]
[]
[]
[ "html", "javascript", "json", "python", "recursion" ]
stackoverflow_0003265218_html_javascript_json_python_recursion.txt
Q: Python over JavaScript? (Facts, please) I recently learned JavaScript an all of the sudden I hear about Python... Should I go learn Python or just stick with my basic JavaScript knowledge? If you have some "facts" I would love to hear them! Like efficiency, difficultylevel and so on, an so on... Thanks :) A: The...
Python over JavaScript? (Facts, please)
I recently learned JavaScript an all of the sudden I hear about Python... Should I go learn Python or just stick with my basic JavaScript knowledge? If you have some "facts" I would love to hear them! Like efficiency, difficultylevel and so on, an so on... Thanks :)
[ "The two are generally used quite differently. Javascript is primarily used as a client side scripting language vs python which is a server based language. So in a website you could use both. But not sure if this is what you were wondering.\n", "If you're just learning a language, then there is none better than P...
[ 15, 12, 4, 3, 2, 2, 1, 1, 0, 0, 0 ]
[ "If you need to ask, then I would say no since you don't have a need in mind for its usage.\n" ]
[ -2 ]
[ "javascript", "python" ]
stackoverflow_0003266223_javascript_python.txt
Q: What is the most efficient way to repeatedly use regular expressions in a Python loop? When you're iterating over hundreds of lines in a file, what is the most (and least) efficient way to run regular expressions in Python? Specifically, is the following bad form? for line in file: data = re.search('(\d+\.\d+)\|...
What is the most efficient way to repeatedly use regular expressions in a Python loop?
When you're iterating over hundreds of lines in a file, what is the most (and least) efficient way to run regular expressions in Python? Specifically, is the following bad form? for line in file: data = re.search('(\d+\.\d+)\|(-\d+\.\d+)\|(.*?)\|(.*?)\|(\d+:\d+\s+\w+)\sTO\s(.*?)',line) one = data.group(1) two = d...
[ "If you're just using this same regex over and over again, you don't need to compile it directly. http://docs.python.org/release/2.6.5/library/re.html#re.compile\n\nThe compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular...
[ 6, 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003266134_python_regex.txt
Q: Django boilerplate template code I am a django newbie and in creating my first project I have come to realize that a lot of my boilerplate code (the lists on the side of my page). I have to recreate them in every view and I am trying to stick with DRY but I find myself rewriting the code every time. Is there a wa...
Django boilerplate template code
I am a django newbie and in creating my first project I have come to realize that a lot of my boilerplate code (the lists on the side of my page). I have to recreate them in every view and I am trying to stick with DRY but I find myself rewriting the code every time. Is there a way to inherit from my base views and ju...
[ "Yes, you'll want to look into template inheritance, which lets you share common elements between templates, and the {% include %} template tag, which lets you create reusable template \"snippets\" that can be included in other templates.\nEdit: Re-reading the question, it sounds like you're talking about boilerpla...
[ 3, 3, 3, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003250463_django_python.txt
Q: Python: Obtain a URL Because I cant get this working: Python: KeyError with form.getfirst I have an alternative option, I have a function in DTML which needs to obtain a URL: For example if the dtml webpage is located at www.blah.com/foo/foo2?variable=55 How would i obtain the URL of this page using a python fu...
Python: Obtain a URL
Because I cant get this working: Python: KeyError with form.getfirst I have an alternative option, I have a function in DTML which needs to obtain a URL: For example if the dtml webpage is located at www.blah.com/foo/foo2?variable=55 How would i obtain the URL of this page using a python function? The function is ca...
[ "for: http://www.blah.com/foo/foo2?job_ID=55555&test=1\n<dtml-var URL> = http://www.blah.com/foo/foo2\n<dtml-var QUERY_STRING> = job_ID=55555&test=1\n<dtml-var \"REQUEST['job_ID']\"> = 55555\nSee: http://wiki.zope.org/zope2/REQUESTX\n" ]
[ 1 ]
[]
[]
[ "dtml", "python", "zope" ]
stackoverflow_0003251020_dtml_python_zope.txt
Q: Python: KeyError with form.getfirst I have a dtml page, which calls a function, with this code: <dtml-var public_blast(form.getfirst('job_ID'))> But i get a key error? stating KeyError: "public_blast(form.getfirst('job_ID'))". I can see the job_ID variable at the top of the page. So i know it is being passed to t...
Python: KeyError with form.getfirst
I have a dtml page, which calls a function, with this code: <dtml-var public_blast(form.getfirst('job_ID'))> But i get a key error? stating KeyError: "public_blast(form.getfirst('job_ID'))". I can see the job_ID variable at the top of the page. So i know it is being passed to the URL. I cant see where im going wrong?
[ "It's been a very long time since I did any DTML, but I don't think you can call Python functions directly like that inside a DTML tag. \nInstead I think you need to use the expr attribute:\n<dtml-var expr=\"public_blast(form.getfirst('job_ID'))\">\n\n", "Try <dtml-var \"REQUEST['job_ID']\">\n" ]
[ 0, 0 ]
[]
[]
[ "dtml", "python" ]
stackoverflow_0003250572_dtml_python.txt
Q: PUT Variables Missing between Python and Tomcat I'm trying to get a PUT request from Python into a servlet in Tomcat. The parameters are missing when I get into Tomcat. The same code is happily working for POST requests, but not for PUT. Here's the client: lConnection = httplib.HTTPConnection('localhost:8080') lH...
PUT Variables Missing between Python and Tomcat
I'm trying to get a PUT request from Python into a servlet in Tomcat. The parameters are missing when I get into Tomcat. The same code is happily working for POST requests, but not for PUT. Here's the client: lConnection = httplib.HTTPConnection('localhost:8080') lHeaders = {"Content-type": "application/x-www-form-url...
[ "I tried your code and it seems that the parameters get to the server using that code. Tcpdump gives:\nPUT /my/url/ HTTP/1.1\nHost: localhost\nAccept-Encoding: identity\nContent-Length: 59\nContent-type: application/x-www-form-urlencoded\nAccept: text/plain\n\nUsername=usr&Password=password&Surname=Last&Forenames=F...
[ 2, 2, 1 ]
[]
[]
[ "http", "put", "python", "tomcat" ]
stackoverflow_0003266997_http_put_python_tomcat.txt
Q: Is there a list of 3rd party Python 3 libraries? More and more libraries are being ported to Python 3, and I suspect the changes will happen more and more rapidly as time goes on. However, as a non-newbie to Python, there are quite a few 3rd party libraries I use (matplotlib, pygame, pyGTK, Tkinter, among others)....
Is there a list of 3rd party Python 3 libraries?
More and more libraries are being ported to Python 3, and I suspect the changes will happen more and more rapidly as time goes on. However, as a non-newbie to Python, there are quite a few 3rd party libraries I use (matplotlib, pygame, pyGTK, Tkinter, among others). I know I should just be able to go to their site(s) t...
[ "On the side menu at pypi.python.org there is a link entitled \"Python 3 packages\":\nhttp://pypi.python.org/pypi?:action=browse&c=533&show=all\n" ]
[ 10 ]
[]
[]
[ "python", "python_3.x", "reference" ]
stackoverflow_0003267805_python_python_3.x_reference.txt
Q: Recommendation for click/event tracking mechanisms (python, django, celery, mongo etc) I'm looking into way to track events in a django application (events would generally be clicks tied to a specific unique user id). These events would essentially contain an event type like "click" and then each click event would...
Recommendation for click/event tracking mechanisms (python, django, celery, mongo etc)
I'm looking into way to track events in a django application (events would generally be clicks tied to a specific unique user id). These events would essentially contain an event type like "click" and then each click event would be assigned to a unique id (many events can go to one id) and each event would have a data ...
[ "I am not familiar with the pre-packaged solutions you mention. Were I to design this from scratch, I'd have a simple JS collecting info on clicks and posting it back to the server via Ajax (using whatever JS framework you're already using), and on the server side I'd simply append that info to a log file for late...
[ 5, 2, 1 ]
[]
[]
[ "django", "events", "mongodb", "python", "tracking" ]
stackoverflow_0003267081_django_events_mongodb_python_tracking.txt
Q: Why aren't the Python 2.7 command-line tools located in `/usr/local/bin` on Mac OS X? The Python 2.7 installer disk image for Mac OS X (python-2.7-macosx10.5.dmg) states: The installer puts the applications in "Python 2.7" in your Applications folder, command-line tools in /usr/local/bin and the underlying machin...
Why aren't the Python 2.7 command-line tools located in `/usr/local/bin` on Mac OS X?
The Python 2.7 installer disk image for Mac OS X (python-2.7-macosx10.5.dmg) states: The installer puts the applications in "Python 2.7" in your Applications folder, command-line tools in /usr/local/bin and the underlying machinery in /Library/Frameworks/Python.framework. However, after installation there are no Pyth...
[ "The python.org Python installer for OS X is a meta package with a set of several packages. You can see the packages by clicking on the Customize button during the installation process. The symlinks in /usr/local/bin are installed by the UNIX command-line tools package. For the 2.7 release, that package is no long...
[ 4, 2 ]
[ "11:54 jsmith@upsidedown find /usr -name python2.7\n11:54 jsmith@upsidedown\n\nYeah, that sucks.\nI'd follow the pattern that the Python 2.6 (and, in my case, 2.5) installer did, and create the symlinks (as you're suspecting). The pattern stayed the same, at least:\n11:57 jsmith@upsidedown /Library/Frameworks/P...
[ -1 ]
[ "installation", "macos", "python" ]
stackoverflow_0003266005_installation_macos_python.txt
Q: How can we properly implement Python bindings of subclassed C++ objects? I'm having an issue with a rather intricate interaction of C++ and Python that I'm hoping the community can help me with. If my explanation doesn't make sense, let me know in the comments and I'll try to clarify. Our C++ code base contains a...
How can we properly implement Python bindings of subclassed C++ objects?
I'm having an issue with a rather intricate interaction of C++ and Python that I'm hoping the community can help me with. If my explanation doesn't make sense, let me know in the comments and I'll try to clarify. Our C++ code base contains a parent classes called "IODevice" which is a parent to other classes such as "...
[ "Are your types FilePy and IODevice derived from PyObject? Otherwise, the C++ compiler will interpret:\ninputFile = (IODevice*) cD_py;\n\nas:\ninputFile = reinterpret_cast<IODevice*> (cD_py);\n\nrather than what you expected:\ninputFile = dynamic_cast<IODevice*> (cD_py);\n\nIf the actual type passed is not PyObjec...
[ 4 ]
[]
[]
[ "c++", "inheritance", "python" ]
stackoverflow_0003268230_c++_inheritance_python.txt
Q: Trouble with syntax - if/else and raw_input() Okay, so the answer is probably obvious, but I don't know the correct way to get the program to respond differently depending on what the user types. octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green"...
Trouble with syntax - if/else and raw_input()
Okay, so the answer is probably obvious, but I don't know the correct way to get the program to respond differently depending on what the user types. octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} squidList = ["first", "second", "...
[ "Edit: After Ned Batchelder formatted the code, I re-read the question and see my guess as to what you want to do wasn't quite correct ... although it's still not 100% clear if you're trying to loop or not. If you only want to go through this once, there's no need for the while loop, just remove it. As for the t...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003268154_python.txt
Q: Why does this Python (Django) code eat up memory? Why does this code eat up memory? When I run it it slowly consumes more memory with every loop, and I have something like 300000 loops. I'm using Windows, and Python 2.6. def LoadVotes(self): old_votes=Votes.objects.all() amount=old_votes.count() print...
Why does this Python (Django) code eat up memory?
Why does this code eat up memory? When I run it it slowly consumes more memory with every loop, and I have something like 300000 loops. I'm using Windows, and Python 2.6. def LoadVotes(self): old_votes=Votes.objects.all() amount=old_votes.count() print 'Amount of votes is: ' + str(amount) c=0 for r...
[ "If you run with DEBUG=True, django is storing all the queries in memory. Try changing to DEBUG=False in your settings.py file.\n", "I'm not sure what the Vote model looks like. But you're only interested in two attributes from Vote (_login and media_file_id). So you might consider using the values or values_li...
[ 5, 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003268127_django_python.txt
Q: ObjectListView Flickers/Flashes when adding a new list object When I update my objectListView list it flickers/flashes white, is this normal behaviour or can it be prevented. The list gets updated around every 1-5 seconds using the AddObject method if that makes any difference. A: I seem to have fixed it by usin...
ObjectListView Flickers/Flashes when adding a new list object
When I update my objectListView list it flickers/flashes white, is this normal behaviour or can it be prevented. The list gets updated around every 1-5 seconds using the AddObject method if that makes any difference.
[ "I seem to have fixed it by using the FastObjectListView class instead...\n", "You might be able to alleviate some of the flickering by Freezing and Thawing the ObjectListView widget as well. \n\nMike Driscoll\nBlog: http://blog.pythonlibrary.org\n" ]
[ 0, 0 ]
[]
[]
[ "objectlistview", "python", "user_interface", "wxpython" ]
stackoverflow_0003268106_objectlistview_python_user_interface_wxpython.txt
Q: python dll swig help First, I have never used SWIG, I dont know what it does... We have a python library, that as far as I can tell uses SWIG, say when I want to use this library I have to put this in my python code: import pylib Now if I go open this vendor's pylib.py I see some classes, functions and this heade...
python dll swig help
First, I have never used SWIG, I dont know what it does... We have a python library, that as far as I can tell uses SWIG, say when I want to use this library I have to put this in my python code: import pylib Now if I go open this vendor's pylib.py I see some classes, functions and this header: # This file was automat...
[ "SWIG is a method of automatically wrapping up a C/C++ library so it can be accessed from Python. The library is actually a C library compiled as a DLL. The Python code is just pass-through code, all autogenerated by SWIG, and you're right that it's not very helpful.\nIf you want to know what arguments to pass, you...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003268371_python.txt
Q: python use __getitem__ for a method is it possible to use getitem inside a method, ie Class MyClass: @property def function(self): def __getitem__(): ... So I can do A = MyClass() A.function[5] A.function[-1] A: Everything is a first-class object in python, so the idea should work (t...
python use __getitem__ for a method
is it possible to use getitem inside a method, ie Class MyClass: @property def function(self): def __getitem__(): ... So I can do A = MyClass() A.function[5] A.function[-1]
[ "Everything is a first-class object in python, so the idea should work (the syntax is off), though I'd suggest making function its own class with properties in it, and then utilizing it in MyClass, unless you have a very good data-hiding reason to not do so...\nI'd like to point out that I'm assuming you want to ha...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003268408_python.txt
Q: How to crop gtk pixbufs I've got a gtk - pixbuf out of an svg and want to crop this to a specific size at specific coordinates. Anyone has an easy possible solution for that ? A: solved it in a different way: simply created a subpixbuf with the coodinates: cropped_buffer=pixbuf.subpixbuf(x,y,width,height) A: ...
How to crop gtk pixbufs
I've got a gtk - pixbuf out of an svg and want to crop this to a specific size at specific coordinates. Anyone has an easy possible solution for that ?
[ "solved it in a different way:\nsimply created a subpixbuf with the coodinates:\ncropped_buffer=pixbuf.subpixbuf(x,y,width,height)\n", "svg has a viewbox attribute. You could use that one.\n" ]
[ 4, 0 ]
[]
[]
[ "gtk", "python", "svg" ]
stackoverflow_0003267981_gtk_python_svg.txt
Q: sets in python problem can we remove a entry from the sets. what are the commands to use for it? like, my set conatins (6,5) , (6,7), (7,9)...I need to remove the second entry...what shud I do?? A: my_set.remove((6, 7)) The remove() method can be used to remove items from a set. A: You can use remove(): >>> s...
sets in python problem
can we remove a entry from the sets. what are the commands to use for it? like, my set conatins (6,5) , (6,7), (7,9)...I need to remove the second entry...what shud I do??
[ "my_set.remove((6, 7))\n\nThe remove() method can be used to remove items from a set.\n", "You can use remove():\n>>> s = set([1, 2, 3])\n>>> s.remove(2)\n>>> s\nset([1, 3])\n\n", "a -= set([(6, 7)])\n:-)\n", "If you've got a list of those tuples you can clear it out like this:\nl = [(1,2),(3,4),(5,6)]\n\n[(1...
[ 3, 3, 2, 1 ]
[]
[]
[ "python", "set" ]
stackoverflow_0003268641_python_set.txt
Q: What's the best performing xml parsing for GAE (Python Version)? I think we all know this page, but the benchmarks provided dated from more than two years ago. So, I would like to know if you could point out the best xml parser around. As I need just a xml parser, the more important thing to me is speed over every...
What's the best performing xml parsing for GAE (Python Version)?
I think we all know this page, but the benchmarks provided dated from more than two years ago. So, I would like to know if you could point out the best xml parser around. As I need just a xml parser, the more important thing to me is speed over everything else. My objective is to process some xml feeds (about 25k) that...
[ "I know that this don't awnser my question directly, but id does what i just needed.\nI remenbered that xml is not the only file type I could use, so instead of using a xml parser I choose to use json. About 2.5 times smaller in size. What means a decrease in download time. I used simplejson as my json libray.\nI u...
[ 1 ]
[]
[]
[ "google_app_engine", "parsing", "python", "xml" ]
stackoverflow_0003252070_google_app_engine_parsing_python_xml.txt
Q: Create a summary text file of a folder with filename and the first two lines out of each file I have a directory with 260+ text files containing scoring information. I want to create a summary text file of all of these files containing filename and the first two lines of each file. My idea was to create two lists ...
Create a summary text file of a folder with filename and the first two lines out of each file
I have a directory with 260+ text files containing scoring information. I want to create a summary text file of all of these files containing filename and the first two lines of each file. My idea was to create two lists separately and 'zip' them. However, I can get the list of the filenames but I can't get the first t...
[ "The problem you're getting is a result of trying to take more than one line at a time from the scores file using a file iterator (for line in f). Here's a quick fix (one of several ways to do it, I'm sure):\n# creating a list of the first two lines of each file\nfor f in os.listdir(\"../scores\"):\n with open(...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "text_files" ]
stackoverflow_0003268246_python_text_files.txt
Q: making python programs "chat" via pipe I'm trying to make two processes communicate using a pipe. I did this in the parent process: process = subprocess.Popen(test, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) process.stdin.write("4\n"); output = process.stdout.read() print output and in the child ...
making python programs "chat" via pipe
I'm trying to make two processes communicate using a pipe. I did this in the parent process: process = subprocess.Popen(test, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) process.stdin.write("4\n"); output = process.stdout.read() print output and in the child process: inp = raw_input() integer = int(inp...
[ "I see a number of possible issues:\na) The child process never actually flushes its output and thus never actually sends its output to the parent.\nb) The parent process runs its read() call before the child process has actually sent its output (flushed its output).\nc) The parent process does a blocking read() wh...
[ 4, 2, 0, 0 ]
[]
[]
[ "multiprocessing", "pipe", "python", "stdin", "stdout" ]
stackoverflow_0003268410_multiprocessing_pipe_python_stdin_stdout.txt
Q: error: list objects are unhashable closed = set() -here closed is a set node is (5,5) The error occurse at execution time. Error is: list objects are unhashable the program is: closed.add(node) for val in closed: print val Node is the output of stack. node = stack.pop() - it gives me...(5,5) Tracebac...
error: list objects are unhashable
closed = set() -here closed is a set node is (5,5) The error occurse at execution time. Error is: list objects are unhashable the program is: closed.add(node) for val in closed: print val Node is the output of stack. node = stack.pop() - it gives me...(5,5) Traceback: File "/home/", line 99, in depthFirst...
[ "Show the actual code that you executed, plus the full traceback. Use copy/paste, don't type from memory. You should always do this. Even better reason in this case is that that error can happen only if node is a list, not a tuple as you have said.\n", "I do not have a problem running the code if node is a tuple,...
[ 2, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0003268966_python_set.txt
Q: Error building 'lxml.etree' extension I'm trying to install lxml, on an Ubuntu server running Python 2.6 (in a virtualenv - the system Python is 2.5). I've checked out via svn and as a result I've also install Cython, as per the instructions. However, I get the following error when running python setup.py build: B...
Error building 'lxml.etree' extension
I'm trying to install lxml, on an Ubuntu server running Python 2.6 (in a virtualenv - the system Python is 2.5). I've checked out via svn and as a result I've also install Cython, as per the instructions. However, I get the following error when running python setup.py build: Building lxml version 2.3.alpha1-76211. Buil...
[ "\"I've checked out via svn\" ...\n\"Building lxml version 2.3.alpha1-76211\" ...\nYou appear to be on the bleeding edge. Suggestions: Use a released version of the lxml source. Consult with the lxml author/maintainer.\n" ]
[ 1 ]
[]
[]
[ "lxml", "python", "ubuntu" ]
stackoverflow_0003266111_lxml_python_ubuntu.txt
Q: Why does Twisted think I'm calling request.finish() twice when I am not? This is an annoying problem I am having with Twisted.web. Basically, I have a class that inherits from twisted.web.resource.Resource and adds some default stuff to Mako templates: from twisted.web.resource import Resource from mako.lookup imp...
Why does Twisted think I'm calling request.finish() twice when I am not?
This is an annoying problem I am having with Twisted.web. Basically, I have a class that inherits from twisted.web.resource.Resource and adds some default stuff to Mako templates: from twisted.web.resource import Resource from mako.lookup import TemplateLookup from project.session import SessionData from project.securi...
[ "Short Answer\n\nIt has to be:\nrequest.redirect(\"/test\")\nrequest.finish()\nreturn twisted.web.server.NOT_DONE_YET\n\nLong Answer\n\nI decided to go sifting through some Twisted source code. I first added a traceback to the area that prints the error if request.finish() is called twice:\ndef finish(self):\n i...
[ 11 ]
[]
[]
[ "python", "twisted.web" ]
stackoverflow_0003254965_python_twisted.web.txt
Q: How to match string with database fields in Django? I have a database with a name column having data like 'Very big News' 'News' 'something else' 'New Nes' 'Fresh News' 'Something else' Now given a string of words, how can I find if any of the words in the given string is contained in the name field? For example...
How to match string with database fields in Django?
I have a database with a name column having data like 'Very big News' 'News' 'something else' 'New Nes' 'Fresh News' 'Something else' Now given a string of words, how can I find if any of the words in the given string is contained in the name field? For example: I have a string 'super very news'. I need to look in my...
[ "Update based on comments. See the query set docs here.\nyour_search_query = 'super very news'\n\nqset = Q()\nfor term in your_search_query.split():\n qset |= Q(name__contains=term)\n\nmatching_results = YourModel.objects.filter(qset)\n\nThis creates the equivalent of:\nmatching_result = YourModel.objects.filter...
[ 7, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003259899_django_django_models_python.txt
Q: Django extend admin "index" view I know how to change or extend a model's views in the Django admin ( http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.add_view ) but I want to extend the admin index (dashboard) view. Specifically, I want to keep it the same, but add some info...
Django extend admin "index" view
I know how to change or extend a model's views in the Django admin ( http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.add_view ) but I want to extend the admin index (dashboard) view. Specifically, I want to keep it the same, but add some information to some of my models that will...
[ "Why do you want to change the templates? You can use ModelAdmin.list_display for printig these columns.\nEdit: And for ordering you can use ModelAdmin.ordering.\n" ]
[ 0 ]
[]
[]
[ "admin", "django", "extend", "python", "view" ]
stackoverflow_0003268999_admin_django_extend_python_view.txt
Q: Django Images Display Ok, now I know how to display images on ONE /myurl/ in Django as a list (YEAH!) But how can I display ONE Image per url with a button to click to the next image etc. So basically I would want to come to the first /urlstart/: text and a next button. brings user to e.g. /urlstart/1 There the fi...
Django Images Display
Ok, now I know how to display images on ONE /myurl/ in Django as a list (YEAH!) But how can I display ONE Image per url with a button to click to the next image etc. So basically I would want to come to the first /urlstart/: text and a next button. brings user to e.g. /urlstart/1 There the first image of a List is disp...
[ "URL regex could look something like this:\nurl(r'^urlstart/(?P<image_id>\\d*)/?$', 'urlstart', name='urlstart')\n\nView code could look something like this:\ndef urlstart(request, image_id=0):\n if image_id == 0:\n image = None\n else:\n image = get_object_or_404(Image, image_id)\n next_image = image_id +...
[ 2, 0 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0003266048_django_python_url.txt
Q: Using if/elif/else and resp=raw_input - how to respond to part of a user's input? print "Please Type Something" resp = raw_input() if resp *contains* "cuttlefish" print "Response One" elif resp *contains* "nautilus" print "Response Two" else: print "Response Three" What I need to know is the correct...
Using if/elif/else and resp=raw_input - how to respond to part of a user's input?
print "Please Type Something" resp = raw_input() if resp *contains* "cuttlefish" print "Response One" elif resp *contains* "nautilus" print "Response Two" else: print "Response Three" What I need to know is the correct syntax to use instead of the filler contains. So, for example, if the user types "tw...
[ "Python is quite an easy language, just think english and you might get it correct ;)\nif 'cuttlefish' in resp:\n\n", "in is the operator you are looking for:\nif \"cuttlefish\" in resp:\n print \"Response One\"\nelif \"nautilus\" in resp:\n print \"Response Two\"\nelse:\n print \"Response Three\"\n\nin ...
[ 5, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003269376_python.txt
Q: "list index out of range" Below I have the following code that is supposed to get the CPU temperature. import wmi w = wmi.WMI() print w.Win32_TemperatureProbe()[0].CurrentReading When I run it I get the following warning however: Traceback (most recent call last): File "<string>", line 244, in run_nodebug Fi...
"list index out of range"
Below I have the following code that is supposed to get the CPU temperature. import wmi w = wmi.WMI() print w.Win32_TemperatureProbe()[0].CurrentReading When I run it I get the following warning however: Traceback (most recent call last): File "<string>", line 244, in run_nodebug File "<module1>", line 3, in <mod...
[ "This just means that TemperatureProbe isn't implemented on your machine (probably your hardware vendor). \nYour other option is to connect to the root\\WMI namespace and query \"select * from MSAcpi_ThermalZoneTemperature\" which will return the probes and you can query for current temperature in tenths of kelvin...
[ 1 ]
[]
[]
[ "cpu", "python", "windows", "wmi" ]
stackoverflow_0003269484_cpu_python_windows_wmi.txt
Q: Manipulating strings in python - concentrating on part of a user's input resp = raw_input("What is your favorite fruit?\n") if "I like" in resp: print "%s" - "I like" + " is a delicious fruit." % resp else: print "Bubbles and beans." OK I know this code doesn't work, and I know why. You can't subtr...
Manipulating strings in python - concentrating on part of a user's input
resp = raw_input("What is your favorite fruit?\n") if "I like" in resp: print "%s" - "I like" + " is a delicious fruit." % resp else: print "Bubbles and beans." OK I know this code doesn't work, and I know why. You can't subtract strings from each other like numbers. But is there a way to break apart a ...
[ "One option would be to simply replace the part that you want to remove with an empty string:\nresp = raw_input(\"What is your favorite fruit?\\n\")\nif \"I like\" in resp:\n print \"%s is a delicious fruit.\" % (resp.replace(\"I like \", \"\"))\nelse:\n print \"Bubbles and beans.\"\n\nIf you want to look in...
[ 5, 0, 0 ]
[ "Can you just strip \"I like\"? \nresp.strip(\"I like\")\n\nbe careful of case sensitivity though. \n" ]
[ -1 ]
[ "python" ]
stackoverflow_0003269721_python.txt
Q: Python circular references trying to have two class that reference each others, in the same file. What would be the best way to have this working: class Foo(object): other = Bar class Bar(object): other = Foo if __name__ == '__main__': print 'all ok' ? The problem seems to be that since the propert...
Python circular references
trying to have two class that reference each others, in the same file. What would be the best way to have this working: class Foo(object): other = Bar class Bar(object): other = Foo if __name__ == '__main__': print 'all ok' ? The problem seems to be that since the property is on the class, since it trie...
[ "This would do what you want:\nclass Foo(object):\n pass\n\nclass Bar(object):\n pass\n\nFoo.other = Bar\nBar.other = Foo\n\nI would prefer to avoid such design completely, though.\n", "Assuming that you really want Foo.other and Bar.other to be class properties, rather than instance properties, then this w...
[ 10, 1 ]
[]
[]
[ "circular_dependency", "python", "sqlalchemy" ]
stackoverflow_0003270045_circular_dependency_python_sqlalchemy.txt
Q: How to select users based on their profile I have a complicated query built up based on a users profile, I start with qset = Profile.objects bunch of stuff that works to return me profile objects (it uses Q objects, and optionally ignores some fields if they were left blank) I could grab the users with selected_...
How to select users based on their profile
I have a complicated query built up based on a users profile, I start with qset = Profile.objects bunch of stuff that works to return me profile objects (it uses Q objects, and optionally ignores some fields if they were left blank) I could grab the users with selected_related() but that still leaves me with a list o...
[ "Make your Q objects refer to profile__whatever and use them in User.objects.filter().\n", "Turns out I had to mod the templates. There is a bug in Django auth.user. When the view code looks like:\n@login_required\ndef test(request):\n a = User.objects.filter(pk=request.user.id).select_related('profile').get...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003172854_django_python.txt
Q: function in python In a function, I need to perform some logic that requires me to call a function inside a function. What I did with this, like: def dfs(problem): stack.push(bache) search(root) while stack.isEmpty() != 0: def search(vertex): closed.add(vertex) for index in sars...
function in python
In a function, I need to perform some logic that requires me to call a function inside a function. What I did with this, like: def dfs(problem): stack.push(bache) search(root) while stack.isEmpty() != 0: def search(vertex): closed.add(vertex) for index in sars: stack.push(in...
[ "There are many mysterious bug-looking aspects in your code. The wrong order of definition (assuming you do need the search function to be a nested one) and the syntax error from the empty while loop have already been observed, but there are more...:\ndef dfs(problem):\n stack.push(bache)\n search(root) ...
[ 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003269963_python.txt
Q: = Try Except Pattern? I find this design pattern comes up a lot: try: year = int(request.GET['year']) except: year = 0 The try block can either fail because the key doesn't exist, or because it's not an int, but I don't really care. I just need a sane value in the end. Shouldn't there be a nicer way to do this? O...
= Try Except Pattern?
I find this design pattern comes up a lot: try: year = int(request.GET['year']) except: year = 0 The try block can either fail because the key doesn't exist, or because it's not an int, but I don't really care. I just need a sane value in the end. Shouldn't there be a nicer way to do this? Or at least a way to do it o...
[ "You're probably better off to use get()\nyear = int(request.GET.get(\"year\", 0))\n\nThis will set year to what ever request.GET['year'] is, or if the key doesn't exist, it will return 0. This gets rid of your KeyError, but you could still have a ValueError from request.GET['year'], if it is not convert'able to an...
[ 10, 6, 5, 2 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0003269887_design_patterns_python.txt
Q: Getting isMultipartContent = false while using python poster library I'm using the python poster library to try to upload a form containing including an image to a servlet. Locally, it runs fine, but when I deploy to app engine, it doesn't recognize it as multipart content. ServletFileUpload.isMultipartContent(...
Getting isMultipartContent = false while using python poster library
I'm using the python poster library to try to upload a form containing including an image to a servlet. Locally, it runs fine, but when I deploy to app engine, it doesn't recognize it as multipart content. ServletFileUpload.isMultipartContent(request) returns false Here's how I'm using the poster library: register_o...
[ "If you're on Windows (or a pedant;-), open(filename) is the wrong way to open a binary file and might mess things up -- use open(filename, 'rb'). Apart from that, assuming of course that you continue with a urllib2.urlopen(request) which you've omitted, that your imports are correct, and that filename and url are...
[ 0 ]
[]
[]
[ "file_upload", "google_app_engine", "multipartform_data", "poster", "python" ]
stackoverflow_0003270102_file_upload_google_app_engine_multipartform_data_poster_python.txt
Q: Step into subroutine call, but not calls made for parameters func(a(), b.c) When executing the line above in the pdb debugger, using step will actually step into a, and then into the getter for b.c if its atypical (such as being a property), before actually stepping into func. Generally I find myself using step f...
Step into subroutine call, but not calls made for parameters
func(a(), b.c) When executing the line above in the pdb debugger, using step will actually step into a, and then into the getter for b.c if its atypical (such as being a property), before actually stepping into func. Generally I find myself using step followed by r to return from the frames I'm not interested in, and ...
[ "tb func (\"temporary break at func\") followed by c (\"continue\") should work.\n", "I would handle this by setting a break at the line number inside func that you're interested in, and then use continue. For example suppose your code looks like this:\n110 def func(a1, a2):\n111 \"\" docstring \"\"\n112 ...
[ 2, 0 ]
[]
[]
[ "debugging", "pdb", "python" ]
stackoverflow_0003270174_debugging_pdb_python.txt
Q: loop until all elements have been accessed N times in python I have a group of buckets, each with a certain number of items in them. I want to make combinations with one item from each bucket. The loop should keep making different combinations until each item has participated in at least some defined number. I can...
loop until all elements have been accessed N times in python
I have a group of buckets, each with a certain number of items in them. I want to make combinations with one item from each bucket. The loop should keep making different combinations until each item has participated in at least some defined number. I can easily see how to run the loop and stop once a single element has...
[ "itertools.product is one way (a very systematic one) to make the \"combinations\" you request (don't confuse with the .combinations function of course) -- or you could make them randomly with random.choose from each bucket; not sure which one is for you since I don't know what your real purpose is.\nAnyway, I'd ke...
[ 1, 0, 0, 0 ]
[]
[]
[ "list", "loops", "python", "sorting", "while_loop" ]
stackoverflow_0003270121_list_loops_python_sorting_while_loop.txt
Q: Chained string formatting in Python In handling a little SQL formatting I was amazed to find I could chain string formatters: def get_sql(table, limit=True): sql = "select report_date from %s" if limit: result = "%s limit 1" % sql % table else: result = sql % table return result Is...
Chained string formatting in Python
In handling a little SQL formatting I was amazed to find I could chain string formatters: def get_sql(table, limit=True): sql = "select report_date from %s" if limit: result = "%s limit 1" % sql % table else: result = sql % table return result Is this legit? Any reason not to do this?
[ "It makes sense that it works because a statement like this:\n'some value goes here %s' % value\nActually returns a string. It's probably a bit more logical to view it like this:\nresult = (\"%s limit 1\" % sql) % table\nThere's nothing expressly wrong with doing that, but chaining operators can lead to problems w...
[ 4, 3, 2, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003268825_python_string.txt
Q: dictionary in python s = problem.getSuccessors(currNode) print s child = dict((t[0], t[1:]) for t in s) print child output of s = [((5, 4), 'South', 1), ((4, 5), 'West', 1)] output of child = {(4, 5): ('West', 1), (5, 4): ('South', 1)} Why the order has been changed?? 5,4 should be at first p...
dictionary in python
s = problem.getSuccessors(currNode) print s child = dict((t[0], t[1:]) for t in s) print child output of s = [((5, 4), 'South', 1), ((4, 5), 'West', 1)] output of child = {(4, 5): ('West', 1), (5, 4): ('South', 1)} Why the order has been changed?? 5,4 should be at first position and ( 4, 5) at 2nd...
[ "(1) In Python dictionaries are unordered. Use an OrderedDict (available since Python 2.7 and 3.1) if you need to maintain the insertion order.\n(2) I don't know what you mean by \"parent node\".\n", "Dictionaries do not preserve key order.\nYou would need to use an ordered dict substitute. \n" ]
[ 10, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003270533_python.txt
Q: general problem- sets,python I got a problem: keys here is a list. keys = [(6,4) , (6,8)] The entries in the keys can be 4,5...or watever Now, I have to pick up only 1 from it.So I used: root = keys[0] print root output: (6,4) Now I have to make a set which is empty, say,... closed = set() for u,v of root: i...
general problem- sets,python
I got a problem: keys here is a list. keys = [(6,4) , (6,8)] The entries in the keys can be 4,5...or watever Now, I have to pick up only 1 from it.So I used: root = keys[0] print root output: (6,4) Now I have to make a set which is empty, say,... closed = set() for u,v of root: if v not in closed: closed.ad...
[ ">>> keys = [(6,4) , (6,8)]\n>>> root = keys[0]\n>>> closed = set()\n>>> closed.update(root)\n>>> closed\n{4, 6}\n\n", "You could try this to add the 6 and the 4 into your set:\nclosed = set()\nclosed.add(root[0])\nclosed.add(root[1])\n\nBut maybe you should explain a bit more, what you are trying to do. Then we ...
[ 2, 0, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0003263443_python_set.txt
Q: Strange logic with bool I can't understand one thing with logic in python. Here is the code: maxCounter = 1500 localCounter = 0 while True: print str(localCounter) + ' >= ' + str(maxCounter) print localCounter >= maxCounter if localCounter >= maxCounter: break localCounter += 30 And the resul...
Strange logic with bool
I can't understand one thing with logic in python. Here is the code: maxCounter = 1500 localCounter = 0 while True: print str(localCounter) + ' >= ' + str(maxCounter) print localCounter >= maxCounter if localCounter >= maxCounter: break localCounter += 30 And the result output: ... 1440 >= 1500 Fa...
[ "To fix your code try this:\ntopPos = int(someClass.get_element_pos('element'))\n\nWhy?\nWhen I copy and paste your original code I get this:\n...\n1440 >= 1500\nFalse\n1470 >= 1500\nFalse\n1500 >= 1500\nTrue\n\nOne small change that I can find to make to your code that reproduces the behaviour you are seeing is to...
[ 4, 1 ]
[]
[]
[ "boolean", "python" ]
stackoverflow_0003270605_boolean_python.txt
Q: How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists? The following snippet is annotated with the output (as seen on ideone.com): print "100" < "2" # True print "5" > "9" # False print "100" < 2 # False print 100 < "2" # Tr...
How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?
The following snippet is annotated with the output (as seen on ideone.com): print "100" < "2" # True print "5" > "9" # False print "100" < 2 # False print 100 < "2" # True print 5 > "9" # False print "5" > 9 # True print [] > float('inf') # True print () > [] # Tr...
[ "From the python 2 manual:\n\nCPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.\n\nWhen you order two strings or two numeric types the ordering is done in the expected...
[ 210, 24 ]
[]
[]
[ "comparison", "python", "python_2.x", "types" ]
stackoverflow_0003270680_comparison_python_python_2.x_types.txt
Q: What is the python equivalent to perl "a".."azc" In perl, to get a list of all strings from "a" to "azc", to only thing to do is using the range operator: perl -le 'print "a".."azc"' What I want is a list of strings: ["a", "b", ..., "z", "aa", ..., "az" ,"ba", ..., "azc"] I suppose I can use ord and chr, looping...
What is the python equivalent to perl "a".."azc"
In perl, to get a list of all strings from "a" to "azc", to only thing to do is using the range operator: perl -le 'print "a".."azc"' What I want is a list of strings: ["a", "b", ..., "z", "aa", ..., "az" ,"ba", ..., "azc"] I suppose I can use ord and chr, looping over and over, this is simple to get for "a" to "z", ...
[ "Generator version:\nfrom string import ascii_lowercase\nfrom itertools import product\n\ndef letterrange(last):\n for k in range(len(last)):\n for x in product(ascii_lowercase, repeat=k+1):\n result = ''.join(x)\n yield result\n if result == last:\n return\...
[ 5, 4, 2, 1, 1, 0 ]
[]
[]
[ "list", "perl", "python" ]
stackoverflow_0003264271_list_perl_python.txt
Q: How to use python modules that were renamed 3 in a cross compatible way? There are several modules that were renamed in Python 3 and I'm looking for a solution that will make your code work in both python flavors. In Python 3, __builtin__ was renamed to builtins. Example: import __builtin__ #... __builtin__.someth...
How to use python modules that were renamed 3 in a cross compatible way?
There are several modules that were renamed in Python 3 and I'm looking for a solution that will make your code work in both python flavors. In Python 3, __builtin__ was renamed to builtins. Example: import __builtin__ #... __builtin__.something # appearing multiple times ("something" may vary)
[ "Benjamin Peterson's six may be what you are looking for. Six \"provides simple utilities for wrapping over differences between Python 2 and Python 3\". For example:\nfrom six.moves import builtin # works for both python 2 and 3\n\n", "You could solve the problem by using nested try .. except-blocks:\ntry:\n ...
[ 3, 1 ]
[]
[]
[ "python", "python_2.x", "python_3.x" ]
stackoverflow_0003270891_python_python_2.x_python_3.x.txt
Q: issue running a test in Python, via rpy2 I have a feeling this will be a quick fix, given that I started coding two weeks ago. I am try to run a statistical test - a Mantel, looking for a correlation between two distance matrices - in Python, by using a function(?) that has already been written in R, via Rpy2. Th...
issue running a test in Python, via rpy2
I have a feeling this will be a quick fix, given that I started coding two weeks ago. I am try to run a statistical test - a Mantel, looking for a correlation between two distance matrices - in Python, by using a function(?) that has already been written in R, via Rpy2. The R module is "ade4" and it contains "mantel.r...
[ "Try robjects.r['mantel.rtest']:\nIn [1]: %cpaste\nPasting code; enter '--' alone on the line to stop.\n:from rpy2 import robjects\nimport rpy2.robjects as robjects\nrobjects.r('library(ade4)')\n::::::--\n\nIn [3]: robjects.r['mantel.rtest']\nOut[5]: <RFunction - Python:0xa2aac0c / R:0xac9ec04>\n\nThis also works:\...
[ 0, 0 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0003266710_python_r_rpy2.txt
Q: Python and rpy2: How do I adjust/clear a graphic during runtime? I'm using rpy2 to do data analysis and plotting in python. It works fine except for the fact that when I draw a plot, it's window hangs around until the program terminates. Is there a way to clear the plot during runtime? Additionally, If I ever resi...
Python and rpy2: How do I adjust/clear a graphic during runtime?
I'm using rpy2 to do data analysis and plotting in python. It works fine except for the fact that when I draw a plot, it's window hangs around until the program terminates. Is there a way to clear the plot during runtime? Additionally, If I ever resize the window, the plot disappears, but the window remains. When using...
[ "Yes, you can use the following commands to control the plot window interatively:\ndev.new() # opens a new window, and can control the size\ndev.off() # closes the window\n\nAs an example, see these questions:\n\nCreating a Plot Window of a Particular Size\nHow to change current Plot Window Size (in R)\nHow to sepa...
[ 4, 1 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0003087137_python_r_rpy2.txt
Q: A href catching I'm using BeautifulSoup for parsing some html. Here is the content: <tr> <th>Your provider:</th> <td> <img src="/isp_logos/la-la-la.ico" alt=""/> <a href="/isp/SomeProvider"> Provider name </a> &nbsp; <a href="http://*/isp-comparer/?isp=000000"> </a> </td> </tr> I have to get SomePr...
A href catching
I'm using BeautifulSoup for parsing some html. Here is the content: <tr> <th>Your provider:</th> <td> <img src="/isp_logos/la-la-la.ico" alt=""/> <a href="/isp/SomeProvider"> Provider name </a> &nbsp; <a href="http://*/isp-comparer/?isp=000000"> </a> </td> </tr> I have to get SomeProvider text from the ...
[ "With your posted code and input, I'm getting:\n[<a href=\"/isp/SomeProvider\"> Provider name </a>]\n\nAs the return of the array. Are you using the newest 3.1.x version of BeautifulSoup? I actually had the same problem, but it turns out I downloaded the 2.x version of BeautifulSoup thinking that the 2.x meant it...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "regex" ]
stackoverflow_0003270907_beautifulsoup_html_python_regex.txt
Q: python- execution time problem I'm able to go through the first function....but the second func is not running....getaction def registerInitialState(self, state): """ This is the first time that the agent sees the layout of the game board. Here, we choose a path to the goal. In this phase, the agent ...
python- execution time problem
I'm able to go through the first function....but the second func is not running....getaction def registerInitialState(self, state): """ This is the first time that the agent sees the layout of the game board. Here, we choose a path to the goal. In this phase, the agent should compute the path to the g...
[ "Add the print statement as per below and tell me what it says. self.actions is probably the None type or not a list-like object. You might want to check == None like the other one.\nself.actionIndex += 1 \nprint self.actions\nif i < len(self.actions): \n return self.actions[i] \nelse: \n return Directions.ST...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003270987_python.txt
Q: SQLAlchemy and max_allowed_packet problem Due to the nature of my application, I need to support fast inserts of large volumes of data into the database. Using executemany() increases performance, but there's a caveat. For example, MySQL has a configuration parameter called max_allowed_packet, and if the total siz...
SQLAlchemy and max_allowed_packet problem
Due to the nature of my application, I need to support fast inserts of large volumes of data into the database. Using executemany() increases performance, but there's a caveat. For example, MySQL has a configuration parameter called max_allowed_packet, and if the total size of my insert queries exceeds its value, MySQL...
[ "I had a similar problem recently and used the - not very elegant - work-around:\n\nFirst I parsed my.cnf for a value for max_allow_packets, if I can't find it, the maximum is set to a default value.\nAll data items are stored in a list.\nNext, for each data item I count the approximate byte length (with strings, i...
[ 2 ]
[]
[]
[ "large_query", "mysql", "python", "sqlalchemy" ]
stackoverflow_0003267580_large_query_mysql_python_sqlalchemy.txt
Q: Converting WAV audio files to MP3 on a server automatically once uploaded? I'm working on a project, using Python/Django running on a Virtual Private Server, which allows me a blank Linux server box that I can pretty much install whatever I need. The project must allow users to upload an uncompressed WAV file for ...
Converting WAV audio files to MP3 on a server automatically once uploaded?
I'm working on a project, using Python/Django running on a Virtual Private Server, which allows me a blank Linux server box that I can pretty much install whatever I need. The project must allow users to upload an uncompressed WAV file for others to download. These will most probably be served up using Amazon S3. I'm n...
[ "Try ffmpeg e.g. something like this may work\n$ ffmpeg -i audio.wav -acodec mp3 -ab 192k audio.mp3\n\nSee docs for more details\n", "gst can help you with the conversion, once the appropriate codecs are in place.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "mp3", "python", "vps" ]
stackoverflow_0003271014_django_mp3_python_vps.txt
Q: How to: python script + imagemagic = windows application? I have a small problem. I have a script in python, which uses imagemagic. It works fine on my Mac, or Linux. But I need to give it to the client, and he uses Windows. Actually the question: how can I build applications for it, and on what to do Gui. (Perhap...
How to: python script + imagemagic = windows application?
I have a small problem. I have a script in python, which uses imagemagic. It works fine on my Mac, or Linux. But I need to give it to the client, and he uses Windows. Actually the question: how can I build applications for it, and on what to do Gui. (Perhaps you know the finished product is open source, who knows how t...
[ "You can use py2exe to build application for it, may be you can bundle imagemagic with your app too.\n" ]
[ 0 ]
[]
[]
[ "python", "tiles", "windows" ]
stackoverflow_0003270991_python_tiles_windows.txt
Q: How to make non-square edges in Tkinter? In order to make one of my programs more aesthetically pleasing I'm using images to create the boarders, however I want to create a non square boarder so the program looks kinda like this ___________ / / /__________/ How should I go about this? This is on wind...
How to make non-square edges in Tkinter?
In order to make one of my programs more aesthetically pleasing I'm using images to create the boarders, however I want to create a non square boarder so the program looks kinda like this ___________ / / /__________/ How should I go about this? This is on windows 7, btw. Edit: A tried to make a pseudo-edg...
[ "The concept you are after is called a \"shapped window\". Search for \"tk shaped window\" with your favorite search engine. There is a tk extension that claims to support this, though I haven't personally tried it. I presume since it works with tcl/tk it can be made to work with Tkinter since Tkinter uses tcl/tk u...
[ 3, 0 ]
[]
[]
[ "python", "tkinter", "windows" ]
stackoverflow_0003267797_python_tkinter_windows.txt
Q: Saving gtk.TextTags to file? So I am trying to write a rich text editor in PyGTK, and originally used the older, third party script InteractivePangoBuffer from Gourmet to do this. While it worked alright, there were still plenty of bugs with it which made it frustrating to use at times, so I decided to write my ow...
Saving gtk.TextTags to file?
So I am trying to write a rich text editor in PyGTK, and originally used the older, third party script InteractivePangoBuffer from Gourmet to do this. While it worked alright, there were still plenty of bugs with it which made it frustrating to use at times, so I decided to write my own utilizing text tags. I have got ...
[ "You can probably use gtk.TextIter.forward_to_tag_toggle(). I.e. loop over all tags you have and for each tags scan the buffer for the position where it is toggled.\n" ]
[ 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003269942_pygtk_python.txt
Q: List of Python regular expressions for a newbie? I recently learned a little Python and I couldnt find a good list of the RegEx's (don't know if that is the correct plural tense...) with complete explanations even a rookie will understand :) Anybody know a such list? A: Vide:       A: Well, for starters - hi...
List of Python regular expressions for a newbie?
I recently learned a little Python and I couldnt find a good list of the RegEx's (don't know if that is the correct plural tense...) with complete explanations even a rookie will understand :) Anybody know a such list?
[ "Vide: \n\n\n     \n", "Well, for starters - hit up the python docs on the re module. Good list of features and methods, as well as info about special regex characters such as \\w. There's also a chapter in Dive into Python about regular expressions that uses the aforementioned module. \n", "Check out the re mo...
[ 13, 5, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003266870_python_regex.txt
Q: Set products in Python A product of n copies of a set S is denoted Sn. For example, {0, 1}3 is the set of all 3­-bit sequences: {0,1}3 = {(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)} What's the simplest way to replicate this idea in Python? A: In Python 2.6 or newer you can use itertools.prod...
Set products in Python
A product of n copies of a set S is denoted Sn. For example, {0, 1}3 is the set of all 3­-bit sequences: {0,1}3 = {(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)} What's the simplest way to replicate this idea in Python?
[ "In Python 2.6 or newer you can use itertools.product with the optional argument repeat:\n>>> from itertools import product\n>>> s1 = set((0, 1))\n>>> set(product(s1, repeat = 3))\n\nFor older versions of Python you can implement product using the code found in the documentation:\ndef product(*args, **kwds):\n #...
[ 16, 2, 1, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0003271931_math_python.txt
Q: Finding missing values in a numpy array Alright, extreme rookie question here. In my program, I generate a 2D numpy array, some of whom's entries are missing (not the "nan" kind of nonexistant, but the "None" kind, or NoneType). I'd like to put a mask over these entries, but I seem to be having some trouble doin...
Finding missing values in a numpy array
Alright, extreme rookie question here. In my program, I generate a 2D numpy array, some of whom's entries are missing (not the "nan" kind of nonexistant, but the "None" kind, or NoneType). I'd like to put a mask over these entries, but I seem to be having some trouble doing so. Ordinarily, to mask over, say, all ent...
[ "Since you have -- entries in your array, I guess that it means that they are already masked:\n>>> m = ma.masked_where([True, False]*5, arange(10))\n>>> print m\n[-- 1 -- 3 -- 5 -- 7 -- 9]\n\nSo, I would say that your entries are already masked and that you can directly use your array.\nIf you want to create an arr...
[ 5, 5 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003262437_numpy_python.txt
Q: Fibonacci under 4 millions Possible Duplicate: Python program to find fibonacci series. More Pythonic way. Hey, i was trying to write a script which sums all the even terms in "Fibonacci Sequence" under 4 millions. Fibonacci1 = 1 Fibonacci2 = 2 a = 2 i = 4 for i in range(1,4000000): Fibonacci1 = Fibonacci1 + Fi...
Fibonacci under 4 millions
Possible Duplicate: Python program to find fibonacci series. More Pythonic way. Hey, i was trying to write a script which sums all the even terms in "Fibonacci Sequence" under 4 millions. Fibonacci1 = 1 Fibonacci2 = 2 a = 2 i = 4 for i in range(1,4000000): Fibonacci1 = Fibonacci1 + Fibonacci2 if Fibonacci1 % 2 == ...
[ "There are a couple of problems with your code:\n\nYou are looping four million times instead of until a condition is true.\nYou have repeated code in the body of your loop.\n\nMost people when they start learning Python learn only imperative programming. This is not surprising because Python is an imperative langu...
[ 25, 3, 3, 2, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "sequence" ]
stackoverflow_0003270863_python_sequence.txt
Q: In python, why is reading from an array slower than reading from list? I'm learning python recently, and is doing many practice with the language. One thing I found interesting is that, when I read from an array, it's almost half of the time slower than list. Does somebody know why? here's my code: from timeit im...
In python, why is reading from an array slower than reading from list?
I'm learning python recently, and is doing many practice with the language. One thing I found interesting is that, when I read from an array, it's almost half of the time slower than list. Does somebody know why? here's my code: from timeit import Timer import array t = 10000 l = range(t) a = array.array('i', l) def ...
[ "lists are \"dynamically growing vectors\" (very much like C++'s std::vector, say) but that in no way slows down random access to them (they're not linked lists!-). Lists' entries are references to Python objects (the items): accessing one just requires (in CPython) an increment of the item's reference count (in o...
[ 11, 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003271813_python.txt
Q: Python Regex (Search Multiple values in one string) In python regex how would I match against a large string of text and flag if any one of the regex values are matched... I have tried this with "|" or statements and i have tried making a regex list.. neither worked for me.. here is an example of what I am trying...
Python Regex (Search Multiple values in one string)
In python regex how would I match against a large string of text and flag if any one of the regex values are matched... I have tried this with "|" or statements and i have tried making a regex list.. neither worked for me.. here is an example of what I am trying to do with the or.. I think my "or" gets commented out ...
[ "patterns=re.compile(r'(\\btext String1\\b)|(\\bText String2\\b)') \n\nYou want a group (optionally capturing), not a character class. Technically, you don't need a group here:\npatterns=re.compile(r'\\btext String1\\b|\\bText String2\\b') \n\nwill also work (without any capture).\nThe way you had it, it check...
[ 7, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003272123_python_regex.txt
Q: how to assign new values to variables in predefined equation? for predefined equations,assigning new values to variables do not changes value of equation. how can i assign new values to variables so that i will get appropriate value of equation and not the previous one a,b,c,d,e,f=sympy.symbols('abcdef') a,b=c,d ...
how to assign new values to variables in predefined equation?
for predefined equations,assigning new values to variables do not changes value of equation. how can i assign new values to variables so that i will get appropriate value of equation and not the previous one a,b,c,d,e,f=sympy.symbols('abcdef') a,b=c,d e=a+b #equation print e c+d #value of eqn a,b=d,f print e c+d #no...
[ "Perhaps use substitution instead of equality:\nimport sympy\na,b,c,d,e,f=sympy.symbols('abcdef')\ne=a+b #equation \nprint e.subs([(a,c),(b,d)])\n# c + d\nprint e.subs([(a,d),(b,f)])\n# d + f\n\n" ]
[ 5 ]
[]
[]
[ "python", "sympy", "variables" ]
stackoverflow_0003272179_python_sympy_variables.txt
Q: Is there a wxpython list widget that displays alternating row colours even when the list is empty? Is there a wxpython list widget that displays alternating row colours even when empty the list is empty? or Is there even one that will display a background colour(other than white) when it is empty? A: You could d...
Is there a wxpython list widget that displays alternating row colours even when the list is empty?
Is there a wxpython list widget that displays alternating row colours even when empty the list is empty? or Is there even one that will display a background colour(other than white) when it is empty?
[ "You could do it with a wx.Grid or you might look at the new UltimateListCtrl, which is a pure python widget. You can hack it if it doesn't do what you want it to!\n", "Indeed. Create your list as a custom class:\nimport wx.lib.mixins.listctrl as listmix\n\nclass CustomList(wx.ListCtrl, listmix.ListRowHighlighter...
[ 1, 1 ]
[]
[]
[ "background_color", "listview", "python", "user_interface", "wxpython" ]
stackoverflow_0003269019_background_color_listview_python_user_interface_wxpython.txt
Q: Python project organization (specially for external libs) I plan to organize my python project the following way: <my_project>/ webapp/ mymodulea.py mymoduleb.py mymodulec.py mylargemodule/ __init.py__ mysubmodule1.py ...
Python project organization (specially for external libs)
I plan to organize my python project the following way: <my_project>/ webapp/ mymodulea.py mymoduleb.py mymodulec.py mylargemodule/ __init.py__ mysubmodule1.py mysubmodule2.py backend/ mybackend1....
[ "If you are treating webapp, backend, and lib as source folders, then you are importing (for example) mymodulea, mybackend1, and python_external_large_lib2. \nThen on the server, you must put webapp, backend, and lib into your python path. Doing it in some kind of startup script is the usual way to do it. Doing ...
[ 1 ]
[]
[]
[ "deployment", "python" ]
stackoverflow_0003272281_deployment_python.txt
Q: Install Panda3d to run with python I am running Ubuntu 10.04, I have python installed and running fine. When I installed pand3d from the deb package from the site and tried to run an sample. Like it is describe in this page: http://www.panda3d.org/manual/index.php/Installing_Panda3D_in_Linux I got the error: Tr...
Install Panda3d to run with python
I am running Ubuntu 10.04, I have python installed and running fine. When I installed pand3d from the deb package from the site and tried to run an sample. Like it is describe in this page: http://www.panda3d.org/manual/index.php/Installing_Panda3D_in_Linux I got the error: Traceback (most recent call last): File "T...
[ "Found the answer. I had two pythons installed. One in /usr/bin and the other in /usr/local/bin. Turn out I needed to use the /usr/bin version to run what I needed. Hope this helps other!\n" ]
[ 2 ]
[]
[]
[ "linux", "panda3d", "python", "ubuntu" ]
stackoverflow_0003271977_linux_panda3d_python_ubuntu.txt
Q: Printing a list of objects I am a Python newbie. I have this small problem. I want to print a list of objects but all it prints is some weird internal representation of object. I have even defined __str__ method but still I am getting this weird output. What am I missing here? class person(object): def __init__(...
Printing a list of objects
I am a Python newbie. I have this small problem. I want to print a list of objects but all it prints is some weird internal representation of object. I have even defined __str__ method but still I am getting this weird output. What am I missing here? class person(object): def __init__(self, name, age): self.name ...
[ "Unless you're explicitly converting to a str, it's the __repr__ method that's used to render your objects.\nSee Difference between __str__ and __repr__ in Python for more details.\n", "Your made this object:\nperson(\"Cheryl\", 20)\n\nThis means repr should be same after creation:\ndef __repr__(self):\n return '...
[ 7, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003272097_python.txt
Q: Re-factoring To MVC pattern -Doubts on separation of view from controller Im trying to refactor my application (with 1000+ lines of GUI code) to an MVC style pattern. The logic code is already seperate from the GUI so that is not a problem. My concern is seperation of the view from the controller. I understand the...
Re-factoring To MVC pattern -Doubts on separation of view from controller
Im trying to refactor my application (with 1000+ lines of GUI code) to an MVC style pattern. The logic code is already seperate from the GUI so that is not a problem. My concern is seperation of the view from the controller. I understand the basic principal of MVC and this tutorial in the wxpython wiki has been very he...
[ "\nIf I were to convert that part to MVC\n I would have to bind the button events\n for each instance of the FilterPanel\n in my controller(instead of in the\n filterPanel class)\n\nNot necessarily! MVC's philosophy and practice do not imply that \"views\" are elementary widgets; your FilterPanel could well be...
[ 9, 1 ]
[]
[]
[ "model_view_controller", "python", "user_interface", "wxpython" ]
stackoverflow_0003271553_model_view_controller_python_user_interface_wxpython.txt
Q: Python: Problem with if statement I have problem with a if statement code below: do_blast(x): test_empty = open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/%s.blast' % (z), 'r') if test_empty.read() == '': test_empty.close() return 'FAIL_NO_RESULTS' else: do_somet...
Python: Problem with if statement
I have problem with a if statement code below: do_blast(x): test_empty = open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/%s.blast' % (z), 'r') if test_empty.read() == '': test_empty.close() return 'FAIL_NO_RESULTS' else: do_something def return_blast(job_ID): if...
[ "I'm not sure if this is the problem, but your code isn't indented correctly (and that matters in Python). I believe this is what you were wanting:\ndo_blast(x):\n test_empty = open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/%s.blast' % (z), 'r')\n if test_empty.read() == '':\n test_empty.close()\n ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003270109_python.txt
Q: how to filter for objects with time so lets say I have a simple class Final and I want to filter the results for the past 2 days by the created field, how do I do this? When I populate the final class it has a utc created time, but I need the difference of that time and currently this is along the line of what I w...
how to filter for objects with time
so lets say I have a simple class Final and I want to filter the results for the past 2 days by the created field, how do I do this? When I populate the final class it has a utc created time, but I need the difference of that time and currently this is along the line of what I want done below, but I am unsure on how to...
[ "I would try:\nresults.filter('created > ', now - datetime.timedelta(days=2))\n\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003272723_google_app_engine_python.txt
Q: Python object instance inheriting changes to parent class by another instance I am confused by this behaviour of Python(2.6.5), can someone shed light on why this happens? class A(): mylist=[] class B(A): j=0 def addToList(self): self.mylist.append(1) b1 = B() print len(b1.mylist) # print...
Python object instance inheriting changes to parent class by another instance
I am confused by this behaviour of Python(2.6.5), can someone shed light on why this happens? class A(): mylist=[] class B(A): j=0 def addToList(self): self.mylist.append(1) b1 = B() print len(b1.mylist) # prints 0 , as A.mylist is empty b1.addToList() print len(b1.mylist) # prints 1 , as w...
[ "You need to do:\nclass A: \n def __init__(self):\n self.mylist=[] \n\nThat way self.mylist is an instance variable. If you define it outside of a method it is a class variable and so shared between all instances.\nIn B if you define a constructor you'll have to explicitly call A's constructor:\nclass B...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003272961_python.txt
Q: Upgraded python and can't get mysqldb to work Running OSX 10.6.3 Just updated python to Python 2.6.5 (r265:79359 rebuilt and reinstalled mysqldb (MySQL-python-1.2.3) rebuilt and reinstalled django (<-- should be unrelated. problem seems to be with mysqldb) I'm getting the following error. File "<stdin>", line 1, ...
Upgraded python and can't get mysqldb to work
Running OSX 10.6.3 Just updated python to Python 2.6.5 (r265:79359 rebuilt and reinstalled mysqldb (MySQL-python-1.2.3) rebuilt and reinstalled django (<-- should be unrelated. problem seems to be with mysqldb) I'm getting the following error. File "<stdin>", line 1, in <module> File "build/bdist.macosx-10.3-fat/egg/M...
[ "Actually, the text of the page you link to does hint at a possible solution:\n\nThis is one from Mac OS X. It seems to\n have been a compiler mismatch, but\n this time between two different\n versions of GCC. It seems nearly every\n major release of GCC changes the ABI\n in some why, so linking code compiled\...
[ 1, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003272493_mysql_python.txt
Q: How to use logical OR in SPARQL regex()? I'm using this line in a SPARQL query in my python program: FILTER regex(?name, "%s", "i" ) (where %s is the search text entered by the user) I want this to match if either ?name or ?featurename contains %s, but I can't seem to find any documentation or tutorial for using ...
How to use logical OR in SPARQL regex()?
I'm using this line in a SPARQL query in my python program: FILTER regex(?name, "%s", "i" ) (where %s is the search text entered by the user) I want this to match if either ?name or ?featurename contains %s, but I can't seem to find any documentation or tutorial for using regex(). I tried a couple things that seemed r...
[ "What about this?\nSELECT ?thing\nWHERE {\n { \n ?thing x:name ?name .\n FILTER regex(?name, \"%s\", \"i\" )\n } UNION {\n ?thing x:featurename ?name .\n FILTER regex(?featurename, \"%s\", \"i\" )\n }\n}\n\n" ]
[ 14 ]
[]
[]
[ "filter", "python", "regex", "sparql" ]
stackoverflow_0003272070_filter_python_regex_sparql.txt
Q: Understanding factorize function Note that this question contains some spoilers. A solution for problem #12 states that "Number of divisors (including 1 and the number itself) can be calculated taking one element from prime (and power) divisors." The (python) code that it has doing this is num_factors = lambda ...
Understanding factorize function
Note that this question contains some spoilers. A solution for problem #12 states that "Number of divisors (including 1 and the number itself) can be calculated taking one element from prime (and power) divisors." The (python) code that it has doing this is num_factors = lambda x: mul((exp+1) for (base, exp) in fact...
[ "The basic idea is that if you have a number factorized into the following form which is the standard form actually:\nlet p be a prime and e be the exponent of the prime:\n\nN = p1^e1 * p2^e2 *....* pk^ek\n\nNow, to know how many divisors N has we have to take into consideration every combination of prime factors. ...
[ 13, 2 ]
[]
[]
[ "math", "python" ]
stackoverflow_0003273379_math_python.txt
Q: Python win32api registry key change I am trying to trigger an event every time a registry value is being modified. import win32api import win32event import win32con import _winreg key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Control Panel\Desktop',0,_winreg.KEY_READ) sub_key = _winreg.CreateKey(key,'Wallpaper'...
Python win32api registry key change
I am trying to trigger an event every time a registry value is being modified. import win32api import win32event import win32con import _winreg key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Control Panel\Desktop',0,_winreg.KEY_READ) sub_key = _winreg.CreateKey(key,'Wallpaper') evt = win32event.CreateEvent(None,0,0,N...
[ "\"WallPaper\" is a value not a key/subkey. So if you bring up regedit.exe, you'll notice that you've created a new key \"HKCU\\Control Panel\\Desktop\\WallPaper\" which is distinct from the \"WallPaper\" value under the \"HKCU\\Control Panel\\Desktop\" key.\nHere's one way to modify your code to listen for chang...
[ 3 ]
[]
[]
[ "python", "pywin32", "registry", "wallpaper", "winapi" ]
stackoverflow_0003057485_python_pywin32_registry_wallpaper_winapi.txt
Q: QPushButton FocusIn generates which signal? I am creating a small PyQt application and got stuck up in MouseOver effect. I have a QMainWindow which has three buttons named createProfileButton, downloadPackagesButton and installPackagesButton. All these are of type QPushButton Now I have created a Label which will ...
QPushButton FocusIn generates which signal?
I am creating a small PyQt application and got stuck up in MouseOver effect. I have a QMainWindow which has three buttons named createProfileButton, downloadPackagesButton and installPackagesButton. All these are of type QPushButton Now I have created a Label which will hold the text when someone hovers the mouse over ...
[ "As you stated, no signals exist for this functionality. You have two basic options.\nOption 1 - Subclass:\nclass FocusEmittingButton(QPushButton):\n #...\n def focusInEvent(self, event):\n # emit your signal\n\nYou can then connect to that signal in your client code. Also, if necessary, you can use ...
[ 4, 1 ]
[]
[]
[ "focus", "pyqt", "python", "qt", "signals_slots" ]
stackoverflow_0002194158_focus_pyqt_python_qt_signals_slots.txt
Q: dictionary and stack in python problem I have made a dictionary and I put the keys of the dict in a list. My list contains elements like this: s = [((5, 4), 'South', 1), ((4, 5), 'West', 1)] I made a dict from this: child = dict((t[0], t[1]) for t in s) keys = child.keys() print keys The output is : [(4, 5), (...
dictionary and stack in python problem
I have made a dictionary and I put the keys of the dict in a list. My list contains elements like this: s = [((5, 4), 'South', 1), ((4, 5), 'West', 1)] I made a dict from this: child = dict((t[0], t[1]) for t in s) keys = child.keys() print keys The output is : [(4, 5), (5, 4)] Now I need to put (4,5) and (5,4) int...
[ "You can use a list as a stack:\nstack = list(child.keys())\nprint stack.pop()\nprint stack.pop()\n\nResult:\n\n(5, 4)\n(4, 5)\n\nImportant note: the keys of a dictionary are not ordered so if you want the items in a specific order you need to handle that yourself. For example if you want them in normal sorted orde...
[ 2, 0, 0 ]
[]
[]
[ "python", "stack" ]
stackoverflow_0003273533_python_stack.txt
Q: Tool to easily create a wxPython preference dialog from a template? I need a wxPython preference dialog box from a Python application. I could hand-code it (and use wxGlade to do part of the job), but I was wondering if there is no tool that makes creation of simple preference dialog boxes easier. The 'easier' par...
Tool to easily create a wxPython preference dialog from a template?
I need a wxPython preference dialog box from a Python application. I could hand-code it (and use wxGlade to do part of the job), but I was wondering if there is no tool that makes creation of simple preference dialog boxes easier. The 'easier' part would be in that you can specify that you need e.g. a text box, and bot...
[ "I wrote an article on something similar, but I used a Configuration file generated with the ConfigObj module. Here's the link:\nhttp://www.blog.pythonlibrary.org/2010/01/20/generating-a-dialog-from-a-file/\nYou can probably take the concepts there and use them for this project.\n" ]
[ 2 ]
[]
[]
[ "preferences", "python", "templates", "wxpython" ]
stackoverflow_0003272884_preferences_python_templates_wxpython.txt
Q: python 2.5.1 and supported version of xpath trying to figure out how to determine what version of XPath is supported by python 2.4.3/2.5.1 using libxml2dom. in looking through various docs, i must be missing something! basically, i'm considering how/if i can have an XPath function, and use regex within the XPath.....
python 2.5.1 and supported version of xpath
trying to figure out how to determine what version of XPath is supported by python 2.4.3/2.5.1 using libxml2dom. in looking through various docs, i must be missing something! basically, i'm considering how/if i can have an XPath function, and use regex within the XPath... i understand the XPath v2.0 supports using rege...
[ "I believe that Python is loading whichever version of libxml2 is on your machine. I think that all versions of libxml2 implement XPath 1.0. I don't know of any Python ready implementation of XPath 2.0.\n" ]
[ 1 ]
[]
[]
[ "python", "xpath" ]
stackoverflow_0003273774_python_xpath.txt
Q: how to Reference some model in a db.ListProperty on google-app-engine this is my model: class Geo(db.Model): entry = db.ListProperty(db.Key) geo=Geo() geo.entry.append(otherModel.key()) and the html is : {% for i in geo.entry %} <p><a href="{{ i.link }}">{{ i.title }}</a></p> {% endfor%} but it show...
how to Reference some model in a db.ListProperty on google-app-engine
this is my model: class Geo(db.Model): entry = db.ListProperty(db.Key) geo=Geo() geo.entry.append(otherModel.key()) and the html is : {% for i in geo.entry %} <p><a href="{{ i.link }}">{{ i.title }}</a></p> {% endfor%} but it show nothing, i think maybe should : class Geo(db.Model): entry = db.ListPr...
[ "You can't use that template (or the like) to show the model directly, but you can easily prepare a context with a list of models by simply calling db.get on the list of keys -- e.g., have {'entries': db.get(listofkeys), ... at the start of your context dictionary, and for i in entries in the template.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "listproperty", "python" ]
stackoverflow_0003272985_google_app_engine_listproperty_python.txt
Q: append tuples to a list How can I append the content of each of the following tuples (ie, elements within the list) to another list which already has 'something' in it? So, I want to append the following to a list (eg: result[]) which isn't empty: l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)] Obviously, the...
append tuples to a list
How can I append the content of each of the following tuples (ie, elements within the list) to another list which already has 'something' in it? So, I want to append the following to a list (eg: result[]) which isn't empty: l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)] Obviously, the following doesn't do the thi...
[ "result.extend(item)\n\n", "You can convert a tuple to a list easily:\n>>> t = ('AAA', 1.11)\n>>> list(t)\n['AAAA', 1.11]\n\nAnd then you can concatenate lists with extend:\n>>> t = ('AAA', 1.11)\n>>> result = ['something']\n>>> result.extend(list(t))\n['something', 'AAA', 1.11])\n\n", "You can use the inbuilt ...
[ 44, 5, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003274095_python.txt
Q: Good compilers for compiling perl/python/php scripts into linux executables? I am working on a project that requires reading text files, extracting data from them, and then generating reports (text files). Since there are a lot of string parsing, I decided to do it in Perl or Python or PHP (preference in that orde...
Good compilers for compiling perl/python/php scripts into linux executables?
I am working on a project that requires reading text files, extracting data from them, and then generating reports (text files). Since there are a lot of string parsing, I decided to do it in Perl or Python or PHP (preference in that order). But I don't want to expose the source code to my client. Is there any good com...
[ "I'm sorry, it's simply not worth spending your time on. For any language you choose (from among the ones you listed), for any compiler/obfuscator someone chooses to come up with, I promise you I can get readable source code out of it (within an hour if it's Perl; longer if it's Python or PHP simply because I'm les...
[ 3, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "compiler_construction", "perl", "php", "python", "scripting_language" ]
stackoverflow_0003270464_compiler_construction_perl_php_python_scripting_language.txt
Q: python dictionary problem output of n is in the form:- ((6,5),'north',1) I am making a dict child for it...in which (6,5) is the key and north and 1 are the values. I need to keep the (6,5) as the key and north as a direction....and I want to keep adding all the values till the while loop continues A: If you wan...
python dictionary problem
output of n is in the form:- ((6,5),'north',1) I am making a dict child for it...in which (6,5) is the key and north and 1 are the values. I need to keep the (6,5) as the key and north as a direction....and I want to keep adding all the values till the while loop continues
[ "If you want to keep all the key / value pairs in one dict (and all keys are distinct, of course):\ntotaldict = {}\n\nfor ...whatever your loop is...:\n ...\n totaldict.update(( t[0], t[1:]) for t in n )\n\nIf you want a list of dicts, @San's answer is good. If you want a single dict with not necessarily all d...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003274114_python.txt
Q: How do I force matplotlib to write out the full form of the x-axis label, avoiding scientific notation? I've created a simple hexbin plot with matplotlib.pyplot. I haven't changed any default settings. My x-axis information ranges from 2003 to 2009, while the y values range from 15 to 35. Rather than writing ou...
How do I force matplotlib to write out the full form of the x-axis label, avoiding scientific notation?
I've created a simple hexbin plot with matplotlib.pyplot. I haven't changed any default settings. My x-axis information ranges from 2003 to 2009, while the y values range from 15 to 35. Rather than writing out 2003, 2004, etc., matplotlib collapses it into 0, 1, 2, ... + 2.003e+03. Is there a simple way to force ma...
[ "I think you can use the xticks function to set string labels:\nnums = arange(2003, 2010)\nxticks(nums, (str(n) for n in nums))\n\nEDIT: This is a better way:\ngca().xaxis.set_major_formatter(FormatStrFormatter('%d'))\n\nor something like that, anyway. (In older versions of Matplotlib the method was called setMajor...
[ 8 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003274200_matplotlib_python.txt
Q: twisted callback function confusion I'm working on a twisted tutorial just to learn more python and it seems I've ran into a road block here. The doRead() function below is the "callback" of a reactor. What I can't understand is how the except part works. The way I read the code is that if bytes += self.sock.recv...
twisted callback function confusion
I'm working on a twisted tutorial just to learn more python and it seems I've ran into a road block here. The doRead() function below is the "callback" of a reactor. What I can't understand is how the except part works. The way I read the code is that if bytes += self.sock.recv(1024) would've caused a block then it wi...
[ "The point is that method doRead gets called only when the socket is \"ready for reading\": either it has some data on it, or else it's all done (and then, reading will return 0). So the solution to your problem cannot be in the doRead function -- it's all in the code calling it only when appropriate.\nThat code i...
[ 2 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003274214_python_twisted.txt
Q: how to create one-to-many relevance on google-app-engine like one forum has many topic , ths specific is : forum and topic has the same model : class Geo(db.Model): #self = db.SelfReferenceProperty() title = db.StringProperty() link = db.StringProperty() updated = db.DateTimeProperty(auto_now =Tru...
how to create one-to-many relevance on google-app-engine
like one forum has many topic , ths specific is : forum and topic has the same model : class Geo(db.Model): #self = db.SelfReferenceProperty() title = db.StringProperty() link = db.StringProperty() updated = db.DateTimeProperty(auto_now =True) author = db.ReferenceProperty(MyUser) id = db.Strin...
[ "If you want a many-to-many relationship, @thethimble's suggestion is good. If you do want a many-to-one relationship, though, you could use a SelfReferenceProperty from forum to topic -- like any other ReferenceProperty, that, too, makes an implicit collection property on the referenced entity (the one, while the...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "listproperty", "one_to_many", "python" ]
stackoverflow_0003273973_google_app_engine_listproperty_one_to_many_python.txt
Q: binary16 in Python The struct module is useful when you're trying to convert data to and from binary formats. However, recently I came across a file format specification that uses the binary16 floating point format. I looked through the Python documentation, but can't find anything that can convert to and from it....
binary16 in Python
The struct module is useful when you're trying to convert data to and from binary formats. However, recently I came across a file format specification that uses the binary16 floating point format. I looked through the Python documentation, but can't find anything that can convert to and from it. What would be the best ...
[ "You can do it roughly like you'd do it in C -- i.e., I think, roughly like this...:\ndef tofloat(b16):\n sign = -1 if b16 & 0x8000 else +1\n expo = ( b16 & 0x7C00 ) >> 10\n prec = b16 & 0x03FF\n if expo == 0:\n return sign * (2.0 ** -24) * prec\n elif expo == 0x1F:\n return sign * float('inf')\n prec |...
[ 4, 2, 1 ]
[]
[]
[ "floating_point", "format", "packing", "python", "struct" ]
stackoverflow_0003274278_floating_point_format_packing_python_struct.txt
Q: How to make a class field [list] read-only in python? i have self.some_field = [] in my class Im enquiring is there a way to make this list read-only like a property? A: You need to make it, indeed, a property...: e.g., in __init__ self._some_field = [] and then later in the class's body: @property def some_fi...
How to make a class field [list] read-only in python?
i have self.some_field = [] in my class Im enquiring is there a way to make this list read-only like a property?
[ "You need to make it, indeed, a property...: e.g., in __init__\nself._some_field = []\n\nand then later in the class's body:\n@property\ndef some_field(self):\n return self._some_field\n\nNote that this does not make the list itself immutable: what will fail is an assignment like, say,\nself.some_field = 'bah'\n...
[ 7, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003274350_oop_python.txt
Q: design workflow/flowchart representation in python? In my web application I have wizards with many next previous buttons and choices ( kind of flow chart with events and options ). Wizard do not run in one go, but may wait for external event, user come later or next day to carry on with that wizard. Currently I am...
design workflow/flowchart representation in python?
In my web application I have wizards with many next previous buttons and choices ( kind of flow chart with events and options ). Wizard do not run in one go, but may wait for external event, user come later or next day to carry on with that wizard. Currently I am manually writing code ( hard coded ) for each states of ...
[ "Looks like you want a Finite State Machine (AKA \"FSM\") -- if so, see here.\n" ]
[ 1 ]
[]
[]
[ "class_design", "flowchart", "oop", "python", "workflow" ]
stackoverflow_0003274403_class_design_flowchart_oop_python_workflow.txt
Q: How do I do this with Django objects.filter? MYTable.objects.filter( where id = 42, 55, 65, and 55) and it returns a query set ? A: MYTable.objects.filter( id__in = [42,55,65,55] )
How do I do this with Django objects.filter?
MYTable.objects.filter( where id = 42, 55, 65, and 55) and it returns a query set ?
[ "MYTable.objects.filter( id__in = [42,55,65,55] )\n\n" ]
[ 12 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0003274492_database_django_mysql_python.txt
Q: Python: defining a union of regular expressions I have a list of patterns like list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to'] what I want to do is to produce a union of all of them yielding a regular expression that matches every element in list_patterns [but presumably does not m...
Python: defining a union of regular expressions
I have a list of patterns like list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to'] what I want to do is to produce a union of all of them yielding a regular expression that matches every element in list_patterns [but presumably does not match any re not in list_patterns -- msw] re.compile(l...
[ "There are a couple of ways of doing this. The simplest is:\nlist_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']\nstring = 'there is an : error: and a cc1plus: in this string'\nprint re.findall('|'.join(list_patterns), string)\n\nOutput:\n[': error:', 'cc1plus:']\n\nwhich is fine as long...
[ 12, 3, 2, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003274027_python_regex.txt
Q: how to combine exponents? (x**a)**b => x**(a*b)? how to simplify exponents in equations in sympy from sympy import symbols a,b,c,d,e,f=symbols('abcdef') j=(a**b**5)**(b**10) print j (a**(b**5))**(b**10) #ans even after using expand simplify # desired output a**(b**15) and if it is not possible with sympy wh...
how to combine exponents? (x**a)**b => x**(a*b)?
how to simplify exponents in equations in sympy from sympy import symbols a,b,c,d,e,f=symbols('abcdef') j=(a**b**5)**(b**10) print j (a**(b**5))**(b**10) #ans even after using expand simplify # desired output a**(b**15) and if it is not possible with sympy which module should i import in python? edit even if i ...
[ "(xm)n = xmn is true only if m, n are real.\n>>> import math\n>>> x = math.e\n>>> m = 2j*math.pi\n>>> (x**m)**m # (e^(2πi))^(2πi) = 1^(2πi) = 1\n(1.0000000000000016+0j)\n>>> x**(m*m) # e^(2πi×2πi) = e^(-4π²) ≠ 1\n(7.157165835186074e-18-0j)\n\nAFAIK, sympy supports complex numbers, so I believe this simpl...
[ 7, 2, 0 ]
[]
[]
[ "exponent", "python", "simplify", "sympy" ]
stackoverflow_0003274487_exponent_python_simplify_sympy.txt
Q: problem in dictionary python I made a dictionary, then split up the values and keys into lists and now its looks like this: keys = [(4,5),(5,6),(4,8)......so on]. values = [('west',1),('south',1).......] Then I made a new dictionary like in this way, final = dict((k,v[0]) for k,v in zip(keys, values)) When I exe...
problem in dictionary python
I made a dictionary, then split up the values and keys into lists and now its looks like this: keys = [(4,5),(5,6),(4,8)......so on]. values = [('west',1),('south',1).......] Then I made a new dictionary like in this way, final = dict((k,v[0]) for k,v in zip(keys, values)) When I execute -print final - output is in t...
[ "Works for me:\n>>> keys=[(4,5),(5,6)]\n>>> values = [\"west\",\"south\"]\n>>> f=dict(zip(keys,values))\n>>> f\n{(4, 5): 'west', (5, 6): 'south'}\n>>> f[(4,5)]\n'west'\n\n", "Works for me:\n>>> final = {(4,5):\"West\", (5,6): \"East\"}\n>>> print final\n{(4, 5): 'West', (5, 6): 'East'}\n>>> final[(4,5)]\n'West'\n...
[ 2, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003274762_dictionary_python.txt
Q: Error in executing python code- dictionary problem while stack.isEmpty() != 1: fin = stack.pop() print fin - output is (1,1) k = final.get(fin) return k def directionToVector(direction, speed = 1.0): dx, dy = Actions._directions[direction] return (dx * s...
Error in executing python code- dictionary problem
while stack.isEmpty() != 1: fin = stack.pop() print fin - output is (1,1) k = final.get(fin) return k def directionToVector(direction, speed = 1.0): dx, dy = Actions._directions[direction] return (dx * speed, dy * speed) directionToVector = staticmethod(dir...
[ "Actions._directions is presumably a dictionary, so the line:\ndx, dy = Actions._directions[direction]\n\nat runtime (based on the error message) is:\ndx, dy = Actions._directions[\"W\"]\n\nand it's complaining that there's no key \"W\" in that dictionary. So you should check to see that you've actually added th...
[ 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003274889_dictionary_python.txt
Q: How can I define a string in a python function? I'm playing with Python and Google App Engine for the first time but am unable to define a string within my function (mytest2), I get an indentation error on the line after the declaration. I can define one in the parameters that works (test) but can't see why I woul...
How can I define a string in a python function?
I'm playing with Python and Google App Engine for the first time but am unable to define a string within my function (mytest2), I get an indentation error on the line after the declaration. I can define one in the parameters that works (test) but can't see why I wouldn't be able to do it in the function aswell. I've re...
[ "Never mix tabs and spaces in python!\nGenerally accepted practice is to use 4 spaces for indentation. This is written in PEP 8 , the python style guide. I strongly recommmend reading it.\nI usually set my editor to replace tabs with 4 spaces, every decent text editor supports this.\nThe reason why tabs are a probl...
[ 2 ]
[]
[]
[ "google_app_engine", "indentation", "python", "syntax_error" ]
stackoverflow_0003274873_google_app_engine_indentation_python_syntax_error.txt
Q: SimpleXmlRpcServer _sock.rcv freezes after thousands of requests I'm serving requests from several XMLRPC clients over WAN. The thing works great for, let's say, a period of one day (sometimes two), then freezes in socket.py: data = self._sock.recv(self._rbufsize) _sock.timeout is -1, _sock.gettimeout is None The...
SimpleXmlRpcServer _sock.rcv freezes after thousands of requests
I'm serving requests from several XMLRPC clients over WAN. The thing works great for, let's say, a period of one day (sometimes two), then freezes in socket.py: data = self._sock.recv(self._rbufsize) _sock.timeout is -1, _sock.gettimeout is None There is nothing special I do in the main thread (just receiving XMLRPC c...
[ "What exactly is happening in your OS's TCP/IP stack (possibly in the python layers on top, but that's less likely) to cause this is a mystery. As a practical workaround, I'd set a timeout longer than the delays you expect between requests (10 seconds should be plenty if you expect a request every 2 seconds) and i...
[ 1, 0 ]
[]
[]
[ "python", "recv", "simplexmlrpcserver" ]
stackoverflow_0003271966_python_recv_simplexmlrpcserver.txt
Q: Is there an equivalent to python's urllib in c/c++? any c/c++ library out there that provides functions like getUrl, urlopen, post etc. ? A: There are some libraries, libcurl and libwww amongst others. libcurl website even lists some other alternatives. A: Not a batteries-included, officially endorsed library,...
Is there an equivalent to python's urllib in c/c++?
any c/c++ library out there that provides functions like getUrl, urlopen, post etc. ?
[ "There are some libraries, libcurl and libwww amongst others.\nlibcurl website even lists some other alternatives.\n", "Not a batteries-included, officially endorsed library, but there are numerous libraries out there. The most popular, AFAIK, is libCURL, which I've used to good effect in the past. It has an \"ea...
[ 7, 1 ]
[]
[]
[ "c++", "python", "url" ]
stackoverflow_0003275252_c++_python_url.txt
Q: What is happening in this Python program? I'd like to know what is getting assigned to what in line 8. # Iterators class Fibs: def __init__(self): self.a = 0 self.b = 1 def next(self): self.a, self.b = self.b, self.a+self.b # <--- here return self.a def __iter__(self): ...
What is happening in this Python program?
I'd like to know what is getting assigned to what in line 8. # Iterators class Fibs: def __init__(self): self.a = 0 self.b = 1 def next(self): self.a, self.b = self.b, self.a+self.b # <--- here return self.a def __iter__(self): return self fibs = Fibs() for f in fi...
[ "It's a multiple assignment roughly equivalent to this:\ntmp = self.a\nself.a = self.b\nself.b = tmp + self.b\n\nOr this pseudo-code:\n\na' = b\nb' = a + b\n\nAs you can see the multiple assignment is much more concise than separate assignments and more closely resembles the pseudo-code example.\nAlmost that exampl...
[ 8, 7, 3, 0 ]
[]
[]
[ "iterator", "python", "variable_assignment" ]
stackoverflow_0003273092_iterator_python_variable_assignment.txt
Q: Compiling .go in Windows ... & Can python connect to Go? i know that go language does not support windows yet, now, how can i compile .go file is windows ? and can python connect to go ? like connecting c++ or java to python ... lol A: While the Go language implementation for Windows is still experimental, it's...
Compiling .go in Windows ... & Can python connect to Go?
i know that go language does not support windows yet, now, how can i compile .go file is windows ? and can python connect to go ? like connecting c++ or java to python ... lol
[ "While the Go language implementation for Windows is still experimental, it's steadily improving. An updated binary version is published regularly: Win32 build of Go.\n" ]
[ 4 ]
[]
[]
[ "go", "python", "windows" ]
stackoverflow_0003275255_go_python_windows.txt
Q: How to write a twisted server that is also a client? How do I create a twisted server that's also a client? I want the reactor to listen while at the same time it can also be use to connect to the same server instance which can also connect and listen. A: Call reactor.listenTCP and reactor.connectTCP. You can h...
How to write a twisted server that is also a client?
How do I create a twisted server that's also a client? I want the reactor to listen while at the same time it can also be use to connect to the same server instance which can also connect and listen.
[ "Call reactor.listenTCP and reactor.connectTCP. You can have as many different kinds of connections - servers or clients - as you want.\nFor example:\nfrom twisted.internet import protocol, reactor\nfrom twisted.protocols import basic\n\nclass SomeServerProtocol(basic.LineReceiver):\n def lineReceived(self, lin...
[ 15 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003275004_python_twisted.txt