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: Error while I use math.atan in Python! When I do 1/2 in Python why does it give me zero? Even if I coerce it with float(1/2) still I get zero. Why? And how can I get around it? When I give arctan(1/2) I get 0 as answer, but when I give arctan(.5) I get the correct answer! A: Because Python 2.x uses integer divis...
Error while I use math.atan in Python!
When I do 1/2 in Python why does it give me zero? Even if I coerce it with float(1/2) still I get zero. Why? And how can I get around it? When I give arctan(1/2) I get 0 as answer, but when I give arctan(.5) I get the correct answer!
[ "Because Python 2.x uses integer division for integers, so:\n1/2 == 0\n\nevaluates to True.\nYou want to do:\n1.0/2\n\nor do a\nfrom __future__ import division\n\n", "First, 1/2 is integer division. Until Python 3.0.\n>>> 1/2\n0\n>>> 1.0/2.0\n0.5\n>>> \n\nSecond, use math.atan2 for this kind of thing.\n>>> math...
[ 7, 6, 3, 2, 2, 1, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000993274_python.txt
Q: User Authentication And Text Parsing in Python Well I am working on a multistage program... I am having trouble getting the first stage done.. What I want to do is log on to Twitter.com, and then read all the direct messages on the user's page. Eventually I am going to be reading all the direct messages looking fo...
User Authentication And Text Parsing in Python
Well I am working on a multistage program... I am having trouble getting the first stage done.. What I want to do is log on to Twitter.com, and then read all the direct messages on the user's page. Eventually I am going to be reading all the direct messages looking for certain thing, but that shouldn't be hard. This is...
[ "Twitter does not use HTTP Basic Authentication to authenticate its users. It would be better, in this case, to use the Twitter API. \nA tutorial for using Python with the Twitter API is here: [http://www.webmonkey.com/tutorial/Get_Started_With_the_Twitter_API](http://www.webmonkey.com/tutorial/Get_Started_With_th...
[ 5, 3 ]
[]
[]
[ "authentication", "http", "python", "urllib2" ]
stackoverflow_0000993619_authentication_http_python_urllib2.txt
Q: How do I wait for an image to load after an ajax call using jquery? I have a Python script that is doing some manipulation on a JPEG image. I pass some parameters to this script and call it from my HTML page. The script returns an img src="newimage.jpg tag. I know how to wait for the reply from the script but I do...
How do I wait for an image to load after an ajax call using jquery?
I have a Python script that is doing some manipulation on a JPEG image. I pass some parameters to this script and call it from my HTML page. The script returns an img src="newimage.jpg tag. I know how to wait for the reply from the script but I don't know how to tell when the image is fully loaded (when it is, I want t...
[ "You can dynamically create a new image, bind something to its load event, and set the source:\n$('<img>').bind('load', function() {\n $(this).appendTo('body');\n}).attr('src', image_source);\n\n", "Image Loading\nWait for ajaxRequest\n", "The other answers have mentioned how to do so with jQuery, but regard...
[ 4, 2, 0 ]
[]
[]
[ "ajax", "jquery", "python" ]
stackoverflow_0000993712_ajax_jquery_python.txt
Q: How to tell a panel that it is being resized when using wx.aui I'm using wx.aui to build my user interface. I'm defining a class that inherits from wx.Panel and I need to change the content of that panel when its window pane is resized. I'm using code very similar to the code below (which is a modified version of ...
How to tell a panel that it is being resized when using wx.aui
I'm using wx.aui to build my user interface. I'm defining a class that inherits from wx.Panel and I need to change the content of that panel when its window pane is resized. I'm using code very similar to the code below (which is a modified version of sample code found here). My question is: is there a wx.Panel method ...
[ "According to the wx.Panel docs, wx.Panel.Layout is called \"automatically by the default EVT_SIZE handler when the window is resized.\"\nEDIT: However, the above doesn't work as I would expect, so try manually binding EVT_SIZE:\nclass ControlPanel(wx.Panel):\n def __init__(self, *args, **kwargs):\n wx.Pa...
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0000993923_python_wxpython.txt
Q: Python regular expression with [:numeric:] I am having some trouble with Python giving me a result I do not expect. Here is a sample code : number = re.search(" [0-9] ", "test test2 test_ 2 333") print number.groups() number = re.search(" [[:digit:]] ", "test test2 test_ 2 333") print number.groups() In the firs...
Python regular expression with [:numeric:]
I am having some trouble with Python giving me a result I do not expect. Here is a sample code : number = re.search(" [0-9] ", "test test2 test_ 2 333") print number.groups() number = re.search(" [[:digit:]] ", "test test2 test_ 2 333") print number.groups() In the first block I get an object returned but with nothin...
[ "The groups() method returns the capture groups. It does not return group 0, in case that's what you were expecting. Use parens to indicate capture groups. eg:\n>>> number = re.search(\" ([0-9]) \", \"test test2 test_ 2 333\")\n>>> print number.groups()\n('2',)\n\nFor your second example, Python's re module doesn't...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "bash", "python", "regex" ]
stackoverflow_0000994178_bash_python_regex.txt
Q: How Much Traffic Can Shared Web Hosting (for a Python Django site) support? Someone in this thread How Much Traffic Can Shared Web Hosting Take? stated that a $5/mo shared hosting account on Reliablesite.net can support 10,000 - 20,000 unique users/day and 100,000 - 200,000 pageviews/day. That seems awfully high ...
How Much Traffic Can Shared Web Hosting (for a Python Django site) support?
Someone in this thread How Much Traffic Can Shared Web Hosting Take? stated that a $5/mo shared hosting account on Reliablesite.net can support 10,000 - 20,000 unique users/day and 100,000 - 200,000 pageviews/day. That seems awfully high for a $5/mo account. And someone else told me it's far less than that. What's you...
[ "100,000 - 200,000 pageviews/day is on average 2 pageviews/s, at most you'll get 10-20 pageviews/s during busy hours. That's not a lot to handle, especially if you have caching.\nAnyways, I'd go for VPS. The problem with shared server is that you can never know the pattern of use the other ppl have.\n", "Webfacti...
[ 3, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "hosting", "python", "shared_hosting", "web_hosting" ]
stackoverflow_0000708799_hosting_python_shared_hosting_web_hosting.txt
Q: How can I explicitly disable compilation of _tkinter.c when compiling Python 2.4.3 on CentOS 5? I'm trying to explicitly disable the compilation of the _tkinter module when compiling Python 2.4.3. It's easy enough to do by modifying the makefile but I'd rather just append a configuration option to avoid supplying ...
How can I explicitly disable compilation of _tkinter.c when compiling Python 2.4.3 on CentOS 5?
I'm trying to explicitly disable the compilation of the _tkinter module when compiling Python 2.4.3. It's easy enough to do by modifying the makefile but I'd rather just append a configuration option to avoid supplying a patch. I do not understand the complex interplay between Modules/Setup*, setup.py and their contrib...
[ "Unfortunately I suspect you can't do it without editing some file or other -- it's not a configure option we wrote in as far as I recall (I hope I'm wrong and somebody else snuck it in while I wasn't looking but a quick look at the configure file seems to confirm they didnt'). Sorry -- we never thought that somebo...
[ 5 ]
[]
[]
[ "compilation", "python", "tkinter" ]
stackoverflow_0000994278_compilation_python_tkinter.txt
Q: If it is decided that our system needs an overhaul, what is the best way to go about it? We are mainting a web application that is built on Classic ASP using VBScript as the primary language. We are in agreement that our backend (framework if you will) is out dated and doesn't provide us with the proper tools to m...
If it is decided that our system needs an overhaul, what is the best way to go about it?
We are mainting a web application that is built on Classic ASP using VBScript as the primary language. We are in agreement that our backend (framework if you will) is out dated and doesn't provide us with the proper tools to move forward in a quick manner. We have pretty much embraced the current webMVC pattern that is...
[ "Don't throw away your code!\nIt's the single worst mistake you can make (on a large codebase). See Things You Should Never Do, Part 1.\nYou've invested a lot of effort into that old code and worked out many bugs. Throwing it away is a classic developer mistake (and one I've done many times). It makes you feel \...
[ 7, 3, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "asp_classic", "python", "vbscript" ]
stackoverflow_0000087522_asp_classic_python_vbscript.txt
Q: How to synthesize sounds? I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that. What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds? This far I've gotten to ...
How to synthesize sounds?
I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that. What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds? This far I've gotten to do this, it produces quite plai...
[ "Sound synthesis is a complex topic which requires many years of study to master. \nIt is also not an entirely solved problem, although relatively recent developments (such as physical modelling synthesis) have made progress in imitating real-world instruments.\nThere are a number of options open to you. If you are...
[ 16, 8, 1, 0 ]
[]
[]
[ "alsa", "numpy", "python" ]
stackoverflow_0000790960_alsa_numpy_python.txt
Q: trouble with pamie I'm having some strange trouble with pamie: http://pamie.sourceforge.net/ . I have written a script to do some port (25) forwarding based on a recepie that I found on the web, Here is the code that matters: # forwardc2s(source, destination): # forwards from client to server. # Tries to p...
trouble with pamie
I'm having some strange trouble with pamie: http://pamie.sourceforge.net/ . I have written a script to do some port (25) forwarding based on a recepie that I found on the web, Here is the code that matters: # forwardc2s(source, destination): # forwards from client to server. # Tries to post the message to ICE. ...
[ "The PAMIE object does not work within threads!!!\nI was originally starting forwardc2s as a thread. When I just call it as a function instead, everything works fine!\nPlease consider this question resolved... with great thanks to the rubber duck.\n" ]
[ 1 ]
[]
[]
[ "debugging", "pamie", "python" ]
stackoverflow_0000994627_debugging_pamie_python.txt
Q: Building a Python shared object binding with cmake, which depends upon external libraries We have a c file called dbookpy.c, which will provide a Python binding some C functions. Next we decided to build a proper .so with cmake, but it seems we are doing something wrong with regards to linking the external library...
Building a Python shared object binding with cmake, which depends upon external libraries
We have a c file called dbookpy.c, which will provide a Python binding some C functions. Next we decided to build a proper .so with cmake, but it seems we are doing something wrong with regards to linking the external library 'libdbook' in the binding: The CMakeLists.txt is as follows: PROJECT(dbookpy) FIND_PACKAGE(Py...
[ "You need to link dbookpy against dbook:\ntarget_link_libraries(dbookpy dbook)\n\nAdding that just after the line ADD_LIBRARY(dbookpy dbookpy) should do it.\nI see you are using IMPORTED - the help for IMPORTED_LINK_INTERFACE_LIBRARIES reads:\n Lists libraries whose interface is included when an IMPORTED library ta...
[ 4 ]
[]
[]
[ "c", "cmake", "linker", "python", "unix" ]
stackoverflow_0000992068_c_cmake_linker_python_unix.txt
Q: How to strip the 8th bit in a KOI8-R encoded character? How to strip the 8th bit in a KOI8-R encoded character so as to have translit for a Russian letter? In particular, how to make it in Python? A: Assuming s is a KOI8-R encoded string you could try this: >>> s = u'Код Обмена Информацией, 8 бит'.encode('koi8-r...
How to strip the 8th bit in a KOI8-R encoded character?
How to strip the 8th bit in a KOI8-R encoded character so as to have translit for a Russian letter? In particular, how to make it in Python?
[ "Assuming s is a KOI8-R encoded string you could try this:\n>>> s = u'Код Обмена Информацией, 8 бит'.encode('koi8-r')\n>>> s\n>>> '\\xeb\\xcf\\xc4 \\xef\\xc2\\xcd\\xc5\\xce\\xc1 \\xe9\\xce\\xc6\\xcf\\xd2\\xcd\\xc1\\xc3\\xc9\\xc5\\xca, 8 \\xc2\\xc9\\xd4'\n\n>>> print ''.join([chr(ord(c) & 0x7F) for c in s])\n>>> kOD...
[ 3, 1, 1 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0000994710_encoding_python.txt
Q: Redirecting console output to a Python string Possible Duplicate: How can I capture the stdout output of a child process? I'm running a cat-like program in bash from Python: import os os.system('cat foo.txt') How do I get the output of the shell command back in the Python script, something like: s = s...
Redirecting console output to a Python string
Possible Duplicate: How can I capture the stdout output of a child process? I'm running a cat-like program in bash from Python: import os os.system('cat foo.txt') How do I get the output of the shell command back in the Python script, something like: s = somefunction('cat foo.txt') ? UPD: Here is a relat...
[ "Use the subprocess module.\nfrom subprocess import Popen, PIPE\n\n(stdout, stderr) = Popen([\"cat\",\"foo.txt\"], stdout=PIPE).communicate()\nprint stdout\n\n" ]
[ 16 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0000994902_bash_python.txt
Q: Any good AJAX framework for Google App Engine apps? I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea? I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine? A: A...
Any good AJAX framework for Google App Engine apps?
I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea? I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?
[ "As Google Web Toolkit is a subset of Java it works best when you Java at the backend too. Since Google App Engine is currently Python only I think you'd have to do a lot of messing about to get your server and client to talk nicely to each other.\njQuery seems to be the most popular JavaScript library option in t...
[ 12, 7, 4, 4, 3, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "ajax", "google_app_engine", "python" ]
stackoverflow_0000053997_ajax_google_app_engine_python.txt
Q: ctypes in python, problem calling a function in a DLL Hey! as you might have noticed I have an annoying issue with ctypes. I'm trying to communicate with an instrument and to do so I have to use ctypes to communicate with the DLL driver. so far I've managed to export the DLL by doing this: >>> from ctypes import *...
ctypes in python, problem calling a function in a DLL
Hey! as you might have noticed I have an annoying issue with ctypes. I'm trying to communicate with an instrument and to do so I have to use ctypes to communicate with the DLL driver. so far I've managed to export the DLL by doing this: >>> from ctypes import * >>>maury = WinDLL( 'MLibTuners') >>> maury (WinDLL 'MlibTu...
[ "I figure it's the value you pass at the long max_range[] argument. The function expects a pointer to a long integer there (it asks for an array of long integers), but you're passing a long value of zero (result of the c_long() call), which is implicitly cast to a null pointer. I suspect the function then tries to ...
[ 3 ]
[]
[]
[ "ctypes", "dll", "pointers", "python" ]
stackoverflow_0000995332_ctypes_dll_pointers_python.txt
Q: What is the equivalent of object oriented constructs in python? How does python handle object oriented constructs such as abstract, virtual, pure virtual etc Examples and links would really be good. A: An abstract method is one that (in the base class) raises NotImplementedError. An abstract class, like in C++,...
What is the equivalent of object oriented constructs in python?
How does python handle object oriented constructs such as abstract, virtual, pure virtual etc Examples and links would really be good.
[ "An abstract method is one that (in the base class) raises NotImplementedError.\nAn abstract class, like in C++, is any class that has one or more abstract methods.\nAll methods in Python are virtual (i.e., all can be overridden by subclasses).\nA \"pure virtual\" method would presumably be the same thing as an abs...
[ 31, 7 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0000994476_oop_python.txt
Q: mod_python caching of variables I'm using mod_python to run Trac in Apache. I'm developing a plugin and am not sure how global variables are stored/cached. I am new to python and have googled the subject and found that mod_python caches python modules (I think). However, I would expect that cache to be reset when ...
mod_python caching of variables
I'm using mod_python to run Trac in Apache. I'm developing a plugin and am not sure how global variables are stored/cached. I am new to python and have googled the subject and found that mod_python caches python modules (I think). However, I would expect that cache to be reset when the web service is restarted, but it ...
[ "Obligatory:\nSwitch to wsgi using mod_wsgi. \nDon't use mod_python.\nThere is Help available for configuring mod_wsgi with trac.\n", "read the mod-python faq it says\n\nGlobal objects live inside mod_python\n for the life of the apache process,\n which in general is much longer than\n the life of a single req...
[ 4, 3 ]
[]
[]
[ "caching", "mod_python", "python", "trac" ]
stackoverflow_0000995416_caching_mod_python_python_trac.txt
Q: Which reactor should i use for qt4? I am using twisted and now i want to make some pretty ui using qt A: You want to use Glen Tarbox's qt4reactor. A: You need a qt4reactor, for example this one (but that's a sandbox and thus not good for production use -- tx @Glyph for clarifying this!). As @Glyph says, the pr...
Which reactor should i use for qt4?
I am using twisted and now i want to make some pretty ui using qt
[ "You want to use Glen Tarbox's qt4reactor.\n", "You need a qt4reactor, for example this one (but that's a sandbox and thus not good for production use -- tx @Glyph for clarifying this!).\nAs @Glyph says, the proper one to use is the one at launchpad.\n" ]
[ 5, 4 ]
[]
[]
[ "python", "qt4", "twisted" ]
stackoverflow_0000992169_python_qt4_twisted.txt
Q: IOError "no such file or folder" even though files are present I wrote a script in Python 2.6.2 that scans a directory for SVG's and resizes them if they are too large. I wrote this on my home machine (Vista, Python 2.6.2) and processed a few folders with no problems. Today, I tried this on my work computer (XP ...
IOError "no such file or folder" even though files are present
I wrote a script in Python 2.6.2 that scans a directory for SVG's and resizes them if they are too large. I wrote this on my home machine (Vista, Python 2.6.2) and processed a few folders with no problems. Today, I tried this on my work computer (XP SP2, Python 2.6.2) and I get IOErrors for every file, even though fi...
[ "It looks to me like you are missing a os.path.join(path, tfile) to get the full path to the file you want to open. Currently it should only work for files in the current directory.\n", "Perhaps it's a security issue? Perhaps you don't have the rights to create files in the folder\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000995985_python.txt
Q: How can this be written on a single line? I've seen some Python list comprehensions before, but can this be done in a single line of Python? errs = {} for f in form: if f.errors: errs[f.auto_id] = f.errors A: errs = dict((f.auto_id, f.errors) for f in form if f.errors) A: Python 3.0 has dict compre...
How can this be written on a single line?
I've seen some Python list comprehensions before, but can this be done in a single line of Python? errs = {} for f in form: if f.errors: errs[f.auto_id] = f.errors
[ "errs = dict((f.auto_id, f.errors) for f in form if f.errors)\n\n", "Python 3.0 has dict comprehensions as a shorter/more readable form of the anser provided by Steef:\nerrs = {f.auto_id: f.errors for f in form if f.errors}\n\n", "It probably could be, but as per the “Readability counts.” rule (PEP 20), I'd say...
[ 20, 9, 4, 0 ]
[]
[]
[ "dictionary", "django", "list_comprehension", "python" ]
stackoverflow_0000995234_dictionary_django_list_comprehension_python.txt
Q: Code reuse between django and appengine Model classes I created a custom django.auth User class which works with Google Appengine, but it involves a fair amount of copied code (practically every method). It isn't possible to create a subclass because appengine and django have different database models with their o...
Code reuse between django and appengine Model classes
I created a custom django.auth User class which works with Google Appengine, but it involves a fair amount of copied code (practically every method). It isn't possible to create a subclass because appengine and django have different database models with their own metaclass magic. So my question is this: is there an el...
[ "Im not sure I understand your question right. Why would you need to define\nanother \"User\" class if Django already provides the same functionality ? \nYou could also just import the \"User\" class and add a ForeignKey to each model\nrequiring a \"user\" attribute.\n", "You might want to take a look at what the...
[ 0, 0 ]
[]
[]
[ "django", "django_authentication", "google_app_engine", "python" ]
stackoverflow_0000991611_django_django_authentication_google_app_engine_python.txt
Q: JavaScript implementation that allows access to [[Call]] The ECMA standard defines a hidden, internal property [[Call]], which, if implemented, mean the object is callable / is a function. In Python, something similar takes place, except that you can override it yourself to create your own callable objects: >>> cl...
JavaScript implementation that allows access to [[Call]]
The ECMA standard defines a hidden, internal property [[Call]], which, if implemented, mean the object is callable / is a function. In Python, something similar takes place, except that you can override it yourself to create your own callable objects: >>> class B: ... def __call__(self, x,y): print x,y ... >>> inst...
[ "As far as I know it's not possible. It is supposed to be an internal property of an object and not exposed to the script itself. The only way I know is to define a function.\nHowever, since functions is first class citizens you can add properties to them:\nfunction myfunc(){\n var myself = arguments.callee;\n my...
[ 2, 1, 1, 0 ]
[]
[]
[ "function", "javascript", "python" ]
stackoverflow_0000383189_function_javascript_python.txt
Q: Adding SSL support to Python 2.6 I tried using the ssl module in Python 2.6 but I was told that it wasn't available. After installing OpenSSL, I recompiled 2.6 but the problem persists. Any suggestions? A: Did you install the OpenSSL development libraries? I had to install openssl-devel on CentOS, for example. ...
Adding SSL support to Python 2.6
I tried using the ssl module in Python 2.6 but I was told that it wasn't available. After installing OpenSSL, I recompiled 2.6 but the problem persists. Any suggestions?
[ "Did you install the OpenSSL development libraries? I had to install openssl-devel on CentOS, for example. On Ubuntu, sudo apt-get build-dep python2.5 did the trick (even for Python 2.6).\n" ]
[ 4 ]
[ "Use the binaries provided by python.org or by your OS distributor. It's a lot easier than building it yourself, and all the features are usually compiled in.\nIf you really need to build it yourself, you'll need to provide more information here about what build options you provided, what your environment is like,...
[ -1, -4 ]
[ "openssl", "python", "ssl" ]
stackoverflow_0000979551_openssl_python_ssl.txt
Q: py2exe windows service problem I have successfully converted my python project to a service. When using the usual options of install and start/stop, everything works correctly. However, I wish to compile the project using py2exe, which seems to work correctly until you install the EXE as a service and try and ru...
py2exe windows service problem
I have successfully converted my python project to a service. When using the usual options of install and start/stop, everything works correctly. However, I wish to compile the project using py2exe, which seems to work correctly until you install the EXE as a service and try and run it. You get the following error me...
[ "You setup.py file should contain\nsetup(service=[\"webserver.py\"])\n\nas shown in the \"old\" py2exe docs\n", "You will find an example in the py2exe package, look in site-packages\\py2exe\\samples\\advanced.\n" ]
[ 4, 1 ]
[]
[]
[ "py2exe", "python", "windows_services" ]
stackoverflow_0000996129_py2exe_python_windows_services.txt
Q: Pixmap transparency in PyGTK How can I create PyGTK pixmaps with one pixel value set to transparent? I know it has something to do with creating a pixmap of depth 1 and setting it as a mask, but all I find is that it either does nothing or totally erases my pixmap when drawn. At the moment, I make a pixmap with r ...
Pixmap transparency in PyGTK
How can I create PyGTK pixmaps with one pixel value set to transparent? I know it has something to do with creating a pixmap of depth 1 and setting it as a mask, but all I find is that it either does nothing or totally erases my pixmap when drawn. At the moment, I make a pixmap with r = self.get_allocation() p1 = gtk.g...
[ "I don't think you can do what you want with a Pixmap or Pixbuf, but here are two strategies for implementing scribbling on top of an existing Widget. The most obvious one is just to catch the draw event and draw straight onto the Widget's Drawable, with no retained image in the middle:\nfrom gtk import Window, Bu...
[ 2, 1 ]
[]
[]
[ "pygtk", "python", "transparency" ]
stackoverflow_0000973073_pygtk_python_transparency.txt
Q: Refactor this block cipher keying function I found a simple pure python blowfish implementation that meets my needs for a particular project. There's just one part of it that bothers me: def initialize(key): """ Use key to setup subkeys -- requires 521 encryptions to set p and s boxes. key is a hex nu...
Refactor this block cipher keying function
I found a simple pure python blowfish implementation that meets my needs for a particular project. There's just one part of it that bothers me: def initialize(key): """ Use key to setup subkeys -- requires 521 encryptions to set p and s boxes. key is a hex number corresponding to a string of 32 up to 4...
[ "Yes. Use int() with a base of 16.\n>>> int('ffffffff',16)\n4294967295L\n\nso:\nsubkey = int(hexkey[pos:pos+8], 16)\n\nshould do the same thing without needing eval.\n[Edit] In fact, there's generally no reason why you'd need to convert to a string representation at all, given an integer - you can simply extract o...
[ 5, 3, 1, 0 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0000996965_encryption_python.txt
Q: Using python regex to extract namespaces from C++ sources I am trying to extract the namespaces defined in C++ files. Basically, if my C++ file contains: namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 I want to be able t...
Using python regex to extract namespaces from C++ sources
I am trying to extract the namespaces defined in C++ files. Basically, if my C++ file contains: namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 I want to be able to retrieve: n1, n1::n2, n1::n3. Does someone have any suggestio...
[ "Searching for the namespace names is pretty easy with a regular expression. However, to determine the nesting level you will have to keep track of the curly bracket nesting level in the source file. This is a parsing problem, one that cannot be solved (sanely) with regular expressions. Also, you may have to deal w...
[ 6, 2, 1, 1, 0, 0 ]
[]
[]
[ "c++", "namespaces", "python", "regex" ]
stackoverflow_0000995165_c++_namespaces_python_regex.txt
Q: Hash method and UnicodeEncodeError In Python 2.5, I have the following hash function: def __hash__(self): return hash(str(self)) It works well for my needs, but now I started to get the following error message. Any idea of what is going on? return hash(str(self)) UnicodeEncodeError: 'ascii' codec can't encode c...
Hash method and UnicodeEncodeError
In Python 2.5, I have the following hash function: def __hash__(self): return hash(str(self)) It works well for my needs, but now I started to get the following error message. Any idea of what is going on? return hash(str(self)) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 16: ordin...
[ "The problem is that you are trying to hash a string that is not convertible to ASCII. The str method takes a unicode object and, by default, converts it to ASCII.\nTo fix this problem you need to either hash the unicode object directly, or else convert the string using the correct codec.\nFor example, you might d...
[ 2, 1 ]
[]
[]
[ "hash", "python", "string", "unicode" ]
stackoverflow_0000998302_hash_python_string_unicode.txt
Q: Why is my bubble sort in Python so slow? I have the following code thats use bubble sort to invert a list and has a worst time performance: for i in xrange(len(l)): for j in xrange(len(l)): if l[i]>l[j]: l[i], l[j] = l[j], l[i] In some cases (when len(l) = 100000) the code spend more then ...
Why is my bubble sort in Python so slow?
I have the following code thats use bubble sort to invert a list and has a worst time performance: for i in xrange(len(l)): for j in xrange(len(l)): if l[i]>l[j]: l[i], l[j] = l[j], l[i] In some cases (when len(l) = 100000) the code spend more then 2h to complete execute, I think its so strange...
[ "Bubble sort is a horrible algorithm to sort with. That is quite possibly the reason. If speed is necessary, I would try another algorithm like quick sort or merge sort. \n", "That's not quite a bubble sort... unless I've made a trivial error, this would be closer to a python bubble sort:\nswapped = True\nwhile ...
[ 25, 13, 6, 5, 4, 3, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "bubble_sort", "python" ]
stackoverflow_0000997322_bubble_sort_python.txt
Q: How can I get the order of an element attribute list using Python xml.sax? How can I get the order of an element attribute list? It's not totally necessary for the final processing, but it's nice to: in a filter, not to gratuitously reorder the attribute list while debugging, print the data in the same order as ...
How can I get the order of an element attribute list using Python xml.sax?
How can I get the order of an element attribute list? It's not totally necessary for the final processing, but it's nice to: in a filter, not to gratuitously reorder the attribute list while debugging, print the data in the same order as it appears in the input Here's my current attribute processor which does a dict...
[ "I don't think it can be done with SAX (at least as currently supported by Python). It could be done with expat, setting the ordered_attributes attribute of the parser object to True (the attributes are then two parallel lists, one of names and one of values, in the same order as in the XML source).\n", "Unfortun...
[ 1, 1 ]
[]
[]
[ "python", "sax", "xml" ]
stackoverflow_0000998514_python_sax_xml.txt
Q: Is  a valid character in XML? On this data: <row Id="37501" PostId="135577" Text="...uses though.&#x10;"/> I'm getting an error with the Python sax parser: xml.sax._exceptions.SAXParseException: comments.xml:29776:332: reference to invalid character number I trimmed the example; 332 points to "&#x10;". Is the p...
Is  a valid character in XML?
On this data: <row Id="37501" PostId="135577" Text="...uses though.&#x10;"/> I'm getting an error with the Python sax parser: xml.sax._exceptions.SAXParseException: comments.xml:29776:332: reference to invalid character number I trimmed the example; 332 points to "&#x10;". Is the parser correct in rejecting this char...
[ "As others have stated, you probably meant &#10;. The reason why &#x10; (0x10 = 10h = 16) is invalid is that it's explicitly excluded by the XML 1.0 standard: (http://www.w3.org/TR/xml/#NT-Char)\nChar ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]\n\n", "&#10; is the linefeed character...
[ 14, 6 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0000998950_python_xml.txt
Q: Python urllib2 timeout when using Tor as proxy? I am using Python's urllib2 with Tor as a proxy to access a website. When I open the site's main page it works fine but when I try to view the login page (not actually log-in but just view it) I get the following error... URLError: <urlopen error (10060, 'Operation ...
Python urllib2 timeout when using Tor as proxy?
I am using Python's urllib2 with Tor as a proxy to access a website. When I open the site's main page it works fine but when I try to view the login page (not actually log-in but just view it) I get the following error... URLError: <urlopen error (10060, 'Operation timed out')> To counteract this I did the following:...
[ "According to the Python Socket Documentation the default is no timeout so specifying a value of \"None\" is redundant. \nThere are a number of possible reasons that your connection is dropping. One could be that your user-agent is \"Python-urllib\" which may very well be blocked. To change your user agent:\nreques...
[ 3, 0, 0 ]
[]
[]
[ "python", "timeout", "tor", "urllib2" ]
stackoverflow_0000997969_python_timeout_tor_urllib2.txt
Q: System theme icons and PyQt4 I'm writing a basic program in python using the PyQt4 module. I'd like to be able to use my system theme's icons for things like the preference dialog's icon, but i have no idea how to do this. So my question is, how do you get the location of an icon, but make sure it changes with the...
System theme icons and PyQt4
I'm writing a basic program in python using the PyQt4 module. I'd like to be able to use my system theme's icons for things like the preference dialog's icon, but i have no idea how to do this. So my question is, how do you get the location of an icon, but make sure it changes with the system's icon theme? If it matter...
[ "Unfortunately, It appears that Qt does not support getting icons for a specific theme. There are ways to do this for both KDE and Gnome.\nThe KDE way is quite elegant, which makes sense considering that Qt is KDE's toolkit. Instead of using the PyQt4.QtGui class QIcon, you instead use the PyKDE4.kdeui class KIcon....
[ 7, 0, 0 ]
[]
[]
[ "icons", "pyqt4", "python" ]
stackoverflow_0000997904_icons_pyqt4_python.txt
Q: Looking for Windows Text Editor which supports GIT I am looking for a Text Editor on Windows which is integrated with GIT (check out, check in from the UI). Also, it would be nice is this editor could also support Python syntax highlighting. Is there anything like that available? Thanks! A: Here's a list of Edit...
Looking for Windows Text Editor which supports GIT
I am looking for a Text Editor on Windows which is integrated with GIT (check out, check in from the UI). Also, it would be nice is this editor could also support Python syntax highlighting. Is there anything like that available? Thanks!
[ "Here's a list of Editors and IDEs that integrate GIT, not sure if there's something that fits your need. The most fitting would be the Eclipse Plugin.\n", "Eclipse should be able to fit the bill. I know there's a decent python plugin, and I'm sure there's one for git by now.\n", "E Text Editor is the text ed...
[ 4, 1, 1, 0 ]
[]
[]
[ "editor", "git", "ide", "python" ]
stackoverflow_0000997485_editor_git_ide_python.txt
Q: KOI8-R: Having trouble translating a string This Python script gets translit for Russian letters: s = u'Код Обмена Информацией, 8 бит'.encode('koi8-r') print ''.join([chr(ord(c) & 0x7F) for c in s]) # kOD oBMENA iNFORMACIEJ, 8 BIT That works. But I want to modify it so as to get user input. Now I'm stuck at this:...
KOI8-R: Having trouble translating a string
This Python script gets translit for Russian letters: s = u'Код Обмена Информацией, 8 бит'.encode('koi8-r') print ''.join([chr(ord(c) & 0x7F) for c in s]) # kOD oBMENA iNFORMACIEJ, 8 BIT That works. But I want to modify it so as to get user input. Now I'm stuck at this: s = raw_input("Enter a string you want to transl...
[ "s = unicode(s) expects ascii encoding by default. You need to supply it an encoding your input is in, e.g. s = unicode(s, 'utf-8').\n", "try unicode(s, encoding) where encoding is whatever your terminal is in.\n", "Looking at the error messages that you are seeing, it seems to me that your terminal encoding is...
[ 2, 1, 0 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0000995531_encoding_python.txt
Q: xml.dom.minidom Document() in Python/django outputting memory location I'm learning Python and django at the same time. I'm trying to create an xml document to return some XML from a view. I'm using the django development server at the moment and I keep getting this information spitting out in my views instead o...
xml.dom.minidom Document() in Python/django outputting memory location
I'm learning Python and django at the same time. I'm trying to create an xml document to return some XML from a view. I'm using the django development server at the moment and I keep getting this information spitting out in my views instead of the document I tried to create. Here's my code from django.http import...
[ "You'll need to call xmlFailed.toxml() or the like in order to get XML out of your object -- looks like that's not what you're doing (in the code you didn't show us).\n" ]
[ 1 ]
[]
[]
[ "django", "minidom", "python", "xml" ]
stackoverflow_0000999462_django_minidom_python_xml.txt
Q: Problems with SQLAlchemy and VirtualEnv I'm trying to use SQLAlchemy under a virtualenv on OS X 10.5, but cannot seem to get it to load whatsoever. Here's what I've done mkvirtualenv --no-site-packages test easy_install sqlalchemy I try to import sqlalchemy from the interpreter and everything works fine, but if i...
Problems with SQLAlchemy and VirtualEnv
I'm trying to use SQLAlchemy under a virtualenv on OS X 10.5, but cannot seem to get it to load whatsoever. Here's what I've done mkvirtualenv --no-site-packages test easy_install sqlalchemy I try to import sqlalchemy from the interpreter and everything works fine, but if i try to import sqlalchemy from a python scrip...
[ "I fixed my own problem... I had another script named sqlalchemy.py in the same folder i was working in that was mucking everything up.\n" ]
[ 8 ]
[]
[]
[ "python", "sqlalchemy", "virtualenv" ]
stackoverflow_0000999677_python_sqlalchemy_virtualenv.txt
Q: Writing tests for Django's admin actions I'm using Django 1.1 beta and hoping to use admin actions. I have to write unit tests for those, but I don't get it how to write tests for them. For normal view handler functions, I can use Django's TestClient to simulate http request/response, but how should it be done wit...
Writing tests for Django's admin actions
I'm using Django 1.1 beta and hoping to use admin actions. I have to write unit tests for those, but I don't get it how to write tests for them. For normal view handler functions, I can use Django's TestClient to simulate http request/response, but how should it be done with admin actions?
[ "Testing django admin is currently pain, because of admin's tight coupling. AFAIK, You can still use request/response, but I gave up and use only functional tests (Selenium, but you can use Windmill as well) and unit testing only our admin extensions.\nThere is a GSoC project for covering admin with Windmill tests,...
[ 4 ]
[]
[]
[ "django", "django_admin", "python", "testing", "unit_testing" ]
stackoverflow_0000999452_django_django_admin_python_testing_unit_testing.txt
Q: Question on importing a GPL'ed Python library in commercial code We're evaluating a couple of Python libraries for Graph manipulation. We tried 'networkx' (http://networkx.lanl.gov/) and 'igraph' (http://igraph.sourceforge.net/). While both are excellent modules, igraph is faster due to its nature - it's a Python ...
Question on importing a GPL'ed Python library in commercial code
We're evaluating a couple of Python libraries for Graph manipulation. We tried 'networkx' (http://networkx.lanl.gov/) and 'igraph' (http://igraph.sourceforge.net/). While both are excellent modules, igraph is faster due to its nature - it's a Python wrapper over libigraph - a blistering fast graph C library (uses LAPAC...
[ "IANAL, etc etc, but:\nThe Free Software Foundation has consistently claimed that software linked to a library covered by GPL is a derived work, and thus needs to be covered by GPL itself (indeed, that's the main difference of the LGPL license). I don't know how the situation stands in court precedents in various j...
[ 32, 13, 3, 2 ]
[ "As far as I know the GPL license is free for open sourced projects.\nMost libraries provide the option to buy a commercial license for commercial use.\nContact the library's author.\nThis is taken from Wt's website:\n\nWt may be used using either the GPL or a Commercial License.\nIf you wish to use the library usi...
[ -1, -1 ]
[ "gpl", "licensing", "python" ]
stackoverflow_0000999468_gpl_licensing_python.txt
Q: list() doesn't work in Google App Engine? I am trying to use set function in App Engine, to prepare a list with unique elements. I hit a snag when i wrote a Python code which works fine in the Python Shell but not in App Engine + Django This is what i intend to do(ran this script in IDLE): import re value=' r.du...
list() doesn't work in Google App Engine?
I am trying to use set function in App Engine, to prepare a list with unique elements. I hit a snag when i wrote a Python code which works fine in the Python Shell but not in App Engine + Django This is what i intend to do(ran this script in IDLE): import re value=' r.dushaynth@gmail.com, dash@ben,, , abc@ac.com.edu...
[ "It seems like you implemented your own list() function. Its return statements should be at line 208 of your file (views.py). You should rename your list() function to something else (even list_()).\nEDIT: Also you can change you regexp, like this:\nimport re\nvalue=' r.dushaynth@gmail.com, dash@ben,, , abc@ac.c...
[ 8 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0001000448_django_google_app_engine_python.txt
Q: How do I load entry-points for a defined set of eggs with Python setuptools? I would like to use the entry point functionality in setuptools. There are a number of occasions where I would like to tightly control the list of eggs that are run, and thence the extensions that contribute to a set of entry points: egg...
How do I load entry-points for a defined set of eggs with Python setuptools?
I would like to use the entry point functionality in setuptools. There are a number of occasions where I would like to tightly control the list of eggs that are run, and thence the extensions that contribute to a set of entry points: egg integration testing, where I want to run multiple test suites on different combin...
[ "We're solving something similar, ability to use setup.py develop if You're mere user without access to global site-packages. So far, we solved it with virtualenv.\nI'd say it will help for your case too: have minimal system-wide install (or explicitly exclude it), create virtual environment with eggs you want and ...
[ 0 ]
[]
[]
[ "distutils", "egg", "python", "setuptools" ]
stackoverflow_0000769766_distutils_egg_python_setuptools.txt
Q: How to get the "python setup.py" submit information on freshmeat? This can submit information about your software on pypi: python setup.py register But there is not a similar command for submitting information to freshmeat. How could I write a distutils.Command that would let me do the following? python setup.py ...
How to get the "python setup.py" submit information on freshmeat?
This can submit information about your software on pypi: python setup.py register But there is not a similar command for submitting information to freshmeat. How could I write a distutils.Command that would let me do the following? python setup.py freshmeat-submit
[ "It should be fairly easy; I'd say freshmeat API will be straightforward.\nFor python site, for setup() function in setup.py, give this argument:\nentry_points = {\n 'distutils.commands' : [\n 'freshmeat-submit = freshsubmitter.submit:SubmitToFreshMeat',\n ],\n},\n\nwhere freshsubmitter is your new pak...
[ 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0000422717_python_setuptools.txt
Q: Generic Views from the object_id or the parent object I have a model that represents a position at a company: class Position(models.Model): preferred_q = ForeignKey("Qualifications", blank=True, null=True, related_name="pref") base_q = ForeignKey("Qualifications", blank=True, null=True, related_name="base"...
Generic Views from the object_id or the parent object
I have a model that represents a position at a company: class Position(models.Model): preferred_q = ForeignKey("Qualifications", blank=True, null=True, related_name="pref") base_q = ForeignKey("Qualifications", blank=True, null=True, related_name="base") #[...] It has two "inner objects", which represent ...
[ "If you want the edit form to be for one of the related instances of InnerModel, but you want to pass in the PK for ParentModel in the URL (as best I can tell this is what you're asking, though it isn't very clear), you will have to use a wrapper view. Otherwise how is Django's generic view supposed to magically k...
[ 0 ]
[ "As explained in the documentation for the update_object generic view, if you have ParentModel as value for the 'model' key in the options_dict in your URL definition, you should be all set. \n" ]
[ -1 ]
[ "django", "django_generic_views", "python" ]
stackoverflow_0000999291_django_django_generic_views_python.txt
Q: How to flatten a fish eye picture (with python)? I've found programs to turn fish eye pictures into flat ones. I'd like to learn the process behind the scenes. Can someone share their knowledge about the technique? A: My understanding is that fish eye effect is basically a projection on a semi-sphere, right? To ...
How to flatten a fish eye picture (with python)?
I've found programs to turn fish eye pictures into flat ones. I'd like to learn the process behind the scenes. Can someone share their knowledge about the technique?
[ "My understanding is that fish eye effect is basically a projection on a semi-sphere, right? To reverse that you need to use equations for projecting a semi-sphere into a plane. A quick search revealed those Fisheye Projection equations, reversing them should be easy. I hope that puts you in the right direction.\n"...
[ 1 ]
[]
[]
[ "fisheye", "image_processing", "photography", "python" ]
stackoverflow_0001000806_fisheye_image_processing_photography_python.txt
Q: Python C API: how to get string representation of exception? If I do (e.g.) open("/snafu/fnord") in Python (and the file does not exist), I get a traceback and the message IOError: [Errno 2] No such file or directory: '/snafu/fnord' I would like to get the above string with Python's C API (i.e., a Python inter...
Python C API: how to get string representation of exception?
If I do (e.g.) open("/snafu/fnord") in Python (and the file does not exist), I get a traceback and the message IOError: [Errno 2] No such file or directory: '/snafu/fnord' I would like to get the above string with Python's C API (i.e., a Python interpreter embedded in a C program). I need it as a string, not output...
[ "I think that Python exceptions are printed by running \"str()\" on the exception instance, which will return the formatted string you're interested in. You can get this from C by calling the PyObject_Str() method described here:\nhttps://docs.python.org/c-api/object.html\nGood luck!\nUpdate: I'm a bit confused why...
[ 8 ]
[]
[]
[ "exception", "python", "python_c_api" ]
stackoverflow_0001001216_exception_python_python_c_api.txt
Q: Why are there extra blank lines in my python program output? I'm not particularly experienced with python, so may be doing something silly below. I have the following program: import os import re import linecache LINENUMBER = 2 angles_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/00...
Why are there extra blank lines in my python program output?
I'm not particularly experienced with python, so may be doing something silly below. I have the following program: import os import re import linecache LINENUMBER = 2 angles_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/angles.txt") lines = angles_file.readlines() for line in lines...
[ "For a GENERAL solution, remove the trailing newline from your INPUT:\nsplitted_line = line.rstrip(\"\\n\").split(\";\")\n\nRemoving the extraneous newline from your output \"works\" in this case but it's a kludge.\nALSO: (1) it's not a good idea to open your output file in the middle of a loop; do it once, otherwi...
[ 16, 8, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001001601_python.txt
Q: How To Reversibly Store Password With Python On Linux? First, my question is not about password hashing, but password encryption. I'm building a desktop application that needs to authentificate the user to a third party service. To speed up the login process, I want to give the user the option to save his credenti...
How To Reversibly Store Password With Python On Linux?
First, my question is not about password hashing, but password encryption. I'm building a desktop application that needs to authentificate the user to a third party service. To speed up the login process, I want to give the user the option to save his credentials. Since I need the password to authentificate him to the ...
[ "Try using PAM. You can make a module that automatically un-encrypts the key when the user logs in. This is internally how GNOME-Keyring works (if possible). You can even write PAM modules in Python with pam_python.\n", "Encrypting the passwords doesn't really buy you a whole lot more protection than storing in p...
[ 5, 5, 0 ]
[]
[]
[ "encryption", "linux", "passwords", "python" ]
stackoverflow_0001001744_encryption_linux_passwords_python.txt
Q: Python + MySQLdb executemany I'm using Python and its MySQLdb module to import some measurement data into a Mysql database. The amount of data that we have is quite high (currently about ~250 MB of csv files and plenty of more to come). Currently I use cursor.execute(...) to import some metadata. This isn't proble...
Python + MySQLdb executemany
I'm using Python and its MySQLdb module to import some measurement data into a Mysql database. The amount of data that we have is quite high (currently about ~250 MB of csv files and plenty of more to come). Currently I use cursor.execute(...) to import some metadata. This isn't problematic as there are only a few entr...
[ "In retrospective this was a really stupid but hard to spot mistake. Values is a keyword in sql so the table name values needs quotes around it.\ndef __insert_values(self, values):\n cursor = self.connection.cursor()\n cursor.executemany(\"\"\"\n insert into `values` (ensg, value, sampleid)\n va...
[ 8, 3 ]
[]
[]
[ "executemany", "mysql", "python" ]
stackoverflow_0000974702_executemany_mysql_python.txt
Q: Showing progress of python's XML parser when loading a huge file Im using Python's built in XML parser to load a 1.5 gig XML file and it takes all day. from xml.dom import minidom xmldoc = minidom.parse('events.xml') I need to know how to get inside that and measure its progress so I can show a progress bar. any...
Showing progress of python's XML parser when loading a huge file
Im using Python's built in XML parser to load a 1.5 gig XML file and it takes all day. from xml.dom import minidom xmldoc = minidom.parse('events.xml') I need to know how to get inside that and measure its progress so I can show a progress bar. any ideas? minidom has another method called parseString() that returns a...
[ "Did you consider to use other means of parsing XML? Building a tree of such big XML files will always be slow and memory intensive. If you don't need the whole tree in memory, stream based parsing will be much faster. It can be a little daunting if you're used to tree based XML manipulation, but it will pay of in ...
[ 5, 5, 3, 2 ]
[]
[]
[ "pyqt", "python", "xml" ]
stackoverflow_0001001871_pyqt_python_xml.txt
Q: PYTHONPATH ignored Environment: debian 4.0 Python 2.4 My 'project' is installed in: /usr/lib/python2.4/site-packages/project. But I want to use my working copy instead of the installed one which is located in: /home/me/dev/project/src So what I do is: export PYTHONPATH=/home/me/dev/project/src ipython import...
PYTHONPATH ignored
Environment: debian 4.0 Python 2.4 My 'project' is installed in: /usr/lib/python2.4/site-packages/project. But I want to use my working copy instead of the installed one which is located in: /home/me/dev/project/src So what I do is: export PYTHONPATH=/home/me/dev/project/src ipython import foo # which is in src f...
[ "According to python documentation, this is expected behavior: https://docs.python.org/2.4/lib/module-sys.html:\n\nNotice that the script directory is\n inserted before the entries inserted\n as a result of PYTHONPATH.\n\nUnder python-2.6 it is different: http://docs.python.org/tutorial/modules.html#the-module-se...
[ 6, 5, 4, 1, 1, 0, 0 ]
[]
[]
[ "debian", "path", "python" ]
stackoverflow_0001001851_debian_path_python.txt
Q: How to put variables on the stack/context in Python In essence, I want to put a variable on the stack, that will be reachable by all calls below that part on the stack until the block exits. In Java I would solve this using a static thread local with support methods, that then could be accessed from methods. Typic...
How to put variables on the stack/context in Python
In essence, I want to put a variable on the stack, that will be reachable by all calls below that part on the stack until the block exits. In Java I would solve this using a static thread local with support methods, that then could be accessed from methods. Typical example: you get a request, and open a database connec...
[ "I went ahead and made something that might just do what you want. It can be used as both a decorator and a context manager:\nfrom __future__ import with_statement\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\n\nclass cached(object):\n \"\"\"Decorator/context manager for caching ...
[ 6, 2, 0, 0 ]
[]
[]
[ "contextmanager", "python", "thread_local" ]
stackoverflow_0001001784_contextmanager_python_thread_local.txt
Q: Python Video Framework I'm looking for a Python framework that will enable me to play video as well as draw on that video (for labeling purposes). I've tried Pyglet, but this doesn't seem to work particularly well - when drawing on an existing video, there is flicker (even with double buffering and all of that g...
Python Video Framework
I'm looking for a Python framework that will enable me to play video as well as draw on that video (for labeling purposes). I've tried Pyglet, but this doesn't seem to work particularly well - when drawing on an existing video, there is flicker (even with double buffering and all of that good stuff), and there doesn'...
[ "Qt (PyQt) has Phonon, which might help out. PyQt is available as GPL or payware. (Qt has LGPL too, but the PyQt wrappers don't)\n", "Try the Python bindings for GStreamer.\n", "Try a Python wrapper for OpenCV such as ctypes-opencv. The C API reference is here, and the wrapper is very close (see docstrings for ...
[ 2, 2, 2 ]
[]
[]
[ "pyglet", "python", "video" ]
stackoverflow_0001003376_pyglet_python_video.txt
Q: Is there a python ftp library for uploading whole directories (including subdirectories)? So I know about ftplib, but that's a bit too low for me as it still requires me to handle uploading files one at a time as well as determining if there are subdirectories, creating the equivalent subdirectories on the server,...
Is there a python ftp library for uploading whole directories (including subdirectories)?
So I know about ftplib, but that's a bit too low for me as it still requires me to handle uploading files one at a time as well as determining if there are subdirectories, creating the equivalent subdirectories on the server, cd'ing into those subdirectories and then finally uploading the correct files into those subdi...
[ "\nThe ftputil Python library is a high-level interface to the ftplib module.\n\nLooks like this could help. ftputil website\n", "If wget is installed on your system, you could have your script call it to do the ftp'ing for you. It supports recursive transfers, site mirroring, and many other features.\n" ]
[ 11, 3 ]
[]
[]
[ "ftp", "python" ]
stackoverflow_0001003968_ftp_python.txt
Q: Getting the name of document that used to launch the application bundle on OS X When writing an OS X Bundle application (.app), how can I get the name of the document that caused the application to be launched? Say I've associated .abcd with MyApp, when I click on foo.abcd MyApp is launched. How can I get the foo....
Getting the name of document that used to launch the application bundle on OS X
When writing an OS X Bundle application (.app), how can I get the name of the document that caused the application to be launched? Say I've associated .abcd with MyApp, when I click on foo.abcd MyApp is launched. How can I get the foo.abcd from inside MyApp? (Command line arguments only contain the process id).
[ "In general, these are handled through Apple Events. Specifically, your application will receive an open document event. How you would handle it depends on what type of application you are writing.\nIf you're writing a document-based app, this is easy: the document controller receives an openDocumentWithContentsOfU...
[ 1, 1 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0000849172_macos_python.txt
Q: Know any creative ways to interface Python with Tcl? Here's the situation. The company I work for has quite a bit of existing Tcl code, but some of them want to start using python. It would nice to be able to reuse some of the existing Tcl code, because that's money already spent. Besides, some of the test equi...
Know any creative ways to interface Python with Tcl?
Here's the situation. The company I work for has quite a bit of existing Tcl code, but some of them want to start using python. It would nice to be able to reuse some of the existing Tcl code, because that's money already spent. Besides, some of the test equipment only has Tcl API's. So, one of the ways I thought of...
[ "I hope you're ready for this. Standard Python\nimport Tkinter\ntclsh = Tkinter.Tcl()\ntclsh.eval(\"\"\"\n proc unknown args {puts \"Hello World!\"}\n }\"!dlroW olleH\" stup{ sgra nwonknu corp\n\"\"\")\n\nEdit in Re to comment: Python's tcl interpreter is not aware of other installed tcl components. You can...
[ 19, 3, 0 ]
[]
[]
[ "python", "tcl" ]
stackoverflow_0001004434_python_tcl.txt
Q: Python class to merge sorted files, how can this be improved? Background: I'm cleaning large (cannot be held in memory) tab-delimited files. As I clean the input file, I build up a list in memory; when it gets to 1,000,000 entries (about 1GB in memory) I sort it (using the default key below) and write the list to...
Python class to merge sorted files, how can this be improved?
Background: I'm cleaning large (cannot be held in memory) tab-delimited files. As I clean the input file, I build up a list in memory; when it gets to 1,000,000 entries (about 1GB in memory) I sort it (using the default key below) and write the list to a file. This class is for putting the sorted files back together. ...
[ "Note that in python2.6, heapq has a new merge function which will do this for you.\nTo handle the custom key function, you can just wrap the file iterator with something that decorates it so that it compares based on the key, and strip it out afterwards:\ndef decorated_file(f, key):\n for line in f: \n y...
[ 16, 2 ]
[]
[]
[ "large_file_support", "merge", "mergesort", "python" ]
stackoverflow_0001001569_large_file_support_merge_mergesort_python.txt
Q: Is there a Perl or Python library for ID3 metadata? Basically, I've got a bunch of music files yoinked from my brother's iPod that retain their metadata but have those absolutely horrendous four character names the iPod seems to like storing them under. I figured I'd write a nice, quick script to just rename them ...
Is there a Perl or Python library for ID3 metadata?
Basically, I've got a bunch of music files yoinked from my brother's iPod that retain their metadata but have those absolutely horrendous four character names the iPod seems to like storing them under. I figured I'd write a nice, quick script to just rename them as I wished, but I'm curious about any good libraries for...
[ "CPAN Search turns up several Perl modules when you search for ID3. The answer to almost any Perl question that starts with \"Is there a library...\" is to check CPAN.\nI tend to like MP3::Tag, but old people like me tend to find something suitable and ignore all advances in technology until we are forced to chang...
[ 9, 5, 4, 2, 2, 1, 0 ]
[]
[]
[ "id3", "perl", "python" ]
stackoverflow_0001000132_id3_perl_python.txt
Q: Instance methods called in a separate thread than the instantiation thread I'm trying to wrap my head around what is happening in this recipe, because I'm planning on implementing a wx/twisted app similar to this (ie. wx and twisted running in separate threads). I understand that both twisted and wx event-loops n...
Instance methods called in a separate thread than the instantiation thread
I'm trying to wrap my head around what is happening in this recipe, because I'm planning on implementing a wx/twisted app similar to this (ie. wx and twisted running in separate threads). I understand that both twisted and wx event-loops need to be accessed in a thread-safe manner (ie. reactor.callFromThread, wx.PostE...
[ "The sole act of passing instance methods between threads is safe as long as you properly synchronize eventual destruction of those instances (threads share memory so it really doesn't matter which one did the allocation/initialization of a bit of it).\nThe overall thread safety depends on what those methods actual...
[ 0, 0 ]
[]
[]
[ "multithreading", "python", "twisted", "wxpython" ]
stackoverflow_0000962323_multithreading_python_twisted_wxpython.txt
Q: pygtk loading a flow of image in only one pixbuf I'm trying to embed a chartdrawer library that can only give me a bmp image in a buffer. I'm loading this image and have to explicitly call delete on the newly created pixbuf and then call the garbage collector. The drawing method is called each 50ms calling the gar...
pygtk loading a flow of image in only one pixbuf
I'm trying to embed a chartdrawer library that can only give me a bmp image in a buffer. I'm loading this image and have to explicitly call delete on the newly created pixbuf and then call the garbage collector. The drawing method is called each 50ms calling the garbage collector is realy CPU consuming. Is there a way ...
[ "You don't need to call the garbage collector. Python is automatically garbage collected. At the end of your method, pixbuf falls out of scope (you also don't need \"del pixbuf\") and will be automatically garbage collected. So for starters, delete the last two lines of your method.\nYou might also want to just ...
[ 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0001002841_pygtk_python.txt
Q: How does one debug a fastcgi application? How does one debug a FastCGI application? I've got an app that's dying but I can't figure out why, even though it's likely throwing a stack trace on stderr. Running it from the commandline results in an error saying: RuntimeError: No FastCGI Environment: 88 - Socket ope...
How does one debug a fastcgi application?
How does one debug a FastCGI application? I've got an app that's dying but I can't figure out why, even though it's likely throwing a stack trace on stderr. Running it from the commandline results in an error saying: RuntimeError: No FastCGI Environment: 88 - Socket operation on non-socket How do I set up a 'FastCG...
[ "It does matter that the application is Python; your question is really \"how do I debug Python when I'm not starting the script myself\".\nYou want to use a remote debugger. The excellent WinPDB has some documentation on embedded debugging which you should be able to use to attach to your FastCGI application and ...
[ 2 ]
[]
[]
[ "debugging", "fastcgi", "python", "web_applications" ]
stackoverflow_0000913817_debugging_fastcgi_python_web_applications.txt
Q: Threading TCP Server as proxy between connected user and unix socket I'm writing web application where I need to push data from server to the connected clients. This data can be send from any other script from web application. For example one user make some changes on the server and other users should be notified ...
Threading TCP Server as proxy between connected user and unix socket
I'm writing web application where I need to push data from server to the connected clients. This data can be send from any other script from web application. For example one user make some changes on the server and other users should be notified about that. So my idea is to use unix socket (path to socket based on use...
[ "I think You should not use unix sockets. If Your app will (someday) become popular or mission-critical, You won't be able to just add another server to add scalability or to make it redundant and fail-safe.\nIf, on the other hand, You will put the data into f.e. memcached (and user's \"dataset number\" as the sepa...
[ 1, 0, 0 ]
[]
[]
[ "multithreading", "python", "sockets", "tcp" ]
stackoverflow_0000833962_multithreading_python_sockets_tcp.txt
Q: Authentication Required - Problems Establishing AIM OSCAR Session using Python I'm writing a simple python script that will interface with the AIM servers using the OSCAR protocol. It includes a somewhat complex handshake protocol. You essentially have to send a GET request to a specific URL, receive XML or JSON e...
Authentication Required - Problems Establishing AIM OSCAR Session using Python
I'm writing a simple python script that will interface with the AIM servers using the OSCAR protocol. It includes a somewhat complex handshake protocol. You essentially have to send a GET request to a specific URL, receive XML or JSON encoded reply, extract a special session token and secret key, then generate a respon...
[ "Try using Twisted's OSCAR support instead of writing your own? It hasn't seen a lot of maintenance, but I believe it works.\n", "URI Encode your digest?\n-moxford\n" ]
[ 1, 0 ]
[]
[]
[ "aim", "json", "python" ]
stackoverflow_0000599218_aim_json_python.txt
Q: How to distinguish field that requires null=True when blank=True is set in Django models? Some model fields such as DateTimeField require null=True option when blank=True option is set. I'd like to know which fields require that (maybe dependent on backend DBMS), and there is any way to do this automatically. A: ...
How to distinguish field that requires null=True when blank=True is set in Django models?
Some model fields such as DateTimeField require null=True option when blank=True option is set. I'd like to know which fields require that (maybe dependent on backend DBMS), and there is any way to do this automatically.
[ "null=True is used to tell that in DB value can be NULL\nblank=True is only for django , so django doesn't raise error if field is blank e.g. in admin interface\nso blank=True has nothing to do with DB\nNULL requirement will vary from DB to DB, and it is upto you to decide if you want some column NULL or not\n", ...
[ 2, 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001005187_django_django_models_python.txt
Q: What are some successful methods for deploying a Django application on the desktop? I have a Django application that I would like to deploy to the desktop. I have read a little on this and see that one way is to use freeze. I have used this with varying success in the past for Python applications, but am not convi...
What are some successful methods for deploying a Django application on the desktop?
I have a Django application that I would like to deploy to the desktop. I have read a little on this and see that one way is to use freeze. I have used this with varying success in the past for Python applications, but am not convinced it is the best approach for a Django application. My questions are: what are some s...
[ "I did this a couple years ago for a Django app running as a local daemon. It was launched by Twisted and wrapped by py2app for Mac and py2exe for Windows. There was both a browser as well as an Air front-end hitting it. It worked pretty well for the most part but I didn't get to deploy it out in the wild because t...
[ 6, 4 ]
[]
[]
[ "django", "python", "web_applications" ]
stackoverflow_0000789673_django_python_web_applications.txt
Q: ctypes in Python 2.6 help I can't seem to get this code to work, I was under the impression I was doing this correctly. from ctypes import * kernel32 = windll.kernel32 string1 = "test" string2 = "test2" kernel32.MessageBox(None, string1, string2, ...
ctypes in Python 2.6 help
I can't seem to get this code to work, I was under the impression I was doing this correctly. from ctypes import * kernel32 = windll.kernel32 string1 = "test" string2 = "test2" kernel32.MessageBox(None, string1, string2, MB_OK) ** I tried to cha...
[ "MessageBox is defined in user32 not kernel32, you also haven't defined MB_OK\nso use this instead\nwindll.user32.MessageBoxA(None, string1, string2, 1)\n\nAlso I recommend using python win32 API isntead of it ,as it has all constant and named functions\nedit: I mean use this\nfrom ctypes import *\n\nkernel32 = win...
[ 4, 0, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0001005117_ctypes_python.txt
Q: Can I trace all the functions/methods executing in a python script? Is there a way to programmatically trace the execution of all python functions/methods? I would like to see what arguments each of them was called with. I really mean all, I'm not interested in a trace decorator. In Ruby, I could alias the method...
Can I trace all the functions/methods executing in a python script?
Is there a way to programmatically trace the execution of all python functions/methods? I would like to see what arguments each of them was called with. I really mean all, I'm not interested in a trace decorator. In Ruby, I could alias the method I wanted and add the extra behaviour there.
[ "Have a look at the trace module.\nYou can also use it via the command line:\npython -m trace --help\n\n" ]
[ 12 ]
[]
[]
[ "debugging", "python", "trace" ]
stackoverflow_0001005665_debugging_python_trace.txt
Q: App Engine Datastore IN Operator - how to use? Reading: http://code.google.com/appengine/docs/python/datastore/gqlreference.html I want to use: := IN but am unsure how to make it work. Let's assume the following class User(db.Model): name = db.StringProperty() class UniqueListOfSavedItems(db.Model): s...
App Engine Datastore IN Operator - how to use?
Reading: http://code.google.com/appengine/docs/python/datastore/gqlreference.html I want to use: := IN but am unsure how to make it work. Let's assume the following class User(db.Model): name = db.StringProperty() class UniqueListOfSavedItems(db.Model): str = db.StringPropery() datesaved = db.DateTimeP...
[ "Since you have a list of keys, you don't need to do a second query - you can do a batch fetch, instead. Try this:\n#and this should get me the items that a user saved\nuseritems = db.get(saveditemkeys)\n\n(Note you don't even need the guard clause - a db.get on 0 entities is short-circuited appropritely.)\nWhat's ...
[ 10, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "gql", "python" ]
stackoverflow_0001003247_google_app_engine_google_cloud_datastore_gql_python.txt
Q: Coding collaboratively for the web In the past I've done the coding-part of my web-projects mostly by myself. Now, as we are a team working on some project, be it python or php or ..., is there some simple versioning system to use? My hoster doesn't seem to support any kind of this sort. On the other hand, I feel ...
Coding collaboratively for the web
In the past I've done the coding-part of my web-projects mostly by myself. Now, as we are a team working on some project, be it python or php or ..., is there some simple versioning system to use? My hoster doesn't seem to support any kind of this sort. On the other hand, I feel it is too early to start renting a whole...
[ "Try Mercurial. If your hosting has ssh and python support, you can run Mercurial on it.\nUPDATE: By the way, you don't need a hosting to run Mercurial - it's distributed and works without any servers. If you still want to have a repository on your hosting server - you can have it if your hoster supports ssh and py...
[ 3, 2, 1, 0 ]
[]
[]
[ "php", "python", "versioning", "web_services" ]
stackoverflow_0001005548_php_python_versioning_web_services.txt
Q: Make my code handle in the background function calls that take a long time to finish Certain functions in my code take a long time to return. I don't need the return value and I'd like to execute the next lines of code in the script before the slow function returns. More precisely, the functions send out commands ...
Make my code handle in the background function calls that take a long time to finish
Certain functions in my code take a long time to return. I don't need the return value and I'd like to execute the next lines of code in the script before the slow function returns. More precisely, the functions send out commands via USB to another system (via a C++ library with SWIG) and once the other system has comp...
[ "Unless the SWIGged C++ code is specifically set up to release the GIL (Global Interpreter Lock) before long delays and re-acquire it before getting back to Python, multi-threading might not prove very useful in practice. You could try multiprocessing instead:\nfrom multiprocessing import Process\n\nif __name__ ==...
[ 4, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0000998674_multithreading_python.txt
Q: Capitalizing non-ASCII words in Python How to capitalize words containing non-ASCII characters in Python? Is there a way to tune string's capitalize() method to do that? A: Use Unicode strings: # coding: cp1252 print u"é".capitalize() # Prints É If all you have is an 8-bit string, decode it into Unicode first: ...
Capitalizing non-ASCII words in Python
How to capitalize words containing non-ASCII characters in Python? Is there a way to tune string's capitalize() method to do that?
[ "Use Unicode strings:\n# coding: cp1252\nprint u\"é\".capitalize()\n# Prints É\n\nIf all you have is an 8-bit string, decode it into Unicode first:\n# coding: cp1252\nprint \"é\".decode('cp1252').capitalize()\n# Prints É\n\nIf you then need it as an 8-bit string again, encode it:\n# coding: cp1252\nprint \"é\".deco...
[ 10, 1 ]
[]
[]
[ "ascii", "capitalization", "python", "unicode" ]
stackoverflow_0001006450_ascii_capitalization_python_unicode.txt
Q: A Python buffer that you can truncate from the left? Right now, I am buffering bytes using strings, StringIO, or cStringIO. But, I often need to remove bytes from the left side of the buffer. A naive approach would rebuild the entire buffer. Is there an optimal way to do this, if left-truncating is a very common o...
A Python buffer that you can truncate from the left?
Right now, I am buffering bytes using strings, StringIO, or cStringIO. But, I often need to remove bytes from the left side of the buffer. A naive approach would rebuild the entire buffer. Is there an optimal way to do this, if left-truncating is a very common operation? Python's garbage collector should actually GC th...
[ "A deque will be efficient if left-removal operations are frequent (Unlike using a list, string or buffer, it's amortised O(1) for either-end removal). It will be more costly memory-wise than a string however, as you'll be storing each character as its own string object, rather than a packed sequence.\nAlternative...
[ 3, 1 ]
[]
[]
[ "buffer", "memoryview", "python", "string" ]
stackoverflow_0001006171_buffer_memoryview_python_string.txt
Q: Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named direct...
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other
I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. Eve...
[ "Set the SESSION_COOKIE_DOMAIN option. You need to set the domain for each of your sites so the cookies don't override each other.\nYou can also use SESSION_COOKIE_NAME to make the cookie names different for each site.\n", "I ran into a similar issue with a live & staging site hosted on the same Apache server (o...
[ 9, 1, 0, 0, 0 ]
[]
[]
[ "admin", "django", "python" ]
stackoverflow_0000327142_admin_django_python.txt
Q: How to tell Buildout to install a egg from a URL (w/o pypi) I have some egg accessible as a URL, say http://myhosting.com/somepkg.egg . Now I don't have this somepkg listed on pypi. How do I tell buildout to fetch and install it for me. I have tried a few recipes but no luck so far. TIA A: You should just be ab...
How to tell Buildout to install a egg from a URL (w/o pypi)
I have some egg accessible as a URL, say http://myhosting.com/somepkg.egg . Now I don't have this somepkg listed on pypi. How do I tell buildout to fetch and install it for me. I have tried a few recipes but no luck so far. TIA
[ "You should just be able to add a 'find-links' option to your [buildout] section within the buildout.cfg file. I just tested this internally with the following buildout.cfg.\n[buildout]\nfind-links = http://buildslave01/eggs/hostapi.core-1.0_r102-py2.4.egg\nparts = mypython\n\n[mypython]\nrecipe = zc.recipe.egg\ni...
[ 5 ]
[]
[]
[ "buildout", "egg", "python" ]
stackoverflow_0001007488_buildout_egg_python.txt
Q: Popen and python Working on some code and I'm given the error when running it from the command prompt... NameError: name 'Popen' is not defined but I've imported both import os and import sys. Here's part of the code exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"'...
Popen and python
Working on some code and I'm given the error when running it from the command prompt... NameError: name 'Popen' is not defined but I've imported both import os and import sys. Here's part of the code exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"' cmd = [exepath, '-el'...
[ "you should do:\nimport subprocess\nsubprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)\n# etc.\n\n", "Popen is defined in the subprocess module\nimport subprocess\n...\nsubprocess.Popen(...)\n\nOr:\nfrom subprocess import Popen\nPopen(...)\n\n", "When you import a module, the module's membe...
[ 38, 7, 2, 1, 1 ]
[ "You should be using os.popen() if you simply import os.\n" ]
[ -2 ]
[ "popen", "python" ]
stackoverflow_0001007855_popen_python.txt
Q: How to spawn parallel child processes on a multi-processor system? I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called: $ python create_graphs.py --...
How to spawn parallel child processes on a multi-processor system?
I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called: $ python create_graphs.py --name=NAME where NAME is something like XYZ, ABC, NYU etc. In my parent ...
[ "What you are looking for is the process pool class in multiprocessing.\nimport multiprocessing\nimport subprocess\n\ndef work(cmd):\n return subprocess.call(cmd, shell=False)\n\nif __name__ == '__main__':\n count = multiprocessing.cpu_count()\n pool = multiprocessing.Pool(processes=count)\n print pool....
[ 70, 3, 1, 1 ]
[]
[]
[ "exec", "multiprocessing", "python", "subprocess" ]
stackoverflow_0000884650_exec_multiprocessing_python_subprocess.txt
Q: Getting distutils to install prebuilt compiled libraries? I manage an open source project (Remix, the source is available there) written in python. We ask users to run python setup.py install to install the software. Recently we added a compiled C++ package (a port of SoundTouch -- go to trunk/externals in the sou...
Getting distutils to install prebuilt compiled libraries?
I manage an open source project (Remix, the source is available there) written in python. We ask users to run python setup.py install to install the software. Recently we added a compiled C++ package (a port of SoundTouch -- go to trunk/externals in the source to see it.) We'd like the setup.py file that installs the b...
[ "Unfortunately, I'd say that overriding install command is the way to go.\nThis can be done easily, using custom distribution command. For example, see [1]\nhttp://svn.zope.org/Zope/branches/2.9/setup.py?rev=69978&view=auto\n", "Your first question is a tough one given the multiplatform requirement. If it was ju...
[ 1, 1 ]
[]
[]
[ "compiled", "installation", "open_source", "python" ]
stackoverflow_0001002581_compiled_installation_open_source_python.txt
Q: How do I test if a string exists in a Genshi stream? I'm working on a plugin for Trac and am inserting some javascript into the rendered HTML by manipulating the Genshi stream. I need to test if a javascript function is already in the HTML and if it is then overwrite it with a new version, if it isn't then add it ...
How do I test if a string exists in a Genshi stream?
I'm working on a plugin for Trac and am inserting some javascript into the rendered HTML by manipulating the Genshi stream. I need to test if a javascript function is already in the HTML and if it is then overwrite it with a new version, if it isn't then add it to the HTML. How do I perform a search to see if the funct...
[ "Aha!! I have solved this by first attempting to remove the function from the stream: \nstream = stream | Transformer('.//head/script[\"functionName()\"]').remove()\n\nand then adding the updated/new version:\nstream = stream | Transformer('.//head').append(tag.script(functionNameCode, type=\"text/javascript\"))\n\...
[ 1 ]
[]
[]
[ "genshi", "python", "stream" ]
stackoverflow_0001008038_genshi_python_stream.txt
Q: Is it possible to launch a Paster shell with some modules pre-imported? Is it possible to run "paster shell blah.ini" (or a variant thereof) and have it automatically load certain libraries? I hate having to always type "from foo.bar import mystuff" as the first command in every paster shell, and would like the co...
Is it possible to launch a Paster shell with some modules pre-imported?
Is it possible to run "paster shell blah.ini" (or a variant thereof) and have it automatically load certain libraries? I hate having to always type "from foo.bar import mystuff" as the first command in every paster shell, and would like the computer to do it for me.
[ "An option to try would be to create a sitecustomize.py script. If you have this in the same folder as your paster shell, the python interpreter should load it up on startup. \nLet me clarify, sitecustomize.py, if found, is always loaded on startup of the interpreter. So if you put it where it can be found, ide...
[ 2, 0 ]
[]
[]
[ "paster", "pylons", "python" ]
stackoverflow_0000922351_paster_pylons_python.txt
Q: How to do a meaningful code-coverage analysis of my unit-tests? I manage the testing for a very large financial pricing system. Recently our HQ have insisted that we verify that every single part of our project has a meaningful test in place. At the very least they want a system which guarantees that when we chang...
How to do a meaningful code-coverage analysis of my unit-tests?
I manage the testing for a very large financial pricing system. Recently our HQ have insisted that we verify that every single part of our project has a meaningful test in place. At the very least they want a system which guarantees that when we change something we can spot unintentional changes to other sub-systems. P...
[ "For the code coverage alone, you could use coverage.py.\nAs for coverage.py vs figleaf:\n\nfigleaf differs from the gold standard\n of Python coverage tools\n ('coverage.py') in several ways. \n First and foremost, figleaf uses the\n same criterion for \"interesting\" lines\n of code as the sys.settrace funct...
[ 6, 4, 4, 3, 1 ]
[]
[]
[ "python", "testing" ]
stackoverflow_0001006189_python_testing.txt
Q: Lookup and combine data in Python I have 3 text files many lines of value1<tab>value2 (maybe 600) many more lines of value2<tab>value3 (maybe 1000) many more lines of value2<tab>value4 (maybe 2000) Not all lines match, some will have one or more vals missing. I want to take file 1, read down it and lookup corres...
Lookup and combine data in Python
I have 3 text files many lines of value1<tab>value2 (maybe 600) many more lines of value2<tab>value3 (maybe 1000) many more lines of value2<tab>value4 (maybe 2000) Not all lines match, some will have one or more vals missing. I want to take file 1, read down it and lookup corresponding values in files 2 & 3, and writ...
[ "Untested:\nf1 = open(\"file1.txt\")\nf2 = open(\"file2.txt\")\nf3 = open(\"file3.txt\")\n\nv1 = [line.split() for line in f1]\n# dict comprehensions following, these need Python 3\nv2 = {vals[0]:vals[1] for vals in line.split() for line in f2}\nv3 = {vals[0]:vals[1] for vals in line.split() for line in f3}\n\nfor ...
[ 5, 3 ]
[]
[]
[ "file", "python", "string" ]
stackoverflow_0001008587_file_python_string.txt
Q: Name of file I'm editing I'm editing a file in ~/Documents. However, my working directory is somewhere else, say ~/Desktop. The file I'm editing is a Python script. I'm interested in doing a command like... :!python without needing to do :!python ~/Documents/script.py Is that possible? If so, what would be the co...
Name of file I'm editing
I'm editing a file in ~/Documents. However, my working directory is somewhere else, say ~/Desktop. The file I'm editing is a Python script. I'm interested in doing a command like... :!python without needing to do :!python ~/Documents/script.py Is that possible? If so, what would be the command? Thank you.
[ "Try: !python %\n", "I quite often map a key to do this for me. I usually use the F5 key as that has no command associated with it by default in vim.\nThe mapping I like to use is:\n:map <F5> :w<CR>:!python % 2>&1 \\| tee /var/tmp/robertw/results<CR>\n\nthis will also make sure that you've written out your script...
[ 9, 6 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0001008557_python_vim.txt
Q: How do you make this code more pythonic? Could you guys please tell me how I can make the following code more pythonic? The code is correct. Full disclosure - it's problem 1b in Handout #4 of this machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesi...
How do you make this code more pythonic?
Could you guys please tell me how I can make the following code more pythonic? The code is correct. Full disclosure - it's problem 1b in Handout #4 of this machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab & I'm using scipy Eg on...
[ "One obvious change is to get rid of the \"for i in range(1, 100):\" and just iterate over the file lines. To iterate over both files (xfile and yfile), zip them. ie replace that block with something like:\n import itertools\n\n for xline, yline in itertools.izip(xfile, yfile):\n s= xline.split(\" \")\n x[...
[ 9, 4, 3, 0, 0 ]
[]
[]
[ "machine_learning", "python", "scipy" ]
stackoverflow_0001007215_machine_learning_python_scipy.txt
Q: Using Perl, Python, or Ruby, how to write a program to "click" on the screen at scheduled time? Using Perl, Python, or Ruby, can I write a program, probably calling Win32 API, to "click" on the screen at scheduled time, like every 1 hour? Details: This is for experimentation -- and can the clicking be effective o...
Using Perl, Python, or Ruby, how to write a program to "click" on the screen at scheduled time?
Using Perl, Python, or Ruby, can I write a program, probably calling Win32 API, to "click" on the screen at scheduled time, like every 1 hour? Details: This is for experimentation -- and can the clicking be effective on Flash content as well as any element on screen? It can be nice if the program can record where on ...
[ "If you are trying to automate some task in a website you might want to look at WWW::Selenium. It, along with Selenium Remote Control, allows you to remote control a web browser.\n", "In Python there is ctypes and in Perl there is Win32::API\nctypes Example\nfrom ctypes import *\nwindll.user32.MessageBoxA(None, ...
[ 8, 7, 6, 1, 0 ]
[]
[]
[ "perl", "python", "ruby", "winapi" ]
stackoverflow_0001007391_perl_python_ruby_winapi.txt
Q: Output 2 dim array 'list of lists" to text file in python Simple question - I am creating a two dim array (ddist = [[0]*d for _ in [0]*d]) using lists in the code below. It outputs distance using gis data. I just want a simple way to take the result of my array/list and output to a text file keeping the same N*N s...
Output 2 dim array 'list of lists" to text file in python
Simple question - I am creating a two dim array (ddist = [[0]*d for _ in [0]*d]) using lists in the code below. It outputs distance using gis data. I just want a simple way to take the result of my array/list and output to a text file keeping the same N*N structure. I have used output from print statements in the past...
[ "that's what you could to output your 2-d list (or any 2d list for that matter):\nwith open(outfile, 'w') as file:\n file.writelines('\\t'.join(str(j) for j in i) + '\\n' for i in top_list)\n\n" ]
[ 5 ]
[]
[]
[ "list", "python", "text" ]
stackoverflow_0001009712_list_python_text.txt
Q: Timestamp conversion is off by an hour I'm trying to parse a twitter feed in django, and I'm having a strange problem converting the published time: I've got the time from the feed into a full 9-tuple correctly: >> print tweet_time time.struct_time(tm_year=2009, tm_mon=6, tm_mday=17, tm_hour=14, tm_min=35, tm_sec=...
Timestamp conversion is off by an hour
I'm trying to parse a twitter feed in django, and I'm having a strange problem converting the published time: I've got the time from the feed into a full 9-tuple correctly: >> print tweet_time time.struct_time(tm_year=2009, tm_mon=6, tm_mday=17, tm_hour=14, tm_min=35, tm_sec=28, tm_wday=2, tm_yday=168, tm_isdst=0) But...
[ "try flipping the isdst (is daylight savings flag) to a -1 and see if that fixes it. -1 tells it to use (guess) the local daylight savings setting and roll with that. \n" ]
[ 5 ]
[]
[]
[ "datetime", "django", "python", "time" ]
stackoverflow_0001009812_datetime_django_python_time.txt
Q: Using Django JSON serializer for object that is not a Model Is it possible to use Django serializer without a Model? How it is done? Will it work with google-app-engine? I don't use Django framework, but since it is available, I would want to use its resources here and there. Here is the code I tried: from djan...
Using Django JSON serializer for object that is not a Model
Is it possible to use Django serializer without a Model? How it is done? Will it work with google-app-engine? I don't use Django framework, but since it is available, I would want to use its resources here and there. Here is the code I tried: from django.core import serializers obj = {'a':42,'q':'meaning of life'} ...
[ "Serializers are only for models. Instead you can use simplejson bundled with Django.\nfrom django.utils import simplejson\njson_str = simplejson.dumps(my_object)\n\nSimplejson 2.0.9 docs are here.\n", "The GQLEncoder class in this library can take a db.Model entity and serialize it. I'm not sure if this is what ...
[ 15, 0 ]
[]
[]
[ "django", "google_app_engine", "json", "python", "serialization" ]
stackoverflow_0001005422_django_google_app_engine_json_python_serialization.txt
Q: Using string as variable name Is there any way for me to use a string to call a method of a class? Here's an example that will hopefully explain better (using the way I think it should be): class helloworld(): def world(self): print "Hello World!" str = "world" hello = helloworld() hello.`str`() Whi...
Using string as variable name
Is there any way for me to use a string to call a method of a class? Here's an example that will hopefully explain better (using the way I think it should be): class helloworld(): def world(self): print "Hello World!" str = "world" hello = helloworld() hello.`str`() Which would output Hello World!. Thank...
[ "You can use getattr:\n>>> class helloworld:\n... def world(self):\n... print(\"Hello World!\")\n... \n>>> m = \"world\"\n>>> hello = helloworld()\n>>> getattr(hello, m)()\nHello World!\n\n\nNote that the parens in class helloworld() as in your example are unnecessary, in this case.\nAnd, as SilentGhost...
[ 16, 2 ]
[ "one way is you can set variables to be equal to functions just like data\ndef thing1():\n print \"stuff\"\n\ndef thing2():\n print \"other stuff\"\n\navariable = thing1\navariable ()\navariable = thing2\navariable ()\n\nAnd the output you'l get is \nstuff\nother stuff\n\nThen you can get more complicated and...
[ -3, -3 ]
[ "python" ]
stackoverflow_0001009831_python.txt
Q: Obtaining financial data from Google Finance which is outside the scope of the API Google's finance API is incomplete -- many of the figures on a page such as: http://www.google.com/finance?fstype=ii&q=NYSE:GE are not available via the API. I need this data to rank companies on Canadian stock exchanges according...
Obtaining financial data from Google Finance which is outside the scope of the API
Google's finance API is incomplete -- many of the figures on a page such as: http://www.google.com/finance?fstype=ii&q=NYSE:GE are not available via the API. I need this data to rank companies on Canadian stock exchanges according to the formula of Greenblatt, available via google search for "greenblatt index scans"....
[ "You could try asking Google to provide the missing APIs. Otherwise, you're stuck with screen scraping, which is never fun, prone to breaking without notice, and likely in violation of Google's terms of service.\nBut, if you still want to write a screen scraper, it's hard to beat a combination of mechanize and Bea...
[ 4, 3, 0 ]
[]
[]
[ "api", "data_mining", "google_finance", "python" ]
stackoverflow_0001009524_api_data_mining_google_finance_python.txt
Q: A question on python sorting efficiency Alright so I am making a commandline based implementation of a website search feature. The website has a list of all the links I need in alphabetical order. Usage would be something like ./find.py LinkThatStartsWithB So it would navigate to the webpage associated with the...
A question on python sorting efficiency
Alright so I am making a commandline based implementation of a website search feature. The website has a list of all the links I need in alphabetical order. Usage would be something like ./find.py LinkThatStartsWithB So it would navigate to the webpage associated with the letter B. My questions is what is the most e...
[ "How are you getting this list of URLS?\nIf your commandline app is crawling the website for links, and you are only looking for a single item, building a dictionary is pointless. It will take at least as long to build the dict as it would to just check as you go! eg, just search as:\nfor link in mysite.getallLin...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0001005494_python_sorting.txt
Q: How to distribute proportionally dates on a scale with Python I have a very simple charting component which takes integer on the x/y axis. My problem is that I need to represent date/float on this chart. So I though I could distribute proportionally dates on a scale. In other words, let's say I have the following ...
How to distribute proportionally dates on a scale with Python
I have a very simple charting component which takes integer on the x/y axis. My problem is that I need to represent date/float on this chart. So I though I could distribute proportionally dates on a scale. In other words, let's say I have the following date : 01/01/2008, 02/01/2008 and 31/12/2008. The algorithm would r...
[ "If you're dealing with dates, then you can use the method toordinal.\nimport datetime\n\njan1=datetime.datetime(2008,1,1)\ndec31=datetime.datetime(2008,12,31)\nfeb1=datetime.datetime(2008,02,01)\n\ndates=[jan1,dec31,feb1]\ndates.sort()\n\ndatesord=[d.toordinal() for d in dates]\nstart,end=datesord[0],datesord[-1]\...
[ 3, 1, 0 ]
[]
[]
[ "algorithm", "datetime", "python", "timedelta" ]
stackoverflow_0001010139_algorithm_datetime_python_timedelta.txt
Q: Would extracting page metadata be a good use of multiple inheritance? I was wondering if I have a couple of models which both include fields like "meta_keywords" or "slug" which have to do with the web page the model instance will be displayed on, whether it would be advisable to break those page metadata elements...
Would extracting page metadata be a good use of multiple inheritance?
I was wondering if I have a couple of models which both include fields like "meta_keywords" or "slug" which have to do with the web page the model instance will be displayed on, whether it would be advisable to break those page metadata elements out into their own class, say PageMeta, and have my other models subclass ...
[ "General advice for a lightly-specified question:\nNontrivial multiple inheritance in Python requires Advanced Techniques to deal with the metaclass/metatype conflict. Look over this recipe from the ActiveState archives and see if it looks like the kind of stuff you like:\nExtract from linked recipe:\n\nThe simple...
[ 0 ]
[]
[]
[ "architecture", "django", "mixins", "multiple_inheritance", "python" ]
stackoverflow_0001010349_architecture_django_mixins_multiple_inheritance_python.txt
Q: How to construct a webob.Request or a WSGI 'environ' dict from raw HTTP request byte stream? Suppose I have a byte stream with the following in it: POST /mum/ble?q=huh Content-Length: 18 Content-Type: application/json; charset="utf-8" Host: localhost:80 ["do", "re", "mi"] Is there a way to produce an WSGI-style...
How to construct a webob.Request or a WSGI 'environ' dict from raw HTTP request byte stream?
Suppose I have a byte stream with the following in it: POST /mum/ble?q=huh Content-Length: 18 Content-Type: application/json; charset="utf-8" Host: localhost:80 ["do", "re", "mi"] Is there a way to produce an WSGI-style 'environ' dict from it? Hopefully, I've overlooked an easy answer, and it is as easy to achieve a...
[ "Reusing Python's standard library code for the purpose is a bit tricky (it was not designed to be reused that way!-), but should be doable, e.g:\nimport cStringIO\nfrom wsgiref import simple_server, util\n\ninput_string = \"\"\"POST /mum/ble?q=huh HTTP/1.0\nContent-Length: 18\nContent-Type: application/json; chars...
[ 5 ]
[]
[]
[ "python", "webob", "wsgi" ]
stackoverflow_0001010103_python_webob_wsgi.txt
Q: plot line at particular angle and offset I'm attempting to plot a particular line over an original image (an array) that i have. Basically, I have an angle and offset (measured from the center of the image) that I want to plot the line over. The problem is, I'm not exactly sure how to do this. I can write a really...
plot line at particular angle and offset
I'm attempting to plot a particular line over an original image (an array) that i have. Basically, I have an angle and offset (measured from the center of the image) that I want to plot the line over. The problem is, I'm not exactly sure how to do this. I can write a really complicated piece of code to do this, but I'm...
[ "Assuming that your offset is actually a x, y coordinate of the center of the line, and that the line should be a fixed length, then it's a simple matter of trigonometry with matplotlib:\nx = [offsetx-linelength*cos(angle), offsetx+linelength*cos(angle)]\ny = [offsety-linelength*sin(angle), offsety+linelength*sin(a...
[ 2, 1 ]
[]
[]
[ "angle", "image", "offset", "plot", "python" ]
stackoverflow_0001010423_angle_image_offset_plot_python.txt
Q: Customizing Django auto admin terminology I'm playing around with Django's admin module, but I've seemed to run into a bit of a bump that's more of an annoyance than an error. I have my modules setup using names like UserData and Status, so Django's admin panel likes to try to call each row in UserData a user data...
Customizing Django auto admin terminology
I'm playing around with Django's admin module, but I've seemed to run into a bit of a bump that's more of an annoyance than an error. I have my modules setup using names like UserData and Status, so Django's admin panel likes to try to call each row in UserData a user datas and each status a statuss. Is there any way I...
[ "You can define verbose_name and verbose_name_plural in your model's inner Meta class to override the values used there. See http://docs.djangoproject.com/en/dev/ref/models/options/#verbose-name-plural\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001010794_django_python.txt
Q: dictionary in python? in how many way i traverse dictionary in python??? A: Many ways! testdict = {"bob" : 0, "joe": 20, "kate" : 73, "sue" : 40} for items in testdict.items(): print (items) for key in testdict.keys(): print (key, testdict[key]) for item in testdict.iteritems(): print item for ...
dictionary in python?
in how many way i traverse dictionary in python???
[ "Many ways!\ntestdict = {\"bob\" : 0, \"joe\": 20, \"kate\" : 73, \"sue\" : 40}\n\nfor items in testdict.items():\n print (items)\n\nfor key in testdict.keys():\n print (key, testdict[key])\n\nfor item in testdict.iteritems():\n print item\n\nfor key in testdict.iterkeys():\n print (key, testdict[key])\...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "python", "traversal" ]
stackoverflow_0001010788_dictionary_python_traversal.txt
Q: how many places are optimized in Python's bytecode(version 2.5) Can anyone tell me how many places there are optimized in Python's bytecode? I was trying to de-compile Python's bytecode these days,but I found that in Python's version 2.5 there are a lot of optimization.For example: to this code a,b,c=([],[],[])#bu...
how many places are optimized in Python's bytecode(version 2.5)
Can anyone tell me how many places there are optimized in Python's bytecode? I was trying to de-compile Python's bytecode these days,but I found that in Python's version 2.5 there are a lot of optimization.For example: to this code a,b,c=([],[],[])#build list the non-optimized bytecode before version2.5 is like that: ...
[ "The Python/peephole.c source file is where basically all such optimizations are performed -- the link I gave is to the current version (2.6 or better), because I'm having trouble getting to the dynamic source browser here, but once it works again it's easy to see specific versions such as the one that was extant f...
[ 2, 0 ]
[]
[]
[ "bytecode", "python" ]
stackoverflow_0001010914_bytecode_python.txt
Q: Traversing multi-dimensional dictionary in django I'm a PHP guy on my first day in Python-land, trying to convert a php site to python (learning experience), and I'm hurting for advice. I never thought it would be so hard to use multi-dimensional arrays or dictionaries as you pythoners call them. So I can create m...
Traversing multi-dimensional dictionary in django
I'm a PHP guy on my first day in Python-land, trying to convert a php site to python (learning experience), and I'm hurting for advice. I never thought it would be so hard to use multi-dimensional arrays or dictionaries as you pythoners call them. So I can create multi-dimensional arrays using this, but i can't loop it...
[ "You should be using the built in ORM instead of using your own queries (at least for something simple like this), makes things much easier (assuming you've also built your models in your models.py file)\nIn your view:\ndef categories_view(request):\n categories = Categories.objects.all() #maybe put an order_b...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "dictionary", "django", "django_models", "django_templates", "python" ]
stackoverflow_0001010848_dictionary_django_django_models_django_templates_python.txt
Q: Python factorization I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents. For example if we have {2:3, 3:2, 5:1} (2^3 * 3^2 * 5 = 360) Then I could write: for i in range(4): for j in range(3): for k in range(1): pri...
Python factorization
I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents. For example if we have {2:3, 3:2, 5:1} (2^3 * 3^2 * 5 = 360) Then I could write: for i in range(4): for j in range(3): for k in range(1): print 2**i * 3**j * 5**k But...
[ "I have blogged about this, and the fastest pure python (without itertools) comes from a post by Tim Peters to the python list, and uses nested recursive generators:\ndef divisors(factors) :\n \"\"\"\n Generates all divisors, unordered, from the prime factorization.\n \"\"\"\n ps = sorted(set(factors))\...
[ 15, 10, 9, 3, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0001010381_algorithm_python.txt
Q: How to get links on a webpage using mechanize and open those links I want to use mechanize with python to get all the links of the page, and then open the links.How can I do it? A: Here is an example from the project's page: import re from mechanize import Browser br = Browser() br.open("http://www.example.com...
How to get links on a webpage using mechanize and open those links
I want to use mechanize with python to get all the links of the page, and then open the links.How can I do it?
[ "Here is an example from the project's page:\n\nimport re\nfrom mechanize import Browser\n\nbr = Browser()\nbr.open(\"http://www.example.com/\")\n\n# ...\n\n# .links() optionally accepts the keyword args of .follow_/.find_link()\nfor link in br.links(url_regex=\"python.org\"):\n print link\n br.follow_link(li...
[ 11, 2 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0001011975_mechanize_python.txt
Q: Execution order with threads and PyGTK on Windows I'm having issues with threads and PyGTK on Windows. According the the PyGTK FAQ (and my own experimentation), the only way to reliably update the GUI from a child thread is to use the gobject.idle_add function. However, it can't be guaranteed when this function ...
Execution order with threads and PyGTK on Windows
I'm having issues with threads and PyGTK on Windows. According the the PyGTK FAQ (and my own experimentation), the only way to reliably update the GUI from a child thread is to use the gobject.idle_add function. However, it can't be guaranteed when this function will be called. How can I guarantee that the line foll...
[ "Don't try to update or access your GUI from a thread. You're just asking for trouble. For example, the fact that \"get_text\" works at all in a thread is almost an accident. You might be able to rely on it in GTK - although I'm not even sure about that - but you won't be able to do so in other GUI toolkits.\nIf...
[ 2, 1 ]
[]
[]
[ "multithreading", "pygtk", "python", "windows" ]
stackoverflow_0001008322_multithreading_pygtk_python_windows.txt