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:
Are there any free/open-source WCF client frameworks/libraries out there?
I am working on a tool that will test the server of a Silverlight application. AFAIK, Silverlight uses WCF to communicate with the server. I am curious if here are any free tools out there that can enable to write test scripts that test the ... | Are there any free/open-source WCF client frameworks/libraries out there? | I am working on a tool that will test the server of a Silverlight application. AFAIK, Silverlight uses WCF to communicate with the server. I am curious if here are any free tools out there that can enable to write test scripts that test the server via WCF, preferably in Java, Python, Ruby or anything that does not requ... | [
"Take a look at WCFStorm, haven't used it yet myself but it seems ok. Of course, it's a tool not a library, and it uses .Net (as it's the most logical choice for a tool that interoperates with WCF).\n"
] | [
1
] | [] | [] | [
".net",
"automated_tests",
"python",
"wcf_client"
] | stackoverflow_0003733111_.net_automated_tests_python_wcf_client.txt |
Q:
Slower search when start character is given is counterintuitive
I've written a Python utility to scan log files for known error patterns.
I was trying to speed up the search by providing the regex engine with additional pattern info. For example, not only that I'm looking for lines with gold, I require that such l... | Slower search when start character is given is counterintuitive | I've written a Python utility to scan log files for known error patterns.
I was trying to speed up the search by providing the regex engine with additional pattern info. For example, not only that I'm looking for lines with gold, I require that such line must start with an underscore, so: ^_.*gold instead of gold.
As 9... | [
"How about\nif line[0] == \"_\" and \"gold\" in line:\n print \"Yup, it starts with an underscore\"\nelse:\n print \"Nope it doesn't\"\n\nSeriously, don't overuse regex\n",
"You're actually doing two things wrong: If you want to look at the beginning of the string use match not search.\nAlso, don't use re.mat... | [
2,
2,
2,
1
] | [] | [] | [
"performance",
"python",
"regex"
] | stackoverflow_0003741581_performance_python_regex.txt |
Q:
How to create a new instance of the same class as the other object?
Having a object x which is an instance of some class how to create a new instance of the same class as the x object, without importing that all possible classes in the same namespace in which we want to create a new object of the same type and usi... | How to create a new instance of the same class as the other object? | Having a object x which is an instance of some class how to create a new instance of the same class as the x object, without importing that all possible classes in the same namespace in which we want to create a new object of the same type and using isinstance to figure out the correct type.
For example if x is a decim... | [
"Calling type(x) is definitely the canonical way to create a new instance of exactly the same type as x. However, what arguments to pass to that call is not a given, because the \"signature\" (number and types of arguments to pass in the call) changes with every different type; so, if you have no idea of what the ... | [
11
] | [] | [] | [
"class",
"instantiation",
"python",
"types"
] | stackoverflow_0003742111_class_instantiation_python_types.txt |
Q:
Adding magic global methods to modules
I'm starting to get into the Python logging module, but unless I want all messages to say "root" I have to create a logger for each module, and it's kind of a pain to do that over and over again.
I was thinking it would be handy if there were a magic __logger__() method that ... | Adding magic global methods to modules | I'm starting to get into the Python logging module, but unless I want all messages to say "root" I have to create a logger for each module, and it's kind of a pain to do that over and over again.
I was thinking it would be handy if there were a magic __logger__() method that would return a logger for the current module... | [
"You can use:\nlogger = logging.getLogger(__name__)\n\nat the top of your class, and use it like so:\nlogger.warn(...)\nlogger.log(...)\n\n"
] | [
2
] | [] | [] | [
"logging",
"magic_methods",
"module",
"python"
] | stackoverflow_0003742349_logging_magic_methods_module_python.txt |
Q:
Disable Window's automated handling of errors in subprocesses
I'm trying to write a test suite for a compiler (LLVM) and it works perfectly fine on every platform except for Windows. On Windows I get the "critical-error-handler" message box which stops the tests indefinitely.
This problem makes it very difficult ... | Disable Window's automated handling of errors in subprocesses | I'm trying to write a test suite for a compiler (LLVM) and it works perfectly fine on every platform except for Windows. On Windows I get the "critical-error-handler" message box which stops the tests indefinitely.
This problem makes it very difficult to test because, with compilers, a problem often means invalid code... | [
"The problem was actually Dr. Watson(link redacted), who rudely ignores SetErrorMode(link redacted). The only way to prevent Dr. Watson from stealing your joy is to prevent him from ever getting the call. There are two ways to do this.\n\nCall SetUnhandledExceptionHandler(yourexceptionhandler);\nIf you call exit in... | [
1,
0
] | [] | [] | [
"python",
"testing",
"winapi"
] | stackoverflow_0003735456_python_testing_winapi.txt |
Q:
Python print works differently on different servers
When I try to print an unicode string on my dev server it works correctly but production server raises exception.
File "/home/user/twistedapp/server.py", line 97, in stringReceived
print "sent:" + json
File "/usr/lib/python2.6/dist-packages/twisted/python/log... | Python print works differently on different servers | When I try to print an unicode string on my dev server it works correctly but production server raises exception.
File "/home/user/twistedapp/server.py", line 97, in stringReceived
print "sent:" + json
File "/usr/lib/python2.6/dist-packages/twisted/python/log.py", line 555, in write
d = (self.buf + data).split(... | [
"printing of Unicode strings relies on sys.stdout (the process's standard output) having a correct .encoding attribute that Python can use to encode the unicode string into a byte string to perform the required printing -- and that setting depends on the way the OS is set up, where standard output is directed to, a... | [
7,
1
] | [] | [] | [
"python",
"twisted",
"unicode"
] | stackoverflow_0003742167_python_twisted_unicode.txt |
Q:
Python Script Fails To Run When Launched From Shell File, But Works When Launched From Terminal
If I launch the Google Code upload Python script from Terminal, it works as expected, but when I launch it using the code below in a Bourne Shell Script file, it fails with the error "close failed in file object destruc... | Python Script Fails To Run When Launched From Shell File, But Works When Launched From Terminal | If I launch the Google Code upload Python script from Terminal, it works as expected, but when I launch it using the code below in a Bourne Shell Script file, it fails with the error "close failed in file object destructor: Error in sys.excepthook: Original exception was:".
#!/bin/sh
BUILD_FOLDER="/Users/James/Document... | [
"echo doesn't accept anything from stdin, so it's doing nothing but outputting a blank line. The script's output should appear without having to do anything to it.\nTry specifying the full path to python. The PATH for the script may be different than it is for your interactive shell. \nYou should be able to quote t... | [
1
] | [] | [] | [
"google_code",
"macos",
"python",
"shell",
"terminal"
] | stackoverflow_0003741949_google_code_macos_python_shell_terminal.txt |
Q:
Learning Pylons - Where to start
I decided to take the leap in to lower level things last night. I've been working with Django for years now, and I feel after all this time that it is simply not made for software outside of the blog/news/social networking sector. Pylons seems to offer flexibility to do anything yo... | Learning Pylons - Where to start | I decided to take the leap in to lower level things last night. I've been working with Django for years now, and I feel after all this time that it is simply not made for software outside of the blog/news/social networking sector. Pylons seems to offer flexibility to do anything you want at the expense of being much mo... | [
"I would recommend this... http://pylonsbook.com/en/1.1/#front-matter\n"
] | [
5
] | [] | [] | [
"pylons",
"python",
"wsgi"
] | stackoverflow_0003742648_pylons_python_wsgi.txt |
Q:
Python openssl problem
I'm trying to write a simple mail retrieval program in python. It seems the connection is getting established. But when I try to authorize it with the username, I don't get a reply from the server. Can anyone tell me what is going wrong here?
import socket, sys
from OpenSSL import SSL
ctx ... | Python openssl problem | I'm trying to write a simple mail retrieval program in python. It seems the connection is getting established. But when I try to authorize it with the username, I don't get a reply from the server. Can anyone tell me what is going wrong here?
import socket, sys
from OpenSSL import SSL
ctx = SSL.Context(SSL.SSLv23_MET... | [
"End the string with a \\r\\n \n"
] | [
1
] | [] | [] | [
"openssl",
"python"
] | stackoverflow_0003742855_openssl_python.txt |
Q:
Why isn't this classprop implementation working?
Based on a question I previously asked, I tried to come up with a class property that would allow setting as well as getting. So I wrote this and put it in a module util:
class classprop(object):
def __init__(self, fget, fset=None):
if isinstance(fget, ... | Why isn't this classprop implementation working? | Based on a question I previously asked, I tried to come up with a class property that would allow setting as well as getting. So I wrote this and put it in a module util:
class classprop(object):
def __init__(self, fget, fset=None):
if isinstance(fget, classmethod):
self.fget = fget
els... | [
"The doc's say:\n\nobject.__set__(self, instance,\n value) Called to set the attribute on\n an instance instance of the owner\n class to a new value, value.\n\nUnlike for __get__, it does not mention class attributes. So Python won't call any __set__ on a class attribute.\n"
] | [
0
] | [] | [] | [
"class",
"class_method",
"descriptor",
"properties",
"python"
] | stackoverflow_0003743079_class_class_method_descriptor_properties_python.txt |
Q:
Force UTF-8 output (mostly when not talking to a tty)
I am doing this:
import sys, codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
But I know there is something missing. I had a huge collection of code before an HD crash, and my snippet in there had somet... | Force UTF-8 output (mostly when not talking to a tty) | I am doing this:
import sys, codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
But I know there is something missing. I had a huge collection of code before an HD crash, and my snippet in there had something in it which prevented:
reload(sys)
From undoing the c... | [
"Quite apart from UTF8 (and thus entirely apart from your Q's title), reload(sys) does not reopen stdandard input, output, and error files. Try a simpler case to see that:\n>>> import sys\n>>> print>>sys.stderr,'ciao'\nciao\n>>> sys.stderr.close()\n>>> print>>sys.stderr,'ciao'\n>>> reload(sys)\n<module 'sys' (buil... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003743239_python.txt |
Q:
Python, how to instantiate classes from a class stored in a database?
I'm using Django and want to be able to store classes in a database for things like forms and models so that I can easily make them creatable through a user interface since they are just stored in the database as opposed to a regular file. I don... | Python, how to instantiate classes from a class stored in a database? | I'm using Django and want to be able to store classes in a database for things like forms and models so that I can easily make them creatable through a user interface since they are just stored in the database as opposed to a regular file. I don't really know a whole lot about this and am not sure if this is a situatio... | [
"Do not store code in the database!!!\nImagine a class with a malicious __init__ method finding it's way in your \"class repository\" in the database. This means whoever has write access to those database tables has the ability to read any file from your web server and even nuke it's file system, since they have th... | [
5,
2
] | [] | [] | [
"class",
"database",
"django",
"python"
] | stackoverflow_0003743329_class_database_django_python.txt |
Q:
design for continuation based python web appliction framework
There are many continuation based framework for java, ruby etc but none in python. Nagare framework somewhat solves the problem but it do not use standard python and uses stackless python to solve continuation problem.
I was wondering,
what part of sta... | design for continuation based python web appliction framework | There are many continuation based framework for java, ruby etc but none in python. Nagare framework somewhat solves the problem but it do not use standard python and uses stackless python to solve continuation problem.
I was wondering,
what part of standard python constraint to create such continuation web framework i... | [
"Before you can even begin to consider writing a continuation based framework you need a programming language that has continuations (or at least co-routines which can be used to emulate continuations). Continuation is a control structure like loops or closures or functions, not a design pattern like MVC. Unfortuna... | [
2,
2
] | [] | [] | [
"architecture",
"frameworks",
"python",
"python_stackless"
] | stackoverflow_0003740330_architecture_frameworks_python_python_stackless.txt |
Q:
WSGI based Python web frameworks
I keep hitting road blocks with Django and have read about Pylons. Pylons seemed to be exactly what I needed (greener grass), but then I realized that they have global variables all over the place and loads of black magic infused by dark spirits (spirits so dark that they even kill... | WSGI based Python web frameworks | I keep hitting road blocks with Django and have read about Pylons. Pylons seemed to be exactly what I needed (greener grass), but then I realized that they have global variables all over the place and loads of black magic infused by dark spirits (spirits so dark that they even kill unicorns).
Is there anything out ther... | [
"\nThe most hard-core low-level web-framework for python - Werkzeug - http://werkzeug.pocoo.org/\nFlask: http://flask.pocoo.org/ It will look like an entry-level framework, but in fact it's extremely powerful. It's based on werkzeug and support Jinja2 out of the box. I'd go with this one. You can get easily integra... | [
6
] | [] | [] | [
"django",
"pylons",
"python",
"web_frameworks",
"wsgi"
] | stackoverflow_0003743408_django_pylons_python_web_frameworks_wsgi.txt |
Q:
Separately validating username and password during Django authentication
When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:
Username was valid, password was invalid
Username was i... | Separately validating username and password during Django authentication | When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:
Username was valid, password was invalid
Username was invalid
I am thinking that I would like to display the appropriate messages to... | [
"You really don't want to distinguish between these two cases. Otherwise, you are giving a potential hacker a clue as to whether or not a username is valid - a significant help towards gaining a fraudulent login.\n",
"This is not a function of the backend simply the authentication form. Just rewrite the form to d... | [
20,
2,
0,
0,
0
] | [] | [] | [
"authentication",
"django",
"python",
"security"
] | stackoverflow_0001549442_authentication_django_python_security.txt |
Q:
Using Python in Netbeans
I have x64 Windows XP machine.
I use Netbeans to code Java.
I am now trying to use it for Python, but I get this error:
\NetBeans was unexpected at this time.
Any idea how to fix it?
A:
You probably want to ask this question on www.serverfault.com rather than stackoverflow as it is more ... | Using Python in Netbeans | I have x64 Windows XP machine.
I use Netbeans to code Java.
I am now trying to use it for Python, but I get this error:
\NetBeans was unexpected at this time.
Any idea how to fix it?
| [
"You probably want to ask this question on www.serverfault.com rather than stackoverflow as it is more of a configuration issue rather than a programming issue.\nInclude the version of Netbeans and the Java you are using - and whether you using native python and/or Jython as well.\nAlso include at which point you s... | [
0
] | [] | [] | [
"netbeans",
"python"
] | stackoverflow_0003728310_netbeans_python.txt |
Q:
Python / Mako : How to get unicode strings/characters parsed correctly?
I'm trying to get Mako render some string with unicode characters :
tempLook=TemplateLookup(..., default_filters=[], input_encoding='utf8',output_encoding='utf-8', encoding_errors='replace')
...
print sys.stdout.encoding
uname=cherrypy.session... | Python / Mako : How to get unicode strings/characters parsed correctly? | I'm trying to get Mako render some string with unicode characters :
tempLook=TemplateLookup(..., default_filters=[], input_encoding='utf8',output_encoding='utf-8', encoding_errors='replace')
...
print sys.stdout.encoding
uname=cherrypy.session['userName']
print uname
kwargs['_toshow']=uname
...
return tempLook.get_temp... | [
"Yes, UTF-8 != Unicode.\nUTF-8 is a specifc string encoding, as are ASCII and ISO 8859-1. Try this: \nFor any input string do a inputstring.decode('utf-8') (or whatever input encoding you get). For any output string do a outputstring.encode('utf-8')(or whatever output encoding you want). For any internal use, take ... | [
3
] | [] | [] | [
"mako",
"python",
"string",
"unicode"
] | stackoverflow_0003744115_mako_python_string_unicode.txt |
Q:
Clear the window in tkinter
I made a tkinter window in python with some widgets like so:
def createWidgets(self):
self.grid(padx=25, pady=25)
self.start = Button(self)
self.start["text"] = "Start"
self.start["width"] = "15"
self.start["height"] = "1"
self.start["command"] = self.st... | Clear the window in tkinter | I made a tkinter window in python with some widgets like so:
def createWidgets(self):
self.grid(padx=25, pady=25)
self.start = Button(self)
self.start["text"] = "Start"
self.start["width"] = "15"
self.start["height"] = "1"
self.start["command"] = self.start_g
self.start.... | [
"You can call grid_forget() on your widget to permanently remove it.\ne.g \nself.start.grid_forget()\n\nIf you wanted to clear the whole window then you could do the same on your main frame.\n"
] | [
4
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003744108_python_tkinter.txt |
Q:
Making Python script accessible system wide
Can someone tell me how to make my script callable in any directory?
My script simply returns the number of files in a directory. I would like it to work in any directory by invoking it, instead of first being copied there and then typing python myscript.py
I am using Ma... | Making Python script accessible system wide | Can someone tell me how to make my script callable in any directory?
My script simply returns the number of files in a directory. I would like it to work in any directory by invoking it, instead of first being copied there and then typing python myscript.py
I am using Mac OS X, but is there a common way to get it insta... | [
"If your script starts with a suitable shebang line, such as:\n#!/usr/bin/env python\n\nAnd your script has the executable bit set (for Linux, OS X, and other Unix-like systems):\nchmod +x myscript.py\n\nAnd the path to your script is in your PATH environment variable:\nexport PATH=${PATH}:`pwd` # on Unix-like syst... | [
12,
0
] | [] | [] | [
"linux",
"osx_leopard",
"python",
"shell",
"windows"
] | stackoverflow_0003743812_linux_osx_leopard_python_shell_windows.txt |
Q:
Why does java/javascript/python force the use of () after a method name, even if it takes no arguments?
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
So I was wondering if there was good logic behind making the... | Why does java/javascript/python force the use of () after a method name, even if it takes no arguments? | One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
So I was wondering if there was good logic behind making the difference between calling on an object's properties and methods explicit.
Obviously, it allows you to have ... | [
"All modern languages require this because referencing a function and calling a function are separate actions.\nFor example,\ndef func():\n print \"hello\"\n return 10\na = func\na()\n\nClearly, a = func and a = func() have very different meanings.\nRuby--the most likely language you're thinking of in contras... | [
13,
8,
5,
3,
3,
2,
2,
2,
1
] | [] | [] | [
"java",
"javascript",
"methods",
"properties",
"python"
] | stackoverflow_0003744180_java_javascript_methods_properties_python.txt |
Q:
how get low frequency from DTMF tone
Hi have made one source in python for get fundamental frequecys from audio files, i want use this for get tones from DTMF audios !
but how get the low tones from the audio?
thks!!
Exactly im apply FFT but its return always the High Frequency.
the table for frequencys here
http... | how get low frequency from DTMF tone | Hi have made one source in python for get fundamental frequecys from audio files, i want use this for get tones from DTMF audios !
but how get the low tones from the audio?
thks!!
Exactly im apply FFT but its return always the High Frequency.
the table for frequencys here
http://www.mediacollege.com/audio/tone/dtmf.ht... | [
"To get frequencies that appear in a wave (any sound, not only DTMF, and all other wave forms), you can apply the Fast Fourier Transform.\nWhen you apply it to a DTMF, you'll get two peaks for the two freqs that the signal contains.\nhttp://en.wikipedia.org/wiki/Fast_Fourier_transform\n",
"Since you only need inf... | [
3,
3
] | [] | [] | [
"audio",
"python",
"signal_processing"
] | stackoverflow_0003743708_audio_python_signal_processing.txt |
Q:
Python: How to write to http input stream
I could see a couple of examples to read from the http stream. But how to write to a http input stream using python?
A:
You could use standard library module httplib: in the HTTPConnection.request method, the body argument (since Python 2.6) can be an open file object (b... | Python: How to write to http input stream | I could see a couple of examples to read from the http stream. But how to write to a http input stream using python?
| [
"You could use standard library module httplib: in the HTTPConnection.request method, the body argument (since Python 2.6) can be an open file object (better be a \"pretty real\" file, since, as the docs say, \"this file object should support fileno() and read() methods\"; but it could be a named or unnamed pipe to... | [
1
] | [] | [] | [
"http",
"python"
] | stackoverflow_0003744445_http_python.txt |
Q:
python's mechanize wont properly parse a form
I'm trying to submit a form using python's mechanize but it wont properly parse the form in question. There are 4 other forms, which are parsed correctly except for this one form. The form is properly parsed in perl's www::mechanize though but i'd like to stick with py... | python's mechanize wont properly parse a form | I'm trying to submit a form using python's mechanize but it wont properly parse the form in question. There are 4 other forms, which are parsed correctly except for this one form. The form is properly parsed in perl's www::mechanize though but i'd like to stick with python.
Is there anyway of retrieving the html of th... | [
"If anyone else is interested. Found the answer in mechanize's FAQ.\nAlternatively, you can process the HTML (and headers) arbitrarily:\nbrowser = mechanize.Browser()\nbrowser.open(\"http://example.com/\")\nhtml = browser.response().get_data().replace(\"<br/>\", \"<br />\")\nresponse = mechanize.make_response(\n ... | [
2
] | [] | [] | [
"mechanize",
"parsing",
"python"
] | stackoverflow_0003744544_mechanize_parsing_python.txt |
Q:
Why do you have to call .items() when iterating over a dictionary in Python?
Why do you have to call items() to iterate over key, value pairs in a dictionary? ie.
dic = {'one': '1', 'two': '2'}
for k, v in dic.items():
print(k, v)
Why isn't that the default behavior of iterating over a dictionary
for k, v in ... | Why do you have to call .items() when iterating over a dictionary in Python? | Why do you have to call items() to iterate over key, value pairs in a dictionary? ie.
dic = {'one': '1', 'two': '2'}
for k, v in dic.items():
print(k, v)
Why isn't that the default behavior of iterating over a dictionary
for k, v in dic:
print(k, v)
| [
"For every python container C, the expectation is that\nfor item in C:\n assert item in C\n\nwill pass just fine -- wouldn't you find it astonishing if one sense of in (the loop clause) had a completely different meaning from the other (the presence check)? I sure would! It naturally works that way for lists, ... | [
173,
10
] | [] | [] | [
"dictionary",
"loops",
"python"
] | stackoverflow_0003744568_dictionary_loops_python.txt |
Q:
Twitter, Error: urllib.error.HTTPError: HTTP Error 401: Unauthorized
def send_to_twitter():
msg = "I am a message that will be sent to Twitter"
password_manager = urllib.request.HTTPPasswordMgr()
password_manager.add_password("Twitter API",
"http://twitter.com/statuses", "username", "password")
... | Twitter, Error: urllib.error.HTTPError: HTTP Error 401: Unauthorized |
def send_to_twitter():
msg = "I am a message that will be sent to Twitter"
password_manager = urllib.request.HTTPPasswordMgr()
password_manager.add_password("Twitter API",
"http://twitter.com/statuses", "username", "password")
http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
... | [
"Twitter no longer supports HTTP Authentication. You should use oauth in stead. \ntweepy seems to be a good library to start with if you want to do twitter from python: it's current, supports oath and looks very complete.\n",
"Your are using the old HTTP Auth method. Upgrade using OAuth.\nGo to the following link... | [
4,
1
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0003744842_python_twitter.txt |
Q:
How to parse a string in Java? Is there anything similar to Python's re.finditer()?
I have an input string with a very simple pattern - capital letter, integer, capital letter, integer, ... and I would like to separate each capital letter and each integer. I can't figure out the best way to do this in Java.
I hav... | How to parse a string in Java? Is there anything similar to Python's re.finditer()? | I have an input string with a very simple pattern - capital letter, integer, capital letter, integer, ... and I would like to separate each capital letter and each integer. I can't figure out the best way to do this in Java.
I have tried regexp using Pattern and Matcher, then StringTokenizer, but still without success... | [
"You could use regex API in Java and achieve the same functionality: \nPattern myPattern = Pattern.compile(\"([A-Z])(\\d+)\")\nMatcher myMatcher = myPattern.matcher(\"A12R5F28\");\nwhile (myMatcher.find()) {\n // Do your stuff here\n}\n\n",
"Expanding on Ravi's Answer....\nPattern myPattern = Pattern.compile... | [
5,
2
] | [] | [] | [
"java",
"parsing",
"python",
"regex"
] | stackoverflow_0003744904_java_parsing_python_regex.txt |
Q:
Replace non-numeric characters
I need to replace non-numeric chars from a string.
For example, "8-4545-225-144" needs to be "84545225144"; "$334fdf890==-" must be "334890".
How can I do this?
A:
''.join(c for c in S if c.isdigit())
A:
It is possible with regex.
import re
...
return re.sub(r'\D', '', theStrin... | Replace non-numeric characters | I need to replace non-numeric chars from a string.
For example, "8-4545-225-144" needs to be "84545225144"; "$334fdf890==-" must be "334890".
How can I do this?
| [
"''.join(c for c in S if c.isdigit())\n\n",
"It is possible with regex.\nimport re\n\n...\n\nreturn re.sub(r'\\D', '', theString)\n\n",
"filter(str.isdigit, s) is faster and IMO clearer than anything else listed here.\nIt will also throw a TypeError if s is a unicode type. Depending on what definition of \"digi... | [
22,
18,
3,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003643065_python_regex_string.txt |
Q:
How to validate the form in pylons in the same controller action that initially rendered it?
I have the following controller:
class FormtestController(BaseController):
def form(self):
return ender('/simpleform.html')
@validate(schema=EmailForm(state=c), form='form', post_only=False, on_get=True,
... | How to validate the form in pylons in the same controller action that initially rendered it? | I have the following controller:
class FormtestController(BaseController):
def form(self):
return ender('/simpleform.html')
@validate(schema=EmailForm(state=c), form='form', post_only=False, on_get=True,
auto_error_formatter=custom_formatter)
def submit(self):
return 'Your em... | [
"Silly me, it was just simple. Here's my code:\nclass FormtestController(BaseController):\n\n@validate(schema=EmailForm(state=c), form='form', post_only=True,\n on_get=False,\n auto_error_formatter=custom_formatter)\ndef form(self):\n if request.method == 'POST':\n return 'Your email is:... | [
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003741088_pylons_python.txt |
Q:
Is there a good python library that provides PGP decryption functionality without the use of a subprocess?
I am looking for a way to decrypt pgp messages in python without the use of a subprocess. I have checked out http://wiki.python.org/moin/GnuPrivacyGuard but none of those solutions worked. Pyme almost worked ... | Is there a good python library that provides PGP decryption functionality without the use of a subprocess? | I am looking for a way to decrypt pgp messages in python without the use of a subprocess. I have checked out http://wiki.python.org/moin/GnuPrivacyGuard but none of those solutions worked. Pyme almost worked except I hit a wall when trying to use set_passphrase_cb to avoid any user interaction but couldn't get it worki... | [
"EDITED: other the two libraries you mentioned. there doesn;t seem to be anything.\n",
"You could use ctypes to roll your own wrapper around just the parts of GPGME you need.\n"
] | [
0,
0
] | [] | [] | [
"pgp",
"python",
"subprocess"
] | stackoverflow_0003743982_pgp_python_subprocess.txt |
Q:
Django: Problem reading multi valued POST variable
I'm missing something obvious here. I am trying to process a POST request that contains a mixture of single value and multi value variables. I can get the single valued variables using request.POST.get('variable_name'), for example:
logging.debug('sale_date: ' + r... | Django: Problem reading multi valued POST variable | I'm missing something obvious here. I am trying to process a POST request that contains a mixture of single value and multi value variables. I can get the single valued variables using request.POST.get('variable_name'), for example:
logging.debug('sale_date: ' + request.POST.get('SALEDATE'))
However, I can't get the m... | [
"prices = request.POST.getlist(\"IPN_PRICE[]\")\n\nThis should do the trick.\n"
] | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003745255_django_python.txt |
Q:
Creating a Relation in __init__ of a model (in Django)
Lets assume I had the following Model
class A(Models.model):
def __init__(self,data):
B(a=self,data=data).save()
class B(Models.model):
data = somefieldtype
a = Models.models.ForeignKey('A')
now as you might suspect, there is an error in this ... | Creating a Relation in __init__ of a model (in Django) | Lets assume I had the following Model
class A(Models.model):
def __init__(self,data):
B(a=self,data=data).save()
class B(Models.model):
data = somefieldtype
a = Models.models.ForeignKey('A')
now as you might suspect, there is an error in this Model definintion, as one cannot create a relation to the A ... | [
"You can put this code in an overridden save method of A:\ndef save(self,**kwargs):\n super(A,self).save(**kwargs)\n B(a=self,data=data).save()\n\n"
] | [
2
] | [] | [] | [
"django",
"django_models",
"entity_relationship",
"python"
] | stackoverflow_0003745516_django_django_models_entity_relationship_python.txt |
Q:
Python persistent socket connection
I'm new to python :) I would like to create persistent socket. I tried to do this using file descriptors. What I tried is:
Open a socket socket connection s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Get it's file descriptor number fd = s.fileno()
Open the file descrip... | Python persistent socket connection | I'm new to python :) I would like to create persistent socket. I tried to do this using file descriptors. What I tried is:
Open a socket socket connection s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Get it's file descriptor number fd = s.fileno()
Open the file descriptor as I/O os.open(fd)
But I get OSError... | [
"You use os.fdopen() to open file descriptors.\nI'm actually surprised that you got that far because os.open requires a filename and flags stating which mode to open the file in. for example fd = os.open('foo.txt', os.O_RONLY). As my example indicates, it returns a file descriptor rather than accepting one.\n",
"... | [
1,
0
] | [] | [] | [
"file_descriptor",
"persistence",
"python",
"sockets"
] | stackoverflow_0003745592_file_descriptor_persistence_python_sockets.txt |
Q:
Python ctypes - Accessing data string in Structure .value fails
I am able to get a Structure populated as a result of a dll-function (as it seems looking into it using x=buffer(MyData) and then repr(str(buffer(x))).
But an error is raised if I try to access the elements of the Structure using .value.
I have a VarD... | Python ctypes - Accessing data string in Structure .value fails | I am able to get a Structure populated as a result of a dll-function (as it seems looking into it using x=buffer(MyData) and then repr(str(buffer(x))).
But an error is raised if I try to access the elements of the Structure using .value.
I have a VarDefs.h that requires a struct like this:
typedef struct
{
char Var1[... | [
"The structure you're trying to use ctypes to interface with contains a several \"arrays of characters\" not \"pointers to arrays of characters\". Rather than using create_string_buffer(9) you'll need to use ctypes.c_char * 9.\nclass TMyData( ctypes.Structure ):\n _fields_ = [ (\"Var1\", ctypes.c_char * 9),\n ... | [
3,
3
] | [] | [] | [
"ctypes",
"python",
"structure"
] | stackoverflow_0003704732_ctypes_python_structure.txt |
Q:
python: how to merge a list into clusters?
I have a list of tuples:
[(3,4), (18,27), (4,14)]
and need a code merging tuples which has repeated numbers, making another list where all list elements will only contain unique numbers. The list should be sorted by the length of the tuples, i.e.:
>>> MergeThat([(3,4), (... | python: how to merge a list into clusters? | I have a list of tuples:
[(3,4), (18,27), (4,14)]
and need a code merging tuples which has repeated numbers, making another list where all list elements will only contain unique numbers. The list should be sorted by the length of the tuples, i.e.:
>>> MergeThat([(3,4), (18,27), (4,14)])
[(3,4,14), (18,27)]
>>> MergeT... | [
"I tried hard to figure this out, but only after I tried the approach Ian's answer (thanks!) suggested I realized what the theoretical problem is: The input is a list of edges and defines a graph. We are looking for the strongly connected components of this graph. It's simple as that.\nWhile you can do this efficie... | [
9,
4,
1,
0,
0,
0
] | [] | [] | [
"cluster_analysis",
"list",
"python"
] | stackoverflow_0003744048_cluster_analysis_list_python.txt |
Q:
How do I migrate model changes in pylons/sqlalchemy?
I created a simple model and then mapped it to a class using sqlalchemy in pylons:
tag_table = schema.Table('tag', meta.metadata,
schema.Column('id', types.Integer,
schema.Sequence('tag_seq_id', optional=True),
primary_key... | How do I migrate model changes in pylons/sqlalchemy? | I created a simple model and then mapped it to a class using sqlalchemy in pylons:
tag_table = schema.Table('tag', meta.metadata,
schema.Column('id', types.Integer,
schema.Sequence('tag_seq_id', optional=True),
primary_key=True),
schema.Column('name', types.Unicode(20), nulla... | [
"You can try this tool: sqlalchemy-migrate\n"
] | [
2
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003745980_pylons_python.txt |
Q:
How to write a python program that automatically starts when windows start?
I'm writing a program using python 2.6 and pyqt4. I want this program to automatically start whenever windows stars (something like uTorrent client). How do I make this work? I am using windows 7.
A:
You can just place a shortcut in the ... | How to write a python program that automatically starts when windows start? | I'm writing a program using python 2.6 and pyqt4. I want this program to automatically start whenever windows stars (something like uTorrent client). How do I make this work? I am using windows 7.
| [
"You can just place a shortcut in the \"Startup\" folder, in the windows start menu.\n",
"You can compile your python script into an exe and add it to your startup items: Start > Programs > Accessories > System Tools > Scheduled Tasks\n"
] | [
2,
0
] | [] | [] | [
"pyqt4",
"python",
"startup",
"windows"
] | stackoverflow_0003745917_pyqt4_python_startup_windows.txt |
Q:
Running a command line from python and piping arguments from memory
I was wondering if there was a way to run a command line executable in python, but pass it the argument values from memory, without having to write the memory data into a temporary file on disk. From what I have seen, it seems to that the subproce... | Running a command line from python and piping arguments from memory | I was wondering if there was a way to run a command line executable in python, but pass it the argument values from memory, without having to write the memory data into a temporary file on disk. From what I have seen, it seems to that the subprocess.Popen(args) is the preferred way to run programs from inside python sc... | [
"with Popen.communicate:\nimport subprocess\nout, err = subprocess.Popen([\"pdftotext\", \"-\", \"-\"], stdout=subprocess.PIPE).communicate(pdf_data)\n\n",
"os.tmpfile is useful if you need a seekable thing. It uses a file, but it's nearly as simple as a pipe approach, no need for cleanup.\ntf=os.tmpfile()\ntf.... | [
2,
2,
1
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0003745178_linux_python.txt |
Q:
Python / Django Web service Confusion
I am trying to explore more about web service in Python/Django and to be honest i am quite confused. There are so many things like SOAPpy, XML-RPC, JSON-RPC RESTful, web service.
Basically all i want to know is what is the standard way of implementing web service in Python/Dj... | Python / Django Web service Confusion | I am trying to explore more about web service in Python/Django and to be honest i am quite confused. There are so many things like SOAPpy, XML-RPC, JSON-RPC RESTful, web service.
Basically all i want to know is what is the standard way of implementing web service in Python/Django and has anyone implemented in live pro... | [
"There isn't a 'standard' way, but a lot of people (including me) have used -- and like! -- Django Piston, which is actually also used to create the web service for BitBucket (where piston's source is hosted)\nAlso, if you're still learning about web services, I can highly recommend the O'Reilly book RESTful Web Se... | [
2,
0
] | [] | [] | [
"django",
"python",
"web_services"
] | stackoverflow_0003745724_django_python_web_services.txt |
Q:
Best practices for programmatically sanity checking environment using Python?
I am building a system that has dependencies such as Apache, Postgresql, and mod_wsgi. As part of my deployment process, I would like to write a sanity-checking script that tries to determine whether the server environment conforms to va... | Best practices for programmatically sanity checking environment using Python? | I am building a system that has dependencies such as Apache, Postgresql, and mod_wsgi. As part of my deployment process, I would like to write a sanity-checking script that tries to determine whether the server environment conforms to various assumptions, the most basic of which is whether the dependencies are installe... | [
"I would run the program and do proper try..except at place of first use of feature in informative message to user for what is missing (not installed db, installed but not running etc)\n"
] | [
1
] | [] | [] | [
"deployment",
"package",
"python"
] | stackoverflow_0003746090_deployment_package_python.txt |
Q:
TypeError in Django with python 2.7
Hey, new to Django and needing assistance, when I add my model to the admin interface in Django it appeares fine, but when I try to add or delete an entry in the database I get:
TypeError at /admin/Users/user/add/
coercing to Unicode: need string or buffer, tuple found
I ... | TypeError in Django with python 2.7 | Hey, new to Django and needing assistance, when I add my model to the admin interface in Django it appeares fine, but when I try to add or delete an entry in the database I get:
TypeError at /admin/Users/user/add/
coercing to Unicode: need string or buffer, tuple found
I done a google search and added:
def __str... | [
"In your MEDIA_ROOT definition, change your replace to have a raw string, as otherwise you'll be replacing a literal single backslash rather than the two you meant.\nMEDIA_ROOT = os.path.join(os.path.dirname(file), \"media\").replace(r\"\\\\\", \"//\")\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003743126_django_python.txt |
Q:
Anything wrong with a really large __init__?
I'm writing a Python program with a GUI built with the Tkinter module. I'm using a class to define the GUI because it makes it easier to pass commands to buttons and makes the whole thing a bit easier to understand.
The actual initialization of my GUI takes about 150 li... | Anything wrong with a really large __init__? | I'm writing a Python program with a GUI built with the Tkinter module. I'm using a class to define the GUI because it makes it easier to pass commands to buttons and makes the whole thing a bit easier to understand.
The actual initialization of my GUI takes about 150 lines of code. To make this easier to understand, I'... | [
"Either store some of those widget references in instance variables or return them (a minimal set mind you; you want to Reduce Coupling) and store them in local variables in __init__ before passing the relevant ones as arguments to your subsequent construction helpers. The latter is cleaner, but requires that thing... | [
5,
2,
2,
1
] | [] | [] | [
"abstraction",
"initialization",
"oop",
"python",
"scope"
] | stackoverflow_0003746285_abstraction_initialization_oop_python_scope.txt |
Q:
Why is VB flamed for being easy and yet Python is not?
I have always wondered about this and seen this among lots of programmers. Why is a VB programmer or VB code easily dismissed as too noobish and easy while the same does not apply to Python or Python code? After all, isn't Python as easy as VB is? And it does ... | Why is VB flamed for being easy and yet Python is not? | I have always wondered about this and seen this among lots of programmers. Why is a VB programmer or VB code easily dismissed as too noobish and easy while the same does not apply to Python or Python code? After all, isn't Python as easy as VB is? And it does provide drag-n-drop GUI application building also. So why is... | [
"VB is flamed less for being easy than for the population of programmers who use it. VB is perceived as being for people one step up from writing Excel macros, often in in-house corporate environments, churning out crapware. Being a Microsoft product doesn't help.\nVB is also seen as being the low-end language in ... | [
7
] | [] | [] | [
"python",
"vb.net"
] | stackoverflow_0003746520_python_vb.net.txt |
Q:
Python Win32GUI Find Window
I have a GUI Windows application and I want to control it using the extension Win32gui in Python. How can I find the string s that I must give to the FindWindow function?
I need to use the following code:
import win32gui as gui
gui.FindWindow(s, None)
Thaks!
A:
You would usually use ... | Python Win32GUI Find Window | I have a GUI Windows application and I want to control it using the extension Win32gui in Python. How can I find the string s that I must give to the FindWindow function?
I need to use the following code:
import win32gui as gui
gui.FindWindow(s, None)
Thaks!
| [
"You would usually use a tool like Spy++ (comes with Visual Studio) or some of the alternatives: Windows Spy, WinCheat or Window Detective\n"
] | [
5
] | [] | [] | [
"findwindow",
"python",
"winapi"
] | stackoverflow_0003746672_findwindow_python_winapi.txt |
Q:
CImg Python 3 bindings or something at least comparable?
i'm searching a Python lib with good image processing functionalities .
I was searching for CImg (which i've already used on C++ projects) bindings, but i wasn't lucky.
I found PIL, but it lacks a lot of features that CImg has so, is there any good alternati... | CImg Python 3 bindings or something at least comparable? | i'm searching a Python lib with good image processing functionalities .
I was searching for CImg (which i've already used on C++ projects) bindings, but i wasn't lucky.
I found PIL, but it lacks a lot of features that CImg has so, is there any good alternative ?
Thanks
UPDATE
PIL is good, but i need Python 3 support on... | [
"I would suggest you to enumerate the functionality that you find desirable which is there in Cimg and not in PIL.\nDiscussion on SO\n\nImage Processing, In Python?\n\npypi also throws up a lot of modules on image processing. Try seeing, if some of them is suitable for you.\n\nhttp://pypi.python.org/pypi?:action=se... | [
1
] | [] | [] | [
"cimg",
"image_processing",
"python",
"python_3.x"
] | stackoverflow_0003746876_cimg_image_processing_python_python_3.x.txt |
Q:
How to work with settings in Django
I want to keep some global settings for my project in Django. I need to have access to these settings from the code. For example, I need to set a current theme for my site that I can set using admin console or from the code. Or I need to set a tagline that will show in the heade... | How to work with settings in Django | I want to keep some global settings for my project in Django. I need to have access to these settings from the code. For example, I need to set a current theme for my site that I can set using admin console or from the code. Or I need to set a tagline that will show in the header of all pages. I suppose I should use mo... | [
"There are quite some packages that store settings in models, pick the one that works best for you:\nhttp://pypi.python.org/pypi?:action=search&term=django+settings&submit=search\n",
"If you are okay with changing these setting programmatically via settings.py you should do that. However, if you want to change th... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003746790_django_django_models_python.txt |
Q:
Change python byte type to string
I'm using python to play with the stackoverflow API. I run the following commands:
f = urllib.request.urlopen('http://api.stackoverflow.com/1.0/stats')
d = f.read()
The type of d is class 'bytes' and if I print it it looks like:
b'\x1f\x8b\x08\x00\x00\x00 .... etc
I tried d=f.r... | Change python byte type to string | I'm using python to play with the stackoverflow API. I run the following commands:
f = urllib.request.urlopen('http://api.stackoverflow.com/1.0/stats')
d = f.read()
The type of d is class 'bytes' and if I print it it looks like:
b'\x1f\x8b\x08\x00\x00\x00 .... etc
I tried d=f.read().decode('utf-8') as that is the ch... | [
"Check to make sure your response body is not gzipped. Believe its transfer encoding or such for the response header, i have a high confidence that your dealing with compressed data and not character set encoding issues.\nupdate: Realizing I have a bad habit of not explaining/providing enough detail. For Python... | [
6
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0003746993_python_urllib.txt |
Q:
How to open a link with different proxy IP adresses in python?
I want to click a link over and over again while different proxies are enabled to trick the host into thinking I am doing it on different IP adresses. What is the simples way to do this in python?
Thanks!
A:
First, get a list of proxies, then use som... | How to open a link with different proxy IP adresses in python? | I want to click a link over and over again while different proxies are enabled to trick the host into thinking I am doing it on different IP adresses. What is the simples way to do this in python?
Thanks!
| [
"First, get a list of proxies, then use something like \nimport socks\nimport socket\nimport urllib2\n\nproxies = ['127.0.0.1:1080', 'someproxy:1888', ... ] # you could load a file here\n\n\nfor proxy in proxies:\n socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, *proxy.split(':', 1))\n socket.socket = socks.so... | [
1
] | [] | [] | [
"proxy",
"python"
] | stackoverflow_0003747068_proxy_python.txt |
Q:
Python ejabberd Auth Script not responding to changes in Database
I have an authentication script in ejabberd (XMPP server) that based off of THIS LINK
I have slightly modified the script so that instead of setting the variable out, it just returns true or false.
I'm using Ubuntu, MySQL, ejabberd, and Python.
I c... | Python ejabberd Auth Script not responding to changes in Database | I have an authentication script in ejabberd (XMPP server) that based off of THIS LINK
I have slightly modified the script so that instead of setting the variable out, it just returns true or false.
I'm using Ubuntu, MySQL, ejabberd, and Python.
I can authenticate all the records that are already on the database. But, ... | [
"I managed to fix this problem by changing the database engine back to MYISAM rather than INNODB. But I would like to know if this can be fixed for INNODB.\nEdit: to fix it in innodb, set autocommit to true\n"
] | [
1
] | [] | [] | [
"authentication",
"ejabberd",
"mysql",
"python",
"xmpp"
] | stackoverflow_0003746431_authentication_ejabberd_mysql_python_xmpp.txt |
Q:
__import__() calls __init__.py twice?
I was just wondering why __import__() calls a __init__ module twice when loading a package.
test.py
testpkg/
__init__.py
test.py:
pkg = __import__("testpkg", fromlist=[''])
__init__.py:
print "Called."
After calling python test.py, Called. will be printed out twice.... | __import__() calls __init__.py twice? | I was just wondering why __import__() calls a __init__ module twice when loading a package.
test.py
testpkg/
__init__.py
test.py:
pkg = __import__("testpkg", fromlist=[''])
__init__.py:
print "Called."
After calling python test.py, Called. will be printed out twice. Why does python execute the __init__ "modu... | [
"This is a Python bug. Passing the null string as an element of fromlist is illegal, and should raise an exception.\nThere's no need to include \"\" in fromlist; that's implicit--the module itself is always loaded. What's actually happening is the module.submodule string is using the null string, resulting in the... | [
5,
5
] | [] | [] | [
"python"
] | stackoverflow_0003745221_python.txt |
Q:
Scrapy make_requests_from_url(url)
In the Scrapy tutorial there is this method of the BaseSpider:
make_requests_from_url(url)
A method that receives a URL and
returns a Request object (or a list of
Request objects) to scrape.
This method is used to construct the
initial requests in the
start_requests() method, an... | Scrapy make_requests_from_url(url) | In the Scrapy tutorial there is this method of the BaseSpider:
make_requests_from_url(url)
A method that receives a URL and
returns a Request object (or a list of
Request objects) to scrape.
This method is used to construct the
initial requests in the
start_requests() method, and is
typically used to convert urls to
r... | [
"That's right, the CrawlSpider is useful and convenient in many cases, but it only covers a subset of all possible spiders. If you need something more complex, you typically subclass BaseSpider and implement start_requests() method.\n"
] | [
5
] | [] | [] | [
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0001810143_python_scrapy_web_crawler.txt |
Q:
Other solutions/languages that are superior to the TCL-based Expect?
I am amazed by how Expect (TCL) can automate a lot of things I normally could not do.
I thought I could dig deeper into Expect by reading a book, but before I do that I want to ask if there are other solutions/languages that could do what Expect ... | Other solutions/languages that are superior to the TCL-based Expect? | I am amazed by how Expect (TCL) can automate a lot of things I normally could not do.
I thought I could dig deeper into Expect by reading a book, but before I do that I want to ask if there are other solutions/languages that could do what Expect does?
Eg. I have read that people compare Expect with Awk and also Perl.
C... | [
"There's more to it.\nBluntly, the original Expect--the Tcl Expect--is the best one. It better supports \"interact\" and various pty eccentricities than any of its successors. It has no superior, for what it does.\nHOWEVER, at the same time, most Expect users exploit such a small fraction of Expect's capabilities... | [
9,
7,
4,
2
] | [] | [] | [
"awk",
"expect",
"perl",
"python",
"tcl"
] | stackoverflow_0003746221_awk_expect_perl_python_tcl.txt |
Q:
Python27 IDLE GUI stopped working
For some reason my Python IDLE interface stopped working :( I ran a some code which seems to have been buggy since i couldn't even exit it with ctrl+F6. I had to close the IDLE window down and since then it won't launch anymore. Reinstalling Python didn't make any difference....an... | Python27 IDLE GUI stopped working | For some reason my Python IDLE interface stopped working :( I ran a some code which seems to have been buggy since i couldn't even exit it with ctrl+F6. I had to close the IDLE window down and since then it won't launch anymore. Reinstalling Python didn't make any difference....any ideas to help me get it runnig again ... | [
"uninstalling Python AND manually deleting the Python installation folder (which isn't removed by default when uninstalling) allowed me to re-install Python successfully\n"
] | [
0
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0003747402_python_user_interface.txt |
Q:
Building python Shell
I have some small python 2.6 scripts built....
Now, I would like run them as seperate processes within a python shell. Each as a seperate process. If one fails to run maybe with its timer, I would like others to continue without killing all scripts.
Should I do this as singleton gui's or com... | Building python Shell | I have some small python 2.6 scripts built....
Now, I would like run them as seperate processes within a python shell. Each as a seperate process. If one fails to run maybe with its timer, I would like others to continue without killing all scripts.
Should I do this as singleton gui's or combine them into bigger launc... | [
"Check joblaunch, a shell tool I made for executing interdependent jobs in parallel locally. It has more options.\n"
] | [
3
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0003747682_python_shell.txt |
Q:
Getting BadValueError on Google App Engine Datastore Delete
I am trying to delete records in the datastore. Unfortunately, whenever I try to delete the items, it gives me a BadValueError, saying Districts (one of the columns) is required. Because of an issue with the bulk loader, Districts is null for all of the... | Getting BadValueError on Google App Engine Datastore Delete | I am trying to delete records in the datastore. Unfortunately, whenever I try to delete the items, it gives me a BadValueError, saying Districts (one of the columns) is required. Because of an issue with the bulk loader, Districts is null for all of the rows...but I still need to clean out the datastore to try to fix... | [
"Try updating your model so that the Districts field is not required (i.e., pass required=False as a keyword parameter to the Districts field). Then the validator shouldn't complain about the existing entities and you should be able to delete the entities.\nAlternatively, if you know the keys for the entities you ... | [
3,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003747772_google_app_engine_python.txt |
Q:
easy way to determine if a string CAN'T be a valid regex
I have a config file that the user can specify sections, and then within those section they can specify regular expressions. I have to parse this config file and separate the regex's into the various sections.
Is there an easy way to delimitate a regex from ... | easy way to determine if a string CAN'T be a valid regex | I have a config file that the user can specify sections, and then within those section they can specify regular expressions. I have to parse this config file and separate the regex's into the various sections.
Is there an easy way to delimitate a regex from a section header? I was thinking just the standard
[section]
... | [
"There's an unlimited ways of making an invalid regexp, but the first thing that comes to mind would be\n*section*\n\nYou can't have a quantifier (*) at the start of the regexp.\n(The other * is there just to satisfy my obsession for symmetry.)\n",
"I don't know your problem domain, so I don't know what forms of ... | [
4,
1,
0,
0
] | [] | [] | [
"delimiter",
"parsing",
"python",
"regex"
] | stackoverflow_0003743653_delimiter_parsing_python_regex.txt |
Q:
Read each line of HTML form submission Python
I'm building a small web app with Python on GAE.
I have an HTML form with a where users enter a list of items (one item per line). When the form is submitted I want to read each line and store separate entries in the datastore for each item (i.e. line).
I want to do s... | Read each line of HTML form submission Python | I'm building a small web app with Python on GAE.
I have an HTML form with a where users enter a list of items (one item per line). When the form is submitted I want to read each line and store separate entries in the datastore for each item (i.e. line).
I want to do something similar to f.readline() for files, but on ... | [
"Sounds like you want (have?) a text area control in your form, like the one I'm typing into now. Something like this?\n<textarea name=\"items\"></textarea>\n\nWhen handling the POST request for the form, you will be able to get the value of the text area like so.\nitemList = self.request.get(\"items\")\n\nIt will ... | [
4
] | [] | [] | [
"forms",
"html",
"python",
"submission"
] | stackoverflow_0003747784_forms_html_python_submission.txt |
Q:
how do I repeat python unit tests on different data?
I am testing classes that parse XML and create DB objects (for a Django app).
There is a separate parser/creater class for each different XML type that we read (they all create essentially the same objects). Each parser class has the same superclass so they all... | how do I repeat python unit tests on different data? | I am testing classes that parse XML and create DB objects (for a Django app).
There is a separate parser/creater class for each different XML type that we read (they all create essentially the same objects). Each parser class has the same superclass so they all have the same interface.
How do I define one set of test... | [
"With nose, you can define test generators. You can define the test case and then write a test generator which will yield one test function for each parser class.\n",
"If you are using unittest, which has the advantage of being supported by django and installed on most systems, you can do something like:\nclass T... | [
3,
2
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0003742791_python_unit_testing.txt |
Q:
Alternative to python atexit module that works when called from other scripts
Using atexit.register(function) to register a function to be called when your python script exits is a common practice.
The problem is that I identified a case when this fails in an ugly way: if your script it executed from another pytho... | Alternative to python atexit module that works when called from other scripts | Using atexit.register(function) to register a function to be called when your python script exits is a common practice.
The problem is that I identified a case when this fails in an ugly way: if your script it executed from another python script using the execfile().
In this case you will discover that Python will not ... | [
"I think the problem you're having is with the location of the current working directory. You could ensure that you're specifying the correct location doing something like this:\nimport os\n\ntarget = os.path.join(os.path.dirname(__file__), \"mytarget.py\")\n\n",
"This works for me. I created a file to be execute... | [
0,
0
] | [] | [] | [
"atexit",
"execfile",
"python"
] | stackoverflow_0003666506_atexit_execfile_python.txt |
Q:
How to package example scripts using distribute?
I use distribute to package a small python library. I made a directory structure as described in the Hitchhiker's Guide to Packaging.
My question: Where (in the directory structure) do I place example scripts that show how to use the library and what changes are nec... | How to package example scripts using distribute? | I use distribute to package a small python library. I made a directory structure as described in the Hitchhiker's Guide to Packaging.
My question: Where (in the directory structure) do I place example scripts that show how to use the library and what changes are necessary to the setup.py?
| [
"I think its good, not to install the examples,\nrather you can keep your examples folder with your distribution, so it may be on the same level where your setup.py,\nIf you want to include them, then include as separate module of package, like 'example' - and that directory holds the all example scripts, that user... | [
1,
1
] | [] | [] | [
"distribute",
"packaging",
"python"
] | stackoverflow_0003661169_distribute_packaging_python.txt |
Q:
Python meta-debugging
Heyo,
Just started writing an assembler for the imaginary computer my class is creating wire-by-wire since the one the TA's provided sucks hard. I chose python even though I've never really used it that much (but know the basic syntax) and am loving it.
My favorite ability is how I can take ... | Python meta-debugging | Heyo,
Just started writing an assembler for the imaginary computer my class is creating wire-by-wire since the one the TA's provided sucks hard. I chose python even though I've never really used it that much (but know the basic syntax) and am loving it.
My favorite ability is how I can take a method I just wrote, past... | [
"you can import the module that your code is in. This will expose all of the symbols prefixed with the module name.\nThe details for the easiest way to do it depend on your operating system but you can always do:\n>>> sys.path.append('/path/to/directory/that/my/module/is/in/')\n>>> import mymod #.py\n\nlater after ... | [
1,
0
] | [] | [] | [
"python",
"python_idle"
] | stackoverflow_0003747980_python_python_idle.txt |
Q:
pythonic way to rewrite an assignment in an if statement
Is there a pythonic preferred way to do this that I would do in C++:
for s in str:
if r = regex.match(s):
print r.groups()
I really like that syntax, imo it's a lot cleaner than having temporary variables everywhere. The only other way that's n... | pythonic way to rewrite an assignment in an if statement | Is there a pythonic preferred way to do this that I would do in C++:
for s in str:
if r = regex.match(s):
print r.groups()
I really like that syntax, imo it's a lot cleaner than having temporary variables everywhere. The only other way that's not overly complex is
for s in str:
r = regex.match(s)
... | [
"How about\nfor r in [regex.match(s) for s in str]:\n if r:\n print r.groups()\n\nor a bit more functional\nfor r in filter(None, map(regex.match, str)):\n print r.groups()\n\n",
"Perhaps it's a bit hacky, but using a function object's attributes to store the last result allows you to do something al... | [
10,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"if_statement",
"python",
"syntax"
] | stackoverflow_0003744382_if_statement_python_syntax.txt |
Q:
webapp folder structure for securing plaintext passwords and sqlite database
Im building a simple web app in Python using web.py - and was wondering what best practices are in terms of securing the application.
I had two main questions at this stage:
I want the application to be able
to send email - its not ... | webapp folder structure for securing plaintext passwords and sqlite database | Im building a simple web app in Python using web.py - and was wondering what best practices are in terms of securing the application.
I had two main questions at this stage:
I want the application to be able
to send email - its not hosted on
GAE, but I thought a simple
solutions might be to write / find a... | [
"Obviously there must not be any direct access to the file system via an HTTP request.\nAnd I'm pretty sure that's impossible if you're using web.py anyway. When you create an application using web.py, you create a list of regular expressions for URLs which map to a class to send the request to. As long as every re... | [
0
] | [] | [] | [
"python",
"security",
"sqlite",
"web_applications"
] | stackoverflow_0003748151_python_security_sqlite_web_applications.txt |
Q:
Python egg found interactively but not in fastcgi
In agreement to this question, and its answer. I added the path of the egg and it worked. However, when I run python interactively and I import flup, it works without any problem or additional path specification. Where is the difference ?
Edit: It appears that whil... | Python egg found interactively but not in fastcgi | In agreement to this question, and its answer. I added the path of the egg and it worked. However, when I run python interactively and I import flup, it works without any problem or additional path specification. Where is the difference ?
Edit: It appears that while doing fastcgi stuff, the .pth files are not parsed, b... | [
"After some more thorough analysis, I think I understand what's going on here.\nWhen Python starts up, it sets up the sys.path (all as part of initializing the interpreter).\nAt this time, the environment is used to determine where to find .pth files. If no PYTHONPATH is defined at this time, then it won't find yo... | [
2,
0,
0,
0
] | [] | [] | [
"egg",
"fastcgi",
"python"
] | stackoverflow_0001384717_egg_fastcgi_python.txt |
Q:
Flask for Python - architectural question regarding the system
I've been using Django and Django passes in a request object to a view when it's run. It looks like (from first glance) in Flask the application owns the request and it's imported (as if it was a static resource). I don't understand this and I'm just t... | Flask for Python - architectural question regarding the system | I've been using Django and Django passes in a request object to a view when it's run. It looks like (from first glance) in Flask the application owns the request and it's imported (as if it was a static resource). I don't understand this and I'm just trying to wrap my brain around WSGI and Flask, etc. Any help is appre... | [
"In Flask request is a thread-safe global, so you actually do import it:\nfrom flask import request\n\nI'm not sure this feature is related to WSGI as other WSGI micro-frameworks do pass request as a view function argument. \"Global\" request object is a feature of Flask. Flask also encourages to store user's data ... | [
7
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0003746844_flask_python.txt |
Q:
Setting up Django on an internal server (os.environ() not working as expected?)
I'm trying to setup Django on an internal company server. (No external connection to the Internet.)
Looking over the server setup documentation it appears that the "Running Django on a shared-hosting provider with Apache" method seems ... | Setting up Django on an internal server (os.environ() not working as expected?) | I'm trying to setup Django on an internal company server. (No external connection to the Internet.)
Looking over the server setup documentation it appears that the "Running Django on a shared-hosting provider with Apache" method seems to be the most-likely to work in this situation.
Here's the server information:
Can'... | [
"In your settings you have to point go actual egg file, not directory where egg file is located. It should look something like:\nsys.path.append('/path/to/flup/egg/flup-1.0.1-py2.5.egg')\n\n",
"Try using a utility called virtualenv. According to the official package page, \"virtualenv is a tool to create isolated... | [
3,
2,
1,
0
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0000531224_apache_django_python.txt |
Q:
List of floats on the google appengine
Been hunting for an hour or so. It would appear that db.Float does not exist. Is there any way to store a list of floats in a ListProperty? Here's the basic idea:
class Data(db.Model):
temperatures = db.ListProperty(item_type=???)
Thanks in advance.
A:
There is a Float... | List of floats on the google appengine | Been hunting for an hour or so. It would appear that db.Float does not exist. Is there any way to store a list of floats in a ListProperty? Here's the basic idea:
class Data(db.Model):
temperatures = db.ListProperty(item_type=???)
Thanks in advance.
| [
"There is a FloatProperty but that has nothing to do with ListProperty's first argument, which, and I quote, is just \"a Python type or class\" (and float is explicitly listed here as a perfectly OK value type, too). IOW,\ntemperatures = db.ListProperty(float)\n\nshould work just fine (float is a Python built-in i... | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003748288_google_app_engine_google_cloud_datastore_python.txt |
Q:
How to get string representations of classes and functions uniformly?
I think is is best explained with an example. Suppose I have a method that calculates the distances between two vectors and prints it. I also want that method to print the distance measure that was used. The distance measure is given to the func... | How to get string representations of classes and functions uniformly? | I think is is best explained with an example. Suppose I have a method that calculates the distances between two vectors and prints it. I also want that method to print the distance measure that was used. The distance measure is given to the function by the caller in the form of a callable object. If the callable is an ... | [
"I don't think functions can be subclassed, which is what you'd need to do in order to change a function's __str__ method. It's much easier to make a class behave like functions (using the __call__ method).\nFunctions have a func_name attribute, that returns the function's name.\nIf you choose to use the func_name ... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003746187_python.txt |
Q:
Complete newbie excited about Python. How hard would this app be to build?
I have been wanting to get into Python for a while now and have accumulated quite a few links to tutorials, books, getting started guides and the like. I have done a little programming in PERL and PHP, but mostly just basic stuff.
I'd like ... | Complete newbie excited about Python. How hard would this app be to build? | I have been wanting to get into Python for a while now and have accumulated quite a few links to tutorials, books, getting started guides and the like. I have done a little programming in PERL and PHP, but mostly just basic stuff.
I'd like to be able to set expectations for myself, so based on the following requirement... | [
"Assuming you're already familiar with another programming language: \n\nTime to learn python basics: 1 week. \nTotal time to figure out email module: 2 days. \nTotal time to figure out httplib module: 1 days. \nTotal time to figure out creating database: 3 days.\nTotal time to learn about SQL: 2 weeks.\nTotal time... | [
7,
0
] | [] | [] | [
"python"
] | stackoverflow_0003748720_python.txt |
Q:
Adding optional parameters to the constructors of multiply-inheriting subclasses of built-in types?
My multiple-inheritance-fu is not strong. I am trying to create a superclass whose __init__ takes an optional named parameter and subclasses of it which also inherit from built-in types. Sadly, I appear to have no... | Adding optional parameters to the constructors of multiply-inheriting subclasses of built-in types? | My multiple-inheritance-fu is not strong. I am trying to create a superclass whose __init__ takes an optional named parameter and subclasses of it which also inherit from built-in types. Sadly, I appear to have no idea how to make this work:
>>> class Super(object):
name = None
def __init__(self, *args, name=... | [
"You just cannot pass arbitrary parameters (whether positional or named ones) to an equally arbitrary superclass (i.e., \"immediately previous type in the mro of whatever the current leaf type is\") -- most types and classes just don't accept arbitrary parameters, for excellent reasons too -- quoting from the middl... | [
3
] | [] | [] | [
"multiple_inheritance",
"python",
"python_3.x"
] | stackoverflow_0003748635_multiple_inheritance_python_python_3.x.txt |
Q:
How do I specify a range of unicode characters in a regular-expression in python?
I am trying to match a range of Unicode characters and I am wondering how to do it. I can match simple ranges like [a-zA-Z] but how do I specify a range of Unicode characters. I've tried
[#xD8-#xF6]
without any luck. Any ideas?
A:
... | How do I specify a range of unicode characters in a regular-expression in python? | I am trying to match a range of Unicode characters and I am wondering how to do it. I can match simple ranges like [a-zA-Z] but how do I specify a range of Unicode characters. I've tried
[#xD8-#xF6]
without any luck. Any ideas?
| [
"Try:\n[\\u00D8-\\u00F6]\n\n",
"Python 2.X\nu'[\\u00d8-\\u00f6]'\n\nPython 3.X\n'[\\u00d8-\\u00f6]'\n\n"
] | [
34,
11
] | [] | [] | [
"python",
"regex",
"unicode"
] | stackoverflow_0003748855_python_regex_unicode.txt |
Q:
Accessing first element of output in lxml.html
With lxml.html, how do I access single elements without using a for loop?
This is the HTML:
<tr class="headlineRow">
<td>
<span class="headline">This is some awesome text</span>
</td>
</tr>
For example, this will fail with IndexError:
for row in doc.cssselec... | Accessing first element of output in lxml.html | With lxml.html, how do I access single elements without using a for loop?
This is the HTML:
<tr class="headlineRow">
<td>
<span class="headline">This is some awesome text</span>
</td>
</tr>
For example, this will fail with IndexError:
for row in doc.cssselect('tr.headlineRow'):
headline = row.cssselect('... | [
"I usually use the xpath method for things like this.\nIt returns a list of matching elements.\n>>> spans = doc.xpath('//tr[@class=\"headlineRow\"]/td/span[@class=\"headline\"]')\n>>> spans[0].text\n'This is some awesome text'\n\n",
"I tried out your example using CSSSelector and headline[0] worked fine. See belo... | [
1,
0,
0,
0
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0003572693_lxml_python.txt |
Q:
erase template cache
I have a Django app where users can select between 2 interface modes, that mode affect some pages... for those pages I use different templates
In urls.py I have something like this:
mode = Config.objects.get().mode
urlpatterns = patterns('',
url(r'^my_url/$', 'custom_view', {'template':'my... | erase template cache | I have a Django app where users can select between 2 interface modes, that mode affect some pages... for those pages I use different templates
In urls.py I have something like this:
mode = Config.objects.get().mode
urlpatterns = patterns('',
url(r'^my_url/$', 'custom_view', {'template':'my_template.html', 'mode':mo... | [
"Getting the mode in urls.py is not going to work. The get will only be executed once, when the file is first imported.\nDo the database work in the view function, instead.\n"
] | [
3
] | [] | [] | [
"django",
"django_cache",
"django_caching",
"python"
] | stackoverflow_0003748851_django_django_cache_django_caching_python.txt |
Q:
Problem with Django using Apache2 (mod_wsgi), Occassionally is "unable to import from module" for no apparent reason
I have put my Django web site up to my web server and have it set up using apache2 and mod_wsgi.. everything works fine most of the time but occasionally it will just give the error that it can't im... | Problem with Django using Apache2 (mod_wsgi), Occassionally is "unable to import from module" for no apparent reason | I have put my Django web site up to my web server and have it set up using apache2 and mod_wsgi.. everything works fine most of the time but occasionally it will just give the error that it can't import a module (usually from my views file). However, it's not an issue with that module as it usually works, for example, ... | [
"It is working most of the time because you likely have a multi process configuration and only one of the processes is affected.\nYou can try alternate WSGI script file as documented in:\nhttp://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html\nThe jury is still out as to whether the issue is the di... | [
1
] | [] | [] | [
"apache2",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0003749033_apache2_django_mod_wsgi_python.txt |
Q:
How to import the Python async module from a worker thread?
I'm using the GitPython package to access a Git repository from Python. This pulls in the async package. In async/__init__.py, the following happens:
def _init_signals():
"""Assure we shutdown our threads correctly when being interrupted"""
import... | How to import the Python async module from a worker thread? | I'm using the GitPython package to access a Git repository from Python. This pulls in the async package. In async/__init__.py, the following happens:
def _init_signals():
"""Assure we shutdown our threads correctly when being interrupted"""
import signal
# ...
signal.signal(signal.SIGINT, thread_interru... | [
"If you pull the latest async code from git, I suspect this will be fixed for you and is called out as a non-fatal error in the patch\n"
] | [
0
] | [] | [] | [
"asynchronous",
"gitpython",
"multithreading",
"python",
"signals"
] | stackoverflow_0003657732_asynchronous_gitpython_multithreading_python_signals.txt |
Q:
Summarizing inside a Django template
I have the following template in django, i want to get the totals of the last 2 columns for each of my document objects
{% for documento in documentos %}
{% for cuenta in documento.cuentasxdocumento_set.all %}
<tr {% cycle 'class="gray"' '' %} >
{% if fo... | Summarizing inside a Django template | I have the following template in django, i want to get the totals of the last 2 columns for each of my document objects
{% for documento in documentos %}
{% for cuenta in documento.cuentasxdocumento_set.all %}
<tr {% cycle 'class="gray"' '' %} >
{% if forloop.first %}
<td>{{ ... | [
"From my experience with Django, I would say that these things aren't easily done in the template. I try to do my calculations in the view instead of the template. \nMy recommendation would be to calculate the two sums you need in the view instead of the template.\nThat beings said, it is possible to do some work i... | [
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003748356_django_django_templates_python.txt |
Q:
How to align 2 toolbars on same the row, one aligned left and one aligned right?
I use wxPython to sketch up a user interface for the a python program. I need to put 2 toolbars on the same row. One toolbar is on the left while the other is on the right.
I use BoxSizer to achieve this (by putting a stretchable spac... | How to align 2 toolbars on same the row, one aligned left and one aligned right? | I use wxPython to sketch up a user interface for the a python program. I need to put 2 toolbars on the same row. One toolbar is on the left while the other is on the right.
I use BoxSizer to achieve this (by putting a stretchable space between 2 toolbars)
However, the stretchable space produces a blank space between 2... | [
"It's been a while since I used wxPython, but have you tried removing the spacer and setting the proportion of the first toolbar to greater than that of the second? Eg\ntopToolBar.Add(toolbar1,1,wx.ALIGN_LEFT,4) # note the 2nd param 'proportion' is 1\n#topToolBar.AddStretchSpacer()\ntopToolBar.Add(toolbar1,0,wx.ALI... | [
4
] | [] | [] | [
"alignment",
"interface",
"python",
"toolbar",
"wxpython"
] | stackoverflow_0003748990_alignment_interface_python_toolbar_wxpython.txt |
Q:
how to create a class in python which would store a tree
I want to make a class in python, which would store a tree.Keeps taking three inputs the main node the left node and right node and stores it in such a way that later I can print it in tree format.
A:
this should help http://knuth.luther.edu/~pythonworks/S... | how to create a class in python which would store a tree | I want to make a class in python, which would store a tree.Keeps taking three inputs the main node the left node and right node and stores it in such a way that later I can print it in tree format.
| [
"this should help http://knuth.luther.edu/~pythonworks/Source/chap5/\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003748239_python.txt |
Q:
Type safety in Python
I've defined a Vector class which has three property variables: x, y and z. Coordinates have to be real numbers, but there's nothing to stop one from doing the following:
>>> v = Vector(8, 7.3, -1)
>>> v.x = "foo"
>>> v.x
"foo"
I could implement "type safety" like this:
import numbers
class... | Type safety in Python | I've defined a Vector class which has three property variables: x, y and z. Coordinates have to be real numbers, but there's nothing to stop one from doing the following:
>>> v = Vector(8, 7.3, -1)
>>> v.x = "foo"
>>> v.x
"foo"
I could implement "type safety" like this:
import numbers
class Vector:
def __init__(s... | [
"You have to ask yourself why you want to test type on setting these values. Just raise a TypeError in any calculation which happens to stumble over the wrong value type. Bonus: standard operations already do this.\n>>> 3.0 / 'abc'\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nTypeError: un... | [
18,
12,
5,
4,
2
] | [] | [] | [
"python",
"type_safety"
] | stackoverflow_0003749796_python_type_safety.txt |
Q:
Unicode problems when using io.StringIO to mock a file
I am using an io.StringIO object to mock a file in a unit-test for a class. The problem is that this class seems expect all strings to be unicode by default, but the builtin str does not return unicode strings:
>>> buffer = io.StringIO()
>>> buffer.write(str((... | Unicode problems when using io.StringIO to mock a file | I am using an io.StringIO object to mock a file in a unit-test for a class. The problem is that this class seems expect all strings to be unicode by default, but the builtin str does not return unicode strings:
>>> buffer = io.StringIO()
>>> buffer.write(str((1, 2)))
TypeError: can't write str to text stream
But
>>> b... | [
"The io package provides python3.x compatibility. In python 3, strings are unicode by default.\nYour code works fine with the standard StringIO package,\n>>> from StringIO import StringIO\n>>> StringIO().write(str((1,2)))\n>>>\n\nIf you want to do it the python 3 way, use unicode() in stead of str(). You have to be... | [
11
] | [] | [] | [
"python",
"stringio",
"unicode"
] | stackoverflow_0003749502_python_stringio_unicode.txt |
Q:
order("-modified") with geomodel
Edit: Solved using key=lambda and learning what I'm actually doing.
With gemodel like
class A(GeoModel,search.SearchableModel):
I'm trying to order by date using db.GeoPt to store google maps
coordinates with GAE and geomodel I can map and match. But order("-
modified") is not wo... | order("-modified") with geomodel | Edit: Solved using key=lambda and learning what I'm actually doing.
With gemodel like
class A(GeoModel,search.SearchableModel):
I'm trying to order by date using db.GeoPt to store google maps
coordinates with GAE and geomodel I can map and match. But order("-
modified") is not working. There is no trace. All ideas ar... | [
"GeoModel performs multiple queries and combines the results into a single resultset. Each query should be executed with your sort order, but the end results may not be sorted according to that order. Sorting the results in memory is probably sufficient to overcome this.\n",
"GeoModel sorts the result of the near... | [
5,
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003745606_google_app_engine_python.txt |
Q:
BulkLoader -export_transform
I have created web application using java.I wantted to download data from appengine datastroe so that I am using BulkLoader concept.
In my project I designed entity as follows
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long school_id;
@Basic
private String scho... | BulkLoader -export_transform | I have created web application using java.I wantted to download data from appengine datastroe so that I am using BulkLoader concept.
In my project I designed entity as follows
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long school_id;
@Basic
private String schoolname;
After that I tried to dow... | [
"Try export_transform: datastore.Key.name\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003749806_google_app_engine_python.txt |
Q:
While running some java DB Unit tests which call a python script how can I test the code coverage for the python script?
I have a python script which generates some reports based on a DB.
I am testing the script using java Db Units which call the python script.
My question is how can I verify the code coverage for... | While running some java DB Unit tests which call a python script how can I test the code coverage for the python script? | I have a python script which generates some reports based on a DB.
I am testing the script using java Db Units which call the python script.
My question is how can I verify the code coverage for the python script while I am running the DB Units?
| [
"I don't know how you can check for inter-language unit test coverage. You will have to tweak the framework yourself to achieve something like this.\nThat said, IMHO this is a wrong approach to take for various reasons. \n\nInter-language disqualifies the tests from being described as \"unit\". These are functional... | [
0,
0
] | [] | [] | [
"code_coverage",
"python"
] | stackoverflow_0003749729_code_coverage_python.txt |
Q:
Mapping result of psycopg2 into dataframe for R with RPY2
With psycopg2, i get result of query in this form :
[(15002325, 24, 20, 1393, -67333094L,
38, 4, 493.48763257822799,
493.63348372593703), (15002339, 76, 20, 1393, -67333094L, 91, 3,
499.95845909922201, 499.970048093743), (15002431, 24, 20, 1394, -67... | Mapping result of psycopg2 into dataframe for R with RPY2 | With psycopg2, i get result of query in this form :
[(15002325, 24, 20, 1393, -67333094L,
38, 4, 493.48763257822799,
493.63348372593703), (15002339, 76, 20, 1393, -67333094L, 91, 3,
499.95845909922201, 499.970048093743), (15002431, 24, 20, 1394, -67333094L,
38, 4, 493.493464900383,
493.63348372593703), (150... | [
"import rpy2.robjects as ro\nr=ro.r\n\ndata=[(15002325, 24, 20, 1393, -67333094L, 38, 4, 493.48763257822799, 493.63348372593703), (15002339, 76, 20, 1393, -67333094L, 91, 3, 499.95845909922201, 499.970048093743), (15002431, 24, 20, 1394, -67333094L, 38, 4, 493.493464900383, 493.63348372593703), (15002483, 76, 20, 1... | [
1
] | [] | [] | [
"dataframe",
"mapping",
"psycopg2",
"python",
"rpy2"
] | stackoverflow_0003750398_dataframe_mapping_psycopg2_python_rpy2.txt |
Q:
Django ORM with Postgres: rows unexpectedly deleted - Bug?
I have the problem that objects were unexpectedly deleted and created a minimal example. I dont't know whether it's a bug or if a made a thinking error.
The models are something like that:
class A(models.Model):
related = models.ForeignKey('C', blank =... | Django ORM with Postgres: rows unexpectedly deleted - Bug? | I have the problem that objects were unexpectedly deleted and created a minimal example. I dont't know whether it's a bug or if a made a thinking error.
The models are something like that:
class A(models.Model):
related = models.ForeignKey('C', blank = True, null = True)
class B(models.Model):
title = models.C... | [
"Django implements foreign keys by default with an \"ON DELETE CASCADE\", which means that records pointing to a deleted record will also be deleted. It's not a bug, it's designed on purpose this way.\nWorkarounds are discussed elsewhere on stackoverflow.\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"postgresql",
"python"
] | stackoverflow_0003750404_django_django_models_postgresql_python.txt |
Q:
Is it possible to generate a Python function with arguments in runtime?
Say,
I have a python function as following:
def ooxx(**kwargs):
doSomething()
for something in cool:
yield something
I would like to provide another function with named arguments for hints as following:
def asdf(arg1, arg2, ar... | Is it possible to generate a Python function with arguments in runtime? | Say,
I have a python function as following:
def ooxx(**kwargs):
doSomething()
for something in cool:
yield something
I would like to provide another function with named arguments for hints as following:
def asdf(arg1, arg2, arg3=1):
frame = inspect.currentframe()
args, _, _, values = inspect.ge... | [
"Your descriptions doesn't make such sense to me: You wrote a really verbose function that does this:\ndef asdf(arg1, arg2, arg3=1):\n return list(ooxx(**locals()))\n\nbut you want to inspect the ooxx and somehow make up appropriate names for asdfs arguments? That is impossible, there is no information about thi... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003751035_python.txt |
Q:
What's Wrong With This HTTP/1.1 Request? Sometimes the Client Accepts it, and Sometimes it Rejects it
I am in the process of writing a small HTTP/1.1 web server. I have threading turned off and am not currently using persistent connections. For normal requests where I specify the Content-Length and write the bytes... | What's Wrong With This HTTP/1.1 Request? Sometimes the Client Accepts it, and Sometimes it Rejects it | I am in the process of writing a small HTTP/1.1 web server. I have threading turned off and am not currently using persistent connections. For normal requests where I specify the Content-Length and write the bytes out to the socket, everything works great.
However, I need the ability to support chunked transfer encodin... | [
"Wild guess: the Connection:close-Header doesn't \"feel\" right. Actually, I think this is a request-header, not a response-header.\nEdit: If I read this part of RFC2616 correctly, HTTP-Continue (HTTP 100) tells the client to continue with its request, so maybe this header should also be omitted.\n"
] | [
0
] | [] | [] | [
"http",
"python"
] | stackoverflow_0003751249_http_python.txt |
Q:
Django on Google App Engine: debug queries to datastore
What is the best way to get something similar to django-debug-toolbar working on Google App Engine? At least I want to log all GQL at my local development environment. I am using django-nonrel + djangoappengine + djangotoolbox.
I tried:
debug-toolbar - does ... | Django on Google App Engine: debug queries to datastore | What is the best way to get something similar to django-debug-toolbar working on Google App Engine? At least I want to log all GQL at my local development environment. I am using django-nonrel + djangoappengine + djangotoolbox.
I tried:
debug-toolbar - does not work
http://popcnt.org/2008/05/google-app-engine-tips.htm... | [
"You need Appstats, which comes with the App Engine Python SDK.\n"
] | [
3
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003751000_django_google_app_engine_python.txt |
Q:
Python: Passing unicode string to C++ module
I'm working with an existing module at the moment that provides a C++ interface and does a few operations with strings.
I needed to use Unicode strings and the module unfortunately didn't have any support for a Unicode interface, so I wrote an extra function to add to t... | Python: Passing unicode string to C++ module | I'm working with an existing module at the moment that provides a C++ interface and does a few operations with strings.
I needed to use Unicode strings and the module unfortunately didn't have any support for a Unicode interface, so I wrote an extra function to add to the interface:
void SomeUnicodeFunction(const wchar... | [
"Found a hack to work around the problem:\nSomeModule.SomeUnicodeFunction(str(s.encode('utf-8')))\n\nIt seems to be working fine for my purposes so far.\nUpdate: Actually, using UTF-8 means I avoid any need for SomeUnicodeFunction and can use the standard SomeFunction without specialising for unicode. Learn somethi... | [
2,
2
] | [] | [] | [
"c++",
"module",
"python",
"unicode"
] | stackoverflow_0003744247_c++_module_python_unicode.txt |
Q:
Encoding calling from pyodbc to a MS SQL Server
I am connecting to a MS SQL server through SQL Alchemy, using pyodbc module. Everything appears to be working fine, until I began having problems with the encodings. Some of the non-ascii characters are being replaced with '?'
The DB has a collation 'Latin1_General_C... | Encoding calling from pyodbc to a MS SQL Server | I am connecting to a MS SQL server through SQL Alchemy, using pyodbc module. Everything appears to be working fine, until I began having problems with the encodings. Some of the non-ascii characters are being replaced with '?'
The DB has a collation 'Latin1_General_CI_AS' (I've checked also the specific fields and they... | [
"You should stop using code pages and switch to Unicode. This is the only way of getting rid of this kind of problems.\n",
"Original comment turned into an answer:\ncp1250 and cp1252 are NOT \"latin1 encodings\". A collation is not an encoding. Re your comment: Who says that \"the server is encoded in latin1\"? I... | [
2,
2,
1,
0
] | [] | [] | [
"encoding",
"python",
"sql_server",
"sqlalchemy"
] | stackoverflow_0003750876_encoding_python_sql_server_sqlalchemy.txt |
Q:
Python string formatting + UTF-8 strange behaviour
When printing a formatted string with a fixed length (e.g, %20s), the width differs from UTF-8 string to a normal string:
>>> str1="Adam Matan"
>>> str2="אדם מתן"
>>> print "X %20s X" % str1
X Adam Matan X
>>> print "X %20s X" % str2
X אדם מתן X
... | Python string formatting + UTF-8 strange behaviour | When printing a formatted string with a fixed length (e.g, %20s), the width differs from UTF-8 string to a normal string:
>>> str1="Adam Matan"
>>> str2="אדם מתן"
>>> print "X %20s X" % str1
X Adam Matan X
>>> print "X %20s X" % str2
X אדם מתן X
Note the difference:
X Adam Matan X
X א... | [
"You need to specify that the second string is Unicode by putting u in front of the string:\n>>> str1=\"Adam Matan\"\n>>> str2=u\"אדם מתן\"\n>>> print \"X %20s X\" % str1\nX Adam Matan X\n>>> print \"X %20s X\" % str2\nX אדם מתן X\n\nDoing this lets Python know that it's counting Unicode char... | [
7,
3,
1
] | [] | [] | [
"python",
"string",
"utf_8"
] | stackoverflow_0003751968_python_string_utf_8.txt |
Q:
Is there a framework or pattern for applying filters to data?
The problem:
I have some hierarchical data in a Django application that will be passed on through to javascript. Some of this data will need to be filtered out from javascript based on the state of several data classes in the javascript. I need a way of... | Is there a framework or pattern for applying filters to data? | The problem:
I have some hierarchical data in a Django application that will be passed on through to javascript. Some of this data will need to be filtered out from javascript based on the state of several data classes in the javascript. I need a way of defining the filters in the backend (Django) that will then be app... | [
"Django filters can easily be piled on top of each other.\ninitial_query_set = SomeModel.objects.filter( ... some defaults ... )\nif got_some_option_from_javascript:\n query_set = initial_query_set.filter( this )\nelse:\n query_set = initial_query_set\nif got_some_other_option:\n query_set = query_set.excl... | [
0
] | [] | [] | [
"design_patterns",
"django",
"filter",
"python",
"rule_engine"
] | stackoverflow_0003752083_design_patterns_django_filter_python_rule_engine.txt |
Q:
Python: catching particular exception
I have such code (Python 2.5, GAE dev server):
try:
yt_service.UpgradeToSessionToken() // this line produces TokenUpgradeFailed
except gdata.service.TokenUpgradeFailed:
return HttpResponseRedirect(auth_sub_url()) # this line will never be executed (why?)
except Excepti... | Python: catching particular exception | I have such code (Python 2.5, GAE dev server):
try:
yt_service.UpgradeToSessionToken() // this line produces TokenUpgradeFailed
except gdata.service.TokenUpgradeFailed:
return HttpResponseRedirect(auth_sub_url()) # this line will never be executed (why?)
except Exception, exc:
return HttpResponseRedirect(au... | [
"This error can occur if your relative/absolute import statements do not match everywhere. If there is a mismatch, the target module can be loaded more than once and in slightly different contexts. Usually this isn't a problem but it does prevent classes from the differently loaded modules from comparing as equal (... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003752048_google_app_engine_python.txt |
Q:
Join string and None/string using optional delimiter
I am basically looking for the Python equivalent to this VB/VBA string operation:
FullName = LastName & ", " + FirstName
In VB/VBA + and & are both concatenation operators, but they differ in how they handle a Null value:
"Some string" + Null ==> Null
"Some str... | Join string and None/string using optional delimiter | I am basically looking for the Python equivalent to this VB/VBA string operation:
FullName = LastName & ", " + FirstName
In VB/VBA + and & are both concatenation operators, but they differ in how they handle a Null value:
"Some string" + Null ==> Null
"Some string" & Null ==> "Some string"
This hidden feature allows ... | [
"The following line can be used to concatenate more not-None elements:\nFullName = ', '.join(filter(None, (LastName, FirstName)))\n\n",
"FullName = LastName + (\", \" + FirstName if FirstName else \"\")\n\n",
"Simple ternary operator would do:\n>>> s1, s\n('abc', None)\n>>> print(s if s is None else s1 + s)\nNo... | [
120,
32,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003752240_python_string.txt |
Q:
Retrieve User Entry IDs from MAPI
I extended the win32comext MAPI with the Interface IExchangeModifyTable to edit ACLs via the MAPI. I can modify existing ACL entries, but I stuck in adding new entries. I need the users entry ID to add it, according this C example
(Example Source from MSDN)
STDMETHODIMP AddUserPe... | Retrieve User Entry IDs from MAPI | I extended the win32comext MAPI with the Interface IExchangeModifyTable to edit ACLs via the MAPI. I can modify existing ACL entries, but I stuck in adding new entries. I need the users entry ID to add it, according this C example
(Example Source from MSDN)
STDMETHODIMP AddUserPermission(
LPSTR szUserAlias,
LPM... | [
"I got this piece of code and it works fine\nfrom binascii import b2a_hex, a2b_hex\nimport active_directory as ad\n\n\n# entry_type, see http://msdn.microsoft.com/en-us/library/cc840018.aspx\n# + AB_DT_CONTAINER 0x000000100\n# + AB_DT_TEMPLATE 0x000000101\n# + AB_DT_OOUSER 0x000000102\n# + AB_DT... | [
0
] | [] | [] | [
"com",
"exchange_server",
"mapi",
"python",
"pywin32"
] | stackoverflow_0003734299_com_exchange_server_mapi_python_pywin32.txt |
Q:
How to use buildout to create localized version of my project?
I am trying to create a localized version of my project.
I started from the following:
mkdir my
cd my
wget http://svn.zope.org/*checkout*/zc.buildout/trunk/bootstrap/bootstrap.py
After the last command I get the following message:
Warning: wildcards ... | How to use buildout to create localized version of my project? | I am trying to create a localized version of my project.
I started from the following:
mkdir my
cd my
wget http://svn.zope.org/*checkout*/zc.buildout/trunk/bootstrap/bootstrap.py
After the last command I get the following message:
Warning: wildcards not supported in
HTTP.
--08:42:17-- http://svn.zope.org/checkou... | [
"You need install sqlite develop library.\nIn ubuntu or debian, run:\nsudo apt-get install libsqlite3-dev\n\n",
"You need to have sqlite installed before you start installing the python bindings.\n"
] | [
4,
0
] | [] | [] | [
"buildout",
"python",
"sqlite"
] | stackoverflow_0001477189_buildout_python_sqlite.txt |
Q:
Socket 'No route to host' error
I have a connection which is behind a restrictive firewall which only allows HTTP(S) access through a proxy (10.10.1.100:9401). The IP address I get is dynamic and the subnet mask is 255.255.255.255 (I know, weird!).
I tried to write a simple Python socket program to connect to the ... | Socket 'No route to host' error | I have a connection which is behind a restrictive firewall which only allows HTTP(S) access through a proxy (10.10.1.100:9401). The IP address I get is dynamic and the subnet mask is 255.255.255.255 (I know, weird!).
I tried to write a simple Python socket program to connect to the proxy in order to send some HTTP requ... | [
"I am not sure what the issue is but try using Wireshark. This will at least let you see what is going on at the network level. There should be enough info from the Wireshark packet logs to diagnose your problem.\n"
] | [
3
] | [] | [] | [
"c",
"python",
"routing",
"sockets"
] | stackoverflow_0003752231_c_python_routing_sockets.txt |
Q:
openid in pylons (not using authkit)
So I'm trying to authenticate users on a Pylons web application using openid. I don't want to use authkit, seeing as it is no longer maintained.
I'm currently trying to use python-openid (available from git at http://github.com/openid/python-openid) and having a hard time with ... | openid in pylons (not using authkit) | So I'm trying to authenticate users on a Pylons web application using openid. I don't want to use authkit, seeing as it is no longer maintained.
I'm currently trying to use python-openid (available from git at http://github.com/openid/python-openid) and having a hard time with it. The pylons framework isn't making it e... | [
"OpenId with pylons through repoze.what works OK. Please see the following discussion in the pylons mailing list to find some pointers: http://groups.google.com/group/pylons-discuss/browse_thread/thread/162ebf131db3582b#\n"
] | [
2
] | [] | [] | [
"openid",
"pylons",
"python",
"python_openid"
] | stackoverflow_0003715323_openid_pylons_python_python_openid.txt |
Q:
Twitter Streaming API with oAuth with Python
I've been trying to search for a good Module to in order to use twitter live streaming API and Python. I have found "tweepy" but it seems like it is using the "Basic Authentication" which is now deprecated. Is there any new module out there to use for that purpose that ... | Twitter Streaming API with oAuth with Python | I've been trying to search for a good Module to in order to use twitter live streaming API and Python. I have found "tweepy" but it seems like it is using the "Basic Authentication" which is now deprecated. Is there any new module out there to use for that purpose that use oAuth?
Thanks,
Joel
| [
"Tweepy has an oAuth module which works very well. See here: http://packages.python.org/tweepy/html/auth_tutorial.html\n"
] | [
0
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0003751727_python_twitter.txt |
Q:
Slow mergesort implementation, what's wrong?
I am getting unexpected(?) results from this mergesort implementation. It's extremely slow compared to my three-way quicksort(also written in python).
My quicksort finishes with 10000 elements after about 0.005s while mergesort needs 1.6s! Including the source code for... | Slow mergesort implementation, what's wrong? | I am getting unexpected(?) results from this mergesort implementation. It's extremely slow compared to my three-way quicksort(also written in python).
My quicksort finishes with 10000 elements after about 0.005s while mergesort needs 1.6s! Including the source code for both implementations.
Mergesort:
#Merges two sort... | [
"Guesses about performance are usually wrong, but i'll go with this once since i do have some experience with this. Profile if you really want to know:\nYou are adding lists, ie left[:1] + merge(left[1:],right), this is one of the slower operations in Python. It creates a new list from both lists, so your mergesort... | [
5,
3,
1,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0003752926_python_sorting.txt |
Q:
How do I get a list of all parent tags in BeautifulSoup?
Let's say I have a structure like this:
<folder name="folder1">
<folder name="folder2">
<bookmark href="link.html">
</folder>
</folder>
If I point to bookmark, what would be the command to just extract all of the folder lines?
For exampl... | How do I get a list of all parent tags in BeautifulSoup? | Let's say I have a structure like this:
<folder name="folder1">
<folder name="folder2">
<bookmark href="link.html">
</folder>
</folder>
If I point to bookmark, what would be the command to just extract all of the folder lines?
For example,
bookmarks = soup.findAll('bookmark')
then beautifulsoupcom... | [
"Here is my stab at it:\n>>> from BeautifulSoup import BeautifulSoup\n>>> html = \"\"\"<folder name=\"folder1\">\n <folder name=\"folder2\">\n <bookmark href=\"link.html\">\n </folder>\n</folder>\n\"\"\"\n>>> soup = BeautifulSoup(html)\n>>> bookmarks = soup.find_all('bookmark')\n>>> [p.get('name') ... | [
7,
3
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python",
"xml_parsing"
] | stackoverflow_0003752327_beautifulsoup_html_parsing_python_xml_parsing.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.