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: Objective reasons for using Python or Ruby for a new REST Web API So this thread is definitely NOT a thread for why Python is better than Ruby or the inverse. Instead, this thread is for objective criticism on why you would pick one over the other to write a RESTful web API that's going to be used by many differen...
Objective reasons for using Python or Ruby for a new REST Web API
So this thread is definitely NOT a thread for why Python is better than Ruby or the inverse. Instead, this thread is for objective criticism on why you would pick one over the other to write a RESTful web API that's going to be used by many different clients, (mobile, web browsers, tablets etc). Again, don't compare Ru...
[ "I would say the important thing is that regardless of which you choose, make sure that your choice does not leak through your REST API. It should not matter to the client of your API which you chose.\n", "I know Ruby, don't know python... you can see which way I'm leaning toward, right?\n", "Choose the one yo...
[ 6, 5, 4, 4, 2, 2, 1 ]
[]
[]
[ "api", "python", "rest", "ruby", "web_services" ]
stackoverflow_0001850640_api_python_rest_ruby_web_services.txt
Q: Python raw_input into dictionary declared in a class I am incredibly new to Python and I really need to be able to work this out. I want to be asking the user via raw_input what the module and grade is and then putting this into the dictionary already defined in the Student class as grades. I've got no idea what t...
Python raw_input into dictionary declared in a class
I am incredibly new to Python and I really need to be able to work this out. I want to be asking the user via raw_input what the module and grade is and then putting this into the dictionary already defined in the Student class as grades. I've got no idea what to do! Thanks in advance! students = [] # List containing a...
[ "A few things:\n\nMove the initialization of your class attributes into an __init__ method:\nGet rid of all the getters and setters as Jeffrey says. \nUse a dict that has module names as keys and grades as values:\n\nSome code snippets:\ndef __init__(self, firstName, lastName, age, studentID, degree):\n self.fi...
[ 2 ]
[]
[]
[ "class", "dictionary", "python", "variables" ]
stackoverflow_0001853093_class_dictionary_python_variables.txt
Q: Codec Errors in Python Does anyone know the name of a codec that can translate any random assortment of bytes into a string? I have been getting the following error after encoding, encrypting, and decoding a string in tkinter.Text. UnicodeDecodeError: 'utf8' codec can't decode byte 0x99 in position 151: unexpected...
Codec Errors in Python
Does anyone know the name of a codec that can translate any random assortment of bytes into a string? I have been getting the following error after encoding, encrypting, and decoding a string in tkinter.Text. UnicodeDecodeError: 'utf8' codec can't decode byte 0x99 in position 151: unexpected code byte Code used to gen...
[ "Strings are by definition a sequence of bytes that only have meaning when interpreted with the knowledge of the encoding. That's one reason why the equivalent of Python 2's string type in Python 3 is the bytes type. As long as you know the encoding of the strings you're working with, I'm not sure you specificall...
[ 1, 1, 0 ]
[]
[]
[ "byte", "character_encoding", "python" ]
stackoverflow_0001835696_byte_character_encoding_python.txt
Q: Hello world Pyamf small error message Hi i am trying to link flex to django with Pyamf As a first step i tried the basic Hello World http://pyamf.org/wiki/DjangoHowto But that results in an ErrorFault. I use django 1.0.2 amfgateway.py in the root folder of my project (same level as settings) import pyamf from pya...
Hello world Pyamf small error message
Hi i am trying to link flex to django with Pyamf As a first step i tried the basic Hello World http://pyamf.org/wiki/DjangoHowto But that results in an ErrorFault. I use django 1.0.2 amfgateway.py in the root folder of my project (same level as settings) import pyamf from pyamf.remoting.gateway.django import DjangoGat...
[ "I think you may need to take the request parameter out of your echo def, at least the method on the pyamf example site doesn't have that parameter in the method\n", "Although the error is unrelated, JMP is correct - you have expose_request=False on the gateway and the service definition for echo has the first ar...
[ 3, 2 ]
[]
[]
[ "apache_flex", "django", "pyamf", "python" ]
stackoverflow_0000631436_apache_flex_django_pyamf_python.txt
Q: Django edit form based on add form? I've made a nice form, and a big complicated 'add' function for handling it. It starts like this... def add(req): if req.method == 'POST': form = ArticleForm(req.POST) if form.is_valid(): article = form.save(commit=False) article.autho...
Django edit form based on add form?
I've made a nice form, and a big complicated 'add' function for handling it. It starts like this... def add(req): if req.method == 'POST': form = ArticleForm(req.POST) if form.is_valid(): article = form.save(commit=False) article.author = req.user # more processin...
[ "If you are extending your form from a ModelForm, use the instance keyword argument. Here we pass either an existing instance or a new one, depending on whether we're editing or adding an existing article. In both cases the author field is set on the instance, so commit=False is not required. Note also that I'm ass...
[ 113, 3 ]
[]
[]
[ "django", "forms", "logic", "python" ]
stackoverflow_0001854237_django_forms_logic_python.txt
Q: Writing a Faster Python Spider I'm writing a spider in Python to crawl a site. Trouble is, I need to examine about 2.5 million pages, so I could really use some help making it optimized for speed. What I need to do is examine the pages for a certain number, and if it is found to record the link to the page. The sp...
Writing a Faster Python Spider
I'm writing a spider in Python to crawl a site. Trouble is, I need to examine about 2.5 million pages, so I could really use some help making it optimized for speed. What I need to do is examine the pages for a certain number, and if it is found to record the link to the page. The spider is very simple, it just needs t...
[ "You could use MapReduce like Google does, either via Hadoop (specifically with Python: 1 and 2), Disco, or Happy.\nThe traditional line of thought, is write your program in standard Python, if you find it is too slow, profile it, and optimize the specific slow spots. You can make these slow spots faster by droppi...
[ 10, 5, 5, 3, 3, 0 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0001853673_python_web_crawler.txt
Q: No readyReadStandardOutput signal from QProcess Why do I never get the readyReadStandardOutput signal when I run the following? import os, sys, textwrap from PyQt4 import QtGui, QtCore out_file = open("sleep_loop.py", 'w') out_file.write(textwrap.dedent(""" import time while True: print "sleepin...
No readyReadStandardOutput signal from QProcess
Why do I never get the readyReadStandardOutput signal when I run the following? import os, sys, textwrap from PyQt4 import QtGui, QtCore out_file = open("sleep_loop.py", 'w') out_file.write(textwrap.dedent(""" import time while True: print "sleeping..." time.sleep(1)""")) out_file.close() de...
[ "Two problems here:\n\nYou should create QApplication instance before creating everything else.\nYour child process is buffering its output.\n\nHere is the fixed code, only two lines changed:\n\napp = QApplication moved before proc = QProcess\nchild process now has sys.stdout.flush()\n\nAnd now everything works as ...
[ 4 ]
[]
[]
[ "pyqt", "python", "qprocess", "qt" ]
stackoverflow_0001854247_pyqt_python_qprocess_qt.txt
Q: List view is not refreshed if setTabText() is called Yes, I know this sounds crazy. But here's the situation. I composed a minimal code reproducing the bug. The code creates main window with QTabWidget, which, in turn, has one tab with QListView and a button. List view is connected to QAbstractListModel. Initially...
List view is not refreshed if setTabText() is called
Yes, I know this sounds crazy. But here's the situation. I composed a minimal code reproducing the bug. The code creates main window with QTabWidget, which, in turn, has one tab with QListView and a button. List view is connected to QAbstractListModel. Initially, list model contains empty list. If user clicks on a butt...
[ "Could not reproduce your problem using Linux, Qt 4.5.3, pyQt 4.5.4, python 2.5.2. \nI guess this is definitely version/platform-dependent. You should try Qt 4.5.3 + pyQt 4.5.4 + python 2.5.2 on MacOS. If you can reproduce the problem, it is more like a bug in MacOS qt port. If you can't you should try newer qt ver...
[ 0 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0001815154_pyqt_pyqt4_python_qt.txt
Q: Replace Multiple lines in Jython I have written a small program to replace a set of characters , but i also want two or more replace command in a single program . Apart from it i also want to add an bracket after random set of characters. This is my Program file_read=open('<%=odiRef.getOption("READ")%>/EXPORT.XM...
Replace Multiple lines in Jython
I have written a small program to replace a set of characters , but i also want two or more replace command in a single program . Apart from it i also want to add an bracket after random set of characters. This is my Program file_read=open('<%=odiRef.getOption("READ")%>/EXPORT.XML','r') file_write=open('<%=odiRef.get...
[ "This is wrong on many levels - you can not simultaneously read and write from the same file, file.read() command reads entire contents, and you dont have to save after each replace. Something like this:\nfile = open('myfile', 'r+')\ncontents = file.read()\nfile.seek(0) # rewind \nfile.write(contents.replace('so...
[ 3 ]
[]
[]
[ "jython", "python", "replace", "string" ]
stackoverflow_0001853921_jython_python_replace_string.txt
Q: Django: PYTHON_EGG_CACHE, access denied error I am deploying my django application on a server, and on last stages I am getting this error: ExtractionError at /admin/ Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission de...
Django: PYTHON_EGG_CACHE, access denied error
I am deploying my django application on a server, and on last stages I am getting this error: ExtractionError at /admin/ Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: '/.python-eggs' The Python egg cache directo...
[ "Well, you are using some strange setuptools-enabled library.\nBut anyway, is there a problem for you to setup PYTHON_EGG_CACHE environment variable to any directory writable for application user?\n" ]
[ 6 ]
[]
[]
[ "django", "python", "python_egg_cache" ]
stackoverflow_0001855219_django_python_python_egg_cache.txt
Q: Dealing with URLs in Django So, basically what I'm trying to do is a hockey pool application, and there are a ton of ways I should be able to filter to view the data. For example, filter by free agent, goals, assists, position, etc. I'm planning on doing this with a bunch of query strings, but I'm not sure what t...
Dealing with URLs in Django
So, basically what I'm trying to do is a hockey pool application, and there are a ton of ways I should be able to filter to view the data. For example, filter by free agent, goals, assists, position, etc. I'm planning on doing this with a bunch of query strings, but I'm not sure what the best approach would be to pass...
[ "Firstly, think about whether you really want to save all the parameters each time. In the example you give, you change the sort order but preserve the page number. Does this really make sense, considering you will now have different elements on that page. Even more, if you change the filters, the currently selecte...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "http", "python", "request" ]
stackoverflow_0001855184_django_http_python_request.txt
Q: Converting a Tuples List into a nested List using Python I want to convert a tuples list into a nested list using Python. How do I do that? I have a sorted list of tuples (sorted by the second value): [(1, 5), (5, 4), (13, 3), (4, 3), (3, 2), (14, 1), (12, 1), (10, 1), (9, 1), (8, 1), (7, 1), (6, 1), (2, 1)] ...
Converting a Tuples List into a nested List using Python
I want to convert a tuples list into a nested list using Python. How do I do that? I have a sorted list of tuples (sorted by the second value): [(1, 5), (5, 4), (13, 3), (4, 3), (3, 2), (14, 1), (12, 1), (10, 1), (9, 1), (8, 1), (7, 1), (6, 1), (2, 1)] Now I want it to have like this (second value ignored and nest...
[ "from operator import itemgetter\nfrom itertools import groupby\n\nlst = [(1, 5), (5, 4), (13, 3), (4, 3), (3, 2), (14, 1),\n (12, 1), (10, 1), (9, 1), (8, 1), (7, 1), (6, 1), (2, 1)]\n\nresult = [[x for x, y in group]\n for key, group in groupby(lst, key=itemgetter(1))]\n\ngroupby(lst, key=itemget...
[ 11, 2, 1, 1, 0 ]
[]
[]
[ "list", "nested", "python", "tuples" ]
stackoverflow_0001855471_list_nested_python_tuples.txt
Q: Dynamically Refreshed Pages produced by Python I've been researching this on and off for a number of months now, but I am incapable of finding clear direction. My goal is to have a page which has a form on it and a graph on it. The form can be filled out and then sent to the CGI Python script (yeah, I'll move to ...
Dynamically Refreshed Pages produced by Python
I've been researching this on and off for a number of months now, but I am incapable of finding clear direction. My goal is to have a page which has a form on it and a graph on it. The form can be filled out and then sent to the CGI Python script (yeah, I'll move to WSGI or fast_cgi later, I'm starting simple!) I'd li...
[ "I'm assuming that you have two pages at the moment - a page which shows the form, and a page which receives the POST request and displays the graph.\nWill a little jQuery you can do exactly what you want.\nFirst add to your form page an empty div with id=\"results\". Next in your graph plotting page put the outpu...
[ 4, 2, 1, 0 ]
[]
[]
[ "ajax", "javascript", "python" ]
stackoverflow_0001855748_ajax_javascript_python.txt
Q: Call method from string If I have a Python class, and would like to call a function from it depending on a variable, how would I do so? I imagined following could do it: class CallMe: # Class def App(): # Method one ... def Foo(): # Method two ... variable = "App" # Method to call CallMe.va...
Call method from string
If I have a Python class, and would like to call a function from it depending on a variable, how would I do so? I imagined following could do it: class CallMe: # Class def App(): # Method one ... def Foo(): # Method two ... variable = "App" # Method to call CallMe.variable() # Calling App() But...
[ "You can do this:\ngetattr(CallMe, variable)()\n\ngetattr is a builtin method, it returns the value of the named attributed of object. The value in this case is a method object that you can call with ()\n", "You can use getattr, or you can assign bound or unbound methods to the variable. Bound methods are tied t...
[ 119, 2, 1, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0001855558_oop_python.txt
Q: Fast conversion of numeric data into fixed width format file in Python What is the fastest way of converting records holding only numeric data into fixed with format strings and writing them to a file in Python? For example, suppose record is a huge list consisting of objects with attributes id, x, y, and wt and ...
Fast conversion of numeric data into fixed width format file in Python
What is the fastest way of converting records holding only numeric data into fixed with format strings and writing them to a file in Python? For example, suppose record is a huge list consisting of objects with attributes id, x, y, and wt and we frequently need to flush them to an external file. The flushing can be do...
[ "I was trying to check if numpy.savetxt could speed things up a bit so I wrote the following simulation:\nimport sys\nimport numpy as np\n\nfmt = '%7.0f %11.5e %11.5e %7.5f'\nrecords = 10000\n\nnp.random.seed(1234)\naray = np.random.rand(records, 4)\n\ndef writ(f, aray=aray, fmt=fmt):\n fw = f.write\n for row in ...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "large_data_volumes", "performance", "python" ]
stackoverflow_0001854713_large_data_volumes_performance_python.txt
Q: how to access sys.argv (or any string variable) in raw mode? I'm having difficulties parsing filepaths sent as arguments: If I type: os.path.normpath('D:\Data2\090925') I get 'D:\\Data2\x0090925' Obviously the \0 in the folder name is upsetting the formatting. I can correct it with the following: os.path.normpat...
how to access sys.argv (or any string variable) in raw mode?
I'm having difficulties parsing filepaths sent as arguments: If I type: os.path.normpath('D:\Data2\090925') I get 'D:\\Data2\x0090925' Obviously the \0 in the folder name is upsetting the formatting. I can correct it with the following: os.path.normpath(r'D:\Data2\090925') which gives 'D:\\Data2\\090925' My problem...
[ "\"Losing\" the last part of your path is nothing to do with escaping (or lack of it) in sys.argv.\nIt is the expected behaviour if you use os.path.normpath() and then os.path.dirname().\n>>> import os\n>>> os.path.normpath(\"c:/foo/bar/\")\n'c:\\\\foo\\\\bar'\n>>> os.path.dirname('c:\\\\foo\\\\bar')\n'c:\\\\foo'\n...
[ 5, 0 ]
[]
[]
[ "python", "string_literals" ]
stackoverflow_0001855477_python_string_literals.txt
Q: Python module database configuration? I have a python module which contains a few objects, one of which uses a MySQL connection to persist some data. What's the best way to allow for easy configuration of the MySQL connection information without making the user go into the installed module location and edit files?...
Python module database configuration?
I have a python module which contains a few objects, one of which uses a MySQL connection to persist some data. What's the best way to allow for easy configuration of the MySQL connection information without making the user go into the installed module location and edit files?
[ "Allow the user to write configuration information for the program in a file of the format that ConfigParser knows how to parse -- this way, the user doesn't have to \"go into the installed module location\" but can edit the configuration file in more convenient places.\nIt is traditional and helpful for the progra...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001856356_python.txt
Q: Python popen wont work with block devices I am wring a small forensic app which looks like this so far import time, os,sys def getter(): filename = sys.argv[1] print "File Entered: " + filename os.system('file ' + filename) print "\n" pipe = os.popen("xxd " + filename, "r") print pipe.rea...
Python popen wont work with block devices
I am wring a small forensic app which looks like this so far import time, os,sys def getter(): filename = sys.argv[1] print "File Entered: " + filename os.system('file ' + filename) print "\n" pipe = os.popen("xxd " + filename, "r") print pipe.read() I input via the command line a file and it...
[ "I assume you've tried the same command from the shell prompt and it worked well, even when piped to less or something of the sort.\nI have a strong feeling that using subprocess will fix this behavior; This module replaces the popen call which is deprecated, and gives a great degree of flexibility in running and g...
[ 4, 3, 1 ]
[]
[]
[ "pipe", "python", "subprocess" ]
stackoverflow_0001856372_pipe_python_subprocess.txt
Q: SyntaxError inconsistency in Python? Consider these two snippets: try: a+a=a except SyntaxError: print "first exception caught" . try: eval("a+a=a") except SyntaxError: print "second exception caught" In the second case the "second exception .." statement is printed (exception caught), while in t...
SyntaxError inconsistency in Python?
Consider these two snippets: try: a+a=a except SyntaxError: print "first exception caught" . try: eval("a+a=a") except SyntaxError: print "second exception caught" In the second case the "second exception .." statement is printed (exception caught), while in the first one isn't. Is first exception (l...
[ "In the first case, the exception is raised by the compiler, which is running before the try/except structure even exists (since it's the compiler itself that will set it up right after parsing). In the second case, the compiler is running twice -- and the exception is getting raised when the compiler runs as part...
[ 24, 4 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0001856408_exception_python.txt
Q: Defining PYTHONPATH for http requests on a shared server I'm installing Django on Bluehost and one of the steps to install it was to install flup on their server. I did so and everything works great when I'm logged in via the SSH. However when I actually hit the page in my browser it can't find flup. I get this er...
Defining PYTHONPATH for http requests on a shared server
I'm installing Django on Bluehost and one of the steps to install it was to install flup on their server. I did so and everything works great when I'm logged in via the SSH. However when I actually hit the page in my browser it can't find flup. I get this error in the server log: ERROR: No module named flup. Unable to...
[ "If you can identify what module exactly is trying to import flup, you can prepend that import with a sys.path.append of the path to which you have installed flup -- as long as the sys.path.append happens before the import flup, you're in clover.\n" ]
[ 2 ]
[]
[]
[ "bluehost", "django", "flup", "python", "pythonpath" ]
stackoverflow_0001856439_bluehost_django_flup_python_pythonpath.txt
Q: What is the best way to call Java code from Python? I have a Java class library (3rd party, proprietary) and I want my python script to call its functions. I already have java code that uses this library. What is the best way to achieve this? A: Can you run your current Python scripts under Jython ? If so, that'...
What is the best way to call Java code from Python?
I have a Java class library (3rd party, proprietary) and I want my python script to call its functions. I already have java code that uses this library. What is the best way to achieve this?
[ "Can you run your current Python scripts under Jython ? If so, that's probably the best way, since the Java library can be exposed directly into Jython as scriptable objects.\nFailing that, there are a number of solutions listed here.\n", "The other answer is JPype, which allows CPython to talk to Java. It's usef...
[ 15, 8, 3 ]
[]
[]
[ "java", "python" ]
stackoverflow_0001855320_java_python.txt
Q: Intelligently launching the default editor from inside a Python CLI program? The answers in this question didn't get to the heart of the problem. In a CLI-based Python program, I want the user to be able to edit a file and then return to the program. Before returning, I want them to be able to cancel their edits. ...
Intelligently launching the default editor from inside a Python CLI program?
The answers in this question didn't get to the heart of the problem. In a CLI-based Python program, I want the user to be able to edit a file and then return to the program. Before returning, I want them to be able to cancel their edits. This should feel like the commit-note-editing feature in Subversion. What are the ...
[ "You could try looking through the sources to Mercurial, which is written in Python.\nThey use os.environ to read the value of environment variables HGEDITOR, VISUAL, and EDITOR, defaulting to vi. Then they use os.system to launch the editor on a temp file created with tempfile.mkstemp. When the editor is done, t...
[ 10, 2 ]
[]
[]
[ "editor", "python" ]
stackoverflow_0001856792_editor_python.txt
Q: Urllib2 Send Post data through proxy I have configured a proxy using proxyhandler and sent a request with some POST data: cookiejar = cookielib.CookieJar() proxies = {'http':'http://some-proxy:port/'} opener = urllib2.build_opener(urllib2.ProxyHandler(proxies),urllib2.HTTPCookieProcessor(cookiejar) ) opener.addhe...
Urllib2 Send Post data through proxy
I have configured a proxy using proxyhandler and sent a request with some POST data: cookiejar = cookielib.CookieJar() proxies = {'http':'http://some-proxy:port/'} opener = urllib2.build_opener(urllib2.ProxyHandler(proxies),urllib2.HTTPCookieProcessor(cookiejar) ) opener.addheaders = [('User-agent', "USER AGENT")] url...
[ "The problem was user-agent header.\n" ]
[ 1 ]
[]
[]
[ "proxy", "python", "urllib2" ]
stackoverflow_0001856814_proxy_python_urllib2.txt
Q: Mac Based Python GUI Libraries I am currently building a GUI based Python application on my mac and was wondering could anyone suggest a good GUI library to use? I was looking at python's gui programming faq and there was a lot of options making it hard to choose. I am developing on snow leopard and cross-platfor...
Mac Based Python GUI Libraries
I am currently building a GUI based Python application on my mac and was wondering could anyone suggest a good GUI library to use? I was looking at python's gui programming faq and there was a lot of options making it hard to choose. I am developing on snow leopard and cross-platform is not essential (if it makes a di...
[ "If you're not concerned about cross-platform compatibility, then PyObjC (also see Apple's info about PyObjC) provides a direct bridge to the native OS X Cocoa interfaces.\n\nPyObjC (pronounced pie-obz-see) is the key piece which makes it possible to write Cocoa applications in Python. It enables Python objects to ...
[ 5, 5, 3 ]
[]
[]
[ "macos", "python", "user_interface" ]
stackoverflow_0001856924_macos_python_user_interface.txt
Q: python crypt.crypt in ruby? hi i need this code in ruby I don't know how I write the crypt.crypt method in ruby, any ideas? (I want to simulate the linux comand .htpasswd) import random import crypt letters = 'abcdefghijklmnopqrstuvwxyz' \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ '0123456789/.' salt = r...
python crypt.crypt in ruby?
hi i need this code in ruby I don't know how I write the crypt.crypt method in ruby, any ideas? (I want to simulate the linux comand .htpasswd) import random import crypt letters = 'abcdefghijklmnopqrstuvwxyz' \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ '0123456789/.' salt = random.choice(letters) + random.ch...
[ "Jordan already told you about String#crypt, so I'll just show you an easier way to create your letters array:\nletters = [*'a'..'z'] + [*'A'..'Z'] + [*0..9] + %w(/ .)\n\nUpdate: since this got upvoted after more than 2 years, I might as well add the 1.9 way of doing this (using multiple splats and character litera...
[ 3, 1 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0001849638_python_ruby.txt
Q: Proper way to implement a Direct Connect client in Twisted? I'm working on writing a Python client for Direct Connect P2P networks. Essentially, it works by connecting to a central server, and responding to other users who are searching for files. Occasionally, another client will ask us to connect to them, and th...
Proper way to implement a Direct Connect client in Twisted?
I'm working on writing a Python client for Direct Connect P2P networks. Essentially, it works by connecting to a central server, and responding to other users who are searching for files. Occasionally, another client will ask us to connect to them, and they might begin downloading a file from us. This is a direct conne...
[ "Without knowing all the details of the protocol, I would still recommend using a single reactor -- a reactor scales quite well (especially advanced ones such as PollReactor) and this way you will avoid the overhead connected with threads (that's how Twisted and other async systems get their fundamental performance...
[ 3 ]
[]
[]
[ "p2p", "python", "twisted" ]
stackoverflow_0001856786_p2p_python_twisted.txt
Q: Python attribute error: type object '_socketobject' has no attribute 'gethostbyname' I am trying to do this in my program: dest = socket.gethostbyname(host) I have included the line: from socket import * in the beginning of the file. I am getting this error: AttributeError: type object '_socketobject' has no...
Python attribute error: type object '_socketobject' has no attribute 'gethostbyname'
I am trying to do this in my program: dest = socket.gethostbyname(host) I have included the line: from socket import * in the beginning of the file. I am getting this error: AttributeError: type object '_socketobject' has no attribute 'gethostbyname' I am running Vista 64bit. Could there be a problem with my ...
[ "You shoulod either use\nimport socket\ndest = socket.gethostbyname(host)\n\nor use\nfrom socket import *\ndest = gethostbyname(host)\n\nNote: the first option is by far the recommended one.\n", "After from socket import *, you'd need to call just the barename gethostbyname -- the barename socket now refers to a ...
[ 20, 2 ]
[]
[]
[ "attributeerror", "gethostbyname", "python" ]
stackoverflow_0001857146_attributeerror_gethostbyname_python.txt
Q: python soappy add header I have the following PHP example code: $client = new SoapClient("http://example.com/example.wsdl"); $h = Array(); array_push($h, new SoapHeader("http://example2.com/example2/", "h", "v")); $client->__setSoapHeaders($h); $s = $client->__soapCall('Op', $data); My question: what's the SOAP...
python soappy add header
I have the following PHP example code: $client = new SoapClient("http://example.com/example.wsdl"); $h = Array(); array_push($h, new SoapHeader("http://example2.com/example2/", "h", "v")); $client->__setSoapHeaders($h); $s = $client->__soapCall('Op', $data); My question: what's the SOAPpy equivalent for the SoapHead...
[ "Here's an example using suds library (an alternative to SOAPpy). It assumes that the custom header is not defined in the wsdl.\nfrom suds.client import Client\nfrom suds.sax.element import Element\n\nclient = Client(\"http://example.com/example.wsdl\")\n\n# <tns:h xmlns:tns=\"http://example2.com/example2/\">...
[ 1 ]
[]
[]
[ "header", "python", "soap", "soappy" ]
stackoverflow_0001856963_header_python_soap_soappy.txt
Q: Deploying Django When finding web hosting for Rails apps, the hoster must have support for ruby on rails -- that is evident. What about hosting for Django? What support does the hoster need to provide? Python, or more than just Python? This might seem like an obvious question, but I'm new to web development fra...
Deploying Django
When finding web hosting for Rails apps, the hoster must have support for ruby on rails -- that is evident. What about hosting for Django? What support does the hoster need to provide? Python, or more than just Python? This might seem like an obvious question, but I'm new to web development frameworks so I must ask ...
[ "It just needs to support Python 2.3 or later (but not 3.0, yet), preferably with mod_wsgi support (although it also works with a bunch of other options, if required).\n", "Technically, as other responders say, the host needs very little (hey, Django even runs with Google app engine for all the latter's limitatio...
[ 6, 3, 3, 2, 0 ]
[]
[]
[ "django", "python", "ruby_on_rails" ]
stackoverflow_0001022914_django_python_ruby_on_rails.txt
Q: Send selected text to a command line argument I found this utility, pytranslate, which translates a variety of languages into each other using Google's translation API. It works exactly as described. However I've gotten sick of selecting a word I do not understand, then middle-clicking it into the command. The co...
Send selected text to a command line argument
I found this utility, pytranslate, which translates a variety of languages into each other using Google's translation API. It works exactly as described. However I've gotten sick of selecting a word I do not understand, then middle-clicking it into the command. The command format is as such: pytranslate WORD Is there...
[ "#!/bin/bash\npytranslate \"$(xsel -p)\"\n\nNow just put this in ~/bin (make sure that's included in your PATH), and run it. (You may need to install the xsel package.) It will take the current contents of the primary selection buffer and pass it to pytranslate.\nIf you want it as a button, create a launcher whic...
[ 4, 3, 1, 0 ]
[]
[]
[ "clipboard", "google_translate", "python", "terminal", "ubuntu_9.04" ]
stackoverflow_0001857287_clipboard_google_translate_python_terminal_ubuntu_9.04.txt
Q: Is there an Open Source Python library for sanitizing HTML and removing all Javascript? I want to write a web application that allows users to enter any HTML that can occur inside a <div> element. This HTML will then end up being displayed to other users, so I want to make sure that the site doesn't open people u...
Is there an Open Source Python library for sanitizing HTML and removing all Javascript?
I want to write a web application that allows users to enter any HTML that can occur inside a <div> element. This HTML will then end up being displayed to other users, so I want to make sure that the site doesn't open people up to XSS attacks. Is there a nice library in Python that will clean out all the event handler...
[ "As Klaus mentions, the clear consensus in the community is to use BeautifulSoup for these tasks:\nsoup = BeautifulSoup.BeautifulSoup(html)\nfor script_elt in soup.findAll('script'):\n script_elt.extract()\nhtml = str(soup)\n\n", "Whitelist approach to allowed tags, attributes and their values is the only reli...
[ 5, 4, 0, 0, 0 ]
[]
[]
[ "javascript", "parsing", "python", "xss" ]
stackoverflow_0001854806_javascript_parsing_python_xss.txt
Q: How do I import the render_to_response method from Django 1.1 inside of Google App Engine? I'm a Python newbie, so I'm sure this is easy. Here's the code in my main.py: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from google.appengine.dist import use_library use_library('django', '1.1') # Use dj...
How do I import the render_to_response method from Django 1.1 inside of Google App Engine?
I'm a Python newbie, so I'm sure this is easy. Here's the code in my main.py: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from google.appengine.dist import use_library use_library('django', '1.1') # Use django form library. from django import forms from django.shortcuts import render_to_response The...
[ "Well, render_to_response is a shortcut for this, so give this a try:\nfrom django.template import Context, loader\nfrom django.http import HttpResponse\n\ndef render_to_response(tmpl, data):\n t = loader.get_template(tmpl)\n c = Context(data)\n return HttpResponse(t.render(c))\n\nrender_to_response(\"temp...
[ 2, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0001738466_django_google_app_engine_python.txt
Q: "Better option" from the python library, any list? I just found out the existence of the optparse module. I personally always used getopt, so I did not care to look for something better. It's clear, however, that optparse is much more advanced, so I would expect it to be the preferred way in the future to get opti...
"Better option" from the python library, any list?
I just found out the existence of the optparse module. I personally always used getopt, so I did not care to look for something better. It's clear, however, that optparse is much more advanced, so I would expect it to be the preferred way in the future to get options from the command line. Anyway, this event struck me....
[ "I suggest this might be a good place to start such a list\nnote that there is pep389 to replace optparse with argparse\ncollections.defaultdict works nicer in most places you would use dict.setdefault \nthe collections module is a good one to become familiar with as it has lots of new stuff in Python3\nGenerator e...
[ 2, 1, 0, 0 ]
[]
[]
[ "argparse", "command_line_arguments", "getopt", "optparse", "python" ]
stackoverflow_0001857432_argparse_command_line_arguments_getopt_optparse_python.txt
Q: How do I break up the controllers (views) into cohesive files in a Django project? I am currently working through the tutorial on Django's website. Upon completing the following command: python manage.py startapp polls it creates the following structure: polls/ __init__.py models.py tests.py views...
How do I break up the controllers (views) into cohesive files in a Django project?
I am currently working through the tutorial on Django's website. Upon completing the following command: python manage.py startapp polls it creates the following structure: polls/ __init__.py models.py tests.py views.py As I was going through the tutorial it occurred to me that the views file could gro...
[ "You could split up views in a similar manner to how this blog entry splits models\nhttp://www.nomadjourney.com/2009/11/splitting-up-django-models/\neg \n/myapp\n\n * /views\n o __init__.py\n o bar.py\n o foo.py\n\nwith appropriate import statements in the __init__.py file\nThis might ...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001857427_django_python.txt
Q: Python proxy checker, change to threaded version i have some python proxy checker. and to speed up check, i was decided change to multithreaded version, and thread module is first for me, i was tried several times to convert to thread version and look for many info, but it not so much easy for novice python progra...
Python proxy checker, change to threaded version
i have some python proxy checker. and to speed up check, i was decided change to multithreaded version, and thread module is first for me, i was tried several times to convert to thread version and look for many info, but it not so much easy for novice python programmer. if anyone can help me really much appreciate!! ...
[ "urllib2.install_opener() function installs global opener, i.e. it's not thread safe. So don't use it and call opener.open() method instead of global urllib2.urlopen() function. Also use Queue class from Queue module to hold the list of proxies to check. The rest of your code is OK to use in threaded mode.\n" ]
[ 4 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001857799_multithreading_python.txt
Q: How to extract every possible values of python Dict's values to list DICTA={'bw':['BW','VW'],'b':['BB','VV'],'a':['AA']} DICTB={'yn':['$YN','$YNN'],'ye':['$YE','A$Y'],'y':['Y$']} How to extract every possible values of that 2 Dict to ["BWYN","VWYN","BBYN","VVYN","AAYN","BWYNN","VWYNN","BBYNN","VVYNN","AAYNN", "BW...
How to extract every possible values of python Dict's values to list
DICTA={'bw':['BW','VW'],'b':['BB','VV'],'a':['AA']} DICTB={'yn':['$YN','$YNN'],'ye':['$YE','A$Y'],'y':['Y$']} How to extract every possible values of that 2 Dict to ["BWYN","VWYN","BBYN","VVYN","AAYN","BWYNN","VWYNN","BBYNN","VVYNN","AAYNN", "BWYE","VWYE","BBYE","VVYE","AAYE","ABWY","AVWY","ABBY","AVVY","AAAY", "YBW",...
[ "Many possible minor variants on the following fundamental theme:\nprint [y.replace('$', x)\n for y in (v for y in DICTB.values() for v in y)\n for x in (v for y in DICTA.values() for v in y)\n]\n\n", "I like to go with itertools myself, but essentially the same as Alex's solution:\nfrom itertools import produc...
[ 4, 4 ]
[]
[]
[ "python" ]
stackoverflow_0001857820_python.txt
Q: With sqlalchemy how to dynamically bind to database engine on a per-request basis I have a Pylons-based web application which connects via Sqlalchemy (v0.5) to a Postgres database. For security, rather than follow the typical pattern of simple web apps (as seen in just about all tutorials), I'm not using a generi...
With sqlalchemy how to dynamically bind to database engine on a per-request basis
I have a Pylons-based web application which connects via Sqlalchemy (v0.5) to a Postgres database. For security, rather than follow the typical pattern of simple web apps (as seen in just about all tutorials), I'm not using a generic Postgres user (e.g. "webapp") but am requiring that users enter their own Postgres us...
[ "Binding global objects (mappers, metadata) to user-specific connection is not good way. As well as using scoped session. I suggest to create new session for each request and configure it to use user-specific connections. The following sample assumes that you use separate metadata objects for each database:\nbinds ...
[ 4 ]
[ "I would look at the connection pooling and see if you can't find a way to have one pool per user.\nYou can dispose() the pool when the user's session has expired\n" ]
[ -1 ]
[ "postgresql", "pylons", "python", "sqlalchemy", "web_applications" ]
stackoverflow_0001857465_postgresql_pylons_python_sqlalchemy_web_applications.txt
Q: Properties dictionary for Events in the Google Wave Python API The Google Wave documentation contains the Robot Events, but doesn't list what values will be put into the properties dictionary. Is this documented anywhere? A: I had the same question and found some hints in the following Google group thread: http:...
Properties dictionary for Events in the Google Wave Python API
The Google Wave documentation contains the Robot Events, but doesn't list what values will be put into the properties dictionary. Is this documented anywhere?
[ "I had the same question and found some hints in the following Google group thread: http://groups.google.com/group/google-wave-api/browse_thread/thread/8d19dbcb6f2147cc\nFor now, I think the closest you can get to an answer to this question is Jason Salas' response: \"the good news is that you can look in the logs ...
[ 3, 0 ]
[]
[]
[ "events", "google_wave", "python" ]
stackoverflow_0001747986_events_google_wave_python.txt
Q: Bind different ip addresses to urllib2 object in seperate threads The following code binds specified ip address to socket in main program globally. import socket true_socket = socket.socket def bound_socket(*a, **k): sock = true_socket(*a, **k) sock.bind((sourceIP, 0)) return sock socket.socket = bound...
Bind different ip addresses to urllib2 object in seperate threads
The following code binds specified ip address to socket in main program globally. import socket true_socket = socket.socket def bound_socket(*a, **k): sock = true_socket(*a, **k) sock.bind((sourceIP, 0)) return sock socket.socket = bound_socket Suppose main program has 10 threads, each with a urllib2 insta...
[ "You can define a dictionary mapping thread identifier to IP address or use threading.local() global object to define it per thread:\nsocket_data = threading.local()\nsocket_data = bind_ip = None\n\ntrue_socket = socket.socket\n\ndef bound_socket(*a, **k):\n sock = true_socket(*a, **k)\n if socket_data.bind_i...
[ 1 ]
[]
[]
[ "ip_address", "python", "urllib2" ]
stackoverflow_0001858310_ip_address_python_urllib2.txt
Q: cat filename.* > Datei I'm looking to translate the unix-command $ cat filename.* > Datei into a Python program. Can somebody help ? A: Something like this should get you started: import glob outfile = file("Datei", "wb") for f in glob.glob("filename.*"): infile = open(f, "rb") outfile.write(infile.read())...
cat filename.* > Datei
I'm looking to translate the unix-command $ cat filename.* > Datei into a Python program. Can somebody help ?
[ "Something like this should get you started:\nimport glob\n\noutfile = file(\"Datei\", \"wb\")\nfor f in glob.glob(\"filename.*\"):\n infile = open(f, \"rb\")\n outfile.write(infile.read())\n infile.close()\noutfile.close()\n\nUPDATE: Of course, input files need to be opened, too.\nUPDATE: Explicitly use binary ...
[ 2, 1, 0, 0 ]
[]
[]
[ "cat", "python" ]
stackoverflow_0001818758_cat_python.txt
Q: How to pass items as args lists in map? This is a piece of my code. Lambda accepts 3 parameters, and I wanted to pass them as a tuple of positional arguments, but apparently map supplies them as a single argument. How can I supply those tuples in the bottom as lists of arguments? (I know I can rewrite the lambda, ...
How to pass items as args lists in map?
This is a piece of my code. Lambda accepts 3 parameters, and I wanted to pass them as a tuple of positional arguments, but apparently map supplies them as a single argument. How can I supply those tuples in the bottom as lists of arguments? (I know I can rewrite the lambda, but it will become not well readable) adds =...
[ "The map() description:\n\nmap(function, iterable, ...)\nApply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another ...
[ 5, 3, 3, 1 ]
[]
[]
[ "arguments", "map", "python" ]
stackoverflow_0001858720_arguments_map_python.txt
Q: Flexible numeric string parsing in Python Are there any Python libraries that help parse and validate numeric strings beyond what is supported by the built-in float() function? For example, in addition to simple numbers (1234.56) and scientific notation (3.2e15), I would like to be able to parse formats like: Num...
Flexible numeric string parsing in Python
Are there any Python libraries that help parse and validate numeric strings beyond what is supported by the built-in float() function? For example, in addition to simple numbers (1234.56) and scientific notation (3.2e15), I would like to be able to parse formats like: Numbers with commas: 2,147,483,647 Named large num...
[ "If you want to convert \"localized\" numbers such as the American \"2,147,483,647\" form, you can use the atof() function from the locale module. Example:\nimport locale\nlocale.setlocale(locale.LC_NUMERIC, 'en_US')\nprint locale.atof('1,234,456.23') # Prints 1234456.23\n\nAs for fractions, Python now handles th...
[ 6, 1, 0 ]
[ "I haven't heard of one. Do you know of any such library for any other languages? That way you could leverage their documentation and tests. \nIf you can't find one, write a bunch of testcases, then we can help you fill out the parsing code.\nGoogle must have one, try searching for 5.5billion * 10, but I don't thi...
[ -1 ]
[ "numbers", "parsing", "python", "validation" ]
stackoverflow_0001858117_numbers_parsing_python_validation.txt
Q: Creating portable Django apps - help needed I'm building a Django app, which I comfortably run (test :)) on a Ubuntu Linux host. I would like to package the app without source code and distribute it to another production machine. Ideally the app could be run by ./runapp command which starts a CherryPy server that ...
Creating portable Django apps - help needed
I'm building a Django app, which I comfortably run (test :)) on a Ubuntu Linux host. I would like to package the app without source code and distribute it to another production machine. Ideally the app could be run by ./runapp command which starts a CherryPy server that runs the python/django code. I've discovered seve...
[ "I suggest you base your distro on setuptools (a tool that enhances the standard Python distro mechanizm distutils).\nUsing setuptools, you should be able to create a Python egg containing your application. The egg's metadata can contain a list of dependencies that will be automatically installed by easy_install (c...
[ 7, 0 ]
[]
[]
[ "cherrypy", "django", "linux", "python", "software_distribution" ]
stackoverflow_0001858749_cherrypy_django_linux_python_software_distribution.txt
Q: What is a library that provides a very simple, universal usage of Naives Bayes classifier? I know that NLTK has this. But...is that only for NLP? Is there a library that specializes in classification? A: http://code.google.com/p/pybayes/ A: Reverend may be another nice option: http://divmod.org/trac/wiki/Divm...
What is a library that provides a very simple, universal usage of Naives Bayes classifier?
I know that NLTK has this. But...is that only for NLP? Is there a library that specializes in classification?
[ "http://code.google.com/p/pybayes/\n", "Reverend may be another nice option: http://divmod.org/trac/wiki/DivmodReverend\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001858447_python.txt
Q: Mark string as safe in Mako I'm using Pylons with Mako templates and I want to avoid typing this all the time: ${ h.some_function_that_outputs_html() | n } I want to somehow mark the function, or a variable as safe (you can do that in Django) so I don't have to pipe-en all the time. Any ideas? A: I just found ...
Mark string as safe in Mako
I'm using Pylons with Mako templates and I want to avoid typing this all the time: ${ h.some_function_that_outputs_html() | n } I want to somehow mark the function, or a variable as safe (you can do that in Django) so I don't have to pipe-en all the time. Any ideas?
[ "I just found out that if you put a html method in your class, then Mako will just call that method and output whatever it returns in the template.\nSo I did:\ndef __html__(self):\n return unicode(self)\n\nThat's basically what h.literal does.\n", "According to the mako docs about filtering, you can set the de...
[ 10, 3 ]
[]
[]
[ "mako", "pylons", "python" ]
stackoverflow_0001825343_mako_pylons_python.txt
Q: Need help understanding how this recursive function is working Here's a function (credit to user Abbot, for providing it in another question) def traverse(ftp): level = {} for entry in (path for path in ftp.nlst() if path not in ('.', '..')): ftp.cwd(entry) level[entry] = traverse(ftp) ...
Need help understanding how this recursive function is working
Here's a function (credit to user Abbot, for providing it in another question) def traverse(ftp): level = {} for entry in (path for path in ftp.nlst() if path not in ('.', '..')): ftp.cwd(entry) level[entry] = traverse(ftp) ftp.cwd('..') return level Here's what I don't understand...
[ "No. Every \"instance\" of the function has its own copy of level and there are no side effects between the various copies of level.\nTake this folder tree:\nroot\n `-home\n |- lyrae\n | |- ftp.py\n | `- http.py\n `- badp\n\nHere's the (simplified) execution flow when you call ftp on root:\n\nftp(ro...
[ 7, 2, 1, 1, 1 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0001860049_python_recursion.txt
Q: How do I get the remote user agent inside a Genshi template when using Trac, and WSGI? I'm trying to do some customization of a Trac project management website and have run into an interesting problem. The project has a set of images that are both SVG and PNG. The SVG images have numerous advantages including mu...
How do I get the remote user agent inside a Genshi template when using Trac, and WSGI?
I'm trying to do some customization of a Trac project management website and have run into an interesting problem. The project has a set of images that are both SVG and PNG. The SVG images have numerous advantages including multiple hyperlinks and a smaller transmitted size against PNG which is bigger and can only li...
[ "user_agent = environ.get('HTTP_USER_AGENT', None)\n\nOr if environ is wrapped in some sort of Request object:\nuser_agent = request.user_agent\n\nbtw, You should probably look at HTTP_ACCEPT header instead of HTTP_USER_AGENT to find out what representation should be sent.\n", "Okay, so I did some digging on the ...
[ 0, 0 ]
[]
[]
[ "genshi", "python", "trac", "wsgi" ]
stackoverflow_0001855576_genshi_python_trac_wsgi.txt
Q: Using AppEngine XMPP for Client Notifications I've been looking for a way to tell clients about expired objects and AppEngine's XMPP implementation seems really interesting because it's scalable, should be reliable and can contain up to 100kb of data. But as I understand it, before a client can listen to messages...
Using AppEngine XMPP for Client Notifications
I've been looking for a way to tell clients about expired objects and AppEngine's XMPP implementation seems really interesting because it's scalable, should be reliable and can contain up to 100kb of data. But as I understand it, before a client can listen to messages, he should have a gmail account. That's very impra...
[ "\nNo this isn't true: you can have the AppEngine robot as contact over any Jabber/XMPP based networks.\n\nUnless you are talking about the need for a GMAIL account to create an AppEngine robot... in which case YES you need to have a Google account.\n", "In that situation, I would perform ajax calls every 5 minut...
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "web_services", "xmpp" ]
stackoverflow_0001859634_google_app_engine_python_web_services_xmpp.txt
Q: How do I read binary C++ protobuf data using Python protobuf? The Python version of Google protobuf gives us only: SerializeAsString() Where as the C++ version gives us both: SerializeToArray(...) SerializeAsString() We're writing to our C++ file in binary format, and we'd like to keep it this way. That said, is...
How do I read binary C++ protobuf data using Python protobuf?
The Python version of Google protobuf gives us only: SerializeAsString() Where as the C++ version gives us both: SerializeToArray(...) SerializeAsString() We're writing to our C++ file in binary format, and we'd like to keep it this way. That said, is there a way of reading the binary data into Python and parsing it ...
[ "I'm not an expert with Python, but you can pass the result of a file.read() operation into message.ParseFromString(...) without having to build a new string type or anything.\n", "Python strings can contain any character, i.e. they are capable of holding \"binary\" data directly. There should be no need to conve...
[ 4, 4 ]
[]
[]
[ "c++", "protocol_buffers", "python" ]
stackoverflow_0001860187_c++_protocol_buffers_python.txt
Q: How do I distinguish "module not found" from "module threw exception" on ImportError? In Python, import does_not_exist raises ImportError, and import exists exists.py: import does_not_exist will also raise ImportError. How should I tell the difference in code? A: The only method I know is to check if the tople...
How do I distinguish "module not found" from "module threw exception" on ImportError?
In Python, import does_not_exist raises ImportError, and import exists exists.py: import does_not_exist will also raise ImportError. How should I tell the difference in code?
[ "The only method I know is to check if the toplevel modulename \"exists\" is in the Exception's message or not:\ntry:\n import exists\nexcept ImportError as exc:\n if \"exists\" in str(exc):\n pass\n else:\n raise\n\nCould this be a feature request for Python's ImportError? Having a variable for the modu...
[ 3, 2 ]
[]
[]
[ "importerror", "python" ]
stackoverflow_0001860363_importerror_python.txt
Q: Pygame sprite transformation with interpolation Im currently working on a Python/Pygame module to wrap some basic sprite animation. Animation in the sense that the image itself is static but I apply rotation and scale with start and end values with a sine wave interpolation. That is, sprite transformation like the...
Pygame sprite transformation with interpolation
Im currently working on a Python/Pygame module to wrap some basic sprite animation. Animation in the sense that the image itself is static but I apply rotation and scale with start and end values with a sine wave interpolation. That is, sprite transformation like the ones that could be made in Flash. I hope you underst...
[ "You can transform images by pygame.transform, but interpolation is not included in pygame. \nRabbyt provides animation including interpolation, even though I haven't used it.\n" ]
[ 1 ]
[]
[]
[ "animation", "interpolation", "pygame", "python", "sprite" ]
stackoverflow_0001859125_animation_interpolation_pygame_python_sprite.txt
Q: Object appended to a list instance appears in a different instance of that list I was writing this little piece of code as an exercise in object-oriented programming. Here I'm trying to define a house as a list of rooms and each room as a list of devices (lamps, for example). First I created all the objects and th...
Object appended to a list instance appears in a different instance of that list
I was writing this little piece of code as an exercise in object-oriented programming. Here I'm trying to define a house as a list of rooms and each room as a list of devices (lamps, for example). First I created all the objects and them appended the two rooms to the house and a different device to each room. Pretty ba...
[ "Default parameter values for functions are evaluated only once. This means that all instances of House will use the same list instance for self.rooms (if rooms parameter wasn't given in construction). In the same manner, all instances of Room will share the same list for self.devs.\nTo solve this, write the code l...
[ 9, 3, 0 ]
[]
[]
[ "arguments", "default", "mutable", "python" ]
stackoverflow_0001860737_arguments_default_mutable_python.txt
Q: Inheritance in Python Such That All Base Functions Are Called Basically, what I want is to do this: class B: def fn(self): print 'B' class A: def fn(self): print 'A' @extendInherit class C(A,B): pass c=C() c.fn() And have the output be A B How would I implement the extendInherit de...
Inheritance in Python Such That All Base Functions Are Called
Basically, what I want is to do this: class B: def fn(self): print 'B' class A: def fn(self): print 'A' @extendInherit class C(A,B): pass c=C() c.fn() And have the output be A B How would I implement the extendInherit decorator?
[ "This is not a job for decorators. You want to completely change the normal behaviour of a class, so this is actually a job for a metaclass.\nimport types\n\nclass CallAll(type):\n \"\"\" MetaClass that adds methods to call all superclass implementations \"\"\"\n def __new__(meta, clsname, bases, attrs):\n ...
[ 4, 1, 1 ]
[]
[]
[ "decorator", "inheritance", "multiple_inheritance", "python" ]
stackoverflow_0001859848_decorator_inheritance_multiple_inheritance_python.txt
Q: How would I call 32bit exes in Windows 64bit with python? I want to call a exe from python on a 64bit version of vista. I know to use subprocess, but all the 32bit apps are store in C:\Program Files (x86)\, and it doesn't like the spaces I believe. i have tried escape characters, doesn't fire, any ideas? A: tex...
How would I call 32bit exes in Windows 64bit with python?
I want to call a exe from python on a 64bit version of vista. I know to use subprocess, but all the 32bit apps are store in C:\Program Files (x86)\, and it doesn't like the spaces I believe. i have tried escape characters, doesn't fire, any ideas?
[ "textEditorExecutablePath = 'C:\\\\Program Files (x86)\\\\Notepad2\\\\Notepad2.exe'\nfilepathToOpen = 'C:\\\\file.txt'\nsubprocess.Popen([textEditorExecutablePath, filepathToOpen])\n\nWorks for me. How are you calling Popen?\n" ]
[ 1 ]
[]
[]
[ "32_bit", "64_bit", "python", "windows" ]
stackoverflow_0001861511_32_bit_64_bit_python_windows.txt
Q: Problem installing Shoutpy + Boost.python on opensolaris Im trying to install shoutpy on opensolaris 2009.6. It relies on boost.python. i've installed the boost_devel libraries from blastwave and linked /opt/csw/include/boost to /usr/include/boost . But when I try to easy_install shoutpy I get the following output...
Problem installing Shoutpy + Boost.python on opensolaris
Im trying to install shoutpy on opensolaris 2009.6. It relies on boost.python. i've installed the boost_devel libraries from blastwave and linked /opt/csw/include/boost to /usr/include/boost . But when I try to easy_install shoutpy I get the following output munderwo@opensolaris-test1:/usr/include$ pfexec easy_install ...
[ "Unfortunately I've never tried to compile shoutpy under OpenSolaris and I don't use it these days. Boost.python requires a lot from its C++ compiler. Use easy_install -b build_directory shoutpy so it'll keep the source code after it fails, then check the C++ compiler Python tries to use against those supported by ...
[ 0 ]
[]
[]
[ "boost", "boost_python", "opensolaris", "python" ]
stackoverflow_0001797110_boost_boost_python_opensolaris_python.txt
Q: Virtualenv: global site-packages vs the site-packages in the virtual environment If I have a certain package installed both in the global site-packages and in the local one, which package will get imported? Will that even work or will I get an error? Which packages should I put in the global site-packages and whic...
Virtualenv: global site-packages vs the site-packages in the virtual environment
If I have a certain package installed both in the global site-packages and in the local one, which package will get imported? Will that even work or will I get an error? Which packages should I put in the global site-packages and which in the local one?
[ "The previous answer wraps up question 1 but ignores question 2.\nThe general best practice I've seen for which packages to put globally: \nFirst, the core Python packages, as these don't change with backwards-incompatible issues unless you're upgrading a major version, and you'll want whatever security fixes from ...
[ 9, 3 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0001860348_python_virtualenv.txt
Q: Python IO Gurus: what are the differences between these two methods? I have two methods for writing binary files: the first works with data received by a server corresponding to a file upload (i.e., handling a form whose enctype="multipart/form-data"), and the second works with file data sent as email attachments ...
Python IO Gurus: what are the differences between these two methods?
I have two methods for writing binary files: the first works with data received by a server corresponding to a file upload (i.e., handling a form whose enctype="multipart/form-data"), and the second works with file data sent as email attachments (i.e., file data obtained by parsing an email message message body using g...
[ "The difference is that the HTTP upload method (the first one) - receives as its parameters the file-like object itself (the \"f\" variable) and creates a CGI module specific \"read_buffer\" to read data in chunks from that file object to copy them to the actual file. \nThsi can make sense in an http upload applic...
[ 2, 1, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0001861651_file_io_python.txt
Q: rdflib graph not updated. Why? I am trying to understand this behavior. It's definitely not what I expect. I have two programs, one reader, and one writer. The reader opens a RDFlib graph store, then performs a query every 2 seconds import rdflib import random from rdflib import store import time default_graph_ur...
rdflib graph not updated. Why?
I am trying to understand this behavior. It's definitely not what I expect. I have two programs, one reader, and one writer. The reader opens a RDFlib graph store, then performs a query every 2 seconds import rdflib import random from rdflib import store import time default_graph_uri = "urn:uuid:a19f9b78-cc43-4866-b9a...
[ "One easy fix is to put \"graph.commit()\" just after the line \"graph = rdflib.ConjunctiveGraph(...)\" in reader.\nI'm not sure what's the cause and why commiting before read fixes this. I'm guessing that:\n\nWhen opening MySQLdb connection, a transaction is started automatically\nThis transaction doesn't see upda...
[ 3 ]
[]
[]
[ "python", "rdf", "rdflib" ]
stackoverflow_0001860282_python_rdf_rdflib.txt
Q: build python program with extensions using py2exe I'm having a hard time finding py2exe recipes, especially for cases that require c extensions. The following recipe works fine without the "ext_modules" part. With it I get "NameError: name 'Extension' is not defined. from distutils.core import setup import py2e...
build python program with extensions using py2exe
I'm having a hard time finding py2exe recipes, especially for cases that require c extensions. The following recipe works fine without the "ext_modules" part. With it I get "NameError: name 'Extension' is not defined. from distutils.core import setup import py2exe import matplotlib import os s = os.popen('svnversio...
[ "After fixing the small error created by forgetting to import Extension, I ran into other errors stating a problem with the -lsqlite3 flag. Turns out I needed to follow the steps outlined here: http://cboard.cprogramming.com/cplusplus-programming/82135-sqlite-questions.html\n\nDownload sqlitedll-3_3_7.zip and sqli...
[ 1, 0 ]
[]
[]
[ "c", "py2exe", "python", "recipe" ]
stackoverflow_0001848275_c_py2exe_python_recipe.txt
Q: Django search capabilities Is there a easy way to add a search capability on fields in Django? Also please let me know what is Lucene search. A: Try Haystack. It's pretty easy to setup. Apache Lucene is full-text search engine written in Java. A: I would use Haystack as mentioned above together with Xapian. Xa...
Django search capabilities
Is there a easy way to add a search capability on fields in Django? Also please let me know what is Lucene search.
[ "\nTry Haystack. It's pretty easy to setup.\nApache Lucene is full-text search engine written in Java.\n\n", "I would use Haystack as mentioned above together with Xapian.\nXapian doesn't require you to run it as a process (which is some sort of advantage in my opinion).\n", "I second the Haystack suggestion. H...
[ 6, 2, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001859866_django_python.txt
Q: How to use Emacs with Python I am new to emacs and I want to use emacs for python development. I am using Ubuntu 9.10. I frustrated to getting emacs work with python. I use GNU Emacs 23.1.50.1 (x86_64-pc-linux-gnu, GTK+ Version 2.18.0). Here what I did. * Emacs come with python mode but it is confusing there are ...
How to use Emacs with Python
I am new to emacs and I want to use emacs for python development. I am using Ubuntu 9.10. I frustrated to getting emacs work with python. I use GNU Emacs 23.1.50.1 (x86_64-pc-linux-gnu, GTK+ Version 2.18.0). Here what I did. * Emacs come with python mode but it is confusing there are two types of mode one is python-mo...
[ "I haven't tried anything, and I haven't had much luck with rope (giant source tree causes my emacs to hang upon any file save). Instead, I find the default completion works well enough for my purposes.\nThe default completion keybinding is M-/. That runs dabbrev-expand which expands the current word to \"the mos...
[ 3, 2, 0, 0 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0001862901_emacs_python.txt
Q: Text extraction from email in Python My users will send me posts by email ala Posterous I'm using Google Apps Engine (GAE) to receive and parse emails. GAE returns the text part of the message. I need to extract the post from the plain text part of the message. The plain text can be "contaminated" with promotional...
Text extraction from email in Python
My users will send me posts by email ala Posterous I'm using Google Apps Engine (GAE) to receive and parse emails. GAE returns the text part of the message. I need to extract the post from the plain text part of the message. The plain text can be "contaminated" with promotional headers, footers, signatures, etc. Also I...
[ "I would go with a list of compiled regular expressions. Something along the lines of: \nimport re\n\nregexes = (\n re.compile(\"visit my blog at: .*$\", re.IGNORECASE),\n re.compile(\"please post this:\", re.IGNORECASE),\n re.compile(\"please can you include this:\", re.IGNORECASE)\n # etc\n)\n\nfor fi...
[ 2 ]
[]
[]
[ "email", "google_app_engine", "python", "regex" ]
stackoverflow_0001860375_email_google_app_engine_python_regex.txt
Q: Python elevator simulation problem I have a homework assignment that's really baking my noodle. It involves an elevator simulation that takes user inputs for the number of floors and the number of people using the elevator. the people's starting floor and destination floors are random numbers within the floors. ...
Python elevator simulation problem
I have a homework assignment that's really baking my noodle. It involves an elevator simulation that takes user inputs for the number of floors and the number of people using the elevator. the people's starting floor and destination floors are random numbers within the floors. I realize that my code is very sparse an...
[ "\nYou need to understand the self\nparameter to all methods.\nYou need to understand __init__,\nthe constructor.\nYou need to understand self.varible\nfor your member variables.\nYou need to understand how to setup a\nmain function.\nYou need to understand how to\nreturn a value from a function or\nmethod.\nYou ne...
[ 7, 3, 1, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0001863303_oop_python.txt
Q: Problem with import curses.ascii I am trying from curses.ascii import * to django project, but I get: No module named _curses, I am using Python 2.5, any suggestion? Anyway I only need isalpha() function to use.... A: You didn't say which platform you are on, but there is probably a package which will install th...
Problem with import curses.ascii
I am trying from curses.ascii import * to django project, but I get: No module named _curses, I am using Python 2.5, any suggestion? Anyway I only need isalpha() function to use....
[ "You didn't say which platform you are on, but there is probably a package which will install the curses bindings for you.\nIn debian/ubuntu for example it is part of the default python install\nIf you built the Python yourself, you may be missing the libcurses-dev\nIf you are on windows maybe check out this wcurse...
[ 3 ]
[]
[]
[ "curses", "django", "python", "windows" ]
stackoverflow_0001863473_curses_django_python_windows.txt
Q: Python: How do I read and parse a unicode utf-8 text file? I am exporting UTF-8 text from Excel and I want to read and parse the incoming data using Python. I've read all the online info so I've already tried this, for example: txtFile = codecs.open( 'halout.txt', 'r', 'utf-8' ) for line in txtFile: print repr...
Python: How do I read and parse a unicode utf-8 text file?
I am exporting UTF-8 text from Excel and I want to read and parse the incoming data using Python. I've read all the online info so I've already tried this, for example: txtFile = codecs.open( 'halout.txt', 'r', 'utf-8' ) for line in txtFile: print repr( line ) The error I am getting is: UnicodeDecodeError: 'utf8'...
[ "That file is not UTF-8; it's UTF-16LE with a byte-order marker.\n", "That is a BOM\nEDIT, from the coments, it seems to be a utf-16 bom\ncodecs.open('foo.txt', 'r', 'utf-16')\n\nshould work.\n", "Expanding on Johnathan's comment, this code should read the file correctly:\nimport codecs\ntxtFile = codecs.open( ...
[ 5, 2, 2, 0 ]
[]
[]
[ "codec", "parsing", "python", "unicode", "xml" ]
stackoverflow_0001862963_codec_parsing_python_unicode_xml.txt
Q: Matplotlib's GUI doesn't allow typing in save box? I've been using matplotlib in python for some time now and I've finally gotten around to asking this question about an issue on my mac. When a plot shows up (after the plot() command, draw(), or show()), I have all the functionality I could want; I can move, zoom,...
Matplotlib's GUI doesn't allow typing in save box?
I've been using matplotlib in python for some time now and I've finally gotten around to asking this question about an issue on my mac. When a plot shows up (after the plot() command, draw(), or show()), I have all the functionality I could want; I can move, zoom, etc. that I didn't do in the code. When I go to save a ...
[ "Just installed matplotlib 0.99.1 on Python 2.6.2 on Snow Leopard and ran the following code:\nfrom pylab import *\nplot([1,2,3])\nshow()\n\nThen, I fiddled around with the plot for a while and clicked the save button. The save dialog box popped up normally and allowed me to save (and type) fine. This was using the...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0000644812_matplotlib_python.txt
Q: grep -r in python i'd like to implement the unix command 'grep -r' in a python function. i know about commands.getstatusoutput(), but for now i don't want to use that. i came up with this: def grep_r (str, dir): files = [ o[0]+"/"+f for o in os.walk(dir) for f in o[2] if os.path.isfile(o[0]+"/"+f) ] retu...
grep -r in python
i'd like to implement the unix command 'grep -r' in a python function. i know about commands.getstatusoutput(), but for now i don't want to use that. i came up with this: def grep_r (str, dir): files = [ o[0]+"/"+f for o in os.walk(dir) for f in o[2] if os.path.isfile(o[0]+"/"+f) ] return [ l for f in files f...
[ "You might want to search() instead of match() to catch matches in the middle of lines, as noted in http://docs.python.org/library/re.html#matching-vs-searching\nAlso, the structure and intent of your code is quite hidden. I've pythonized it.\ndef grep_r (pattern, dir):\n r = re.compile(pattern)\n for parent,...
[ 9, 6, 3, 2, 1 ]
[]
[]
[ "grep", "python" ]
stackoverflow_0001863236_grep_python.txt
Q: Python after Ruby on Rails I have been working with Ruby on Rails for over a year now and have been offered some development work with Python. I would like know if development with Python is as enjoyable as Ruby in terms of the clarity and ease of use. And how well is Python suited for Web development. I've heard ...
Python after Ruby on Rails
I have been working with Ruby on Rails for over a year now and have been offered some development work with Python. I would like know if development with Python is as enjoyable as Ruby in terms of the clarity and ease of use. And how well is Python suited for Web development. I've heard of Pylons being a direct port of...
[ "Django is one of the most famous. It follows a different approach to web devlopment then ruby does, but it is just as powerful and feature rich. An example website running Django is lawrence.com\nPylons is another popular one, I don't know why you heard it was a Rails clone, because it is not. It is a lightweight ...
[ 5, 3, 3, 3, 1 ]
[]
[]
[ "pylons", "python", "ruby_on_rails" ]
stackoverflow_0001834829_pylons_python_ruby_on_rails.txt
Q: Strip final 0 off a python string #!/usr/bin/env python import os, sys, subprocess, time while True: print subprocess.call("xsel", shell=True); time.sleep(1); Takes an entry from the clipboard and prints it, every 1 second. Result: copied0 entry0 from0 clipboard0 I do not know why it returns the fina...
Strip final 0 off a python string
#!/usr/bin/env python import os, sys, subprocess, time while True: print subprocess.call("xsel", shell=True); time.sleep(1); Takes an entry from the clipboard and prints it, every 1 second. Result: copied0 entry0 from0 clipboard0 I do not know why it returns the final 0, but it apparently stops me from us...
[ "Edit: subprocess.call isn't returning a string, but an int -- that 0 you're seeing (after xsel's actual output). Use, instead:\nprint subprocess.Popen('xsel', stdout=subprocess.PIPE).communicate()[0]\n\n", "As Mark pointed out, subprocess.call() does not do what you want\nSomething like this should work\n#!/usr...
[ 4, 4, 2, 2, 2, 1 ]
[]
[]
[ "integer", "popen", "python", "string", "subprocess" ]
stackoverflow_0001864613_integer_popen_python_string_subprocess.txt
Q: Re-format items inside list read from CSV file in Python I have some lines in a CSV file like this: 1000001234,Account Name,0,0,"3,711.32",0,0,"18,629.64","22,340.96",COD,"20,000.00",Some string,Some string 2 If you notice, some numbers are enclosed in " " and has a thousand separator ",". I want to remove the th...
Re-format items inside list read from CSV file in Python
I have some lines in a CSV file like this: 1000001234,Account Name,0,0,"3,711.32",0,0,"18,629.64","22,340.96",COD,"20,000.00",Some string,Some string 2 If you notice, some numbers are enclosed in " " and has a thousand separator ",". I want to remove the thousand separator and the double quote enclosure. For the qoute...
[ "You could simply parse the CSV, make the necessary changes and then write it again.\n(I haven't tested this code but it should be something like this)\nimport csv\nreader = csv.reader(open('IN.csv', 'r'))\nwriter = csv.writer(open('OUT.csv', 'w')\nfor row in reader:\n # do stuff to the row here\n # row is just a l...
[ 2, 2, 1, 1, 1, 1 ]
[]
[]
[ "csv", "delimiter", "parsing", "python", "replace" ]
stackoverflow_0001864422_csv_delimiter_parsing_python_replace.txt
Q: Convert UTF-8 octets to unicode code points I have a set of UTF-8 octets and I need to convert them back to unicode code points. How can I do this in python. e.g. UTF-8 octet ['0xc5','0x81'] should be converted to 0x141 codepoint. A: Python 3.x: In Python 3.x, str is the class for Unicode text, and bytes is for...
Convert UTF-8 octets to unicode code points
I have a set of UTF-8 octets and I need to convert them back to unicode code points. How can I do this in python. e.g. UTF-8 octet ['0xc5','0x81'] should be converted to 0x141 codepoint.
[ "Python 3.x:\nIn Python 3.x, str is the class for Unicode text, and bytes is for containing octets.\nIf by \"octets\" you really mean strings in the form '0xc5' (rather than '\\xc5') you can convert to bytes like this:\n>>> bytes(int(x,0) for x in ['0xc5', '0x81'])\nb'\\xc5\\x81'\n\nYou can then convert to str (ie:...
[ 16, 6, 3, 1 ]
[]
[]
[ "python", "unicode", "utf_8" ]
stackoverflow_0001864701_python_unicode_utf_8.txt
Q: running a method within another method. python I am calling a method within another. and the error for this script i am getting is NameError: name 'mnDialog' is not defined Is there a reason for it? I think it has something to do with executing a command which isn't on the global level. (i didn't have the impres...
running a method within another method. python
I am calling a method within another. and the error for this script i am getting is NameError: name 'mnDialog' is not defined Is there a reason for it? I think it has something to do with executing a command which isn't on the global level. (i didn't have the impression that python has a global and local variable dec...
[ "The problem is that the mnDialog is not being looked up from mnMakeWin, you are passing the name and it gets looked up later when you are not in the correct scope.\nIt may work to pass the function in instead of the name. I don't have maya installed, so I can't try it.\nOtherwise you'll have to define mnDialog in ...
[ 2, 1, 1, 0 ]
[]
[]
[ "command", "maya", "methods", "python" ]
stackoverflow_0001862945_command_maya_methods_python.txt
Q: Showing processing message in Python I want to show the processing information or log in the original page when the submitted request is being served until it completes the execution. I thought it would be meaningful to the user to know what is happening behind the request. I don't find a clue to do so though, can...
Showing processing message in Python
I want to show the processing information or log in the original page when the submitted request is being served until it completes the execution. I thought it would be meaningful to the user to know what is happening behind the request. I don't find a clue to do so though, can you guys help me out as how people are do...
[ "there are two ways i could imagine handling this:\n\nhave your backend script (python) output the information of a long process to a log of some sort (text file, database, session, etc...) and then have javascript grab the information via ajax and update the current page.\nsame deal, but instead of ajax just have ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000308220_python.txt
Q: Display data from a table using Django Can someone please give me a small piece of code where we display data from a table and point me to code that goes into views.py and templates/index.html to display the table of contents? A: Read the Django tutorial. It shows, in 4 parts, the basics of this framework. As f...
Display data from a table using Django
Can someone please give me a small piece of code where we display data from a table and point me to code that goes into views.py and templates/index.html to display the table of contents?
[ "Read the Django tutorial. It shows, in 4 parts, the basics of this framework. \nAs for your question, a very quick example.\nIn views.py:\ndef display(request):\n return render_to_response('template.tmpl', {'obj': models.Book.objects.all()})\n\nIn models.py:\nclass Book(models.Model):\n author = models.CharField...
[ 10 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001865479_django_python.txt
Q: Search a file for a string, and execute a function if string not found; in python def checkCache(cachedText): for line in open("cache"): if cachedText + ":" in line: print line open("cache").close() else: requestDefinition(cachedText) This code searches each...
Search a file for a string, and execute a function if string not found; in python
def checkCache(cachedText): for line in open("cache"): if cachedText + ":" in line: print line open("cache").close() else: requestDefinition(cachedText) This code searches each line of a file (cache) for a specific string (cachedText + ":"). If it does not find ...
[ "your for loop is broken. you are actually checking each line of the file and executing the function for each line which does not match.\nnote also that calling open(\"cache\").close() will reopen the cache file and close it immediately, without closing the handle which was open at the beginning of the for loop.\no...
[ 2, 1, 1 ]
[]
[]
[ "caching", "file", "python", "search", "string" ]
stackoverflow_0001865484_caching_file_python_search_string.txt
Q: What does first argument to `type` do? Some code. In [1]: A = type('B', (), {}) In [2]: a = A() In [3]: b = B() --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/shabda/<ipython console> in <module>() Na...
What does first argument to `type` do?
Some code. In [1]: A = type('B', (), {}) In [2]: a = A() In [3]: b = B() --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/shabda/<ipython console> in <module>() NameError: name 'B' is not defined What does ...
[ "It's setting the __name__ property of the created class.\nWhen you say:\nclass B(object):\n\ntwo things happen with that 'B':\n\nThe name 'B' is assigned the class. This is just like if you'd said \"B = ...\".\nThe __name__ property of the class is set to 'B'.\n\nWhen you invoke the type constructor manually only ...
[ 2, 0, 0 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0001865250_metaprogramming_python.txt
Q: How to use time > year 2038 on official Windows Python 2.5 The official Python 2.5 on Windows was build with Visual Studio.Net 2003, which uses 32 bit time_t. So when the year is > 2038, it just gives exceptions. Although this is fixed in Python 2.6 (which changed time_t to 64 bit with VS2008), I'd like to use 2.5...
How to use time > year 2038 on official Windows Python 2.5
The official Python 2.5 on Windows was build with Visual Studio.Net 2003, which uses 32 bit time_t. So when the year is > 2038, it just gives exceptions. Although this is fixed in Python 2.6 (which changed time_t to 64 bit with VS2008), I'd like to use 2.5 because many modules are already compiled for it. So here's my ...
[ "The datetime module in the standard library should work fine for you. What do you need from module time that datetime doesn't offer?\n", "I don't mean to sound trite, but why not:\n\nforget about the Y2038 bug with Python 2.5\nupgrade to Python 2.6 at some point in the future before 2038\n\nedit:\nTo clarify: (...
[ 7, 7, 4 ]
[]
[]
[ "python", "python_2.5", "time", "time_t", "year2038" ]
stackoverflow_0000839755_python_python_2.5_time_time_t_year2038.txt
Q: Working with bit streams I have a base64 encoded bit stream, I want to work with. After decoding it with base64.b64decode I get a bytes object (Py3k btw) containing the decoded code. The problem is now, that I would like to work on that bytes object with bit-wise operations, such as shifting, bit wise and etc, but...
Working with bit streams
I have a base64 encoded bit stream, I want to work with. After decoding it with base64.b64decode I get a bytes object (Py3k btw) containing the decoded code. The problem is now, that I would like to work on that bytes object with bit-wise operations, such as shifting, bit wise and etc, but that is not possible as it is...
[ "try using\nlist(bytestring)\n\nEg.\n>>> bstring=b\"Hello World\"\n>>> list( bstring)\n[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]\n>>> \n\nIf you want one huge bitfield instead of all those octets\n>>> from functools import reduce\n>>> reduce(lambda x,y:(x<<8)+y,list(b\"Hello World\"))\n875216180888825337...
[ 4, 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001863571_python_python_3.x.txt
Q: How do I mimic browser back arrow in my application page? request.path gives me the clicked url. I need a return link on that page which on clicking, should return to Referrer page, just as it would happen in case of browser back arrow . I do not maintain any session and do not want to hardcode the referrer page ...
How do I mimic browser back arrow in my application page?
request.path gives me the clicked url. I need a return link on that page which on clicking, should return to Referrer page, just as it would happen in case of browser back arrow . I do not maintain any session and do not want to hardcode the referrer page url.
[ "history.go(-1)\nhttp://www.devguru.com/Technologies/Ecmascript/Quickref/history_go.html\n", "How about trying Javascript instead?\n <a href=\"#\" onclick=\"history.go(-1);\">Go back</a>\n\n", "You can do so using Javascript:\n<span onclick='javascript: history.back()'>Previous page</span>\n\n" ]
[ 5, 1, 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0001865981_django_html_python.txt
Q: Which Python language rule allows the descriptor to be found first? I bumped into the following last night and I'm still at a loss as to explain it: class Foo(object): @property def dave(self): vars(self)['dave'] = 1 return 2 f = Foo() print f.dave print f.dave Running this code produces:...
Which Python language rule allows the descriptor to be found first?
I bumped into the following last night and I'm still at a loss as to explain it: class Foo(object): @property def dave(self): vars(self)['dave'] = 1 return 2 f = Foo() print f.dave print f.dave Running this code produces: 2 2 The question is why? My understanding of attribute access is that t...
[ "\nMy understanding of attribute access is that the instance dictionary is checked before the class dictionary, and the dictionary of any bases\n\nData descriptors are an exception:\n\nFor instance bindings, the precedence of descriptor invocation depends on the which descriptor methods are defined. Normally, data ...
[ 5 ]
[]
[]
[ "python", "rules" ]
stackoverflow_0001865902_python_rules.txt
Q: Unit Testing File Modifications A common task in programs I've been working on lately is modifying a text file in some way. (Hey, I'm on Linux. Everything's a file. And I do large-scale system admin.) But the file the code modifies may not exist on my desktop box. And I probably don't want to modify it if it IS on...
Unit Testing File Modifications
A common task in programs I've been working on lately is modifying a text file in some way. (Hey, I'm on Linux. Everything's a file. And I do large-scale system admin.) But the file the code modifies may not exist on my desktop box. And I probably don't want to modify it if it IS on my desktop. I've read about unit tes...
[ "You're talking about testing too much at once. If you start trying to attack a testing problem by saying \"Let's verify that it modifies its environment correctly\", you're doomed to failure. Environments have dozens, maybe even millions of potential variations.\nInstead, look at the pieces (\"units\") of your p...
[ 16, 7, 3, 2, 1, 1 ]
[]
[]
[ "linux", "python", "unit_testing" ]
stackoverflow_0000106766_linux_python_unit_testing.txt
Q: How to create a .py file for Google App Engine? I am just at the very start of what I think is gonna be a long journey exploring the world of applications in Google App Engine using Python. I have just downloaded Python 2.6.4 from the Python official website and installed it on my computer (I am using Windows XP)...
How to create a .py file for Google App Engine?
I am just at the very start of what I think is gonna be a long journey exploring the world of applications in Google App Engine using Python. I have just downloaded Python 2.6.4 from the Python official website and installed it on my computer (I am using Windows XP). I also downloaded the App Engine Python software de...
[ "When you downloaded and installed Python, you also installed IDLE. You can use this to easily write, run, debug and save .py files with syntax highlighting. To get started, just open IDLE, and select File -> New Window.\n", "A .py file is a text file containing Python syntax. Use your favourite programming ed...
[ 3, 2, 1, 1, 1 ]
[]
[]
[ "file", "google_app_engine", "makefile", "python" ]
stackoverflow_0001866147_file_google_app_engine_makefile_python.txt
Q: Syntax Error exec-ing python code from database I'm loading some python code from a database (it's doing dynamic mapping of values that I can change at runtime without a code redeploy). In my code, I'm doing this to execute the database code: if lMapping: print lMapping exec lMapping lValue = mapping(lValue,...
Syntax Error exec-ing python code from database
I'm loading some python code from a database (it's doing dynamic mapping of values that I can change at runtime without a code redeploy). In my code, I'm doing this to execute the database code: if lMapping: print lMapping exec lMapping lValue = mapping(lValue, lCsvRow) and here's the value of lMapping: def mapp...
[ "Do you BLOB or other binary type column to store code? Otherwise database might change line endings and exec will break with SyntaxError:\n>>> s='''\\\n... print 'ok'\n... '''\n>>> s\n\"print 'ok'\\n\"\n>>> exec s\nok\n>>> exec s.replace('\\n', '\\r\\n')\nTraceback (most recent call last):\n File \"<stdin>\", lin...
[ 1 ]
[]
[]
[ "exec", "python" ]
stackoverflow_0001866439_exec_python.txt
Q: How to design an application in a modular way? I am looking for pointers, suggestions, links, warnings, ideas and even anecdotical accounts about "how to design an application in a modular way". I am going to use python for this project, but advice does not need to necessarily refer to this language, although I am...
How to design an application in a modular way?
I am looking for pointers, suggestions, links, warnings, ideas and even anecdotical accounts about "how to design an application in a modular way". I am going to use python for this project, but advice does not need to necessarily refer to this language, although I am only willing to implement a design based on OOP. He...
[ "Try to keep things loosely coupled, and use interfaces liberally to help.\nI'd start the design with the Separation of Concerns. The major architectural layers are:\n\nProblem Domain (aka. Engine, Back-end): the domain classes, which do all the actual work, have domain knowledge implement domain behaviour\nPersis...
[ 13, 9, 2, 1, 1 ]
[]
[]
[ "design_patterns", "modularity", "oop", "python", "software_design" ]
stackoverflow_0001865727_design_patterns_modularity_oop_python_software_design.txt
Q: Authenticate imaplib.IMAP4_SSL against an Exchange imap server with AUTH=NTLM Yesterday, the IT department made changes to the Exchange server. I was previously able to use imaplib to fetch messages from the server. But now it seems they have turned off the authentication mechanism I was using. From the output bel...
Authenticate imaplib.IMAP4_SSL against an Exchange imap server with AUTH=NTLM
Yesterday, the IT department made changes to the Exchange server. I was previously able to use imaplib to fetch messages from the server. But now it seems they have turned off the authentication mechanism I was using. From the output below, it looks as if the server now supports NTLM authentication only. >>> from ima...
[ "I was able to use the python-ntlm project. \npython-ntlm implements NTLM authentication for HTTP. It was easy to add NTLM authentication for IMAP by extending this project.\nI submitted a patch for the project with my additions.\n" ]
[ 4 ]
[]
[]
[ "exchange_server", "imap", "ntlm", "python" ]
stackoverflow_0001866460_exchange_server_imap_ntlm_python.txt
Q: Python reference problem I'm experiencing a (for me) very weird problem in Python. I have a class called Menu: (snippet) class Menu: """Shows a menu with the defined items""" menu_items = {} characters = map(chr, range(97, 123)) def __init__(self, menu_items): self.init_menu(menu_items) ...
Python reference problem
I'm experiencing a (for me) very weird problem in Python. I have a class called Menu: (snippet) class Menu: """Shows a menu with the defined items""" menu_items = {} characters = map(chr, range(97, 123)) def __init__(self, menu_items): self.init_menu(menu_items) def init_menu(self, menu_it...
[ "The menu_items dict is a class attribute that's shared between all Menu instances. Initialize it like this instead, and you should be fine:\nclass Menu:\n \"\"\"Shows a menu with the defined items\"\"\"\n characters = map(chr, range(97, 123))\n\n def __init__(self, menu_items):\n self.menu_items =...
[ 16, 5 ]
[]
[]
[ "python", "reference" ]
stackoverflow_0001867068_python_reference.txt
Q: Insert python variables into SQLITE DB from another cursor object Using an example from the Python DOCs: stocks = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ]: for t in stocks c.execute('inse...
Insert python variables into SQLITE DB from another cursor object
Using an example from the Python DOCs: stocks = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ]: for t in stocks c.execute('insert into stocks values (?,?,?,?,?)', t) In my code, the stocks from abo...
[ "Tuples are immutable, but you can easily extract their contents and form new tuples. Also, I'm not sure, but I don't think the execute() call absolutely must have a tuple. Can't any sequence, including lists, work as well?\nAnyway, here's what you need:\nfor t in stocks:\n c.execute('insert into stock values ...
[ 1, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0001867018_python_sqlite.txt
Q: Mechanize submit login form from http to https I have a web page containing a login form which loads via HTTP, but it submits the data via HTTPS. I'm using python-mechanize to log into this site, but it seems that the data is submitted via HTTP. My code is looks like this: import mechanize b = mechanize.Browser()...
Mechanize submit login form from http to https
I have a web page containing a login form which loads via HTTP, but it submits the data via HTTPS. I'm using python-mechanize to log into this site, but it seems that the data is submitted via HTTP. My code is looks like this: import mechanize b = mechanize.Browser() b.open('http://site.com') form = b.forms().next() ...
[ "mechanize uses urllib2 internally and the later had a bug: HTTPS over (Squid) Proxy fails. The bug is fixed in Python 2.6.3, so updating Python should solve your problem.\n", "Ok, it seems to be a bug in mechanize\nhttp://sourceforge.net/mailarchive/forum.php?thread_name=alpine.DEB.2.00.0910062211230.8646%40alic...
[ 2, 1 ]
[]
[]
[ "forms", "https", "mechanize", "post", "python" ]
stackoverflow_0001866888_forms_https_mechanize_post_python.txt
Q: How should I organise my functions with pyparsing? I am parsing a file with python and pyparsing (it's the report file for PSAT in Matlab but that isn't important). here is what I have so far. I think it's a mess and would like some advice on how to improve it. Specifically, how should I organise my grammar defini...
How should I organise my functions with pyparsing?
I am parsing a file with python and pyparsing (it's the report file for PSAT in Matlab but that isn't important). here is what I have so far. I think it's a mess and would like some advice on how to improve it. Specifically, how should I organise my grammar definitions with pyparsing? Should I have all my grammar defi...
[ "I could go either way on using a single big method to create your parser vs. taking it in steps the way you have it now.\nI can see that you have defined some useful helper utilities, such as slit (\"suppress Literal\", I presume), stringtolits, and decimaltable. This looks good to me.\nI like that you are using ...
[ 2 ]
[]
[]
[ "coding_style", "pyparsing", "python", "refactoring" ]
stackoverflow_0001866329_coding_style_pyparsing_python_refactoring.txt
Q: Simple Automatic Classification of the (R-->R) Functions Given data values of some real-time physical process (e.g. network traffic) it is to find a name of the function which "at best" matches with the data. I have a set of functions of type y=f(t) where y and t are real: funcs = set([cos, tan, exp, log]) and ...
Simple Automatic Classification of the (R-->R) Functions
Given data values of some real-time physical process (e.g. network traffic) it is to find a name of the function which "at best" matches with the data. I have a set of functions of type y=f(t) where y and t are real: funcs = set([cos, tan, exp, log]) and a list of data values: vals = [59874.141, 192754.791, 342413.3...
[ "Just write the error ( quadratic sum of error at each point for instance ) for each function of the set and choose the function giving the minimum.\nBut you should still fit each function before choosing\n", "Scipy has functions for fitting data, but they use polynomes or splines. You can use one of Gauß' many d...
[ 2, 1, 1, 0 ]
[]
[]
[ "algorithm", "function", "math", "python" ]
stackoverflow_0001866862_algorithm_function_math_python.txt
Q: Python Selector (URL routing library), experience/opinions? Does anyone have opinions about or experience with Python Selector? It looks great, but I'm a bit put off by its "Alpha" status on pypi and lack of unit tests. I mostly like that its simple, self contained, and pure WSGI. All other url routers I've foun...
Python Selector (URL routing library), experience/opinions?
Does anyone have opinions about or experience with Python Selector? It looks great, but I'm a bit put off by its "Alpha" status on pypi and lack of unit tests. I mostly like that its simple, self contained, and pure WSGI. All other url routers I've found assume I'm using django, or pylons, or paste, or pull in lots o...
[ "I've used Selector for the last couple years and found it perfectly stable. It's been at 0.8.11 for at least two years now. \nI would draw two conclusions from that: \n\nIt could be basically unmaintained. If you find a bug in it or need a new feature, I wouldn't count on being able to get Luke Arno to jump up and...
[ 8, 6 ]
[]
[]
[ "python", "selector", "url_routing", "wsgi" ]
stackoverflow_0001864393_python_selector_url_routing_wsgi.txt
Q: What is "Python interpreter None"? I just created my first application for Google App Engines, which is called "Hello World". It was the first lesson from Google App Engines How-to-get-started tutorial. I tested it on my computer (I am using Windows XP), and it was working just fine - whenever I would open a new w...
What is "Python interpreter None"?
I just created my first application for Google App Engines, which is called "Hello World". It was the first lesson from Google App Engines How-to-get-started tutorial. I tested it on my computer (I am using Windows XP), and it was working just fine - whenever I would open a new window with my web browser (FireFox), I w...
[ "Well, it is basically saying that it cannot find your just installed python interpreter.\nIt looks like you are on Windows so check your environment variables, particularly PATH and PYTHONPATH, they are probably still pointing to the previous 2.6 installation folder.\n", "You need to set the python interpreter i...
[ 3, 1 ]
[]
[]
[ "app_launcher", "google_app_engine", "python" ]
stackoverflow_0001867657_app_launcher_google_app_engine_python.txt
Q: Django to use different settings.py file based on subdomains How can Django use different settings.py file based on subdomains. Can these utilities ("django-admin", "python manage.py") still be used if there were different settings connecting to different databases. A: ok you have two dimensions you need to cov...
Django to use different settings.py file based on subdomains
How can Django use different settings.py file based on subdomains. Can these utilities ("django-admin", "python manage.py") still be used if there were different settings connecting to different databases.
[ "ok you have two dimensions you need to cover with your settings:\n\nDomain (site)\nCurrent Machine\n\nHere is what I recommend:\nuniversal_settings.py - all the settings you want to inherit everywhere (all machines, all domains)\nlocal_settings.py - settings on a per machine basis (database settings, mail server, ...
[ 5 ]
[]
[]
[ "django", "python", "subdomain" ]
stackoverflow_0001866760_django_python_subdomain.txt
Q: Conway's Life: Iterate over a closed universe in Python I have just started learning Python, and I'm trying to write a program for Conway's Game of Life. I'm trying to create a closed universe with boundary conditions(which are the opposite side/corner). I think I have done this, but I'm not iterating over the loo...
Conway's Life: Iterate over a closed universe in Python
I have just started learning Python, and I'm trying to write a program for Conway's Game of Life. I'm trying to create a closed universe with boundary conditions(which are the opposite side/corner). I think I have done this, but I'm not iterating over the loop when it runs, and can't work out how to do this. Thanks ver...
[ "your problem could be the break statement\nEdit: Also, you probably want just 1 loop, first you initialize universe_array n_iter times, doing nothing after the first time. then you apply the rules n_iter times, you most likely want to put them in the same loop so that the universe gets correctly updated after each...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001867716_python.txt
Q: Using Google App Engine to display a Rss/Atom feed Im thinking of setting up a Google App that simply displays an RSS or Atom feed. The idea is that every once in a while (a cron job or at the push of a magic button) the feed is read and copied into the apps internal data, ready to be viewed. This would be done in...
Using Google App Engine to display a Rss/Atom feed
Im thinking of setting up a Google App that simply displays an RSS or Atom feed. The idea is that every once in a while (a cron job or at the push of a magic button) the feed is read and copied into the apps internal data, ready to be viewed. This would be done in Python. I found this page that seems to explain what I ...
[ "One option is to use the universal feed parser library, which will take care of most of these issues for you. Another option would be to use a PubSubHubbub-powered service such as Superfeedr, which will POST updates to you in a pre-sanitized form, eliminating most of your polling and parsing issues.\n", "What ab...
[ 3, 0 ]
[]
[]
[ "atom_feed", "feed", "google_app_engine", "python", "rss" ]
stackoverflow_0001860407_atom_feed_feed_google_app_engine_python_rss.txt
Q: Iteration in a single line I have some code of the form: for i in range(nIterations): y = f(y) Where f is a function defined elsewhere. hopefully the idea of that code is that after it's run y will have had f applied to it nIterations times. Is there a way in python to write this in a single line? A: like ...
Iteration in a single line
I have some code of the form: for i in range(nIterations): y = f(y) Where f is a function defined elsewhere. hopefully the idea of that code is that after it's run y will have had f applied to it nIterations times. Is there a way in python to write this in a single line?
[ "like this?\nfor i in range(nIterations): y = f(y)\n\nA for loop with one command can be written as a single line.\nEDIT\nOr maybe slightly cleaner:\nfor _ in xrange(nIterations): y = f(y)\n\nSince you don't want to have a something that can be split into two separate statements (i think), here's another one:\nredu...
[ 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001867715_python.txt
Q: Highlight a row in wxGrid (with wxPython) when a cell in that row changes programatically How do I highlight a row after an update of the underlying PyGridTableBase? I can't seem to get my head around it. I am able to create alternate row highlighting lines when the table is first drawn: ### Style the table a litt...
Highlight a row in wxGrid (with wxPython) when a cell in that row changes programatically
How do I highlight a row after an update of the underlying PyGridTableBase? I can't seem to get my head around it. I am able to create alternate row highlighting lines when the table is first drawn: ### Style the table a little. def GetAttr(self, row, col, prop): attr = gridlib.GridCellAttr() if self.i...
[ "You are doing the right thing, the only problem that comes to mind is that you perhaps didn't manually refresh the grid after the GridTableBase update. Here is a small working example that will hopefully help you out.\nimport wx, wx.grid\n\nclass GridData(wx.grid.PyGridTableBase):\n _cols = \"a b c\".split()\n ...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001866321_python_wxpython.txt
Q: Set an object's superclass at __init__? Is it possible, when instantiating an object, to pass-in a class which the object should derive from? For instance: class Red(object): def x(self): print '#F00' class Blue(object): def x(self): print '#00F' class Circle(object): def __init__(sel...
Set an object's superclass at __init__?
Is it possible, when instantiating an object, to pass-in a class which the object should derive from? For instance: class Red(object): def x(self): print '#F00' class Blue(object): def x(self): print '#00F' class Circle(object): def __init__(self, parent): # here, we set Bar's pare...
[ "Perhaps what you are looking for is a class factory:\n#!/usr/bin/env python\nclass Foo(object):\n def x(self):\n print('y')\n\ndef Bar(parent=Foo):\n class Adoptee(parent):\n def __init__(self):\n self.x()\n return Adoptee()\nobj=Bar(parent=Foo)\n\n", "I agree with @AntsAasma. ...
[ 7, 4, 1, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0001867258_oop_python.txt
Q: Properly specifying path for git pull from my local development machine I'm trying to setup Fabric so that I can automatically deploy my Django app to my web server. What I want to do is to pull the data from my Development machine (os X) to the server. How do I correctly specify my path in the git url? This i...
Properly specifying path for git pull from my local development machine
I'm trying to setup Fabric so that I can automatically deploy my Django app to my web server. What I want to do is to pull the data from my Development machine (os X) to the server. How do I correctly specify my path in the git url? This is the error I'm getting: $ git pull fatal: '/Users/Bryan/work/tempReview_...
[ "On your server, create a folder called myapp. Chdir to this folder, and then run\nserver ~/myapp$ git init\n\nThen, let git know about your server. After this, push to the server's repository from your local machine.\nlocal ~/myapp$ git remote add origin user@server:~/myapp.git\nlocal ~/myapp$ git push origin mast...
[ 1 ]
[]
[]
[ "git", "python" ]
stackoverflow_0001868393_git_python.txt
Q: Message instance has no attribute 'read' in Google app engine mail receive Code in receive handler class LogSenderHandler(InboundMailHandler): def receive(self, mail_message): logging.info("Received a message from: " + mail_message.sender) #logging.info("Received a message from: " + mail_message.attac...
Message instance has no attribute 'read' in Google app engine mail receive
Code in receive handler class LogSenderHandler(InboundMailHandler): def receive(self, mail_message): logging.info("Received a message from: " + mail_message.sender) #logging.info("Received a message from: " + mail_message.attachments) logging.info("Received a message from: " + mail_message.date) lo...
[ "Do you have the latest version of the API? for the incoming mail function need to be the 1.2.6 or greatest.\nLater i saw in google groups the \"solution\" I quote Joshua Smith\n\"I've found that you need to restart the local dev environment before\ndoing any inbound mail testing. Otherwise, you'll get that read...
[ 0 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0001862041_email_google_app_engine_python.txt