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: Generating a List Class in Python I am having some problems generating a list for a class in Python. I know there is something simple I'm overlooking, but I just can't figure it out. My basic code so far: class Test: def __init__(self,test): self.__test = test My problem is that if I enter t = Test(...
Generating a List Class in Python
I am having some problems generating a list for a class in Python. I know there is something simple I'm overlooking, but I just can't figure it out. My basic code so far: class Test: def __init__(self,test): self.__test = test My problem is that if I enter t = Test([1,3,5]) things will work just fine, b...
[ "I'm not exactly sure what you're looking for, but you probably want to use None as a default:\nclass Test:\n def __init__(self,test=None):\n if test is None:\n self.__test = []\n else:\n self.__test = test\n\n", "You could use the following idiom:\nclass Test:\n def __...
[ 4, 3, 3 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002675965_list_python.txt
Q: Pushing data once a URL is requested Given, when a user requests /foo on my server, I send the following HTTP response (not closing the connection): Content-Type: multipart/x-mixed-replace; boundary=----------------------- ----------------------- Content-Type: text/html <a href="/bar">foo</a> When the user goes...
Pushing data once a URL is requested
Given, when a user requests /foo on my server, I send the following HTTP response (not closing the connection): Content-Type: multipart/x-mixed-replace; boundary=----------------------- ----------------------- Content-Type: text/html <a href="/bar">foo</a> When the user goes to /bar (which will send 204 No Content s...
[ "If the problem is to pass some command from /bar application to /foo application and you are using some servlet-like approach (the Python code is loaded once and not for each request as in CGI), you can just change some class property of the /foo application and be ready to react to the change in the /foo instance...
[ 1, 1, 1 ]
[ "Not sure if this is quite what you're looking for, but there is a fairly old way of doing server push using a mime content of multipart/x-mixed-replace \nBasically you compose the response as a mime object with content type multipart/x-mixed-replace, and send the first \"version\" of a document down. The browser w...
[ -1 ]
[ "python", "wsgi" ]
stackoverflow_0002576715_python_wsgi.txt
Q: In which scenario it is useful to use Disassembly on python? The dis module can be effectively used to disassemble Python methods, functions and classes into low-level interpreter instructions. I know that dis information can be used for: 1. Find race condition in programs that use threads 2. Find possible optimiz...
In which scenario it is useful to use Disassembly on python?
The dis module can be effectively used to disassemble Python methods, functions and classes into low-level interpreter instructions. I know that dis information can be used for: 1. Find race condition in programs that use threads 2. Find possible optimizations From your experience, do you know any other scenarios where...
[ "dis is useful, for example, when you have different code doing the same thing and you wonder where the performance difference lies in.\nExample: list += [item] vs list.append(item)\ndef f(x): return 2*x\n\ndef f1(func, nums):\n result = []\n for item in nums:\n result += [fun(item)]\n return result\n\ndef f2...
[ 7, 5, 3 ]
[]
[]
[ "assembly", "python" ]
stackoverflow_0002676154_assembly_python.txt
Q: Objects array with numpy are there any way to create an object form any class inside a numpy array?. Something like: a = zeros(4) for i in range(4): a[i]=Register() Thanks A: Yes, you can do this: a = numpy.array([Register() for _ in range(4)]) Here, a.dtype is dtype('object'). Alternatively, if you really...
Objects array with numpy
are there any way to create an object form any class inside a numpy array?. Something like: a = zeros(4) for i in range(4): a[i]=Register() Thanks
[ "Yes, you can do this:\na = numpy.array([Register() for _ in range(4)])\n\nHere, a.dtype is dtype('object').\nAlternatively, if you really need to reserve memory for your array and then build it element by element, you can do:\na = numpy.empty(shape=(4,), dtype=object)\na[0] = Register() # etc.\n\n", "The items ...
[ 17, 5 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0002674139_arrays_numpy_python.txt
Q: How do you throw an HTTP error with mod_python I have a setup where I'm serving simple python pages using the mod_python publisher. At some points I'd like to have the python function raise a standard apache error - for example throwing a 500 error if a required file is missing. How can I throw an apache error fr...
How do you throw an HTTP error with mod_python
I have a setup where I'm serving simple python pages using the mod_python publisher. At some points I'd like to have the python function raise a standard apache error - for example throwing a 500 error if a required file is missing. How can I throw an apache error from within a mod_python script?
[ "I am not a python expert but from this documentation, it would appear that you can do:\nraise apache.SERVER_RETURN, apache.HTTP_INTERNAL_SERVER_ERROR\n\nHere is a quote of the documentation in case of link rot:\n\nA handler function will always be passed a reference to a request\n object. (Throughout this manual,...
[ 2, 1 ]
[]
[]
[ "apache", "http_error", "mod_python", "python" ]
stackoverflow_0002520659_apache_http_error_mod_python_python.txt
Q: Long running, polling, queueing process for Python. What's the best stuff to use? Feel free to close and/or redirect if this has been asked, but here's my situation: I've got an application that will require doing a bunch of small units of work (polling a web service until something is done, then parsing about 1MB...
Long running, polling, queueing process for Python. What's the best stuff to use?
Feel free to close and/or redirect if this has been asked, but here's my situation: I've got an application that will require doing a bunch of small units of work (polling a web service until something is done, then parsing about 1MB worth of XML and putting it in a database). I want to have a simple async queueing me...
[ "There's celery.\nYou could break it down into 2 different Tasks: one to poll the web service and queue the second task, which would be in charge of parsing the XML and persisting it.\n", "This problem sounds like a pretty good candidate for Python's built-in (2.6+ anyway) multiprocessing module: http://docs.pyth...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002676057_python.txt
Q: Facebook API non-interactive authorization/login i'm trying to build a facebook API client using python, code follows: import os import urllib2 import urllib import cookielib import hashlib import json USER = '' PASS = '' LOGIN = 'http://www.facebook.com/login.php?login_attempt=1' HOST = 'http://api.facebook.com...
Facebook API non-interactive authorization/login
i'm trying to build a facebook API client using python, code follows: import os import urllib2 import urllib import cookielib import hashlib import json USER = '' PASS = '' LOGIN = 'http://www.facebook.com/login.php?login_attempt=1' HOST = 'http://api.facebook.com/restserver.php' API_KEY = 'eca5c767f0e5b6594241957437...
[ "You also need a call_id parameter which can be based on time.time(), as well as a method parameter. \n" ]
[ 1 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0002674202_facebook_python.txt
Q: Elegant way to collapse or expand sub-sequences of a list in Python? I want to collapse or expand sub-sequences of a list e.g. ['A', 'B', 'D', 'E', 'H'] -> ['AB', 'DE', 'H'] and vice versa EDIT: the example above may cause misunderstanding. the following is better: e.g. ['foo', 'bar', 'wtf'] <-> ['baz', 'wtf'] cu...
Elegant way to collapse or expand sub-sequences of a list in Python?
I want to collapse or expand sub-sequences of a list e.g. ['A', 'B', 'D', 'E', 'H'] -> ['AB', 'DE', 'H'] and vice versa EDIT: the example above may cause misunderstanding. the following is better: e.g. ['foo', 'bar', 'wtf'] <-> ['baz', 'wtf'] currently I wrote some ugly code like: while True: for i, x in enumerate(s...
[ "I wouldn't call this much better but it's a different way to do it, and it also handles the quirk Justin points out. (I was more interested in finding a subsequence from a list, and I couldn't find a good function on Google)\ndef findsubseq(L, subseq):\n if not subseq: return # just die on zero-len input\n ...
[ 2, 1, 0 ]
[]
[]
[ "compiler_construction", "design_patterns", "list", "python" ]
stackoverflow_0002674647_compiler_construction_design_patterns_list_python.txt
Q: Google App Engine: JSON module I'm using JSON with Google App Engine. I'm using JSON for comunication, so on the Python side I have: import json The error I'm getting is this: <class 'django.core.exceptions.ViewDoesNotExist'>: Could not import views.ganttapp. Error was: No module named json In my stand-alone th...
Google App Engine: JSON module
I'm using JSON with Google App Engine. I'm using JSON for comunication, so on the Python side I have: import json The error I'm getting is this: <class 'django.core.exceptions.ViewDoesNotExist'>: Could not import views.ganttapp. Error was: No module named json In my stand-alone this works great. Is there any problem...
[ "Maybe you can import the Django simplejson wrapper:\nfrom django.utils import simplejson\n\n" ]
[ 17 ]
[]
[]
[ "django", "google_app_engine", "json", "python" ]
stackoverflow_0002676767_django_google_app_engine_json_python.txt
Q: What version of Visual Studio is Python on my computer compiled with? I am trying to find out the version of Visual Studio that is used to compile the Python on my computer It says Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 What I do not understand is this MSC V.1500 de...
What version of Visual Studio is Python on my computer compiled with?
I am trying to find out the version of Visual Studio that is used to compile the Python on my computer It says Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 What I do not understand is this MSC V.1500 designation. Does it mean it is compiled with Visual Studio 2005? I cannot fi...
[ "\n\n\n\nVisual C++ version\n_MSC_VER\n\n\n\n\nVisual C++ 4.x\n1000\n\n\nVisual C++ 5\n1100\n\n\nVisual C++ 6\n1200\n\n\nVisual C++ .NET\n1300\n\n\nVisual C++ .NET 2003\n1310\n\n\nVisual C++ 2005 (8.0)\n1400\n\n\nVisual C++ 2008 (9.0)\n1500\n\n\nVisual C++ 2010 (10.0)\n1600\n\n\nVisual C++ 2012 (11.0)\n1700\n\n\n...
[ 184, 13 ]
[]
[]
[ "python", "visual_c++", "visual_studio", "windows" ]
stackoverflow_0002676763_python_visual_c++_visual_studio_windows.txt
Q: Sorting HTML table (with anchor tags and data in cells) in Python I have a necessity to sort a given HTML table of the following structure, in Python. <table> <tr> <td><a href="#">ABCD</a></td> <td>A23BND</td> <td><a title="ABCD">345345</td> </tr> <tr> <td><a href="#">EF...
Sorting HTML table (with anchor tags and data in cells) in Python
I have a necessity to sort a given HTML table of the following structure, in Python. <table> <tr> <td><a href="#">ABCD</a></td> <td>A23BND</td> <td><a title="ABCD">345345</td> </tr> <tr> <td><a href="#">EFG</a></td> <td>Add4D</td> <td><a title="EFG">3432</td> ...
[ "It sorts by the text because that's what you're extracting as the key when you do\nkey = elem.findtext(colName)\n\nI imagine colName is some tag string, and findtext will just find the text of the first subelement matching that tag. If what you want instead is to use as the key the value of some attribute (e.g. t...
[ 1, 0, 0 ]
[]
[]
[ "html", "html_table", "python", "sorting" ]
stackoverflow_0002578971_html_html_table_python_sorting.txt
Q: Stealing Cookies with no user input? I'm creating a static site generator with a dynamic admin backend for one user. The site accepts no user input. Does this mean that I am safe from attackers who are trying to steal my admin cookie? (there is no user input, so XSS and other methods don't work, right?) A: If th...
Stealing Cookies with no user input?
I'm creating a static site generator with a dynamic admin backend for one user. The site accepts no user input. Does this mean that I am safe from attackers who are trying to steal my admin cookie? (there is no user input, so XSS and other methods don't work, right?)
[ "If there's no user input (no links to click that have any effects, etc.), how does the admin backend qualify as \"dynamic\"?\nBut basically: No, not unless you're using HTTPS. Even if you're not accepting input, the cookie is transmitted in plaintext and so can be captured (by a man-in-the-middle attack, etc.) and...
[ 1, 0 ]
[]
[]
[ "python", "security", "xss" ]
stackoverflow_0002676747_python_security_xss.txt
Q: Explaining Python variable scope I'm teaching myself Python and I was translating some sample code into this class Student(object): def __init__( self, name, a,b,c ): self.name = name self.a = a self.b = b self.c = c def average(self): return ( a+b+c ) / 3.0 Which...
Explaining Python variable scope
I'm teaching myself Python and I was translating some sample code into this class Student(object): def __init__( self, name, a,b,c ): self.name = name self.a = a self.b = b self.c = c def average(self): return ( a+b+c ) / 3.0 Which is pretty much my intended class defi...
[ "Barenames (like a, b, c) are always scoped as local or global (save for nested functions, which are nowhere around in your code). The rationale is that adding further scopes would needlessly make things more complicated -- e.g, if in your self.a = a the barename a could be scoped to mean what you appear to want (...
[ 10, 2 ]
[ "All instance variables should be called using self\n" ]
[ -1 ]
[ "python", "scope" ]
stackoverflow_0002677545_python_scope.txt
Q: Why use Python interactive mode? When I first started reading about Python, all of the tutorials have you use Python's Interactive Mode. It is difficult to save, write long programs, or edit your existing lines (for me at least). It seems like a far more difficult way of writing Python code than opening up a code....
Why use Python interactive mode?
When I first started reading about Python, all of the tutorials have you use Python's Interactive Mode. It is difficult to save, write long programs, or edit your existing lines (for me at least). It seems like a far more difficult way of writing Python code than opening up a code.py file and running the interpreter on...
[ "Let's see:\n\nIf you want to know how something works, you can just try it. There is no need to write up a file. I almost always scratch write my programs in the interpreter before coding them. It's not just for things that you don't know how they work in the programming language. I never remember what the co...
[ 39, 14, 5, 2, 2, 2, 2, 2, 1, 0 ]
[]
[]
[ "interactive_mode", "python", "python_interactive" ]
stackoverflow_0002664785_interactive_mode_python_python_interactive.txt
Q: How to reload Django models without losing my locals in an interactive session? I'm doing some research with an interactive shell and using a Django app (shell_plus) for storing data and browsing it using the convenient admin. Occasionally I add or change some of the app models, and run a syncdb (or South migratio...
How to reload Django models without losing my locals in an interactive session?
I'm doing some research with an interactive shell and using a Django app (shell_plus) for storing data and browsing it using the convenient admin. Occasionally I add or change some of the app models, and run a syncdb (or South migration when changing a model). The changes to the models don't take effect in my interacti...
[ "You can use this snippet to rebuild the AppCache. Do not forget to remove all *.pyc files if any by using something like:\nfind . -name \"*.pyc\" -exec rm {} \\;\n\nOtherwise the reload() will ignore your changes in your models.py file.\n" ]
[ 1 ]
[]
[]
[ "django", "ipython", "module", "python" ]
stackoverflow_0002677649_django_ipython_module_python.txt
Q: Scraping data from Flash (Games) I saw this video, and I am really curious how it was performed. Does anyone have any ideas? My intuition is that he scraped pixels from the screen (one per 'box'), and then fed that into some program to determine the next move. Is scraping pixel-by-pixel the way to do this, or is t...
Scraping data from Flash (Games)
I saw this video, and I am really curious how it was performed. Does anyone have any ideas? My intuition is that he scraped pixels from the screen (one per 'box'), and then fed that into some program to determine the next move. Is scraping pixel-by-pixel the way to do this, or is there a better way? I am looking to do ...
[ "Yes, i think he scanned the pixels. Actually it should be very simple because you only need to scan the new shape for each move. With that information you can locally calculate the grid and further use it for your AI calculations.\n", "Probably that's the most reliable way. There are ways to inspect what is happ...
[ 2, 2 ]
[]
[]
[ "flash", "java", "python", "screen_scraping" ]
stackoverflow_0002678091_flash_java_python_screen_scraping.txt
Q: Slow XML-RPC in Windows 7 with XML-RPC.NET I'm considering to use XML-RPC.NET to communicate with a Linux XML-RPC server written in Python. I have tried a sample application (MathApp) from Cook Computing's XML-RPC.NET but it took 30 seconds for the app to add two numbers within the same LAN with server. I have al...
Slow XML-RPC in Windows 7 with XML-RPC.NET
I'm considering to use XML-RPC.NET to communicate with a Linux XML-RPC server written in Python. I have tried a sample application (MathApp) from Cook Computing's XML-RPC.NET but it took 30 seconds for the app to add two numbers within the same LAN with server. I have also tried to run a simple client written in Pytho...
[ "There is a bug that affects BaseHTTPServer and its subclasses (including SimpleXMLRPCServer). Basically, your server is likely to call socket.getfqdn function for every IP address it is trying to log. This article probably explains it better.\nThe workaround describes there, for TL;DR:\nimport BaseHTTPServer\ndef ...
[ 2, 0 ]
[]
[]
[ ".net", "c#", "python", "windows_7", "xml_rpc" ]
stackoverflow_0002235643_.net_c#_python_windows_7_xml_rpc.txt
Q: Building a user subscription application I'm trying to come up with the best way to handle user subscription and management for our magazine website. What I want to happen is a user purchases a subscription and they are granted online access of a certain membership role for a certain amount of time depending on ho...
Building a user subscription application
I'm trying to come up with the best way to handle user subscription and management for our magazine website. What I want to happen is a user purchases a subscription and they are granted online access of a certain membership role for a certain amount of time depending on how many years they subscribed for. I would also...
[ "You just need to keep track of their expiration date, not their join date. If the expiration date is in the future, they're active. Otherwise, they aren't. From that, you could implement a custom decorator similar to @login_required to check for this stuff. \nhttp://code.djangoproject.com/browser/django/trunk/djan...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002678411_django_python.txt
Q: Share headers amongst files in python? Is there a way to share headers in python? i import the same things in different controllers in pylons. A: Try putting the common code in the __init__.py file. As in here: "The __init__.py file is usually empty, but can be used to export selected portions of the package un...
Share headers amongst files in python?
Is there a way to share headers in python? i import the same things in different controllers in pylons.
[ "Try putting the common code in the __init__.py file. As in here: \"The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient names, hold convenience functions, etc.\"\n", "You could put the \"header\" things into a module of their own and then, wherev...
[ 3, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002678514_import_python.txt
Q: Speeding up templates in GAE-Py by aggregating RPC calls Here's my problem: class City(Model): name = StringProperty() class Author(Model): name = StringProperty() city = ReferenceProperty(City) class Post(Model): author = ReferenceProperty(Author) content = StringProperty() The code isn't important....
Speeding up templates in GAE-Py by aggregating RPC calls
Here's my problem: class City(Model): name = StringProperty() class Author(Model): name = StringProperty() city = ReferenceProperty(City) class Post(Model): author = ReferenceProperty(Author) content = StringProperty() The code isn't important... its this django template: {% for post in posts %} <div>{{po...
[ "I have been in a similar situation. Instead of ReferenceProperty, I had parent/child relationships but the basics are the same. My current solution is not polished but at least it is efficient enough for reports and things with 200-1,000 entities, each with several subsequent child entities that require fetching.\...
[ 1, 0 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0002076470_django_templates_google_app_engine_python.txt
Q: How to workaround Python "WindowsError messages are not properly encoded" problem? It's a trouble when Python raised a WindowsError, the encoding of message of the exception is always os-native-encoded. For example: import os os.remove('does_not_exist.file') Well, here we get an exception: Traceback (most recent...
How to workaround Python "WindowsError messages are not properly encoded" problem?
It's a trouble when Python raised a WindowsError, the encoding of message of the exception is always os-native-encoded. For example: import os os.remove('does_not_exist.file') Well, here we get an exception: Traceback (most recent call last): File "<stdin>", line 1, in <module> WindowsError: [Error 2] 系統找不到指定的檔案。: ...
[ "We have the same problem in Russian version of MS Windows: the code page of the default locale is cp1251, but the default code page of the Windows console is cp866:\n>>> import sys\n>>> print sys.stdout.encoding\ncp866\n>>> import locale\n>>> print locale.getdefaultlocale()\n('ru_RU', 'cp1251')\n\nThe solution sho...
[ 4, 0, 0 ]
[]
[]
[ "encoding", "python", "windowserror" ]
stackoverflow_0002668319_encoding_python_windowserror.txt
Q: Several numpy arrays with SWIG I am using SWIG to pass numpy arrays from Python to C++ code: %include "numpy.i" %init %{ import_array(); %} %apply (float* INPLACE_ARRAY1, int DIM1) {(float* data, int n)}; class Class { public: void test(float* data, int n) { //... } }; and in Python: c = Class() a...
Several numpy arrays with SWIG
I am using SWIG to pass numpy arrays from Python to C++ code: %include "numpy.i" %init %{ import_array(); %} %apply (float* INPLACE_ARRAY1, int DIM1) {(float* data, int n)}; class Class { public: void test(float* data, int n) { //... } }; and in Python: c = Class() a = zeros(5) c.test(a) This works, b...
[ "I found out the answer from a collegue of mine:\n%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data1, int n1), (float* data2, int n2)};\n\nclass Class \n{\n public: \n void test(float* data1, int n1, float* data2, int n2)\n {\n //...\n }\n};\n\nNow two numpy arrays are passed to Class::test.\n" ]
[ 9 ]
[]
[]
[ "c++", "numpy", "python", "swig" ]
stackoverflow_0002674046_c++_numpy_python_swig.txt
Q: How do I store values of arbitrary type in a single Django model? Say I have the unknown number of questions. For example: Is the sky blue [y/n] What date were your born on [date] What is pi [3.14] What is a large integ [100] Now each of these questions poses a different but very type specific answer (boolean...
How do I store values of arbitrary type in a single Django model?
Say I have the unknown number of questions. For example: Is the sky blue [y/n] What date were your born on [date] What is pi [3.14] What is a large integ [100] Now each of these questions poses a different but very type specific answer (boolean, date, float, int). Natively django can happily deal with these in a ...
[ "I actually just faced this type of problem regarding extensible user settings. My solution was to store the type on the model in a CharField and use a getter to do the type conversion with a smart use of __builtin__ and getattr. This is my code (adapt for your needs):\nVALUE_TYPE_CHOICES = (\n (\"unicode\", \"U...
[ 6, 2, 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002678770_django_django_models_python.txt
Q: Changing contents of currently displayed listbox in urwid/python2.6 I'm writing a music player in python, with a cli using urwid. I intend to have the current playlist in a simpleListWalker, wrapped by a listbox, then columns, a pile, and finally a frame. How do I replace the entire contents of this listbox (or s...
Changing contents of currently displayed listbox in urwid/python2.6
I'm writing a music player in python, with a cli using urwid. I intend to have the current playlist in a simpleListWalker, wrapped by a listbox, then columns, a pile, and finally a frame. How do I replace the entire contents of this listbox (or simpleListWalker) with something else? Relevant code: class mainDisplay(ob...
[ "self.mainListContent[:] = [new, list, of, widgets]\n\nshould replace the whole list of widgets in place.\nNext time post your question to the mailing list or the IRC channel if you want a faster response!\n" ]
[ 8 ]
[]
[]
[ "python", "urwid" ]
stackoverflow_0002137354_python_urwid.txt
Q: Storing processed objects in database with sqlalchemy i have things that requires processing and rarely changes except with certain events to take advantage of memcached. can i store a serial version of an object in a data field quickly? A: Just pickle (or marshal or even JSON) it and throw it in memcached.
Storing processed objects in database with sqlalchemy
i have things that requires processing and rarely changes except with certain events to take advantage of memcached. can i store a serial version of an object in a data field quickly?
[ "Just pickle (or marshal or even JSON) it and throw it in memcached.\n" ]
[ 3 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002678861_python_sqlalchemy.txt
Q: What is Ruby's analog to Python Metaclasses? Python has the idea of metaclasses that, if I understand correctly, allow you to modify an object of a class at the moment of construction. You are not modifying the class, but instead the object that is to be created then initialized. Python (at least as of 3.0 I belie...
What is Ruby's analog to Python Metaclasses?
Python has the idea of metaclasses that, if I understand correctly, allow you to modify an object of a class at the moment of construction. You are not modifying the class, but instead the object that is to be created then initialized. Python (at least as of 3.0 I believe) also has the idea of class decorators. Again i...
[ "Ruby doesn't have metaclasses. There are some constructs in Ruby which some people sometimes wrongly call metaclasses but they aren't (which is a source of endless confusion).\nHowever, there's a lot of ways to achieve the same results in Ruby that you would do with metaclasses. But without telling us what exactly...
[ 24, 13 ]
[]
[]
[ "metaclass", "metaprogramming", "python", "ruby" ]
stackoverflow_0002676007_metaclass_metaprogramming_python_ruby.txt
Q: Python - Memory Leak I'm working on solving a memory leak in my Python application. Here's the thing - it really only appears to happen on Windows Server 2008 (not R2) but not earlier versions of Windows, and it also doesn't look like it's happening on Linux (although I haven't done nearly as much testing on Linux...
Python - Memory Leak
I'm working on solving a memory leak in my Python application. Here's the thing - it really only appears to happen on Windows Server 2008 (not R2) but not earlier versions of Windows, and it also doesn't look like it's happening on Linux (although I haven't done nearly as much testing on Linux). To troubleshoot it, I s...
[ "If there's never any garbage in gc.garbage, then I'm not sure what you're trying to do by enabling GC debugging. Sure, it'll tell you which objects are considered for cleanup, but that's not particularly interesting if you end up with no circular references that can't be cleaned up.\nIf your program is using more ...
[ 25, 3 ]
[]
[]
[ "memory_leaks", "python" ]
stackoverflow_0002678906_memory_leaks_python.txt
Q: Why is Django reverse() failing with unicode? Here is a django models file that is not working as I would expect. I would expect the to_url method to do the reverse lookup in the urls.py file, and get a url that would correspond to calling that view with arguments supplied by the Arguments model. from django.db im...
Why is Django reverse() failing with unicode?
Here is a django models file that is not working as I would expect. I would expect the to_url method to do the reverse lookup in the urls.py file, and get a url that would correspond to calling that view with arguments supplied by the Arguments model. from django.db import models class Element(models.Model): viewna...
[ "In your to_url method, you need to make sure the keys in the d dict are not Unicode strings. This isn't peculiar to Django, it's just how keyword arguments to functions work in Python. Here's a simple example:\n>>> def f(**kwargs): print kwargs\n... \n>>> d1 = { u'foo': u'bar' }\n>>> d2 = { 'foo': u'bar' }\n>>> ...
[ 5 ]
[]
[]
[ "django", "python", "unicode" ]
stackoverflow_0002679052_django_python_unicode.txt
Q: Django Backend-neutral DictCursor Is there any way to get a backend-neutral dictionary cursor in Django? This would be a cursor that is a dict rather than a tuple. I am forced to use Oracle for the school project I'm working on. in Python's MySQLDb module it's called a DictCursor. With WoLpH's inspiring suggesti...
Django Backend-neutral DictCursor
Is there any way to get a backend-neutral dictionary cursor in Django? This would be a cursor that is a dict rather than a tuple. I am forced to use Oracle for the school project I'm working on. in Python's MySQLDb module it's called a DictCursor. With WoLpH's inspiring suggestion I know I am very close.. def dict_cu...
[ "You could write it in a couple of lines :)\ndef dict_cursor(cursor):\n description = [x[0] for x in cursor.description]\n for row in cursor:\n yield dict(zip(description, row))\n\nOr if you really want to save space:\nsimplify_description = lambda cursor: [x[0] for x in cursor.description]\ndict_curso...
[ 7 ]
[]
[]
[ "database_cursor", "dictionary", "django", "python" ]
stackoverflow_0002678991_database_cursor_dictionary_django_python.txt
Q: Regex for finding valid sphinx fields I'm trying to validate that the fields given to sphinx are valid, but I'm having difficulty. Imagine that valid fields are cat, mouse, dog, puppy. Valid searches would then be: @cat search terms @(cat) search terms @(cat, dog) search term @cat searchterm1 @dog searchterm2 @...
Regex for finding valid sphinx fields
I'm trying to validate that the fields given to sphinx are valid, but I'm having difficulty. Imagine that valid fields are cat, mouse, dog, puppy. Valid searches would then be: @cat search terms @(cat) search terms @(cat, dog) search term @cat searchterm1 @dog searchterm2 @(cat, dog) searchterm1 @mouse searchterm2 ...
[ "To match all allowed fields, the following rather fearful looking regex works:\n\n@((?:cat|mouse|dog|puppy)\\b|\\((?:(?:cat|mouse|dog|puppy)(?:, *|(?=\\))))+\\))\n\nIt returns these matches, in order: @cat, @(cat), @(cat, dog), @cat, @dog, @(cat, dog), @mouse.\nThe regex breaks down as follows:\n\n@ ...
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "django", "python", "regex", "sphinx" ]
stackoverflow_0002677713_django_python_regex_sphinx.txt
Q: how to read specific number of floats from file in python? I am reading a text file from the web. The file starts with some header lines containing the number of data points, followed the actual vertices (3 coordinates each). The file looks like: # comment HEADER TEXT POINTS 6 float 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8...
how to read specific number of floats from file in python?
I am reading a text file from the web. The file starts with some header lines containing the number of data points, followed the actual vertices (3 coordinates each). The file looks like: # comment HEADER TEXT POINTS 6 float 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 POLYGONS the line star...
[ "I'm not entirely sure what your goal is from your explanation. \nFor the record, here is code that does basically the same thing as yours seems to be trying to that uses some techniques I would employ over the ones you have chosen. It's usually a sign that you're doing something wrong if you're using while loops a...
[ 3, 0 ]
[]
[]
[ "python", "readfile" ]
stackoverflow_0002679290_python_readfile.txt
Q: Keep PyGTK Button from Resizing on Label Change I'm working on a PyGTK app with some Buttons that, when clicked, give a text entry dialog, then set the text on the button to whatever was entered in the box. The problem is that if the text is longer than the button can show, the button changes size to accomodate. H...
Keep PyGTK Button from Resizing on Label Change
I'm working on a PyGTK app with some Buttons that, when clicked, give a text entry dialog, then set the text on the button to whatever was entered in the box. The problem is that if the text is longer than the button can show, the button changes size to accomodate. How do I keep GTK Buttons from resizing when the text ...
[ "Have you tried set_size_request?\nhttp://library.gnome.org/devel/pygtk/stable/class-gtkwidget.html#method-gtkwidget--set-size-request\nbutton = gtk.Button(\"text on button\")\nbutton.set_size_request(width=30, height=20)\n\nSee:\nhttp://www.pygtk.org/docs/pygtk/class-gtkwidget.html#method-gtkwidget--set-size-reque...
[ 1 ]
[]
[]
[ "button", "pygtk", "python", "user_interface" ]
stackoverflow_0002679500_button_pygtk_python_user_interface.txt
Q: jQuery as a replacement for Django or Web2Py I was planning to write a new webapp, I figured out two options for my backend - web2py or django. I recently came across jQuery and found it to be very cool. Could I just use jQuery as a replacement for django and web2py and finish this webapp. Some features that I'm ...
jQuery as a replacement for Django or Web2Py
I was planning to write a new webapp, I figured out two options for my backend - web2py or django. I recently came across jQuery and found it to be very cool. Could I just use jQuery as a replacement for django and web2py and finish this webapp. Some features that I'm going to implement - user profiles, users can add ...
[ "It's definitely possible to do all of the front-end in Javascript on the client's browser (unless you have to support JS-less or very old browser), reducing the server's role to that of offering a REST-ish interface for the client's AJAX calls (as well of course as serving static files of various sort;).\nThis app...
[ 8, 4, 3 ]
[]
[]
[ "django", "jquery", "python", "web2py" ]
stackoverflow_0002677117_django_jquery_python_web2py.txt
Q: How to get the coordinates of an object in a tkinter canvas? I can't seem to figure out how to retrieve the x,y position of an oval created on a Tkinter canvas using Python via c.create_oval(x0, y0, x1, y2) I understand that Tkinter creates the oval inside the box specified by x0,y0,x1,y2 and if I can get those c...
How to get the coordinates of an object in a tkinter canvas?
I can't seem to figure out how to retrieve the x,y position of an oval created on a Tkinter canvas using Python via c.create_oval(x0, y0, x1, y2) I understand that Tkinter creates the oval inside the box specified by x0,y0,x1,y2 and if I can get those coordinates that would also work. I need the coordinates to move th...
[ "Assign the results of c.create_oval to x -- that's the \"object ID\" of the oval. Then,\nc.coords(x)\n\ngives you the (x1, y1, x2, y2) tuple of the oval's coordinates (you call coords with new coordinates following the x to move the oval).\n" ]
[ 45 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0002679418_python_tkinter.txt
Q: python gio waiting for async operations to be done I have to mount a WebDav location and wait for the operation to be finished before to proceed (it's a script). So I'm using the library in this way: location = gio.File("dav://server.bb") location.mount_enclosing_volume(*args,**kw) # The setup is not much relevant...
python gio waiting for async operations to be done
I have to mount a WebDav location and wait for the operation to be finished before to proceed (it's a script). So I'm using the library in this way: location = gio.File("dav://server.bb") location.mount_enclosing_volume(*args,**kw) # The setup is not much relevant location.get_path() # Returns None because it's not yet...
[ "To wait for termination, you need to call mount_enclosing_volume_finished with the async-result object returned by mount_enclosing_volume (alternatively, you could pass the latter a callback, if you want to operate asynchronously, but it looks like you want sync-like operations here).\n" ]
[ 1 ]
[]
[]
[ "asynchronous", "file_io", "pygtk", "python" ]
stackoverflow_0002676951_asynchronous_file_io_pygtk_python.txt
Q: Serializing Python bytestrings to JSON, preserving ordinal character values I have some binary data produced as base-256 bytestrings in Python (2.x). I need to read these into JavaScript, preserving the ordinal value of each byte (char) in the string. If you'll allow me to mix languages, I want to encode a strin...
Serializing Python bytestrings to JSON, preserving ordinal character values
I have some binary data produced as base-256 bytestrings in Python (2.x). I need to read these into JavaScript, preserving the ordinal value of each byte (char) in the string. If you'll allow me to mix languages, I want to encode a string s in Python such that ord(s[i]) == s.charCodeAt(i) after I've read it back into...
[ "\nIs there a way to encode bytestrings\n to Unicode strings that preserves\n ordinal character values?\n\nThe byte -> unicode transformation is called decode, not encode. But yes, decoding with a codec such as iso-8859-1 should indeed \"preserve ordinal character values\" as you wish.\n", "Could you just use ...
[ 5, 3 ]
[]
[]
[ "json", "python" ]
stackoverflow_0002679936_json_python.txt
Q: Swig - wrapping C struct I am trying to write Python wrap for C code which uses struct. modules.c: struct foo { int a; }; struct foo bar; modulues.i %module nepal %{ struct foo { int a; } %} extern struct foo bar; But during compiling I am given error: In function ‘Swig_var_bar_set’: er...
Swig - wrapping C struct
I am trying to write Python wrap for C code which uses struct. modules.c: struct foo { int a; }; struct foo bar; modulues.i %module nepal %{ struct foo { int a; } %} extern struct foo bar; But during compiling I am given error: In function ‘Swig_var_bar_set’: error: ‘bar’ undeclared (first u...
[ "Try this:\n%module nepal\n%{\n struct foo\n {\n int a;\n };\n\n extern struct foo bar;\n%}\n\nstruct foo\n{\n int a;\n};\n\nextern struct foo bar;\n\nThe code in %{ %} is inserted in the wrapper, and the code below it is parsed to create the wrapper. It's easier to put this all in a header f...
[ 2 ]
[]
[]
[ "c", "python", "struct", "swig" ]
stackoverflow_0002676453_c_python_struct_swig.txt
Q: exceptions with python unicode encode/decode functions (why doesn't errors=ignore actually ignore them??) Does anyone know why the string conversion functions throw exceptions when errors="ignore" is passed? How can I convert from regular Python string objects to unicode without errors being thrown? Thanks very mu...
exceptions with python unicode encode/decode functions (why doesn't errors=ignore actually ignore them??)
Does anyone know why the string conversion functions throw exceptions when errors="ignore" is passed? How can I convert from regular Python string objects to unicode without errors being thrown? Thanks very much! python -c "import codecs; codecs.open('tmp', 'wb', encoding='utf8', errors='ignore').write('кошка')" retur...
[ "The write method (in Python 2) takes a unicode object, and you're passing it a str -- so the encode call in codecs.py line 351 is first trying to build a unicode object (with the default codec, 'ascii'). Fix is easy: change the write call to \nwrite(u'кошка')\n\nThe u prefix tells Python you're using a Unicode ob...
[ 3, 3, 2, 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0002679930_python_unicode.txt
Q: maya2008 win32api 64 bit python How is it possible to run import win32api successfully on a 64bit maya version 2008? The following error occurs: Error: No module named win32api Traceback (most recent call last): File "", line 1, in ImportError: No module named win32api I need to get mouse cursor position in p...
maya2008 win32api 64 bit python
How is it possible to run import win32api successfully on a 64bit maya version 2008? The following error occurs: Error: No module named win32api Traceback (most recent call last): File "", line 1, in ImportError: No module named win32api I need to get mouse cursor position in python so that I can place window exac...
[ "Maya uses its own Python installation. You need to add the path where pywin32 is installed by one way or another ... you can create a .pth file in \n\nC:\\Program\n Files\\Autodesk\\Maya2009\\Python\\Lib\\site-packages\\\n\nAlso, like Adam pointed out, make sure you have the 64 bit pywin32 installed.\nHere's an a...
[ 1 ]
[]
[]
[ "maya", "python" ]
stackoverflow_0002680589_maya_python.txt
Q: Right clicking on QHeaderView inside of QTreeView I've written a descendant of QTreeView with multiple columns. I want to create a popup menu that appears whe nthe user right-clicks over the column headers. I have tried catching signals from QTreeView for this, but QTreeView doesn't seem to emit signals on the hea...
Right clicking on QHeaderView inside of QTreeView
I've written a descendant of QTreeView with multiple columns. I want to create a popup menu that appears whe nthe user right-clicks over the column headers. I have tried catching signals from QTreeView for this, but QTreeView doesn't seem to emit signals on the headers. QTreeView.header() does. I therefore believe I mu...
[ "I discovered the setContextMenuPolicy function:\nself.header().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\nself.header().customContextMenuRequested.connect(self.headerMenu)\n\nThen, in headerMenu: \ndef headerMenu(self, pos):\n globalPos = self.mapToGlobal(pos)\n menu = QMenu()\n menu.addAction(\"...
[ 5, 0 ]
[]
[]
[ "pyqt", "python", "qheaderview", "qt", "qtreeview" ]
stackoverflow_0002673326_pyqt_python_qheaderview_qt_qtreeview.txt
Q: Using Python as a CGI script without the CGI module? Is it possible to use Python as CGI without using the CGI module and still get access to all of the browser information and everything? I tried: #!/usr/bin/python import sys print "Content-type: text/html" print data = sys.stdin.readlines() print len(data) but ...
Using Python as a CGI script without the CGI module?
Is it possible to use Python as CGI without using the CGI module and still get access to all of the browser information and everything? I tried: #!/usr/bin/python import sys print "Content-type: text/html" print data = sys.stdin.readlines() print len(data) but it always prints 0.
[ "It is indeed possible, but a lot of the information is passed in as environment variables, not on standard input. In fact, the only thing that is passed in on standard input is the body of the incoming request, which would only have contents if a form is being POSTed.\nFor more information on how to work with CGI,...
[ 3, 2 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0002680119_cgi_python.txt
Q: how to write or create (when no exist) a file using python and Google AppEngine this is my code: f = open('text/a.log', 'wb') f.write('hahaha') f.close() and it is not create a new file when not exist how to do this , thanks updated class MyThread(threading.Thread): def run(self): f = open('a.log', 'w...
how to write or create (when no exist) a file using python and Google AppEngine
this is my code: f = open('text/a.log', 'wb') f.write('hahaha') f.close() and it is not create a new file when not exist how to do this , thanks updated class MyThread(threading.Thread): def run(self): f = open('a.log', 'w') f.write('hahaha') f.close() error is : Traceback (most recent cal...
[ "You are using the Google App Engine.\nFrom the Google App Engine documentation:\n\nThe Sandbox\nApplications run in a secure environment that provides limited access to the underlying operating system. These limitations allow App Engine to distribute web requests for the application across multiple servers, and st...
[ 9, 7, 3, 0, 0 ]
[]
[]
[ "file", "google_app_engine", "python" ]
stackoverflow_0002680215_file_google_app_engine_python.txt
Q: Facebook connect on Google App Engine with Django Patch We are building a website on Google App Engine, using django patch. We would like to use Facebook connect for two purposes: Authenticate users. Access user's social data. Searching for a solution in the usual places (google, FB, SO) brigs up a lot of noise...
Facebook connect on Google App Engine with Django Patch
We are building a website on Google App Engine, using django patch. We would like to use Facebook connect for two purposes: Authenticate users. Access user's social data. Searching for a solution in the usual places (google, FB, SO) brigs up a lot of noise, many partial solutions and no clear answer. So the question...
[ "Honza: we where looking for something that also does authentication Django style.\nWe ended up doing the login on the client side than sending an AJAX request to Django and wrote our own authenticate/login logic.\nOnce we get the user's credentials, we use PyFacebook for FB connectivity.\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "google_app_engine", "python" ]
stackoverflow_0002064673_django_facebook_google_app_engine_python.txt
Q: how to send some data to the Thread module on python and google-map-engine from google.appengine.ext import db class Log(db.Model): content = db.StringProperty(multiline=True) class MyThread(threading.Thread): def run(self,request): #logs_query = Log.all().order('-date') #logs = logs_query...
how to send some data to the Thread module on python and google-map-engine
from google.appengine.ext import db class Log(db.Model): content = db.StringProperty(multiline=True) class MyThread(threading.Thread): def run(self,request): #logs_query = Log.all().order('-date') #logs = logs_query.fetch(3) log=Log() log.content=request.POST.get('content',None)...
[ "You cannot use threads on App Engine.\n", "I am not sure this will meet your needs or even possible in google appengine but\nif you change thr.start(request) to thr.run(request) the error should gone\n" ]
[ 1, 0 ]
[]
[]
[ "django", "google_app_engine", "multithreading", "python" ]
stackoverflow_0002681169_django_google_app_engine_multithreading_python.txt
Q: Is there a way to set the encoding for all files read and written by python I have a script in python that needs to read iso-8859-1 files and also write in that encoding. Now I am running the script in an environment with all locales set at utf-8. Is there a way to define in my python scripts that all file acces h...
Is there a way to set the encoding for all files read and written by python
I have a script in python that needs to read iso-8859-1 files and also write in that encoding. Now I am running the script in an environment with all locales set at utf-8. Is there a way to define in my python scripts that all file acces have to use the iso-8859-1 encoding?
[ "Python doesn't really listen to the environment when it comes to reading and writing files in a particular encoding. It only listens to the environment when it comes to encoding unicode written to stdout, if stdout is connected to a terminal.\nWhen reading and writing files in Python 2.x, you deal with bytestrings...
[ 4 ]
[]
[]
[ "encoding", "file_io", "python" ]
stackoverflow_0002681713_encoding_file_io_python.txt
Q: Adaptive Threshold in OpenCV (Version 1 - the swig version) I'm trying to get adaptive thresholding working in the python binding to opencv (the swig one - cannot get opencv 2.0 working as I am using a beagleboard as the cross compiling is not working yet). I have a greyscale image (ccg.jpg) and the following co...
Adaptive Threshold in OpenCV (Version 1 - the swig version)
I'm trying to get adaptive thresholding working in the python binding to opencv (the swig one - cannot get opencv 2.0 working as I am using a beagleboard as the cross compiling is not working yet). I have a greyscale image (ccg.jpg) and the following code import opencv from opencv import highgui img = highgui.cvLoadI...
[ "I'm not a user of the swig interface, but in C the cvLoadImage function loads an image as 3 channel RGB by default, so if that's true for swig as well, then you're going to need to either change your code to load img as grayscale (CV_LOAD_IMAGE_GRAYSCALE) or do an intermediate step to convert it to grayscale with ...
[ 2 ]
[]
[]
[ "beagleboard", "opencv", "python" ]
stackoverflow_0002668663_beagleboard_opencv_python.txt
Q: printing the instance in Python class Complex: def init(self, realpart, imagpart): self.real = realpart self.imag = imagpart print self.real, self.imag I get this output: >>> Complex(3,2) 3 2 <__main__.Complex instance at 0x01412210> But why does he print the last line?...
printing the instance in Python
class Complex: def init(self, realpart, imagpart): self.real = realpart self.imag = imagpart print self.real, self.imag I get this output: >>> Complex(3,2) 3 2 <__main__.Complex instance at 0x01412210> But why does he print the last line?
[ "You running the code from an interactive python prompt, which prints out the result of any statements, unless it is None.\nTry it:\n>>> 1\n1\n>>> 1 + 3\n4\n>>> \"foobar\"\n'foobar'\n>>> \n\nSo your call to Complex(3,2) is creating an object, and python is printing it out.\n", "Because it is the result of the sta...
[ 5, 3, 3, 1 ]
[]
[]
[ "class", "instance", "python", "python_idle" ]
stackoverflow_0002682771_class_instance_python_python_idle.txt
Q: Python: "inline" block / condition to return a char? I would like to create a string that uses a plural if count > 1. For that, I would like have an "inline" condition that returns 's' to concatenate to my noun. print "The plural of plural is plural{0}. {1}".format( {'s' if count > 1}, "Isnt't it!?") A: print "T...
Python: "inline" block / condition to return a char?
I would like to create a string that uses a plural if count > 1. For that, I would like have an "inline" condition that returns 's' to concatenate to my noun. print "The plural of plural is plural{0}. {1}".format( {'s' if count > 1}, "Isnt't it!?")
[ "print \"The plural of plural is plural{0}. {1}\".format('s' if count > 1 else '', \"Isnt't it!?\")\n\n", "You need to add the else part to the 's' if count > 1 otherwise this is not a valid expression (because the value to return when count <= 1 has not been specified and Python cannot guess what this should be)...
[ 1, 1 ]
[]
[]
[ "conditional_statements", "python", "return" ]
stackoverflow_0002683086_conditional_statements_python_return.txt
Q: How to read a media file from .py file using Django? I can read a.txt file like this: text = open('a.txt', 'rb').read() But when I put the a.txt to the media folder, this doesn't work: text = open('/media/a.txt', 'rb').read() I'm getting the following error: IOError at / [Errno 13] file not accessible: '/media/a...
How to read a media file from .py file using Django?
I can read a.txt file like this: text = open('a.txt', 'rb').read() But when I put the a.txt to the media folder, this doesn't work: text = open('/media/a.txt', 'rb').read() I'm getting the following error: IOError at / [Errno 13] file not accessible: '/media/a.txt' How can I read file from the media directory?
[ "To be more generic (and be sure that you use the media folder), you could change it to:\nimport os\nfrom django.conf import settings\ntext = open(os.path.join(settings.MEDIA_ROOT, 'a.txt'), 'rb').read()\n\n", "The initial / means that it is an absolute path, accessed from the root of the filesystem. If you want ...
[ 9, 2 ]
[ "You cannot read static files from your application code in Google App Engine. Files marked as static are served from different servers and not included with your application. If your application needs to read them and they don't need to be served directly to users, don't mark them static. If you need to both se...
[ -1 ]
[ "django", "file_io", "python" ]
stackoverflow_0002679993_django_file_io_python.txt
Q: Visual Studio COM access Is it possible to control Visual Studio like you can control Excel through the Python COM API? I'm trying to kick off a build through COM (don't ask!) An example would be much appreciated. A: Yes. See the Visual Studio SDK. http://msdn.microsoft.com/en-us/library/bb166441%28VS.80%29.asp...
Visual Studio COM access
Is it possible to control Visual Studio like you can control Excel through the Python COM API? I'm trying to kick off a build through COM (don't ask!) An example would be much appreciated.
[ "Yes. See the Visual Studio SDK.\nhttp://msdn.microsoft.com/en-us/library/bb166441%28VS.80%29.aspx\nThere are C# wrappers for the COM objects, but the underlying technology is COM.\n" ]
[ 0 ]
[]
[]
[ "com", "python", "visual_studio" ]
stackoverflow_0002683712_com_python_visual_studio.txt
Q: Why is this Python class copying another class contents? I'm trying to understand an estrange behavior in Python. I have the next python code: class IntContainer: listOfInts = [] def __init__(self, initListOfInts): for i in initListOfInts: self.listOfInts.append(i) def printInts...
Why is this Python class copying another class contents?
I'm trying to understand an estrange behavior in Python. I have the next python code: class IntContainer: listOfInts = [] def __init__(self, initListOfInts): for i in initListOfInts: self.listOfInts.append(i) def printInts(self): print self.listOfInts if __name__ == "__main...
[ "Since you made listOfInts a class variable, that's what self.listOfInts is accessing, whatever self instance it may be; so, all the appends are going to the same list.\nIf that's not what you want, you need to make listOfInts an instance variable, for example by assigning self.listOfInts = [] at the start of the _...
[ 6, 2 ]
[]
[]
[ "class", "python", "variables" ]
stackoverflow_0002684265_class_python_variables.txt
Q: Reload mod_fcgid without killing Python Service I'm currently running a Django project on my school's webserver with FCGI. I did follow the multiple guides that recommends installing a virtual local Python environment and it worked out great. The only issue i had was that "touching" my fcgi-file to reload source-f...
Reload mod_fcgid without killing Python Service
I'm currently running a Django project on my school's webserver with FCGI. I did follow the multiple guides that recommends installing a virtual local Python environment and it worked out great. The only issue i had was that "touching" my fcgi-file to reload source-files wasn't enough, but instead i had to kill the pyt...
[ "here's what I would do:\n## top of my .fcgi script\nimport sys, time\noriginal_modules = sys.modules.copy()\n\n## in a separate thread\nold_ctime = os.path.getctime(\"mymodule.py\")\nwhile True:\n time.sleep(10)\n new_ctime = os.path.getctime(\"mymodule.py\")\n if new_ctime > old_ctime:\n sys.modul...
[ 0 ]
[]
[]
[ "django", "mod_fcgid", "python" ]
stackoverflow_0002684427_django_mod_fcgid_python.txt
Q: Where is the PyGTK event stack? You can know if the event stack is empty calling the gtk.events_pending() method, but I want to manipulate the pending events and filter it before the next gtk loop cycle, this data must be stored somewhere, but where? Thanks. A: You can control the event loop yourself. Rather th...
Where is the PyGTK event stack?
You can know if the event stack is empty calling the gtk.events_pending() method, but I want to manipulate the pending events and filter it before the next gtk loop cycle, this data must be stored somewhere, but where? Thanks.
[ "You can control the event loop yourself. Rather than calling gtk.main(), you can use gtk.main_iteration.\nYour loop could then be:\nwhile running:\n #filter events here\n gtk.main_iteration(true)\n\nsee here for more info.\n" ]
[ 1 ]
[]
[]
[ "gnome", "gtk", "pygtk", "python" ]
stackoverflow_0002685014_gnome_gtk_pygtk_python.txt
Q: In MAYA 2009, is it possible to capture the cube rotate event? I need to call a function ( Maya-Python ) based on cube rotationX. For that I have to capture the event, programmatically. I tried using while loop but It stucks in the loop, Nothing can be done in that time. I tried theading (python), still same. Can ...
In MAYA 2009, is it possible to capture the cube rotate event?
I need to call a function ( Maya-Python ) based on cube rotationX. For that I have to capture the event, programmatically. I tried using while loop but It stucks in the loop, Nothing can be done in that time. I tried theading (python), still same. Can it be done this or other way? If yes, How? Maya 2009 in Windows XP S...
[ "It sounds like a scriptJob may be what you're after. Here's a simple example below. However, in this example the callback will only be called when you release the mouse from rotating.\nimport maya.cmds\n\ndef myRotateCallback():\n print 'do something'\n\nmaya.cmds.scriptJob( attributeChange=['pCube1.rotateX',...
[ 1 ]
[]
[]
[ "3d", "events", "maya", "python" ]
stackoverflow_0002656891_3d_events_maya_python.txt
Q: How to keep same substrings in vim regex I'd ideally like a vim answer to this: I want to change [*, 1, *, *] to [*, 2, *, *] Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example [0, 1, 0, 1] to [0, 2, 0, 1] [1, 1, 1, 1] to [1, 2, 1, 1] If people know ...
How to keep same substrings in vim regex
I'd ideally like a vim answer to this: I want to change [*, 1, *, *] to [*, 2, *, *] Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example [0, 1, 0, 1] to [0, 2, 0, 1] [1, 1, 1, 1] to [1, 2, 1, 1] If people know how to do this in perl or python or whatever, ...
[ "This works :)\n1,$s/\\[\\(\\d\\+\\),\\s\\+\\d\\+,\\s\\+\\(\\d\\+\\),\\s\\+\\(\\d\\+\\)\\]/[\\1, 2, \\2, \\3]/g\n\nor\n%s/\\[\\(\\d\\+\\),\\s\\+\\d\\+,\\s\\+\\(\\d\\+\\),\\s\\+\\(\\d\\+\\)\\]/[\\1, 2, \\2, \\3]/\n\n", "The following should do what you want:\n:%s/\\(\\[[^,]*, *\\)\\(\\d\\)\\([^]]*\\]\\)/\\=submatc...
[ 4, 2, 1, 1, 1 ]
[]
[]
[ "perl", "python", "regex", "vim" ]
stackoverflow_0002683810_perl_python_regex_vim.txt
Q: Why am I getting a TypeError when looping? I'm working on a Python extension module, and one of my little test scripts is doing something strange, viz.: x_max, y_max, z_max = m.size for x in xrange(x_max): for y in xrange(y_max): for z in xrange(z_max): #do my stuff What makes no sense is...
Why am I getting a TypeError when looping?
I'm working on a Python extension module, and one of my little test scripts is doing something strange, viz.: x_max, y_max, z_max = m.size for x in xrange(x_max): for y in xrange(y_max): for z in xrange(z_max): #do my stuff What makes no sense is that the loop gets to the end of the first 'z' ...
[ "The problem is here: x_max, y_max, z_max = m.size\nThis syntax x_max, y_max, z_max expects a tuple/list on the other end of the equality sign so unless m.size is one -- and I take it it's an integer -- you need the following:\nx_max = y_max = z_max = m.size\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002685565_python.txt
Q: Conditional CellRenderCombo in pyGTK TreeView I have a two column TreeView attached to a ListStore. Both columns are CellRenderCombo combo boxes. When the user selects an entry in the first box, I need to dynamically load a set of options in the second. For example, the behavior I want is: On row 0, the user sele...
Conditional CellRenderCombo in pyGTK TreeView
I have a two column TreeView attached to a ListStore. Both columns are CellRenderCombo combo boxes. When the user selects an entry in the first box, I need to dynamically load a set of options in the second. For example, the behavior I want is: On row 0, the user selects "Alphabet" in the first column box. The se...
[ "First, you need to bind model property of the second renderer from the model, like:\ngtk.TreeViewColumn ('...', gtk.CellRendererCombo (), text = N, model = M)\n\nwhere M is the column number which stores models (likely gtk.ListStore). Or use any other method of binding properties from model columns.\nThen connect...
[ 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002682139_gtk_pygtk_python.txt
Q: python multiprocessing member variable not set In the following script, I get the "stop message received" output but the process never ends. Why is that? Is there another way to end a process besides terminate or os.kill that is along these lines? from multiprocessing import Process from time import sleep class T...
python multiprocessing member variable not set
In the following script, I get the "stop message received" output but the process never ends. Why is that? Is there another way to end a process besides terminate or os.kill that is along these lines? from multiprocessing import Process from time import sleep class Test(Process): def __init__(self): Proces...
[ "The start method has cloned the object into a separate process, where it executes run. The end method is nothing special, so it runs in the process that calls it -- the changes it performs to that object are not sent to the clone object.\nSo, use instead an appropriate means of interprocess communication, such as...
[ 3 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0002685845_multiprocessing_python.txt
Q: Google app engine How to count SUM from datestore? Im wondering, how can i get a SUM of a rating entity i get from the datastore (python)? should i: ratingsum = 0 for rating in ratings: ratingsum + rating print ratingsum ? A: Yep, that's pretty much it. Retrieve all the entities you want to sum, and sum t...
Google app engine How to count SUM from datestore?
Im wondering, how can i get a SUM of a rating entity i get from the datastore (python)? should i: ratingsum = 0 for rating in ratings: ratingsum + rating print ratingsum ?
[ "Yep, that's pretty much it. Retrieve all the entities you want to sum, and sum them in your app. There is no SUM in GQL.\nIf what you're trying to accomplish is to find the average rating for an entity, there's a better way.\nclass RateableThing(db.Model):\n num_ratings = db.IntegerProperty()\n avg_rating ...
[ 12, 0 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0002686361_google_app_engine_gql_python.txt
Q: Django Deploy trouble Well, i've walking around this for a couples of days now... I think is time to ask for some help, i think my installation is ok... Server OS: Centos 5 Python -v 2.6.5 Django -v (1, 1, 1, 'final', 0) my apache conf: <VirtualHost *:80> DocumentRoot /opt/workshop ServerName taller.antell...
Django Deploy trouble
Well, i've walking around this for a couples of days now... I think is time to ask for some help, i think my installation is ok... Server OS: Centos 5 Python -v 2.6.5 Django -v (1, 1, 1, 'final', 0) my apache conf: <VirtualHost *:80> DocumentRoot /opt/workshop ServerName taller.antell.com.py WSGIScriptAlias...
[ "Try adding both the directory containing the settings.py file and its parent directory to sys.path. Better still, read 'http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html' and use the WSGI script file contents described right at the end (after you have read the post as to why it is an issue). ...
[ 4, 0 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0002685994_apache_django_mod_wsgi_python.txt
Q: Syntax error when using "with open" in Python (python newbie) [root@234571-app2 git]# ./test.py File "./test.py", line 4 with open("/home/git/post-receive-email.log",'a') as log_file: ^ SyntaxError: invalid syntax The code looks like this: [root@234571-app2 git]# more test.py #!/usr/bin/python...
Syntax error when using "with open" in Python (python newbie)
[root@234571-app2 git]# ./test.py File "./test.py", line 4 with open("/home/git/post-receive-email.log",'a') as log_file: ^ SyntaxError: invalid syntax The code looks like this: [root@234571-app2 git]# more test.py #!/usr/bin/python from __future__ import with_statement with open("/home/git/post-r...
[ "What you have should be correct. Python 2.5 introduced the with statement as something you can import from __future__. Since your code is correct, the only explanation I can think of is that your python version is not what you think it is. There's a good chance you have multiple versions of python installed on ...
[ 8, 5, 1 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0002685097_python_syntax_error.txt
Q: Feedback on availability with Google App Engine We've had some good experiences building an app on Google App Engine, this first app's target audience are Google Apps users, so no issues there in terms of it being hosted on Google infrastructure. We like it so much that we would like to investigate using it for an...
Feedback on availability with Google App Engine
We've had some good experiences building an app on Google App Engine, this first app's target audience are Google Apps users, so no issues there in terms of it being hosted on Google infrastructure. We like it so much that we would like to investigate using it for another app, however this next project is for a client ...
[ "You are correct: you are not in as much control vs. traditional hosting. However, hopefully the gains outweight the negatives. App Engine is extremely scalable -- it runs on the same hardware that runs Google itself. How often have you visited http://google.com and had that page or a search result fail?\nAlthough ...
[ 8, 2 ]
[]
[]
[ "google_app_engine", "google_apps", "python" ]
stackoverflow_0002682062_google_app_engine_google_apps_python.txt
Q: Django-admin.py not working (-bash:django-admin.py: command not found) I'm having trouble getting django-admin.py to work... it's in this first location: /Users/mycomp/bin/ but I think I need it in another location for the terminal to recognize it, no? Noob, Please help. Thanks!! my-computer:~/Django-1.1.1 mycomp...
Django-admin.py not working (-bash:django-admin.py: command not found)
I'm having trouble getting django-admin.py to work... it's in this first location: /Users/mycomp/bin/ but I think I need it in another location for the terminal to recognize it, no? Noob, Please help. Thanks!! my-computer:~/Django-1.1.1 mycomp$ sudo ln -s /Users/mycomp/bin/django-admin.py /Users/mycomp/django-1.1.1/dj...
[ "you need to export /Users/mycomp/bin to environment variable PATH\nfor a session\nexport PATH=/Users/mycomp/bin:$PATH\n\nfor permanent, whenever you use bash\necho \"export PATH=/Users/mycomp/bin:\\$PATH\" >> ~/.bashrc\nsource ~/.bashrc\n\nNote: And I think django automatically create executable django-admin file ...
[ 3 ]
[]
[]
[ "django", "django_admin", "framework_installation", "python" ]
stackoverflow_0002687704_django_django_admin_framework_installation_python.txt
Q: Can't get python.manage.py syncdb to work I just created my first django app, initialized variables DATABASE_ENGINE and DATABASE_NAME in settings.py, but now when I run python manage.py syncdb, I get the following error Can somebody help? Does this have to do with having two python versions installed? I'm a django...
Can't get python.manage.py syncdb to work
I just created my first django app, initialized variables DATABASE_ENGINE and DATABASE_NAME in settings.py, but now when I run python manage.py syncdb, I get the following error Can somebody help? Does this have to do with having two python versions installed? I'm a django/python noob, please help. thanks!! my-computer...
[ "You need to run manage.py from the root folder of your project. Looks like you are trying from the Django install folder. \n" ]
[ 6 ]
[]
[]
[ "django", "django_syncdb", "manage.py", "python" ]
stackoverflow_0002687853_django_django_syncdb_manage.py_python.txt
Q: Problem with recognizing "\t" for vim in python output I have a python code something like this file_out.write(str(i).strip()+"\t"+str(dict1[i]).strip()+"\n") But when i try to recognize this with vim by saying on the file that was written. :%s/\t/|/g But it does not recognize the \t A: :%s/\\\t/|/g because ...
Problem with recognizing "\t" for vim in python output
I have a python code something like this file_out.write(str(i).strip()+"\t"+str(dict1[i]).strip()+"\n") But when i try to recognize this with vim by saying on the file that was written. :%s/\t/|/g But it does not recognize the \t
[ ":%s/\\\\\\t/|/g\n\nbecause the \\ is itself a special char that needs escaping with \\.\n", "I'd do :%s/^V^I/|/g where ^V means control-V and ^I means control-I -- that's how you get a tab into your vim command!\n" ]
[ 2, 0 ]
[]
[]
[ "python", "sed", "vim" ]
stackoverflow_0002687618_python_sed_vim.txt
Q: Fitting Gaussian KDE in numpy/scipy in Python I am fitting a Gaussian kernel density estimator to a variable that is the difference of two vectors, called "diff", as follows: gaussian_kde_covfact(diff, smoothing_param) -- where gaussian_kde_covfact is defined as: class gaussian_kde_covfact(stats.gaussian_kde): ...
Fitting Gaussian KDE in numpy/scipy in Python
I am fitting a Gaussian kernel density estimator to a variable that is the difference of two vectors, called "diff", as follows: gaussian_kde_covfact(diff, smoothing_param) -- where gaussian_kde_covfact is defined as: class gaussian_kde_covfact(stats.gaussian_kde): def __init__(self, dataset, covfact = 'scotts'): ...
[ "A density peaked whose mass is at one point is not Gaussian, so strictly speaking, what you want to do is undefined (and such distribution does not have a finite covariance).\nNow, in your case, for a vector which is all zero, you could special-case it, bypassing the whole infrastructure. A simple way to detect th...
[ 2 ]
[]
[]
[ "numpy", "probability", "python", "scipy", "statistics" ]
stackoverflow_0002678425_numpy_probability_python_scipy_statistics.txt
Q: Compiling scipy on Windows 32-bit: linker error with libf77blas.a Has anyone tried compiling SciPy 0.7.1 on Windows using numpy-1.3.0 that was built with the pre-built ATLAS libraries (atlas3.6.0_WinNT_P4SSE2.zip) linked in the installation document. I get the following linker error, and have no ideas as to how to...
Compiling scipy on Windows 32-bit: linker error with libf77blas.a
Has anyone tried compiling SciPy 0.7.1 on Windows using numpy-1.3.0 that was built with the pre-built ATLAS libraries (atlas3.6.0_WinNT_P4SSE2.zip) linked in the installation document. I get the following linker error, and have no ideas as to how to fix this issue. $ python setup.py config --compiler=mingw32 build --c...
[ "Our installation instructions are awfully out of date. First, you should use the binary installer unless you have a very good reason not to on windows. Here you are linking against an ATLAS which is different than the one numpy itself was built on, which is unlikely to work well (numpy and scipy would use differen...
[ 1 ]
[]
[]
[ "atlas", "linker_errors", "python", "scipy", "windows" ]
stackoverflow_0002596069_atlas_linker_errors_python_scipy_windows.txt
Q: Mako template depending on object class? whats a clean way to use different templates depending on an object class? other than buncha if statements A: You can make a dict, call it type2templ, with types (i.e., classes) as the keys, and mako.template.Template instances as the values -- then t = type2templ.get(t...
Mako template depending on object class?
whats a clean way to use different templates depending on an object class? other than buncha if statements
[ "You can make a dict, call it type2templ, with types (i.e., classes) as the keys, and mako.template.Template instances as the values -- then \nt = type2templ.get(type(theobj), default_templ)\n... t.render() ...\n\nThis assumes that theobj is an instance of a new-style class (not the obsolete, best-avoided \"legacy\...
[ 2 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0002687063_mako_python.txt
Q: python multiprocessing server connections I wish to get a list of connections to a manager. I can get last_accepted from the servers' listener, but I want all connections. There HAS to be a method I am missing somewhere to return all connections to a server or manager Please help!! A: Looking at multiprocessing/...
python multiprocessing server connections
I wish to get a list of connections to a manager. I can get last_accepted from the servers' listener, but I want all connections. There HAS to be a method I am missing somewhere to return all connections to a server or manager Please help!!
[ "Looking at multiprocessing/connection.py, the listener just doesn't seem to track all connections -- you could, however, subclass it and override accept to append accepted connections to a list.\n" ]
[ 0 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0002686893_multiprocessing_python.txt
Q: Python hash() can't handle long integer? I defined a class: class A: ''' hash test class >>> a = A(9, 1196833379, 1, 1773396906) >>> hash(a) -340004569 This is weird, 12544897317L expected. ''' def __init__(self, a, b, c, d): self.a = a self.b = b self.c = c ...
Python hash() can't handle long integer?
I defined a class: class A: ''' hash test class >>> a = A(9, 1196833379, 1, 1773396906) >>> hash(a) -340004569 This is weird, 12544897317L expected. ''' def __init__(self, a, b, c, d): self.a = a self.b = b self.c = c self.d = d def __hash__(self): ...
[ "It appears to be limited to 32-bits. By reading this question, it looks like your code might have produced the expected result on a 64-bit machine (with those particular values, since the result fits in 64 bits).\nThe results of the built-in hash function are platform dependent and constrained to the native word ...
[ 10, 7, 4 ]
[]
[]
[ "hash", "integer", "python" ]
stackoverflow_0002687829_hash_integer_python.txt
Q: How to iterate over the first n elements of a list? Say I've got a list and I want to iterate over the first n of them. What's the best way to write this in Python? A: The normal way would be slicing: for item in your_list[:n]: ... A: I'd probably use itertools.islice (<- follow the link for the docs), w...
How to iterate over the first n elements of a list?
Say I've got a list and I want to iterate over the first n of them. What's the best way to write this in Python?
[ "The normal way would be slicing:\nfor item in your_list[:n]: \n ...\n\n", "I'd probably use itertools.islice (<- follow the link for the docs), which has the benefits of:\n\nworking with any iterable object\nnot copying the list\n\nUsage:\nimport itertools\n\nn = 2\nmylist = [1, 2, 3, 4]\nfor item in itertool...
[ 120, 38, 13, 2 ]
[]
[]
[ "list", "python", "slice" ]
stackoverflow_0002688079_list_python_slice.txt
Q: Writing a blocking wrapper around twisted's IRC client I'm trying to write a dead-simple interface for an IRC library, like so: import simpleirc connection = simpleirc.Connect('irc.freenode.net', 6667) channel = connection.join('foo') find_command = re.compile(r'google ([a-z]+)').findall for msg in channel: ...
Writing a blocking wrapper around twisted's IRC client
I'm trying to write a dead-simple interface for an IRC library, like so: import simpleirc connection = simpleirc.Connect('irc.freenode.net', 6667) channel = connection.join('foo') find_command = re.compile(r'google ([a-z]+)').findall for msg in channel: for t in find_command(msg): channel.say("http://goog...
[ "In general, if you're trying to use Twisted in a \"blocking\" way, you're going to run into a lot of difficulties, because that's neither the way it's intended to be used, nor the way in which most people use it.\nGoing with the flow is generally a lot easier, and in this case, that means embracing callbacks. The...
[ 10 ]
[]
[]
[ "asynchronous", "python", "twisted" ]
stackoverflow_0002687656_asynchronous_python_twisted.txt
Q: Can PyAMF support service deployment by way of the filesystem? I'm evaluating PyAMF to replace our current PHP (ugh) AMF services framework, and I'm unable to find the one crucial piece of information that would allow me to provide a compelling use case for changing over: Right now, new PHP AMF services are deploy...
Can PyAMF support service deployment by way of the filesystem?
I'm evaluating PyAMF to replace our current PHP (ugh) AMF services framework, and I'm unable to find the one crucial piece of information that would allow me to provide a compelling use case for changing over: Right now, new PHP AMF services are deployed simply by putting the .php files in the filesystem; the next time...
[ "web2py includes pyamf support. The way it works is that you create functions like\ndef add(a,b): return a+b\n\nand then you decorate them with @service.amfrpc3('domain')\n@service.amfrpc3('domain')\ndef add(a,b): return a+b\n\nYou do not need to restart the web server or do anything else. You just add and delete f...
[ 2, 0 ]
[]
[]
[ "cherrypy", "django", "mod_wsgi", "pyamf", "python" ]
stackoverflow_0002683946_cherrypy_django_mod_wsgi_pyamf_python.txt
Q: Python Job Service Daemon? What packages should I look at for writing a python daemon and processing jobs? Also, what do I need to do for a python daemon? A: I'm pretty happy with beanstalkd, which has client libraries available in various languages: Daemon: http://kr.github.com/beanstalkd/ Python client librar...
Python Job Service Daemon?
What packages should I look at for writing a python daemon and processing jobs? Also, what do I need to do for a python daemon?
[ "I'm pretty happy with beanstalkd, which has client libraries available in various languages:\nDaemon:\nhttp://kr.github.com/beanstalkd/\nPython client library:\nhttp://code.google.com/p/pybeanstalk/\n", "Your question is a bit ambiguous, but I'm assuming you mean you would like to write a python daemon that will...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002688306_python.txt
Q: Python reference external module in Netbeans I'm working with a Netbeans for Python development, I have a number of projects (which have a number of modules). What I basically want to know is, how do I import one of these modules into a new project? I have tried editing the python path in netbeans, but to no avail...
Python reference external module in Netbeans
I'm working with a Netbeans for Python development, I have a number of projects (which have a number of modules). What I basically want to know is, how do I import one of these modules into a new project? I have tried editing the python path in netbeans, but to no avail. Here's my setup: Netbeans projects ============...
[ "Hadji, you may want to discard Netbeans' default structures for Python development.\nFirst of all, Python code file (.py) is a module. A package contains a number of modules.\nWhat you should do is structure your files like the following:\nNetbeans projects\n=================\nPackageA\n __init__.py (This file i...
[ 2 ]
[]
[]
[ "module", "netbeans", "projects", "python" ]
stackoverflow_0002279628_module_netbeans_projects_python.txt
Q: Code completion in NetBeans' python plugin does not work properly I am asking on StackOverflow because surely I am doing something completely silly and I hope S.O. might provide me with a quick answer. I've installed the latest stable Python-plugin for NetBeans. It works great, and I tested code completion with v...
Code completion in NetBeans' python plugin does not work properly
I am asking on StackOverflow because surely I am doing something completely silly and I hope S.O. might provide me with a quick answer. I've installed the latest stable Python-plugin for NetBeans. It works great, and I tested code completion with various packages such as sys, os and so on. It works beautifully. Howeve...
[ "I'm afraid to tell you that this is a Known Bug for over a year. Some people have suggested that it seems the Python development in NetBeans is stalled.\nPersonally, I'm using Eclipse. PyDev is still under active support, and the auto-completion is smart. In addition, it supports more variety in syntax-highlightin...
[ 4 ]
[]
[]
[ "netbeans", "netbeans6.8", "python" ]
stackoverflow_0002624137_netbeans_netbeans6.8_python.txt
Q: help with UnicodeEncodeError('ascii', u'Phase \u2013 II', 6, 7, 'ordinal not in range(128)') having problem with UnicodeEncodeError('ascii', u'Phase \u2013 II', 6, 7, 'ordinal not in range(128)') Basically what I am doing here is reading the value from excel sheet and sheet contain address in this format Phase-...
help with UnicodeEncodeError('ascii', u'Phase \u2013 II', 6, 7, 'ordinal not in range(128)')
having problem with UnicodeEncodeError('ascii', u'Phase \u2013 II', 6, 7, 'ordinal not in range(128)') Basically what I am doing here is reading the value from excel sheet and sheet contain address in this format Phase- II So wanted to know how to change` somestring = u'Phase \u2013 II' to str thanks `
[ "Excel mostly uses cp1252, so try this:\n>>> somestring.encode('cp1252', 'replace')\n'Phase \\x96 II'\n>>> print somestring.encode('cp1252', 'replace')\nPhase – II\n\nThat doesn't give you an ascii string (since your unicode string contains non-ascii characters it cannot), but it does give you a byte string that Ex...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0002688847_python.txt
Q: foo and _foo - about variables inside a class class ClassName(object): """ """ def __init__(self, foo, bar): """ """ self.foo = foo # read-write property self.bar = bar # simple attribute def _set_foo(self, value): self._foo = value def _get_foo(sel...
foo and _foo - about variables inside a class
class ClassName(object): """ """ def __init__(self, foo, bar): """ """ self.foo = foo # read-write property self.bar = bar # simple attribute def _set_foo(self, value): self._foo = value def _get_foo(self): return self._foo foo = property(_g...
[ "Docs for property explain how it's supposed to be used. There is no difference between these lines:\nself.foo = foo # read-write property\n\nand \na.foo = 3\n\nYou're also not supposed to call setters and getters manually.\neta: if you don't understand what property does after looking at the examples provided in t...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "class", "python", "variables" ]
stackoverflow_0002683447_class_python_variables.txt
Q: get average from set of objects in django Hay, i have a simple rating system for a property. You give it a mark out of 5 (stars). The models are defined like this def Property(models.Model) # stuff here def Rating(models.Model) property = models.ForeignKey(Property) stars = models.IntegerField() What...
get average from set of objects in django
Hay, i have a simple rating system for a property. You give it a mark out of 5 (stars). The models are defined like this def Property(models.Model) # stuff here def Rating(models.Model) property = models.ForeignKey(Property) stars = models.IntegerField() What i want to do is get a property, find all the R...
[ "You should use Aggregation(doc):\nfrom django.db.models import Avg\n\np = Property.objects.get(...)\nstars_average = p.rating_set.aggregate(Avg('stars')).values()[0]\n\nA little bit unsure about my example though.\n" ]
[ 41 ]
[]
[]
[ "average", "django", "python" ]
stackoverflow_0002689664_average_django_python.txt
Q: How do I install pyCurl? I tried everything! I cannot find a way to install pyCurl on my Windows 7 machine! I found these binaries link... BUT there are no binaries for 2.6. : ( Help would be great. : ) A: Here is a python2.6 binary for pycurl someone compiled for that, and for amd64 also A: http://wiki.woodp...
How do I install pyCurl?
I tried everything! I cannot find a way to install pyCurl on my Windows 7 machine! I found these binaries link... BUT there are no binaries for 2.6. : ( Help would be great. : )
[ "Here is a python2.6 binary for pycurl someone compiled for that, and for amd64 also\n", "http://wiki.woodpecker.org.cn/moin/PyCurl?action=AttachFile&do=get&target=pycurl-7.20.1.win32-py2.6.zip\nand this is mine, with newer libcurl 7.20.1, openSSL 1.0.0, etc.\n" ]
[ 3, 1 ]
[]
[]
[ "installation", "pycurl", "python", "windows" ]
stackoverflow_0002666365_installation_pycurl_python_windows.txt
Q: What is it in Java standard library that Python's lacks? I hear that the Java standard library is larger than that of Python. That makes me curious about what is missing in Python's? A: The one flaw in Python imho is that Python lacks one real canonical method of deployment. (Yes there are good ones out there, b...
What is it in Java standard library that Python's lacks?
I hear that the Java standard library is larger than that of Python. That makes me curious about what is missing in Python's?
[ "The one flaw in Python imho is that Python lacks one real canonical method of deployment. (Yes there are good ones out there, but nothing that's really rock solid).\nWhich can hamper its adoption in some Enterprise environments.\n", "Java provides a lot of varied implementations of interfaces for the basic types...
[ 8, 6, 4, 3 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002690147_java_python.txt
Q: Django: Serving Media Behind Custom URL So I of course know that serving static files through Django will send you straight to hell but I am confused on how to use a custom url to mask the true location of the file using Django. Django: Serving a Download in a Generic View but the answer I accepted seems to be th...
Django: Serving Media Behind Custom URL
So I of course know that serving static files through Django will send you straight to hell but I am confused on how to use a custom url to mask the true location of the file using Django. Django: Serving a Download in a Generic View but the answer I accepted seems to be the "wrong" way of doing things. urls.py: url(r...
[ "To expand on the previous answers you should be able to modify the following code and have nginx directly serve your download files whilst still having the files protected.\nFirst of all add a location such as :\nlocation /files/ {\n alias /true/path/to/mp3/files/;\n internal;\n}\n\nto your nginx.conf file (th...
[ 25, 3, 1 ]
[]
[]
[ "django", "nginx", "python", "url_rewriting" ]
stackoverflow_0002687957_django_nginx_python_url_rewriting.txt
Q: Permutations in python 2.5.2 I have a list of numbers for input, e.g. 671.00 1,636.00 436.00 9,224.00 and I want to generate all possible sums with a way to id it for output, e.g.: 671.00 + 1,636.00 = 2,307.00 671.00 + 436.00 = 1,107.00 671.00 + 9,224.00 = 9,224.00 671.00 + 1,636.00 + 436.00 = 2,743.00 ... an...
Permutations in python 2.5.2
I have a list of numbers for input, e.g. 671.00 1,636.00 436.00 9,224.00 and I want to generate all possible sums with a way to id it for output, e.g.: 671.00 + 1,636.00 = 2,307.00 671.00 + 436.00 = 1,107.00 671.00 + 9,224.00 = 9,224.00 671.00 + 1,636.00 + 436.00 = 2,743.00 ... and I would like to do it in Python ...
[ "Permutations are about taking an ordered set of things and moving these things around (i.e. changing order). Your question is about combinations of things from your list.\nNow, an easy way of enumerating combinations is by mapping entries from your list to bits in a number. For example, lets assume that if bit #0 ...
[ 3, 0, 0 ]
[]
[]
[ "list", "permutation", "python" ]
stackoverflow_0002689903_list_permutation_python.txt
Q: How to create A matrix of images in opencv with python bindings to feed Kmeans2 i am trying to cluster a set of images, my peblems resides in using Kmeans2 parameters in opencv. i dont know exactly how to form the points input for Kmeans2 for clustering. here what i do : samples = CreateMat ( samples_len,1,CV_32FC...
How to create A matrix of images in opencv with python bindings to feed Kmeans2
i am trying to cluster a set of images, my peblems resides in using Kmeans2 parameters in opencv. i dont know exactly how to form the points input for Kmeans2 for clustering. here what i do : samples = CreateMat ( samples_len,1,CV_32FC2) labels = CreateMat ( samples_len,1,CV_43SC1) index = 0 for name in imglist : ...
[ "Kmeans2 only takes 2-dimensional input data, so unless your images are only 2 pixels this approach will not work. You'll either need to write your own clustering algorithm that handle higher dimensional dagta or write a function that maps your images down to only 2 points (e.g. mean and variance of the grayscale ...
[ 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0002690052_opencv_python.txt
Q: Error in writing a class I am running through a tutorial online at http://www.sthurlow.com/python/lesson08/ and I believe I understand how classes work in python, at least to some degree but when I run this code: class Shape: def __init__(self,x,y): self.x = x self.y = y description = "This...
Error in writing a class
I am running through a tutorial online at http://www.sthurlow.com/python/lesson08/ and I believe I understand how classes work in python, at least to some degree but when I run this code: class Shape: def __init__(self,x,y): self.x = x self.y = y description = "This shape has not been described ...
[ "You need to indent the last line.\ndef scaleSize(self,scale): \n self.x = self.x * scale \nself.y = self.y * scale \n\nShould be \ndef scaleSize(self,scale): \n self.x = self.x * scale \n self.y = self.y * scale \n\n", "The last part of your code is wrong,\ndef scaleSize(self,scale):\n self.x = self....
[ 10, 3, 1, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0002691627_class_python.txt
Q: Can I find the path of the executable running a python script from within the python script? Is there a way to retreive the path of the executable that is running the current python script (from within the python script)? A: That should do what you want >>> import sys >>> sys.executable 'C:\\Python26\\python...
Can I find the path of the executable running a python script from within the python script?
Is there a way to retreive the path of the executable that is running the current python script (from within the python script)?
[ "That should do what you want \n>>> import sys\n>>> sys.executable\n'C:\\\\Python26\\\\python.exe'\n\n>>> import os\n>>> os.path.dirname(sys.executable)\n'C:\\\\Python26'\n\n" ]
[ 7 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0002691655_introspection_python.txt
Q: Where to store deployment scripts Assuming that I have the following directory structure for a Python project: config/ scripts/ src/ where should a fabric deployment script should go? I assume that it should be in scripts, obviously, but for me it seems more appropriate to store in scripts, the actual code that fi...
Where to store deployment scripts
Assuming that I have the following directory structure for a Python project: config/ scripts/ src/ where should a fabric deployment script should go? I assume that it should be in scripts, obviously, but for me it seems more appropriate to store in scripts, the actual code that fires up the project.
[ "This is really a preference thing -- however there are a couple places I like, depending on situation.\nMost frequently, and particularly in cases like yours where the fabfile is tied to a piece of software, I like to put it the project directory. I view fabfiles as akin to Makefiles in this case, so this feels li...
[ 2 ]
[]
[]
[ "deployment", "fabric", "python" ]
stackoverflow_0002691528_deployment_fabric_python.txt
Q: use python glob to find a folder that is a 14 digit number I have a folder with subfolders that are all in the pattern YYYYMMDDHHMMSS (timestamp). I want to use glob to only select the folders that match that pattern. A: Since glob doesn't support regular expressions, you'll have to brute-force creating the mat...
use python glob to find a folder that is a 14 digit number
I have a folder with subfolders that are all in the pattern YYYYMMDDHHMMSS (timestamp). I want to use glob to only select the folders that match that pattern.
[ "Since glob doesn't support regular expressions, you'll have to brute-force creating the match string. One way is to take advantage of the fact that character ranges in [] are expanded:\nC:\\temp\\py>mkdir 12345678901234\n\nC:\\temp\\py>C:\\Python26\\python.exe\nPython 2.6.2 Stackless 3.1b3 060516 (release26-maint...
[ 31 ]
[]
[]
[ "glob", "python" ]
stackoverflow_0002692706_glob_python.txt
Q: Quote POSIX shell special characters in Python output There are times that I automagically create small shell scripts from Python, and I want to make sure that the filename arguments do not contain non-escaped special characters. I've rolled my own solution, that I will provide as an answer, but I am almost certai...
Quote POSIX shell special characters in Python output
There are times that I automagically create small shell scripts from Python, and I want to make sure that the filename arguments do not contain non-escaped special characters. I've rolled my own solution, that I will provide as an answer, but I am almost certain I've seen such a function lost somewhere in the standard ...
[ "pipes.quote():\n>>> from pipes import quote\n>>> quote(\"\"\"some'horrible\"string\\with lots of junk!$$!\"\"\")\n'\"some\\'horrible\\\\\"string\\\\\\\\with lots of junk!\\\\$\\\\$!\"'\n\nAlthough note that it's arguably got a bug where a zero-length arg will return nothing:\n>>> quote(\"\")\n''\n\nProbably it wou...
[ 6, 1 ]
[]
[]
[ "escaping", "posix", "python", "shell", "special_characters" ]
stackoverflow_0002692873_escaping_posix_python_shell_special_characters.txt
Q: python: find and replace numbers < 1 in text file I'm pretty new to Python programming and would appreciate some help to a problem I have... Basically I have multiple text files which contain velocity values as such: 0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 ...
python: find and replace numbers < 1 in text file
I'm pretty new to Python programming and would appreciate some help to a problem I have... Basically I have multiple text files which contain velocity values as such: 0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+03 0.137865E+00 etc for many l...
[ "I think when you are beginning programming, it's useful to see some examples; and I assume you've tried this problem on your own first!\nHere is a break-down of how you could approach this:\ncontents='0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+...
[ 7, 4, 3, 3, 0, 0 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0002685015_python_replace.txt
Q: Programming language for opengl screenshot software I need to develop a multiplatform software that takes screenshots from opengl games without affecting the game in performance, it will run in the background and will add a watermark to my screenshots. What language should i use? I thought of Perl / Python. Anyone...
Programming language for opengl screenshot software
I need to develop a multiplatform software that takes screenshots from opengl games without affecting the game in performance, it will run in the background and will add a watermark to my screenshots. What language should i use? I thought of Perl / Python. Anyone can point me out something to start? Thanks!
[ "I would suggest C++. That way you can use OpenGL and DirectX libraries and API calls natively. Libraries that provide such functionality to other languages typically abstract the good stuff away from reach.\n", "The language you know best that has some sort of OpenGL Bindings.\nMy personal preference for such ki...
[ 1, 0, 0, 0 ]
[]
[]
[ "opengl", "perl", "python" ]
stackoverflow_0002691289_opengl_perl_python.txt
Q: Rare PyCairo antialias getting directly the surface data After create a Pycairo context and surface (ImageSurface) I get a diferent export results if I get directly from surface buffer surface.get_data() or from PNG export method surface.write_to_png() The context antialias flag is obviously the same and, yes, ...
Rare PyCairo antialias getting directly the surface data
After create a Pycairo context and surface (ImageSurface) I get a diferent export results if I get directly from surface buffer surface.get_data() or from PNG export method surface.write_to_png() The context antialias flag is obviously the same and, yes, the get_data method result has antialiasing, but with much poo...
[ "I answer myself, Cairo uses premultiplied color (ARGB) and GTK only it's able to manage true color (RGBA). Use it directly result in a display with gray fridges\nI could make the conversion manually, losing a lot of performace, obviously.\n" ]
[ 0 ]
[]
[]
[ "cairo", "pycairo", "python", "vector" ]
stackoverflow_0002690047_cairo_pycairo_python_vector.txt
Q: Best (or appropriate) WSGI server for this Python script? - Python I'm having quite a problem deciding how to serve a few Python scripts. The problem is that the basic functionality could be generalized by this: do_something() time.sleep(3) do_something() I tried various WSGI servers, but they have all been givin...
Best (or appropriate) WSGI server for this Python script? - Python
I'm having quite a problem deciding how to serve a few Python scripts. The problem is that the basic functionality could be generalized by this: do_something() time.sleep(3) do_something() I tried various WSGI servers, but they have all been giving me concurrency limitations, as in I have to specify how many threads ...
[ "Have you checked tornado with its non-blocking asynchronous requests?\nhttp://www.tornadoweb.org/\nI have never used it though but here is an example from doc:\nclass MainHandler(tornado.web.RequestHandler):\n @tornado.web.asynchronous\n def get(self):\n http = tornado.httpclient.AsyncHTTPClient()\n ...
[ 1, 1, 0, 0 ]
[]
[]
[ "cherrypy", "concurrency", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0002692189_cherrypy_concurrency_mod_wsgi_python_wsgi.txt
Q: Python - set source port number with sockets I'd like to send a specific UDP broadcast packet. Unfortunately, I need to send the UDP packets from a very specific port. Let's say I broadcast via UDP "BLABLAH". The server will only answer if my incoming packet source port was 1444; if not, then the packet is discard...
Python - set source port number with sockets
I'd like to send a specific UDP broadcast packet. Unfortunately, I need to send the UDP packets from a very specific port. Let's say I broadcast via UDP "BLABLAH". The server will only answer if my incoming packet source port was 1444; if not, then the packet is discarded. My broadcast socket setup looks like this: s =...
[ "You need to bind the socket to the specific port you want to send from. The bind method takes an address tuple, much like connect, though you can use the wildcard address. For example:\ns.bind(('0.0.0.0', 1444))\n\n", "Use s.bind(('', port)).\n" ]
[ 20, 10 ]
[]
[]
[ "port", "python", "sockets" ]
stackoverflow_0002694212_port_python_sockets.txt
Q: Best canvas for drawing in wxPython? I have to draw a graph of elements composing a topological model of a physical network. There would be nodes and arches, and the latter could be unidirectional or bidirectional. I would like to capture the clicking events for the nodes and the arches (to select the element and ...
Best canvas for drawing in wxPython?
I have to draw a graph of elements composing a topological model of a physical network. There would be nodes and arches, and the latter could be unidirectional or bidirectional. I would like to capture the clicking events for the nodes and the arches (to select the element and show its properties somewhere), and the dr...
[ "I've tried FloatCanvas, although there has been a lot of work to get everything to work. I've managed to get through mouse interaction things like connectivity, movement, automatic reconnection in case of movement, etc.\nFloatCanvas is also quite nice in terms of performance and visual results. Anti-aliasing (1) (...
[ 3, 2 ]
[]
[]
[ "canvas", "python", "wxpython" ]
stackoverflow_0002327918_canvas_python_wxpython.txt
Q: Maintenance Scripts with Pylons' objects? How do I import classes from a pylons project for maintenance scripts? A: Maybe this could be interesting to you: You'll need to know where your config ini file is, and load your app from the script. Your websetup.py script in your project should have code to do thi...
Maintenance Scripts with Pylons' objects?
How do I import classes from a pylons project for maintenance scripts?
[ "Maybe this could be interesting to you:\n\nYou'll need to know where your config ini file is, and load your app\n from the script. Your websetup.py script in your project should have\n code to do this (in 0.9.6 it does). If it doesn't, you'll need to run\n this first before importing your models (again, this wo...
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002694057_pylons_python.txt
Q: Anyone tried Solace? Solace - a multilingual support platform Has anyone tried Solace yet? "Solace is a fully open-sourced multilingual support and knowledge exchange platform written in Python." Just wanted to know your experience. Are there any other such platforms available in open source? A: This one seems...
Anyone tried Solace? Solace - a multilingual support platform
Has anyone tried Solace yet? "Solace is a fully open-sourced multilingual support and knowledge exchange platform written in Python." Just wanted to know your experience. Are there any other such platforms available in open source?
[ "This one seems better.\n", "I already set up my own server. Solace seems great. \n", "We just started using it at our company. You get what you pay for. Feels like a weekender project. Gets the job done, but lacks the polish of Stack Overflow. The documentation is weak. I find it ironic that Plurk doesn't run ...
[ 3, 2, 2 ]
[]
[]
[ "open_source", "platform", "python" ]
stackoverflow_0001369167_open_source_platform_python.txt
Q: Dynamic Operator Overloading on dict classes in Python I have a class that dynamically overloads basic arithmetic operators like so... import operator class IshyNum: def __init__(self, n): self.num=n self.buildArith() def arithmetic(self, other, o): return o(self.num, other) ...
Dynamic Operator Overloading on dict classes in Python
I have a class that dynamically overloads basic arithmetic operators like so... import operator class IshyNum: def __init__(self, n): self.num=n self.buildArith() def arithmetic(self, other, o): return o(self.num, other) def buildArith(self): map(lambda o: setattr(self, "_...
[ "The answer is found in the two types of class that Python has.\nThe first code-snippet you provided uses a legacy \"old-style\" class (you can tell because it doesn't subclass anything - there's nothing before the colon). Its semantics are peculiar. In particular, you can add a special method to an instance:\nclas...
[ 4, 3, 2, 2 ]
[]
[]
[ "dictionary", "operator_overloading", "python" ]
stackoverflow_0002694619_dictionary_operator_overloading_python.txt
Q: Open Source Library for Linguistic Inquiry and Word Count (LIWC) I am looking for an open source library for Linguistic Inquiry and Word Count (LIWC). Something in java or python will be good, though I am open to use other language. Does anyone know where I can get one ? Cheers, A: As ealdent points out, LIWC is...
Open Source Library for Linguistic Inquiry and Word Count (LIWC)
I am looking for an open source library for Linguistic Inquiry and Word Count (LIWC). Something in java or python will be good, though I am open to use other language. Does anyone know where I can get one ? Cheers,
[ "As ealdent points out, LIWC is both software and a data set. The data set is proprietary so there is no open-source version of that. For the software side, TAWC is a useful open source Perl version. From the comments:\n\nThis is a semi-complicated script adapted from the one used in my CHI\n papers. The task of ...
[ 2 ]
[ "You may find the Natural Language Toolkit (NLTK) for Python useful: http://www.nltk.org/\n" ]
[ -6 ]
[ "java", "nlp", "open_source", "python" ]
stackoverflow_0002511876_java_nlp_open_source_python.txt
Q: python list Index out of range error I am working on a python tetris game that my proffessor assigned for the final project of a concepts of programming class. I have got just about everything he wanted to work on it at this point but I am having a slight problem with one part of it. Whenever I start moving pieces...
python list Index out of range error
I am working on a python tetris game that my proffessor assigned for the final project of a concepts of programming class. I have got just about everything he wanted to work on it at this point but I am having a slight problem with one part of it. Whenever I start moving pieces left and right I keep getting "index out ...
[ "There a typo that would cause that problem in the first method.\nWhen you're checking each cell in the block shifted one right, you don't check if they are off the grid.\nif (col >= 0 and ...)\n\nprobably should be\nif (col < num_cols and ...)\n\nI also agree with CrazyDrummer, make a generic clear function\n\nSpo...
[ 2, 0 ]
[]
[]
[ "python", "tetris" ]
stackoverflow_0002695118_python_tetris.txt