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 server via WCF, preferably in Java, Python, Ruby or anything that does not require .NET.
A:
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).
| 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 require .NET.
| [
"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 line must start with an underscore, so: ^_.*gold instead of gold.
As 99% of the lines do not start with an underscore I was expecting a big performance payoff because the regex engine could abort reading the line after just one character. I was surprised to learn the other way.
The following program illustrated the problem:
import re
from time import time
def main():
line = r'I do not start with an underscore 123456789012345678901234567890'
p1 = re.compile(r"^_") # requires underscore as a first char
p2 = re.compile(r"abcdefghijklmnopqrstuvwxyz")
patterns = (p1, p2)
for p in patterns:
start = time()
for i in xrange(1000*1000):
match = re.search(p, line)
end = time()
print 'Elapsed: ' + str(end-start)
main()
I've tried reviewing sre_compile.py looking for an explanation, but its code was too hairy for me.
Could the observed performance be explained by that that the inclusion of the start of line character turns the regex engine operation from a simple substring op to a much more complicated backtracking state machine op? Thereby outweighing any benefits like aborting the search after the first character?
Thinking so, I tried multiplying the line's length by x8, expecting the start of line search to shine, but instead the gap only grow wider (22sec Vs 6sec).
I'm puzzled :o am I missing something here?
A:
How about
if line[0] == "_" and "gold" in line:
print "Yup, it starts with an underscore"
else:
print "Nope it doesn't"
Seriously, don't overuse regex
A:
You're actually doing two things wrong: If you want to look at the beginning of the string use match not search.
Also, don't use re.match( pattern, line), compile the pattern and use pattern.match(line).
import re
from time import time
def main():
line = r'I do not start with an underscore 123456789012345678901234567890'
p1 = re.compile(r"_") # requires underscore as a first char
p2 = re.compile(r"abcdefghijklmnopqrstuvwxyz")
patterns = (p1, p2)
for p in patterns:
start = time()
for i in xrange(1000*1000):
match = p.match(line)
end = time()
print 'Elapsed: ' + str(end-start)
main()
You will see that you have the expected behavior now - both pattern take exactly the same time.
A:
Interesting observation! I've played a bit with it. My guess would be that the regexp engine will scan the entire string for an underscore, and matches this against a line beginning once a match has been found. Perhaps this has to do with uniform behaviour when using re.MULTILINE
If you use re.match in stead of re.search for the underscore pattern, both seem to be equally fast, i.e.
def main():
line = r'I do not start with an underscore 123456789012345678901234567890'
p1 = re.compile(r"_.*") # requires underscore as a first char
p2 = re.compile(r"abcdefghijklmnopqrstuvwxyz")
patterns = (p1, p2)
start = time()
for i in xrange(1000*1000):
match = re.match(p1, line)
end = time()
print 'Elapsed: ' + str(end-start)
start = time()
for i in xrange(1000*1000):
match = re.search(p2, line)
end = time()
print 'Elapsed: ' + str(end-start)
In this case, match will require a match to start matching at the beginning of the string.
Also, be aware that the following use of precompiled patterns seems to be faster:
for p in patterns:
start = time()
for i in xrange(1000*1000):
match = p.search(line)
end = time()
print 'Elapsed: ' + str(end-start)
But the speed difference remains...
A:
Regexes don't always behave as you'd expect. I don't understand the internals, so I can't precisely explain the behavior. One thing to note, if you change from search to match, the patterns switch which is faster (though that isn't exactly what you want).
You're doing the right thing: measure and use the technique that is empirically faster.
| 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 99% of the lines do not start with an underscore I was expecting a big performance payoff because the regex engine could abort reading the line after just one character. I was surprised to learn the other way.
The following program illustrated the problem:
import re
from time import time
def main():
line = r'I do not start with an underscore 123456789012345678901234567890'
p1 = re.compile(r"^_") # requires underscore as a first char
p2 = re.compile(r"abcdefghijklmnopqrstuvwxyz")
patterns = (p1, p2)
for p in patterns:
start = time()
for i in xrange(1000*1000):
match = re.search(p, line)
end = time()
print 'Elapsed: ' + str(end-start)
main()
I've tried reviewing sre_compile.py looking for an explanation, but its code was too hairy for me.
Could the observed performance be explained by that that the inclusion of the start of line character turns the regex engine operation from a simple substring op to a much more complicated backtracking state machine op? Thereby outweighing any benefits like aborting the search after the first character?
Thinking so, I tried multiplying the line's length by x8, expecting the start of line search to shine, but instead the gap only grow wider (22sec Vs 6sec).
I'm puzzled :o am I missing something here?
| [
"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 using isinstance to figure out the correct type.
For example if x is a decimal number:
>>> from decimal import Decimal
>>> x = Decimal('3')
>>> x
Decimal('3')
how to create new instance of Decimal. I think the obvious thing to do would be either of these:
>>> type(x)('22')
Decimal('22')
>>> x.__class__('22')
Decimal('22')
Since __class__ will not work on int for example:
>>> 1.__class__
File "<stdin>", line 1
1.__class__
Is it good practice to use type to achieve this, or is there some other ways or more caveats when using this approach for creating new objects?
Note:
There was an answer that is now deleted that gave a right way to get __class__ of int.
>>> (1).__class__
<type 'int'>
Use case
The question is mostly theoretical, but I am using this approach right now with Qt to create new instances of QEvent. For example, since the QEvent objects are consumed by the application event handler in order to post the event to QStateMachine you need to create a new instance of the event otherwise you get runtime error because the underlying C++ object get deleted.
And since I am using custom QEvent subclasses that all share the same base class thus objects accept same predefined set of arguments.
A:
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 type might be, you need more introspection for this purpose (as well as some rule or heuristic about what all arguments you want to pass once you've determined, for example, that you may pass any number from 0 to 3, and that the optional/keyword argument names are 'y', 'z', 't'... obviously it's impossible to establish a general rule here!).
So, can you please clarify (once the type to instantiate is, easily, determined;-) how you're going to be tackling the hard parts of your problem, that you don't even mention? What constraints can you assume on the type's signature? Do you need to perform some sanity checks on that or is it OK to just cause a TypeError by calling with the wrong kind or number of arguments? Etc, etc... without more info of this nature, your question just doesn't lend itself to proving an answer that can actually be used in the real world!-)
| 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 decimal number:
>>> from decimal import Decimal
>>> x = Decimal('3')
>>> x
Decimal('3')
how to create new instance of Decimal. I think the obvious thing to do would be either of these:
>>> type(x)('22')
Decimal('22')
>>> x.__class__('22')
Decimal('22')
Since __class__ will not work on int for example:
>>> 1.__class__
File "<stdin>", line 1
1.__class__
Is it good practice to use type to achieve this, or is there some other ways or more caveats when using this approach for creating new objects?
Note:
There was an answer that is now deleted that gave a right way to get __class__ of int.
>>> (1).__class__
<type 'int'>
Use case
The question is mostly theoretical, but I am using this approach right now with Qt to create new instances of QEvent. For example, since the QEvent objects are consumed by the application event handler in order to post the event to QStateMachine you need to create a new instance of the event otherwise you get runtime error because the underlying C++ object get deleted.
And since I am using custom QEvent subclasses that all share the same base class thus objects accept same predefined set of arguments.
| [
"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 would return a logger for the current module, creating it if necessary. A magic __logger__ variable that could be called without parenthesis would be even better. How would I go about that?
For example, in a module named foo, I could call __logger__.debug('this is a debug message for the foo module'), and it would show up in my console as:
DEBUG:foo:this is a debug message for the foo module
A:
You can use:
logger = logging.getLogger(__name__)
at the top of your class, and use it like so:
logger.warn(...)
logger.log(...)
| 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, creating it if necessary. A magic __logger__ variable that could be called without parenthesis would be even better. How would I go about that?
For example, in a module named foo, I could call __logger__.debug('this is a debug message for the foo module'), and it would show up in my console as:
DEBUG:foo:this is a debug message for the foo 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 to test because, with compilers, a problem often means invalid code on the assembly level, and thus crazy, unpredictable errors.
I found During a subprocess call, catch critical windows errors in Python instead of letting the OS handle it by showing nasty error pop-ups while searching for the answer, but this doesn't work for me. I still get the message boxes when testing.
The documentation on [SetErrorMode](http://msdn.microsoft.com/en-us/library/ms680621(VS100).aspx) Says that:
SEM_FAILCRITICALERRORS:
The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
SEM_NOGPFAULTERRORBOX:
The system does not display the Windows Error Reporting dialog.
Each process has an associated error mode that indicates to the system how the application is going to respond to serious errors. A child process inherits the error mode of its parent process.
However, after calling SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX) and launching the process with CreateProcess with dwCreationFlags = CREATE_NEW_CONSOLE, I still get the boxes when subprocesses fail.
In case it matters, the exact Python code I am using is:
import ctypes
# 3 is SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX
ctypes.windll.kernel32.SetErrorMode(3)
How do I fix it?
A:
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.
Call SetUnhandledExceptionHandler(yourexceptionhandler);
If you call exit in this handler, the program terminates normally and Dr. Watson is never invoked.
UnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
fputs("Application crashed with unhandled exception!\n", stderr);
// Exit to prevent anything else from handling this exception.
_exit(-3);
}
int main() {
SetUnhandledExceptionFilter(UnhandledExceptionFilter);
}
This only works if you have access to the source code and feel like modifying it. In my case I had access to the source code, but it was a collection of a few hundred separate files, and so adding this code in all of them was a non starter. It also wouldn't handle the case of an error before main, or just plain invalid executables.
Run the process under a debugger using CreateProcess(..., DEBUG_PROCESS, ...)(link redacted) and WaitForDebugEvent(link redacted)
When running a process like this, all exceptions are propagated to the debugger, and thus they can be handled appropriately.
This is a rather complex solution to what should be a simple problem, but it is the only way I have found to completely block Dr. Watson. I am Currently writing a minimal program that tries to run the subprocess normally in every way except for catching unhandled exceptions. I will post a link here once it is committed.
A:
The error mode is normally be inherited by subprocesses. It sounds like the implementation of system (or execv, or whatever's being used to spawn sub-processes) is passing the CREATE_DEFAULT_ERROR_MODE flag when it calls CreateProcess. To get the behavior you want (inheriting the error mode you've set), you'll have to either modify the library implementation so whatever you're using to spawn the processes doesn't pass that flag, or else implement (and use) something new that doesn't pass it.
| 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 on the assembly level, and thus crazy, unpredictable errors.
I found During a subprocess call, catch critical windows errors in Python instead of letting the OS handle it by showing nasty error pop-ups while searching for the answer, but this doesn't work for me. I still get the message boxes when testing.
The documentation on [SetErrorMode](http://msdn.microsoft.com/en-us/library/ms680621(VS100).aspx) Says that:
SEM_FAILCRITICALERRORS:
The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
SEM_NOGPFAULTERRORBOX:
The system does not display the Windows Error Reporting dialog.
Each process has an associated error mode that indicates to the system how the application is going to respond to serious errors. A child process inherits the error mode of its parent process.
However, after calling SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX) and launching the process with CreateProcess with dwCreationFlags = CREATE_NEW_CONSOLE, I still get the boxes when subprocesses fail.
In case it matters, the exact Python code I am using is:
import ctypes
# 3 is SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX
ctypes.windll.kernel32.SetErrorMode(3)
How do I fix it?
| [
"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.py", line 555, in write
d = (self.buf + data).split('\n')
exceptions.UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 28: ordinal not in range(128)
Actually it is twisted application and print forwards to log file.
repr() of strings are the same. Locale set to en_US.UTF-8.
Are there any configs I need to check to make it work the same on the both servers?
A:
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, and so forth.
If there's no such attribute, the default coded ascii is used, and, as you've seen, it often does not provide the desired results;-).
You can check getattr(sys.stdout, 'encoding', None) to see if the encoding is there (if it is, you can just keep your fingers crossed that it's correct... or, maybe, try some heavily platform-specific trick to guess at the correct system encoding to check;-). If it isn't, in general, there's no reliable or cross-platform way to guess what it could be. You could try 'utf8', the universal encoding that works in a lot of cases (surely more than ascii does;-), but it's really a spin of the roulette wheel.
For more reliability, your program should have its own configuration file to tell it what output encoding to use (maybe with 'utf8' just as the default if not otherwise specified).
It's also better, for portability, to perform your own encoding, that is, not
print someunicode
but rather
print someunicode.encode(thecodec)
and actually, if you'd rather have incomplete output than a crash,
print someunicode.encode(thecodec, 'ignore')
(which simply skips non-encodable characters), or, usually better,
print someunicode.encode(thecodec, 'replace')
(which uses question-mark placeholders for non-encodable characters).
A:
Unicode is not supported by Twisted's built-in log observers. See http://twistedmatrix.com/trac/ticket/989 for progress on adding support for this, or to see what you can do to help out.
Until #989 is resolved and the fix is in a Twisted release your application is deployed on, do not log unicode. Only log str.
| 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('\n')
exceptions.UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 28: ordinal not in range(128)
Actually it is twisted application and print forwards to log file.
repr() of strings are the same. Locale set to en_US.UTF-8.
Are there any configs I need to check to make it work the same on the both servers?
| [
"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 destructor: Error in sys.excepthook: Original exception was:".
#!/bin/sh
BUILD_FOLDER="/Users/James/Documents/Xcode Projects/Uber Sweep - Mac/build/Release & Package"
if [ -f "$BUILD_FOLDER/Uber Sweep (64 bit).zip" ]; then
python /Users/James/Scripts/Google\ Code\ Upload.py -s "Uber Sweep - Mac OS X (64 bit)" -p "uber-sweep" -u "EXCLUDED" -l "Featured,Type-Archive,OpSys-OSX" "$BUILD_FOLDER/Uber Sweep (64 bit).zip" | echo
fi
Why is this?
Thank you for your help,
jrtc27
A:
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.
Try specifying the full path to python. The PATH for the script may be different than it is for your interactive shell.
You should be able to quote the name of your Python script and avoid the awkward escaping of spaces.
| 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/Documents/Xcode Projects/Uber Sweep - Mac/build/Release & Package"
if [ -f "$BUILD_FOLDER/Uber Sweep (64 bit).zip" ]; then
python /Users/James/Scripts/Google\ Code\ Upload.py -s "Uber Sweep - Mac OS X (64 bit)" -p "uber-sweep" -u "EXCLUDED" -l "Featured,Type-Archive,OpSys-OSX" "$BUILD_FOLDER/Uber Sweep (64 bit).zip" | echo
fi
Why is this?
Thank you for your help,
jrtc27
| [
"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 you want at the expense of being much more complicated to use (at first).
I could take the "Getting Started" tutorial, but I really want to understand more about WSGI and Pylons' general approach. The 5,000 foot view is important to me before I write a single line of code. What do you suggest?
A:
I would recommend this... http://pylonsbook.com/en/1.1/#front-matter
| 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 more complicated to use (at first).
I could take the "Getting Started" tutorial, but I really want to understand more about WSGI and Pylons' general approach. The 5,000 foot view is important to me before I write a single line of code. What do you suggest?
| [
"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 = SSL.Context(SSL.SSLv23_METHOD)
print "Creating socket"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "done"
ssl = SSL.Connection(ctx, s)
print "Establishing Connection"
ssl.connect(("pop.gmail.com", 995))
print "done"
print "Requesting Documents"
print "done"
try:
buf = ssl.read(4096)
except SSL.ZeroReturnError:
print "1"
sys.stdout.write(buf)
ssl.send("USER username")
try:
buf2 = ssl.recv(4096)
except SSL.ZeroReturnError:
print "2"
sys.stdout.write(buf2)
ssl.send("PASS secret")
try:
buf3 = ssl.read(4096)
except SSL.ZeroReturnError:
print "2"
sys.stdout.write(buf3)
print "connected"
ssl.close()
A:
End the string with a \r\n
| 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_METHOD)
print "Creating socket"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "done"
ssl = SSL.Connection(ctx, s)
print "Establishing Connection"
ssl.connect(("pop.gmail.com", 995))
print "done"
print "Requesting Documents"
print "done"
try:
buf = ssl.read(4096)
except SSL.ZeroReturnError:
print "1"
sys.stdout.write(buf)
ssl.send("USER username")
try:
buf2 = ssl.recv(4096)
except SSL.ZeroReturnError:
print "2"
sys.stdout.write(buf2)
ssl.send("PASS secret")
try:
buf3 = ssl.read(4096)
except SSL.ZeroReturnError:
print "2"
sys.stdout.write(buf3)
print "connected"
ssl.close()
| [
"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, classmethod):
self.fget = fget
else:
self.fget = classmethod(fget)
if not fset or isinstance(fset, classmethod):
self.fset = fset
else:
self.fset = classmethod(fset)
def __get__(self, *a):
return self.fget.__get__(*a)()
def __set__(self, cls, value):
print 'In __set__'
if not self.fset:
raise AttributeError, "can't set attribute"
fset = self.fset.__get__(cls)
fset(value)
class X(object):
@classmethod
def _get_x(cls):
return 1
@classmethod
def _set_x(cls, value):
print 'You set x to {0}'.format(value)
x = classprop(fget=_get_x, fset=_set_x)
While getting is working, setting doesn't seem to be getting called:
>>> util.X.x
1
>>> util.X.x = 1
>>>
What am I doing wrong?
(And I have seen implementations of this that work a bit differently. I'm specifically wanting to know why this implementation isn't working.)
A:
The doc's say:
object.__set__(self, instance,
value) Called to set the attribute on
an instance instance of the owner
class to a new value, value.
Unlike for __get__, it does not mention class attributes. So Python won't call any __set__ on a class attribute.
| 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
else:
self.fget = classmethod(fget)
if not fset or isinstance(fset, classmethod):
self.fset = fset
else:
self.fset = classmethod(fset)
def __get__(self, *a):
return self.fget.__get__(*a)()
def __set__(self, cls, value):
print 'In __set__'
if not self.fset:
raise AttributeError, "can't set attribute"
fset = self.fset.__get__(cls)
fset(value)
class X(object):
@classmethod
def _get_x(cls):
return 1
@classmethod
def _set_x(cls, value):
print 'You set x to {0}'.format(value)
x = classprop(fget=_get_x, fset=_set_x)
While getting is working, setting doesn't seem to be getting called:
>>> util.X.x
1
>>> util.X.x = 1
>>>
What am I doing wrong?
(And I have seen implementations of this that work a bit differently. I'm specifically wanting to know why this implementation isn't working.)
| [
"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 something in it which prevented:
reload(sys)
From undoing the codec changes. Does anyone know what that might have been?
A:
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:
>>> import sys
>>> print>>sys.stderr,'ciao'
ciao
>>> sys.stderr.close()
>>> print>>sys.stderr,'ciao'
>>> reload(sys)
<module 'sys' (built-in)>
>>> print>>sys.stderr,'ciao'
If you want to restore sys.stdout and/or sys.stderr after rebinding them, just stash away the old references and just rebind them to the "stashed away" refs to restore. (You could use sys.__stdout__ and sys.__stderr__, where Python itself stashes them away at startup, but that might run athwart advanced shells or debuggers you might be running, as the latter may be doing their own similar operations).
If you also want to survive file or file-descriptor closures, you'll have to go deeper (reopening e.g. with os.fdopen the standard descriptors 0, 1, and 2 -- if the descriptors themselves have been closer, that gets even hairier;-) and living peacefully with advanced shells or debuggers in general may become a lost cause. But for simpler cases, just rebinding things back and forth can work fine.
| 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 codec changes. Does anyone know what that might have been?
| [
"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't really know a whole lot about this and am not sure if this is a situation where I need to use exec in python or if there is some other way. My searches on this aren't turning up much of anything.
Basically, it would just be where I do a database call and get the contents of a class, then I want to instantiate it. Any advice is appreciated on how to best do this sort of thing.
EDIT: In response to the idea of a malicious __init__ in the class, these are only for things like forms or models where it is tightly controlled through validation what goes in the class, there would never be an __init__ in the class and it would be basically impossible, since I would validate everything server side, to put anything malicious in the class.
A:
Do not store code in the database!!!
Imagine 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 the ability to execute any python code on it.
A:
Don't store the class itself, store the import path as a string in the database (e.g. 'django.forms.CharField')
I started doing this same thing for another project, and saved off the code in my local repository. To address the security concerns I was going to add an argument to the field constructor of allowed base classes. If you do implement this, let me know, I'd love to have it.
helpers.py
def get_class_from_concrete_classpath(class_path):
# Unicode will throw errors in the __import__ (at least in 2.6)
class_path = str(class_path)
mod_list = class_path.split('.')
module_path = '.'.join(mod_list[:-1])
class_name = mod_list[-1]
base_mod = __import__(module_path, fromlist=[class_name,])
return getattr(base_mod, class_name)
def get_concrete_name_of_class(klass):
"""Given a class return the concrete name of the class.
klass - The reference to the class we're interested in.
Raises a `TypeError` if klass is not a class.
"""
if not isinstance(klass, (type, ClassType)):
raise TypeError('The klass argument must be a class. Got type %s; %s' %
(type(klass), klass))
return '%s.%s' % (klass.__module__, klass.__name__)
fields.py
class ClassFormField(forms.Field):
def to_python(self, value):
return get_concrete_name_of_class(value)
class ClassField(models.CharField):
__metaclass__ = models.SubfieldBase
"""Field used for storing a class as a string for later retrieval"""
MAX_LENGTH = 255
default_error_messages = {
'invalid': _(u'Enter a valid class variable.'),
}
def __init__(self, *args, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', ClassField.MAX_LENGTH)
super(ClassField, self).__init__(*args, **kwargs)
def get_prep_value(self, value):
if isinstance(value, (basestring, NoneType)):
return value
return get_concrete_name_of_class(value)
def to_python(self, value):
if isinstance(value, basestring):
return get_class_from_concrete_classpath(value)
return value
def formfield(self, **kwargs):
defaults = {'form_class' : ClassFormField}
defaults.update(kwargs)
return super(ClassField, self).formfield(**defaults)
| 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 situation where I need to use exec in python or if there is some other way. My searches on this aren't turning up much of anything.
Basically, it would just be where I do a database call and get the contents of a class, then I want to instantiate it. Any advice is appreciated on how to best do this sort of thing.
EDIT: In response to the idea of a malicious __init__ in the class, these are only for things like forms or models where it is tightly controlled through validation what goes in the class, there would never be an __init__ in the class and it would be basically impossible, since I would validate everything server side, to put anything malicious in the class.
| [
"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 standard python constraint to create such continuation web framework in standard python ?
and What are the workaround to it ? and what are standard part in continuation framework architecture ( as model view controller are in MVC ) ?
A:
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. Unfortunately the (currently) standard Python does not support continuations. Which is one of the reason people developed stackless python.
Java is a bit of a special case. The language itself does not support continuations but the virtual machine does (in order to support exceptions). I think what they did was to modify the compiled bytecode at runtime and re-order instructions so that it looks like it supports continuations. Kind of like implementing stackless python by monkey-patching.
A:
Right, continuation is a property of a language and CPython sadly has not continuations.
The workarounds in pure Python are well known : use callbacks / deferers like Twisted and Tornado for example or use 'yield' everywhere to mimic co-routines, like Diesel. But both approaches force you to change the way you design and code your application. Also a continuation can be "replayed" which is how the continuation based frameworks automatically handle the "back" button problem.
Finally, to be exact, in Nagare we are using the pickling of a freezed tasklet to obtain a continuation object.
| 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 in standard python ?
and What are the workaround to it ? and what are standard part in continuation framework architecture ( as model view controller are in MVC ) ?
| [
"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 unicorns).
Is there anything out there that is enterprise worthy (ie, doesn't impose performance or scaling restrictions), stays the hell out of my way, but provides the basic request/response handling, sessions, SQLAlchemy (perhaps), and a way to plug in templates, etc? Is there any hope?
I've been trying to develop an SAAS in Django, which is a nightmare. They don't support multiple column primary keys, and there are a number of other problems with ModelForms, etc that you don't run into until you're developing a more complex application (especially with multitenancy. I don't use their auth system and don't need to as I built my own. I just need security (CSRF, XSS, SQL injection, etc).
A:
The most hard-core low-level web-framework for python - Werkzeug - http://werkzeug.pocoo.org/
Flask: 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 integrated SQLAlchemy with extensions like flask-sqlalchemy and WTForms (similar API to django.forms) with flask-wtform. There are tons of useful other extensions for it, like extensions that add the ability to use mongodb and couchdb easily. What's most notable about flask extensions is they provide very consistent behavior and there is an actual approval process for them, as opposed to django reusable apps 95% of which are a mess.
| 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 there that is enterprise worthy (ie, doesn't impose performance or scaling restrictions), stays the hell out of my way, but provides the basic request/response handling, sessions, SQLAlchemy (perhaps), and a way to plug in templates, etc? Is there any hope?
I've been trying to develop an SAAS in Django, which is a nightmare. They don't support multiple column primary keys, and there are a number of other problems with ModelForms, etc that you don't run into until you're developing a more complex application (especially with multitenancy. I don't use their auth system and don't need to as I built my own. I just need security (CSRF, XSS, SQL injection, etc).
| [
"\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 invalid
I am thinking that I would like to display the appropriate messages to the user in these 2 cases, rather than a single "username or password was invalid...".
Anyone have any experience with simple ways to do this. The crux of the matter seems to go right to the lowest level - in the django.contrib.auth.backends.ModelBackend class. The authenticate() method of this class, which takes the username and password as arguments, simply returns the User object, if authentication was successful, or None, if authentication failed. Given that this code is at the lowest level (well, lowest level that is above the database code), bypassing it seems like a lot of code is being thrown away.
Is the best way simply to implement a new authentication backend and add it to the AUTHENTICATION_BACKENDS setting? A backend could be implemented that returns a (User, Bool) tuple, where the User object is only None if the username did not exist and the Bool is only True if the password was correct. This, however, would break the contract that the backend has with the django.contrib.auth.authenticate() method (which is documented to return the User object on successful authentication and None otherwise).
Maybe, this is all a worry over nothing? Regardless of whether the username or password was incorrect, the user is probably going to have to head on over to the "Lost password" page anyway, so maybe this is all academic. I just can't help feeling, though...
EDIT:
A comment regarding the answer that I have selected:
The answer I have selected is the way to implement this feature. There is another answer, below, that discusses the potential security implications of doing this, which I also considered as the nominated answer. However, the answer I have nominated explains how this feature could be implemented. The security based answer discusses whether one should implement this feature which is, really, a different question.
A:
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.
A:
This is not a function of the backend simply the authentication form. Just rewrite the form to display the errors you want for each field. Write a login view that use your new form and make that the default login url. (Actually I just saw in a recent commit of Django you can now pass a custom form to the login view, so this is even easier to accomplish). This should take about 5 minutes of effort. Everything you need is in django.contrib.auth.
To clarify here is the current form:
class AuthenticationForm(forms.Form):
"""
Base class for authenticating users. Extend this to get a form that accepts
username/password logins.
"""
username = forms.CharField(label=_("Username"), max_length=30)
password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
def __init__(self, request=None, *args, **kwargs):
"""
If request is passed in, the form will validate that cookies are
enabled. Note that the request (a HttpRequest object) must have set a
cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
running this validation.
"""
self.request = request
self.user_cache = None
super(AuthenticationForm, self).__init__(*args, **kwargs)
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
elif not self.user_cache.is_active:
raise forms.ValidationError(_("This account is inactive."))
# TODO: determine whether this should move to its own method.
if self.request:
if not self.request.session.test_cookie_worked():
raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
return self.cleaned_data
def get_user_id(self):
if self.user_cache:
return self.user_cache.id
return None
def get_user(self):
return self.user_cache
Add:
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
raise forms.ValidationError("The username you have entered does not exist.")
return username
A:
We had to deal with this on a site that used an external membership subscription service. Basically you do
from django.contrib.auth.models import User
try:
user = User.objects.get(username=whatever)
# if you get here the username exists and you can do a normal authentication
except:
pass # no such username
In our case, if the username didn't exist, then we had to go check an HTPASSWD file that was updated by a Perl script from the external site. If the name existed in the file then we would create the user, set the password, and then do the auth.
A:
This answer is not specific to Django, but this is the pseudo-code I would use to accomplish this:
//Query if user exists who's username=<username> and password=<password>
//If true
//successful login!
//If false
//Query if user exists who's username=<username>
//If true
//This means the user typed in the wrong password
//If false
//This means the user typed in the wrong username
A:
def clean_username(self):
"""
Verifies that the username is available.
"""
username = self.cleaned_data["username"]
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
return username
else:
raise forms.ValidationError(u"""\
This username is already registered,
please choose another one.\
""")
| 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 the user in these 2 cases, rather than a single "username or password was invalid...".
Anyone have any experience with simple ways to do this. The crux of the matter seems to go right to the lowest level - in the django.contrib.auth.backends.ModelBackend class. The authenticate() method of this class, which takes the username and password as arguments, simply returns the User object, if authentication was successful, or None, if authentication failed. Given that this code is at the lowest level (well, lowest level that is above the database code), bypassing it seems like a lot of code is being thrown away.
Is the best way simply to implement a new authentication backend and add it to the AUTHENTICATION_BACKENDS setting? A backend could be implemented that returns a (User, Bool) tuple, where the User object is only None if the username did not exist and the Bool is only True if the password was correct. This, however, would break the contract that the backend has with the django.contrib.auth.authenticate() method (which is documented to return the User object on successful authentication and None otherwise).
Maybe, this is all a worry over nothing? Regardless of whether the username or password was incorrect, the user is probably going to have to head on over to the "Lost password" page anyway, so maybe this is all academic. I just can't help feeling, though...
EDIT:
A comment regarding the answer that I have selected:
The answer I have selected is the way to implement this feature. There is another answer, below, that discusses the potential security implications of doing this, which I also considered as the nominated answer. However, the answer I have nominated explains how this feature could be implemented. The security based answer discusses whether one should implement this feature which is, really, a different question.
| [
"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 of a configuration issue rather than a programming issue.
Include the version of Netbeans and the Java you are using - and whether you using native python and/or Jython as well.
Also include at which point you see the error message - when you create a new file, new project etc - does Netbeans start up ok etc ?
| 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['userName']
print uname
kwargs['_toshow']=uname
...
return tempLook.get_template(page).render(**kwargs)
The related template file :
...${_toshow}...
And the output is :
UTF-8
Deşghfkskhü
...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 1: ordinal not in range(128)
I don't think there's any problem with the string itself since I can print it just fine.
Altough I've played (a lot) with input/output_encoding and default_filters parameters, it always complains about being unable to decode/encode with ascii codec.
So I decided to try out the example found on the documentation, and the following works the "best" :
input_encoding='utf-8', output_encoding='utf-8'
#(note : it still raised an error without output_encoding, despite tutorial not implying it)
With
${u"voix m’a réveillé."}
And the result being
voix mâ�a réveillé
I simply don't get why this doesn't work. "Magic encoding comment"s don't work either. All the files are encoded with UTF-8.
I've spent hours to no avail, am I missing something ?
Update :
I have a simpler question now :
Now that all the variables are unicode, how can I get Mako to render unicode strings without applying anything ? Passing a blank filter / render_unicode() doesn't help.
A:
Yes, UTF-8 != Unicode.
UTF-8 is a specifc string encoding, as are ASCII and ISO 8859-1. Try this:
For 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 unicode strings ('this is a normal string'.decode('utf-8') == u'this is a normal string')
'foo' is a string, u'foo' is a unicode string, which doesn't "have" an encoding (can't be decoded). SO anytime python want to change an encoding of a normal string, it first tries to "decode" it, the to "encode" it. And the default is "ascii", which fails more often than not :-)
| 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_template(page).render(**kwargs)
The related template file :
...${_toshow}...
And the output is :
UTF-8
Deşghfkskhü
...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 1: ordinal not in range(128)
I don't think there's any problem with the string itself since I can print it just fine.
Altough I've played (a lot) with input/output_encoding and default_filters parameters, it always complains about being unable to decode/encode with ascii codec.
So I decided to try out the example found on the documentation, and the following works the "best" :
input_encoding='utf-8', output_encoding='utf-8'
#(note : it still raised an error without output_encoding, despite tutorial not implying it)
With
${u"voix m’a réveillé."}
And the result being
voix mâ�a réveillé
I simply don't get why this doesn't work. "Magic encoding comment"s don't work either. All the files are encoded with UTF-8.
I've spent hours to no avail, am I missing something ?
Update :
I have a simpler question now :
Now that all the variables are unicode, how can I get Mako to render unicode strings without applying anything ? Passing a blank filter / render_unicode() doesn't help.
| [
"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.start_g
self.start.grid(row=0, column=1, pady=5, sticky=N)
The problem is, I want to remove a widget, so I could add something else to this window. I tried remove() grid_forget() and I can get rid of the widget. Is there any way to remove a widget or wipe the window?
A:
You can call grid_forget() on your widget to permanently remove it.
e.g
self.start.grid_forget()
If you wanted to clear the whole window then you could do the same on your main frame.
| 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.grid(row=0, column=1, pady=5, sticky=N)
The problem is, I want to remove a widget, so I could add something else to this window. I tried remove() grid_forget() and I can get rid of the widget. Is there any way to remove a widget or wipe the window?
| [
"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 Mac OS X, but is there a common way to get it installed on Windows and Linux?
A:
If your script starts with a suitable shebang line, such as:
#!/usr/bin/env python
And your script has the executable bit set (for Linux, OS X, and other Unix-like systems):
chmod +x myscript.py
And the path to your script is in your PATH environment variable:
export PATH=${PATH}:`pwd` # on Unix-like systems
SET PATH=%PATH%;\path\to # on Windows
Then you can call myscript.py from wherever you are.
A:
All of those operating systems should support a PATH environment variable which specifies directories that have executables that should be available everywhere. Make your script executable by chmod +x and place it into one of those directories (or add a new one to your PATH - I have ~/bin for instance).
I don't know how to make new kinds of files directly executable on Windows, though, but I guess you could use a .bat file as a proxy.
| 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 installed on Windows and Linux?
| [
"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 difference between calling on an object's properties and methods explicit.
Obviously, it allows you to have properties and methods that share the same name, but I don't think that comes up much.
The only big benefit I can come up with is readability. Sometimes you might want to know whether something is a method or a property while you're looking at code, but I'm having trouble coming up with specific examples when that would be really helpful. But I am a n00b, so I probably just haven't encountered such a situation yet. I'd appreciate examples of such a situation.
Also, are there other languages where the difference isn't explicit?
Anyways, if you could answer, it will help me be less annoyed every time I make this mistake ^-^.
UPDATE:
Thanks everyone for the awesome answers so far! I only have about a week's worth of js, and 1 day of python, so I had no idea you could reference functions without calling them. That's awesome. I have a little more experience with java, so that's where I was mostly coming from... can anyone come up with an equally compelling argument for that to be the case in java, where you can't reference functions? Aside from it being a very explicit language, with all the benefits that entails :).
A:
All modern languages require this because referencing a function and calling a function are separate actions.
For example,
def func():
print "hello"
return 10
a = func
a()
Clearly, a = func and a = func() have very different meanings.
Ruby--the most likely language you're thinking of in contrast--doesn't require the parentheses; it can do this because it doesn't support taking references to functions.
A:
In languages like Python and JavaScript, functions are first–class objects. This means that you can pass functions around, just like you can pass around any other value. The parentheses after the function name (the () in myfunc()) actually constitute an operator, just like + or *. Instead of meaning "add this number to another number" (in the case of +), () means "execute the preceding function". This is necessary because it is possible to use a function without executing it. For example, you may wish to compare it to another function using ==, or you may wish to pass it into another function, such as in this JavaScript example:
function alertSomething(message) {
alert(message);
}
function myOtherFunction(someFunction, someArg) {
someFunction(someArg);
}
// here we are using the alertSomething function without calling it directly
myOtherFunction(alertSomething, "Hello, araneae!");
In short: it is important to be able to refer to a function without calling it — this is why the distinction is necessary.
A:
At least in JS, its because you can pass functions around.
var func = new Function();
you can then so something like
var f = func
f()
so 'f' and 'func' are references to the function, and f() or func() is the invocation of the function.
which is not the same as
var val = f();
which assigns the result of the invocation to a var.
For Java, you cannot pass functions around, at least like you can in JS, so there is no reason the language needs to require a () to invoke a method. But it is what it is.
I can't speak at all for python.
But the main point is different languages might have reasons why syntax may be necessary, and sometimes syntax is just syntax.
A:
I think you answered it yourself:
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.
Consider the following:
if (colorOfTheSky == 'blue')
vs:
if (colorOfTheSky() == 'blue')
We can tell just by looking that the first checks for a variable called colorOfTheSky, and we want to know if its value is blue. In the second, we know that colorOfTheSky() calls a function (method) and we want to know if its return value is blue.
If we didn't have this distinction it would be extremely ambiguous in situations like this.
To answer your last question, I don't know of any languages that don't have this distinction.
Also, you probably have a design problem if you can't tell the difference between your methods and your properties; as another answer points out, methods and properties have different roles to play. Furthermore it is good practice for your method names to be actions, e.g. getPageTitle, getUserId, etc., and for your properties to be nouns, e.g., pageTitle, userId. These should be easily decipherable in your code for both you and anyone who comes along later and reads your code.
A:
If you're having troubles, distinguishing between your properties and methods, you're probably not naming them very well.
In general, your methods should have a verb in them: i.e. write, print, echo, open, close, get, set, and property names should be nouns or adjectives: name, color, filled, loaded.
It's very important to use meaningful method and property names, without it, you'll find that you'll have difficulty reading your own code.
A:
Because referencing and calling a method are two different things. Consider X.method being the method of class X and x being an instance of X, so x.method == 'blue' would'nt ever be able to be true because methods are not strings.
You can try this: print a method of an object:
>>> class X(object):
... def a(self):
... print 'a'
...
>>> x=X()
>>> print x.a
<bound method X.a of <__main__.X object at 0x0235A910>>
A:
In Java, I can think of two reasons why the () is required:
1) Java had a specific design goal to have a "C/C++ like" syntax, to make it easy for C and C++ programmers to learn the language. Both C and C++ require the parentheses.
2) The Java syntax specifically requires the parentheses to disambiguate a reference to an attribute or local from a call to a method. This is because method names and attribute / local names are declared in different namespaces. So the following is legal Java:
public class SomeClass {
private int name;
private int name() { ... }
...
int norm = name; // this one
}
If the () was not required for a method call, the compiler would not be able to tell if the labeled statement ("this one") was assigning the value of the name attribute or the result of calling the name() method.
A:
The difference isn't always explicit in VBA. This is a call to a Sub (i.e. a method with no return value) which takes no parameters (all examples are from Excel):
Worksheets("Sheet1").UsedRange.Columns.AutoFit
whereas this is accessing an attribute then passing it as a parameter:
MsgBox Application.Creator
As in the previous example, parentheses are also optional around parameters if there is no need to deal with the return value:
Application.Goto Worksheets("Sheet2").Range("A1")
but are needed if the return value is used:
iRows = Len("hello world")
A:
Typically properties are accessors, and methods perform some sort of action. Going on this assumption, it's cheap to use a property, expensive to use a method.
Foo.Bar, for example, would indicate to me that it would return a value, like a string, without lots of overhead.
Foo.Bar() (or more likely, Foo.GetBar()), on the other hand, implies needing to retrieve the value for "Bar", perhaps from a database.
Properties and methods have different purposes and different implications, so they should be differentiated in code as well.
By the way, in all languages I know of the difference in syntax is explicit, but behind the scenes properties are often treated as simply special method calls.
| 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 properties and methods that share the same name, but I don't think that comes up much.
The only big benefit I can come up with is readability. Sometimes you might want to know whether something is a method or a property while you're looking at code, but I'm having trouble coming up with specific examples when that would be really helpful. But I am a n00b, so I probably just haven't encountered such a situation yet. I'd appreciate examples of such a situation.
Also, are there other languages where the difference isn't explicit?
Anyways, if you could answer, it will help me be less annoyed every time I make this mistake ^-^.
UPDATE:
Thanks everyone for the awesome answers so far! I only have about a week's worth of js, and 1 day of python, so I had no idea you could reference functions without calling them. That's awesome. I have a little more experience with java, so that's where I was mostly coming from... can anyone come up with an equally compelling argument for that to be the case in java, where you can't reference functions? Aside from it being a very explicit language, with all the benefits that entails :).
| [
"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://www.mediacollege.com/audio/tone/dtmf.html
For exemple when i get one .wav audio file of key "1" i have just the requency 1209
how get the low frequency in this case for key "1" is 697, FFT dont give me this :-(
A:
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.
When you apply it to a DTMF, you'll get two peaks for the two freqs that the signal contains.
http://en.wikipedia.org/wiki/Fast_Fourier_transform
A:
Since you only need information on a few frequencies with DTMF, you might want to try using the Goertzel algorithm for each frequency. You don't need all the FFT bins; and you might be able to target the frequencies of interest more precisely, depending on the time window, then wherever the FFT bins end up centered.
Compare the magnitude outputs of the Goertzel filters with the RMS total energy to make some decision for tone presence. Then do a table look up for the DTMF frequencies present to get the code.
| 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.html
For exemple when i get one .wav audio file of key "1" i have just the requency 1209
how get the low frequency in this case for key "1" is 697, FFT dont give me this :-(
| [
"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 (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 which a separate process can be writing). The advantage is however dubious, since (again per the docs) "The header Content-Length is automatically set to the correct value" -- which, since headers come before body, and the file's content length can't be known until the file is read, implies the whole file's going to be read into memory anyway.
If you're desperate to "stream" dynamically generated content into an HTTP POST (rather than preparing it all beforehand and then posting), you need a server supporting HTTP's "chunked transfer encoding": this SO question's accepted answer mentions that the popular asynchronous networking Python package twisted does, and gives some useful pointers.
| 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 python.
Is there anyway of retrieving the html of the page and editing it and get mechanize to parse and submit the form based on the retrieved HTML?
A:
If anyone else is interested. Found the answer in mechanize's FAQ.
Alternatively, you can process the HTML (and headers) arbitrarily:
browser = mechanize.Browser()
browser.open("http://example.com/")
html = browser.response().get_data().replace("<br/>", "<br />")
response = mechanize.make_response(
html, [("Content-Type", "text/html")],
"http://example.com/", 200, "OK")
browser.set_response(response)
| 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 the page and editing it and get mechanize to parse and submit the form based on the retrieved HTML?
| [
"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 dic:
print(k, v)
A:
For every python container C, the expectation is that
for item in C:
assert item in C
will 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, sets, tuples, ...
So, when C is a dictionary, if in were to yield key/value tuples in a for loop, then, by the principle of least astonishment, in would also have to take such a tuple as its left-hand operand in the containment check.
How useful would that be? Pretty useless indeed, basically making if (key, value) in C a synonym for if C.get(key) == value -- which is a check I believe I may have performed, or wanted to perform, 100 times more rarely than what if k in C actually means, checking the presence of the key only and completely ignoring the value.
On the other hand, wanting to loop just on keys is quite common, e.g.:
for k in thedict:
thedict[k] += 1
having the value as well would not help particularly:
for k, v in thedict.items():
thedict[k] = v + 1
actually somewhat less clear and less concise. (Note that items was the original spelling of the "proper" methods to use to get key/value pairs: unfortunately that was back in the days when such accessors returned whole lists, so to support "just iterating" an alternative spelling had to be introduced, and iteritems it was -- in Python 3, where backwards compatibility constraints with previous Python versions were much weakened, it became items again).
A:
My guess: Using the full tuple would be more intuitive for looping, but perhaps less so for testing for membership using in.
if key in counts:
counts[key] += 1
else:
counts[key] = 1
That code wouldn't really work if you had to specify both key and value for in. I am having a hard time imagining use case where you'd check if both the key AND value are in the dictionary. It is far more natural to only test the keys.
# When would you ever write a condition like this?
if (key, value) in dict:
Now it's not necessary that the in operator and for ... in operate over the same items. Implementation-wise they are different operations (__contains__ vs. __iter__). But that little inconsistency would be somewhat confusing and, well, inconsistent.
| 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")
http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
page_opener = urllib.request.build_opener(http_handler)
urllib.request.install_opener(page_opener)
params = urllib.parse.urlencode( {'status': msg} )
resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)
resp.read()
When I execute this code through IDLE, I get an error along the lines of;
urllib.error.HTTPError: HTTP Error 401: Unauthorized
What maybe wrong with my code?
A:
Twitter no longer supports HTTP Authentication. You should use oauth in stead.
tweepy 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.
A:
Your are using the old HTTP Auth method. Upgrade using OAuth.
Go to the following link to setup your Twitter Application: twitter.com/apps/new
(Tip: You can set your URL to 127.0.0.1 for testing purposes AND Remember to set application to Browser and specify Callback URL)
And you can continue from there.
| 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)
page_opener = urllib.request.build_opener(http_handler)
urllib.request.install_opener(page_opener)
params = urllib.parse.urlencode( {'status': msg} )
resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)
resp.read()
When I execute this code through IDLE, I get an error along the lines of;
urllib.error.HTTPError: HTTP Error 401: Unauthorized
What maybe wrong with my code?
| [
"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 have tried regexp using Pattern and Matcher, then StringTokenizer, but still without success.
This is what I want to do, shown in Python:
for token in re.finditer( "([A-Z])(\d*)", inputString):
print token.group(1)
print token.group(2)
For input "A12R5F28" the result would be:
A
12
R
5
F
28
A:
You could use regex API in Java and achieve the same functionality:
Pattern myPattern = Pattern.compile("([A-Z])(\d+)")
Matcher myMatcher = myPattern.matcher("A12R5F28");
while (myMatcher.find()) {
// Do your stuff here
}
A:
Expanding on Ravi's Answer....
Pattern myPattern = Pattern.compile("([A-Z])(\\d+)");
Matcher myMatcher = myPattern.matcher("A12R5F28");
while (myMatcher.find()) {
System.out.println(myMatcher.group(1) + "\n" + myMatcher.group(2));
}
| 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.
This is what I want to do, shown in Python:
for token in re.finditer( "([A-Z])(\d*)", inputString):
print token.group(1)
print token.group(2)
For input "A12R5F28" the result would be:
A
12
R
5
F
28
| [
"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', '', theString)
A:
filter(str.isdigit, s) is faster and IMO clearer than anything else listed here.
It will also throw a TypeError if s is a unicode type. Depending on what definition of "digits" you want, this can be more or less useful than the alternative filter(type(s).isdigit, s), slightly slower but still faster than the re and comprehension versions for me.
Edit: Although if you are a poor sucker stuck with Python 3, you will need to use "".join(filter(str.isdigit, s)) which puts you firmly in the realm of equivalently bad performance. Such progress.
A:
Let's time the join and the re versions:
In [3]: import re
In [4]: def withRe(theString): return re.sub('\D', '', theString)
...:
In [5]:
In [6]: def withJoin(S): return ''.join(c for c in S if c.isdigit())
...:
In [11]: s = "8-4545-225-144"
In [12]: %timeit withJoin(s)
100000 loops, best of 3: 6.89 us per loop
In [13]: %timeit withRe(s)
100000 loops, best of 3: 4.77 us per loop
The join version is much nicer, compared to the re one, but unfortunately is 50% slower. So if the performance is an issue, the elegance might need to be sacrificed.
EDIT
In [16]: def withFilter(s): return filter(str.isdigit, s)
....:
In [19]: %timeit withFilter(s)
100000 loops, best of 3: 2.75 us per loop
It looks like filter is the performance and readability winner
A:
Although a little more complicated to set up, using the translate() string method to delete the characters as shown below can as much as 4-6 times faster than using join() or re.sub() according to timing tests I performed -- so if it is something done many times, you might want to consider using this instead.
nonnumerics = ''.join(c for c in ''.join(chr(i) for i in range(256)) if not c.isdigit())
astring = '123-$ab #6789'
print astring.translate(None, nonnumerics)
# 1236789
A:
I prefer regular expressions, so here's a way if you like
import re
myStr = '$334fdf890==-'
digts = re.sub('[^0-9]','',myStr)
This should replace all nonnumeric occurences with '' i.e. with nothing. So digts variable should be '334890'
| 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,
auto_error_formatter=custom_formatter)
def submit(self):
return 'Your email is: %s and the date selected was %r.' % (
self.form_result['email'],
self.form_result['date'],
)
The first action is for initial form rendering and the second one is when the form is submitted. Is it possible to merge them and just use an if request.POST == 'POST' to check if the form has been submitted?
I tried it and move the @validate decorator to the form action but it gives me a WSOD and the server stops serving:
class FormtestController(BaseController):
@validate(schema=EmailForm(state=c), form='form', post_only=False, on_get=True,
auto_error_formatter=custom_formatter)
def form(self):
if request.method == 'POST':
return 'Your email is: %s and the date selected was %r.' % (
self.form_result['email'],
self.form_result['date'],
)
return render('/simpleform.html')
Is there a way to have a single action and still use the validate decorator?
A:
Silly me, it was just simple. Here's my code:
class FormtestController(BaseController):
@validate(schema=EmailForm(state=c), form='form', post_only=True,
on_get=False,
auto_error_formatter=custom_formatter)
def form(self):
if request.method == 'POST':
return 'Your email is: %s and the date selected was %r.' % (
self.form_result['email'],
self.form_result['date'],
)
return render('/simpleform.html')
| 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 email is: %s and the date selected was %r.' % (
self.form_result['email'],
self.form_result['date'],
)
The first action is for initial form rendering and the second one is when the form is submitted. Is it possible to merge them and just use an if request.POST == 'POST' to check if the form has been submitted?
I tried it and move the @validate decorator to the form action but it gives me a WSOD and the server stops serving:
class FormtestController(BaseController):
@validate(schema=EmailForm(state=c), form='form', post_only=False, on_get=True,
auto_error_formatter=custom_formatter)
def form(self):
if request.method == 'POST':
return 'Your email is: %s and the date selected was %r.' % (
self.form_result['email'],
self.form_result['date'],
)
return render('/simpleform.html')
Is there a way to have a single action and still use the validate decorator?
| [
"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 except I hit a wall when trying to use set_passphrase_cb to avoid any user interaction but couldn't get it working ( Problem decrypting PGP in python with pyme without user interaction ).
The platform is Ubuntu 10.04. What library would you recommend?
A:
EDITED: other the two libraries you mentioned. there doesn;t seem to be anything.
A:
You could use ctypes to roll your own wrapper around just the parts of GPGME you need.
| 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 working ( Problem decrypting PGP in python with pyme without user interaction ).
The platform is Ubuntu 10.04. What library would you recommend?
| [
"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: ' + request.POST.get('SALEDATE'))
However, I can't get the multi value variables using request.POST.getlist('variable_name'). For example, the following returns an empty list.
prices = request.POST.getlist("IPN_PRICE")
I can't show all the fields in the request here, because it's work for a client. However this log call:
logging.debug(repr(request.POST))
gives this output (start only)
<QueryDict: {u'IPN_PRICE[]': [u'15.76'], ...
By the way, the request I'm trying to process is an IPN (Instant Payment Notification) from a payment processing service.
A:
prices = request.POST.getlist("IPN_PRICE[]")
This should do the trick.
| 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 multi value variables using request.POST.getlist('variable_name'). For example, the following returns an empty list.
prices = request.POST.getlist("IPN_PRICE")
I can't show all the fields in the request here, because it's work for a client. However this log call:
logging.debug(repr(request.POST))
gives this output (start only)
<QueryDict: {u'IPN_PRICE[]': [u'15.76'], ...
By the way, the request I'm trying to process is an IPN (Instant Payment Notification) from a payment processing service.
| [
"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 Model definintion, as one cannot create a relation to the A instance before ainstance.save() has been called. However, this type of init method would make my controllers much simpler. Is there a way to avoid this problem?
A:
You can put this code in an overridden save method of A:
def save(self,**kwargs):
super(A,self).save(**kwargs)
B(a=self,data=data).save()
| 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 instance before ainstance.save() has been called. However, this type of init method would make my controllers much simpler. Is there a way to avoid this problem?
| [
"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 descriptor as I/O os.open(fd)
But I get OSError: [Errno 9] Bad file descriptor
I said I'm new to python and maybe I'm wrong with the implementation. But I tried a simpler example os.close(s.fileno()) and I get the same error OSError: [Errno 9] Bad file descriptor
I found an example written in ruby and I tested it, it works. How do I make persistent network sockets on Unix in Ruby?
Can any one write this into python for me, what I want to achieve is:
socket_start.py google.com (thie will print the fd number)
sleep 10
socket_write.py fd_number 'something'
sleep 10
socket_read.py fd_number 1024
I hope you understand what I want to do. Thanks in advice!
After your responses I tried next code:
1
#!/usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('google.com', 80))
s.send('GET /\n')
print s.fileno()
2
#!/usr/bin/python
import os
import sys
fd = int(sys.argv[1])
os.read(fd, 1024)
And the error is OSError: [Errno 9] Bad file descriptor
I'm sure what the problem is (I'm a php developer). I think same as php, python deletes garbage after closing a script. How to solve this in python ?
A:
You use os.fdopen() to open file descriptors.
I'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.
A:
If you want to re-create the socket by a parameter received on the commandline (i.e., the socket), use socket.fromfd
| 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: [Errno 9] Bad file descriptor
I said I'm new to python and maybe I'm wrong with the implementation. But I tried a simpler example os.close(s.fileno()) and I get the same error OSError: [Errno 9] Bad file descriptor
I found an example written in ruby and I tested it, it works. How do I make persistent network sockets on Unix in Ruby?
Can any one write this into python for me, what I want to achieve is:
socket_start.py google.com (thie will print the fd number)
sleep 10
socket_write.py fd_number 'something'
sleep 10
socket_read.py fd_number 1024
I hope you understand what I want to do. Thanks in advice!
After your responses I tried next code:
1
#!/usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('google.com', 80))
s.send('GET /\n')
print s.fileno()
2
#!/usr/bin/python
import os
import sys
fd = int(sys.argv[1])
os.read(fd, 1024)
And the error is OSError: [Errno 9] Bad file descriptor
I'm sure what the problem is (I'm a php developer). I think same as php, python deletes garbage after closing a script. How to solve this in python ?
| [
"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 VarDefs.h that requires a struct like this:
typedef struct
{
char Var1[8+1];
char Var2[11+1];
char Var3[3+1];
...
}TMyData
that should be passed to a function like this:
__declspec(dllexport) int AFunction(TOtherData *OtherData, TMyData *MyData);
In Python I am now able to declare the structure this way (thanks to Mr. Martelli: see here Python ctypes - dll function accepting structures crashes ):
class TMyData( Structure ):
_fields_ = [
("Var1" , type( create_string_buffer(9) ) ),
("Var2" , type( create_string_buffer(12)) ),
...
I call the function this way: result = Afunction( byref(OtherData) , byref(MyData ) )
As said, as I try to access MyData.Var1.value I get an error (sorry, can't be more specific now!), but repr(str(x)) where x is a copy of buffer(MyData) shows that there are data in it!
How should I do it instead? Thanks!
A:
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.
class TMyData( ctypes.Structure ):
_fields_ = [ ("Var1", ctypes.c_char * 9),
("Var2", ctypes.c_char * 12), ... ]
A:
Just use print MyData.Var1. The character array is converted to a Python string type when accessed through a Structure instance, which doesn't have a .value method.
Contrived, working example:
DLL Code (x.c, compiled with MSVC with "cl /LD x.c")
#include <string.h>
typedef struct
{
char Var1[5];
char Var2[10];
char Var3[15];
} TMyData;
__declspec(dllexport) int AFunction(TMyData *MyData)
{
strcpy(MyData->Var1,"four");
strcpy(MyData->Var2,"--nine---");
strcpy(MyData->Var3,"---fourteen---");
return 3;
}
Python Code
import ctypes as c
class TMyData(c.Structure):
_fields_ = [
("Var1", c.c_char * 5),
("Var2", c.c_char * 10),
("Var3", c.c_char * 15)]
lib = c.CDLL('x')
data = TMyData()
lib.AFunction(c.byref(data))
print data.Var1
print data.Var2
print data.Var3
print data.Var1.value # error!
Output
four
--nine---
---fourteen---
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 436, in ImportFile
my_reload(sys.modules[modName])
File "C:\x.py", line 12, in <module>
print data.Var1.value
AttributeError: 'str' object has no attribute 'value'
| 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[8+1];
char Var2[11+1];
char Var3[3+1];
...
}TMyData
that should be passed to a function like this:
__declspec(dllexport) int AFunction(TOtherData *OtherData, TMyData *MyData);
In Python I am now able to declare the structure this way (thanks to Mr. Martelli: see here Python ctypes - dll function accepting structures crashes ):
class TMyData( Structure ):
_fields_ = [
("Var1" , type( create_string_buffer(9) ) ),
("Var2" , type( create_string_buffer(12)) ),
...
I call the function this way: result = Afunction( byref(OtherData) , byref(MyData ) )
As said, as I try to access MyData.Var1.value I get an error (sorry, can't be more specific now!), but repr(str(x)) where x is a copy of buffer(MyData) shows that there are data in it!
How should I do it instead? Thanks!
| [
"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), (18,27), (4,14)])
[(3,4,14), (18,27)]
>>> MergeThat([(1,3), (15,21), (1,10), (57,66), (76,85), (66,76)])
[(57,66,76,85), (1,3,10), (15,21)]
I understand it's something similar to hierarchical clustering algorithms, which I've read about, but can't figure them out.
Is there a relatively simple code for a MergeThat() function?
A:
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.
While you can do this efficiently, there is actually no reason to implement this yourself! Just import a good graph library:
import networkx as nx
# one of your examples
g1 = nx.Graph([(1,3), (15,21), (1,10), (57,66), (76,85), (66,76)])
print nx.connected_components(g1) # [[57, 66, 76, 85], [1, 10, 3], [21, 15]]
# my own test case
g2 = nx.Graph([(1,2),(2,10), (20,3), (3,4), (4,10)])
print nx.connected_components(g2) # [[1, 2, 3, 4, 10, 20]]
A:
import itertools
def merge_it(lot):
merged = [ set(x) for x in lot ] # operate on sets only
finished = False
while not finished:
finished = True
for a, b in itertools.combinations(merged, 2):
if a & b:
# we merged in this iteration, we may have to do one more
finished = False
if a in merged: merged.remove(a)
if b in merged: merged.remove(b)
merged.append(a.union(b))
break # don't inflate 'merged' with intermediate results
return merged
if __name__ == '__main__':
print merge_it( [(3,4), (18,27), (4,14)] )
# => [set([18, 27]), set([3, 4, 14])]
print merge_it( [(1,3), (15,21), (1,10), (57,66), (76,85), (66,76)] )
# => [set([21, 15]), set([1, 10, 3]), set([57, 66, 76, 85])]
print merge_it( [(1,2), (2,3), (3,4), (4,5), (5,9)] )
# => [set([1, 2, 3, 4, 5, 9])]
Here's a snippet (including doctests): http://gist.github.com/586252
A:
def collapse(L):
""" The input L is a list that contains tuples of various sizes.
If any tuples have shared elements,
exactly one instance of the shared and unshared elements are merged into the first tuple with a shared element.
This function returns a new list that contain merged tuples and an int that represents how many merges were performed."""
answer = []
merges = 0
seen = [] # a list of all the numbers that we've seen so far
for t in L:
tAdded = False
for num in t:
pleaseMerge = True
if num in seen and pleaseMerge:
answer += merge(t, answer)
merges += 1
pleaseMerge = False
tAdded= True
else:
seen.append(num)
if not tAdded:
answer.append(t)
return (answer, merges)
def merge(t, L):
""" The input L is a list that contains tuples of various sizes.
The input t is a tuple that contains an element that is contained in another tuple in L.
Return a new list that is similar to L but contains the new elements in t added to the tuple with which t has a common element."""
answer = []
while L:
tup = L[0]
tupAdded = False
for i in tup:
if i in t:
try:
L.remove(tup)
newTup = set(tup)
for i in t:
newTup.add(i)
answer.append(tuple(newTup))
tupAdded = True
except ValueError:
pass
if not tupAdded:
L.remove(tup)
answer.append(tup)
return answer
def sortByLength(L):
""" L is a list of n-tuples, where n>0.
This function will return a list with the same contents as L
except that the tuples are sorted in non-ascending order by length"""
lengths = {}
for t in L:
if len(t) in lengths.keys():
lengths[len(t)].append(t)
else:
lengths[len(t)] = [(t)]
l = lengths.keys()[:]
l.sort(reverse=True)
answer = []
for i in l:
answer += lengths[i]
return answer
def MergeThat(L):
answer, merges = collapse(L)
while merges:
answer, merges = collapse(answer)
return sortByLength(answer)
if __name__ == "__main__":
print 'starting'
print MergeThat([(3,4), (18,27), (4,14)])
# [(3, 4, 14), (18, 27)]
print MergeThat([(1,3), (15,21), (1,10), (57,66), (76,85), (66,76)])
# [(57, 66, 76, 85), (1, 10, 3), (15, 21)]
A:
Here's another solution that doesn't use itertools and takes a different, slightly more verbose, approach. The tricky bit of this solution is the merging of cluster sets when t0 in index and t1 in index.
import doctest
def MergeThat(a):
""" http://stackoverflow.com/questions/3744048/python-how-to-merge-a-list-into-clusters
>>> MergeThat([(3,4), (18,27), (4,14)])
[(3, 4, 14), (18, 27)]
>>> MergeThat([(1,3), (15,21), (1,10), (57,66), (76,85), (66,76)])
[(57, 66, 76, 85), (1, 3, 10), (15, 21)]
"""
index = {}
for t0, t1 in a:
if t0 not in index and t1 not in index:
index[t0] = set()
index[t1] = index[t0]
elif t0 in index and t1 in index:
index[t0] |= index[t1]
oldt1 = index[t1]
for x in index.keys():
if index[x] is oldt1:
index[x] = index[t0]
elif t0 not in index:
index[t0] = index[t1]
else:
index[t1] = index[t0]
assert index[t0] is index[t1]
index[t0].add(t0)
index[t0].add(t1)
return sorted([tuple(sorted(x)) for x in set(map(frozenset, index.values()))], key=len, reverse=True)
if __name__ == "__main__":
import doctest
doctest.testmod()
A:
The code others have written will surely work, but here's another option, maybe simpler to understand and maybe less algorithmic complexity.
Keep a dictionary from numbers to the cluster (implemented as a python set) they're a member of. Also include that number in the corresponding set. Process an input pair either as:
Neither element is in the dictionary: create a new set, hook up dictionary links appropriately.
One or the other, but not both elements are in the dictionary: Add the yet-unseen element to the set of its brother, and add its dictionary link into the correct set.
Both elements are seen before, but in different sets: Take the union of the old sets and update all dictionary links to the new set.
You've seen both members before, and they're in the same set: Do nothing.
Afterward, simply collect the unique values from the dictionary and sort in descending order of size. This portion of the job is O(m log n) and thus will not dominate runtime.
This should work in a single pass. Writing the actual code is left as an exercise for the reader.
A:
This is not efficient for huge lists.
def merge_that(lot):
final_list = []
while len(lot) >0 :
temp_set = set(lot[0])
deletable = [0] #list of all tuples consumed by temp_set
for i, tup2 in enumerate(lot[1:]):
if tup2[0] in temp_set or tup2[1] in temp_set:
deletable.append(i)
temp_set = temp_set.union(tup2)
for d in deletable:
del lot[d]
deletable = []
# Some of the tuples consumed later might have missed their brothers
# So, looping again after deleting the consumed tuples
for i, tup2 in enumerate(lot):
if tup2[0] in temp_set or tup2[1] in temp_set:
deletable.append(i)
temp_set = temp_set.union(tup2)
for d in deletable:
del lot[d]
final_list.append(tuple(temp_set))
return final_list
It looks ugly but works.
| 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)]
>>> MergeThat([(1,3), (15,21), (1,10), (57,66), (76,85), (66,76)])
[(57,66,76,85), (1,3,10), (15,21)]
I understand it's something similar to hierarchical clustering algorithms, which I've read about, but can't figure them out.
Is there a relatively simple code for a MergeThat() function?
| [
"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=True),
schema.Column('name', types.Unicode(20), nullable=False, unique=True),
)
class Tag(object):
pass
orm.mapper(Tag, tag_table)
When I run paster setup-app development.ini I can see that the table is created but if I add another column to my table, how do I migrate the only column that I've added?
I've seen this migration in Rails and Django but is there something similar for Pylons?
A:
You can try this tool: sqlalchemy-migrate
| 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), nullable=False, unique=True),
)
class Tag(object):
pass
orm.mapper(Tag, tag_table)
When I run paster setup-app development.ini I can see that the table is created but if I add another column to my table, how do I migrate the only column that I've added?
I've seen this migration in Rails and Django but is there something similar for Pylons?
| [
"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 "Startup" folder, in the windows start menu.
A:
You can compile your python script into an exe and add it to your startup items: Start > Programs > Accessories > System Tools > Scheduled Tasks
| 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 subprocess.Popen(args) is the preferred way to run programs from inside python scripts.
For example, I have a pdf file in memory. I want to convert it to text using the commandline function pdftotext which is present in most linux distros. But I would prefer not to write the in-memory pdf file to a temporary file on disk.
pdfInMemory = myPdfReader.read()
convertedText = subprocess.<method>(['pdftotext', ??]) <- what is the value of ??
what is the method I should call and how should I pipe in memory data into its first input and pipe its output back to another variable in memory?
I am guessing there are other pdf modules that can do the conversion in memory and information about those modules would be helpful. But for future reference, I am also interested about how to pipe input and output to the commandline from inside python.
Any help would be much appreciated.
A:
with Popen.communicate:
import subprocess
out, err = subprocess.Popen(["pdftotext", "-", "-"], stdout=subprocess.PIPE).communicate(pdf_data)
A:
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.
tf=os.tmpfile()
tf.write(...)
tf.seek(0)
subprocess.Popen( ... , stdin = tf)
This may not work on Posix-impaired OS 'Windows'.
A:
Popen.communicate from subprocess takes an input parameter that is used to send data to stdin, you can use that to input your data. You also get the output of your program from communicate, so you don't have to write it into a file.
The documentation for communicate explicitly warns that everything is buffered in memory, which seems to be exactly what you want to achieve.
| 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 scripts.
For example, I have a pdf file in memory. I want to convert it to text using the commandline function pdftotext which is present in most linux distros. But I would prefer not to write the in-memory pdf file to a temporary file on disk.
pdfInMemory = myPdfReader.read()
convertedText = subprocess.<method>(['pdftotext', ??]) <- what is the value of ??
what is the method I should call and how should I pipe in memory data into its first input and pipe its output back to another variable in memory?
I am guessing there are other pdf modules that can do the conversion in memory and information about those modules would be helpful. But for future reference, I am also interested about how to pipe input and output to the commandline from inside python.
Any help would be much appreciated.
| [
"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/Django and has anyone implemented in live production environment
A:
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)
Also, if you're still learning about web services, I can highly recommend the O'Reilly book RESTful Web Services -- although it's a book with a focus on REST (which I agree is the best design pattern for a web service) it also explains RPC and SOAP, too.
A:
There are so many things like SOAPpy, XML-RPC, JSON-RPC RESTful, web service.
This should give you a clue - there are different services out there that use one or more of these mechanisms.
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 production environment
There is no single standard way of implementing a web service. This is as true for Django/Python as for other web frameworks.
Different people have used Django in different ways to create a web service to suit their needs.
| 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 production environment
| [
"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 various assumptions, the most basic of which is whether the dependencies are installed.
Checks I have considered:
Check the service is responding, e.g. make an HTTP request, connect to a database, etc.
Check somehow that a service is running, e.g. maybe grepping ps ax?
(This seems unreliable)
Check that the package is installed, e.g. through querying dpkg.
These obviously go in order of decreasing specificity, the hope being that if one test fails, I might find out why by running a more specific test.
But where do I stop? How many levels of specificity should I check? Are there any best practices for doing this sort of thing?
Thanks!
A:
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)
| 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 installed.
Checks I have considered:
Check the service is responding, e.g. make an HTTP request, connect to a database, etc.
Check somehow that a service is running, e.g. maybe grepping ps ax?
(This seems unreliable)
Check that the package is installed, e.g. through querying dpkg.
These obviously go in order of decreasing specificity, the hope being that if one test fails, I might find out why by running a more specific test.
But where do I stop? How many levels of specificity should I check? Are there any best practices for doing this sort of thing?
Thanks!
| [
"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 done a google search and added:
def __str__(self):
return ""
To the end of my User model class but with no success. Not sure if I have to enter something into my admin.py? I also have no "add" method in my User class, it also returns nothing else other than the method above.
Thanks for any help!
The User Class:
class User(models.Model):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
username = models.CharField(max_length=30)
email = models.EmailField()
password = models.CharField(max_length=30)
birth_date = models.DateField()
description = models.CharField(max_length=200)
gender = models.CharField(max_length = 1, choices = GENDER_CHOICES, default = "M")
image = models.ImageField(upload_to="media/photos/")
signupIP = models.IPAddressField()
privateOrPublic = models.BooleanField(default=1)
def __str__(self):
return ""
And the simple admin.py in /Users/
from Users.models import User
from django.contrib import admin
admin.site.register(User)
Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1/admin/Users/user/add/
Django Version: 1.2.3
Python Version: 2.7.0
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'Users']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
239. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
69. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
190. return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
21. return decorator(bound_func)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
17. return func(self, *args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\db\transaction.py" in _commit_on_success
299. res = func(*args, **kw)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in add_view
795. self.save_model(request, new_object, form, change=False)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in save_model
597. obj.save()
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save
434. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save_base
517. for f in meta.local_fields if not isinstance(f, AutoField)]
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in pre_save
255. file.save(file.name, file, save=False)
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in save
91. name = self.field.generate_filename(self.instance, name)
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in generate_filename
282. return os.path.join(self.get_directory_name(), self.get_filename(filename))
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in get_filename
279. return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))
File "C:\Python27\lib\site-packages\django\utils\functional.py" in __getattr__
276. self._setup()
File "C:\Python27\lib\site-packages\django\core\files\storage.py" in _setup
242. self._wrapped = get_storage_class()()
File "C:\Python27\lib\site-packages\django\core\files\storage.py" in __init__
133. self.location = os.path.abspath(location)
File "C:\Python27\lib\ntpath.py" in abspath
465. path = _getfullpathname(path)
Exception Type: TypeError at /admin/Users/user/add/
Exception Value: coercing to Unicode: need string or buffer, tuple found
A:
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.
MEDIA_ROOT = os.path.join(os.path.dirname(file), "media").replace(r"\\", "//")
| 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__(self):
return ""
To the end of my User model class but with no success. Not sure if I have to enter something into my admin.py? I also have no "add" method in my User class, it also returns nothing else other than the method above.
Thanks for any help!
The User Class:
class User(models.Model):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
username = models.CharField(max_length=30)
email = models.EmailField()
password = models.CharField(max_length=30)
birth_date = models.DateField()
description = models.CharField(max_length=200)
gender = models.CharField(max_length = 1, choices = GENDER_CHOICES, default = "M")
image = models.ImageField(upload_to="media/photos/")
signupIP = models.IPAddressField()
privateOrPublic = models.BooleanField(default=1)
def __str__(self):
return ""
And the simple admin.py in /Users/
from Users.models import User
from django.contrib import admin
admin.site.register(User)
Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1/admin/Users/user/add/
Django Version: 1.2.3
Python Version: 2.7.0
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'Users']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
239. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
69. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
190. return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
21. return decorator(bound_func)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
17. return func(self, *args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\db\transaction.py" in _commit_on_success
299. res = func(*args, **kw)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in add_view
795. self.save_model(request, new_object, form, change=False)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in save_model
597. obj.save()
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save
434. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save_base
517. for f in meta.local_fields if not isinstance(f, AutoField)]
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in pre_save
255. file.save(file.name, file, save=False)
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in save
91. name = self.field.generate_filename(self.instance, name)
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in generate_filename
282. return os.path.join(self.get_directory_name(), self.get_filename(filename))
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in get_filename
279. return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))
File "C:\Python27\lib\site-packages\django\utils\functional.py" in __getattr__
276. self._setup()
File "C:\Python27\lib\site-packages\django\core\files\storage.py" in _setup
242. self._wrapped = get_storage_class()()
File "C:\Python27\lib\site-packages\django\core\files\storage.py" in __init__
133. self.location = os.path.abspath(location)
File "C:\Python27\lib\ntpath.py" in abspath
465. path = _getfullpathname(path)
Exception Type: TypeError at /admin/Users/user/add/
Exception Value: coercing to Unicode: need string or buffer, tuple found
| [
"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 lines of code. To make this easier to understand, I've written the __init__ function like so:
def __init__(self, root):
self.root = root
self._init_menu()
self._init_connectbar()
self._init_usertree()
self._init_remotetree()
self._init_bottom()
where _init_menu(), _init_connectbar(), and so on do all the initialization work. This makes my code easier to follow and prevents __init__ from getting too big.
However, this creates scope issues. Since an Entry widget that I defined in _init_connectbar() is in the function scope and is not a class attribute, I can't refer to it in other methods in the class.
I can make these problems go away by doing most of the initialization in __init__, but I'll lose the abstraction I got with my first method.
Should I expand __init__, or find another way to bring the widgets into class scope?
A:
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 things be decoupled enough that you can create an ordering that makes it possible.
A:
In my opinion, you should store the widgets as instance variables so that you can refer to them from any method. As in most programming languages, readability decreases when functions get too large, so your approach of splitting up the initialization code is a good idea.
When the class itself grows too large for one source file, you can also split up the class using mix-in classes (similar to having partial classes in C#).
For example:
class MainGuiClass(GuiMixin_FunctionalityA, GuiMixin_FunctionalityB):
def __init__(self):
GuiMixin_FunctionalityA.__init__(self)
GuiMixin_FunctionalityB.__init__(self)
This comes in handy when the GUI consists of different functionalities (for instance a configuration tab, an execution tab or whatsoever).
A:
Why don't you make your widgets that you need to refer to, instance variables. This is what I usaully do and seems to be quite a common approach.
e.g.
self.some_widget
A:
You should look into the builder-pattern for this kind of stuff. If your GUI is complex, then there will be some complexity in describing it. Whether that is a complex function or a complex description in some file comes down to the same. You can just try to make it as readable and maintainable as possible, and in my experience the builder pattern really helps here.
| 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've written the __init__ function like so:
def __init__(self, root):
self.root = root
self._init_menu()
self._init_connectbar()
self._init_usertree()
self._init_remotetree()
self._init_bottom()
where _init_menu(), _init_connectbar(), and so on do all the initialization work. This makes my code easier to follow and prevents __init__ from getting too big.
However, this creates scope issues. Since an Entry widget that I defined in _init_connectbar() is in the function scope and is not a class attribute, I can't refer to it in other methods in the class.
I can make these problems go away by doing most of the initialization in __init__, but I'll lose the abstraction I got with my first method.
Should I expand __init__, or find another way to bring the widgets into class scope?
| [
"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 provide drag-n-drop GUI application building also. So why is it that VB is flamed and yet Python is not?
I am just wondering out of curiosity.
A:
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.
VB is also seen as being the low-end language in the Microsoft ecosystem, with an ad-hoc design.
Python, on the other hand is open source, and cool because it is used in scientific applications, web startups, etc.
I'm not defending these positions, just giving you the perspective I've seen. As others have said, language wars are usually pointless. Occasionally you'll get a discussion that will truly touch on interesting differences between languages, but usually not.
| 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 it that VB is flamed and yet Python is not?
I am just wondering out of curiosity.
| [
"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 a tool like Spy++ (comes with Visual Studio) or some of the alternatives: Windows Spy, WinCheat or Window Detective
| 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 alternative ?
Thanks
UPDATE
PIL is good, but i need Python 3 support on a Mac OS X system.
A:
I would suggest you to enumerate the functionality that you find desirable which is there in Cimg and not in PIL.
Discussion on SO
Image Processing, In Python?
pypi also throws up a lot of modules on image processing. Try seeing, if some of them is suitable for you.
http://pypi.python.org/pypi?:action=search&term=image+processing&submit=search
| 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 a Mac OS X system.
| [
"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 header of all pages. I suppose I should use models for keeping the settings but I can't realize how I should better do it.
A:
There are quite some packages that store settings in models, pick the one that works best for you:
http://pypi.python.org/pypi?:action=search&term=django+settings&submit=search
A:
If you are okay with changing these setting programmatically via settings.py you should do that. However, if you want to change these settings via the Admin Console, you should use models.
| 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 models for keeping the settings but I can't realize how I should better do it.
| [
"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.read().decode('utf-8') as that is the charset indicated in the header, but I get a
'utf8' codec can't decode byte 0x8b in position 1" error message
How do I convert the byte object I received from my urllib.request call to a string?
A:
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.
update: Realizing I have a bad habit of not explaining/providing enough detail. For Python gzip'd byte strings they always start with 1f8b Someone explains it better here https://stackoverflow.com/a/3703300/9908
| 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 charset indicated in the header, but I get a
'utf8' codec can't decode byte 0x8b in position 1" error message
How do I convert the byte object I received from my urllib.request call to a string?
| [
"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 something like
import socks
import socket
import urllib2
proxies = ['127.0.0.1:1080', 'someproxy:1888', ... ] # you could load a file here
for proxy in proxies:
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, *proxy.split(':', 1))
socket.socket = socks.socksocket
urllib2.urlopen(URL)
| 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 can authenticate all the records that are already on the database. But, when I add or remove records (I do this through phpMyAdmin), the script doesn't seem to know that the database has changed (I remove a user in phpMyAdmin and it still authenticates the user). The only time when the script recognizes the new records is when I restart or force-reload the ejabberd server. I've already been told its not a mySQL caching problem. I made sure I turned off external authentication caching for ejabberd.
That's all I can think of right now. I'll add more information if I can think of it. Any help is appreciated. I have no idea what is going on.
Addition: I turned on the MySQL logs, and all the queries there so there is not skipping queries.
A:
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.
Edit: to fix it in innodb, set autocommit to true
| 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, when I add or remove records (I do this through phpMyAdmin), the script doesn't seem to know that the database has changed (I remove a user in phpMyAdmin and it still authenticates the user). The only time when the script recognizes the new records is when I restart or force-reload the ejabberd server. I've already been told its not a mySQL caching problem. I made sure I turned off external authentication caching for ejabberd.
That's all I can think of right now. I'll add more information if I can think of it. Any help is appreciated. I have no idea what is going on.
Addition: I turned on the MySQL logs, and all the queries there so there is not skipping queries.
| [
"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. Why does python execute the __init__ "module" twice?
A:
This is a Python bug. Passing the null string as an element of fromlist is illegal, and should raise an exception.
There'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 module name testpkg., with a trailing period. That gets imported literally, and since it has a different name than testpkg, it's imported as a separate module.
Try this:
pkg = __import__("testpkg", fromlist=[''])
import sys
print sys["testpkg"]
print sys["testpkg."]
... and you'll see the duplicate module.
Someone should probably file a ticket on this if there isn't already one; too tired to do it myself right now.
A:
Using the fromlist=[''] hack to import a specific module is explicitly frowned upon by python-dev. While it has been filed as an issue, the chances of it being fixed are low specifically because this is viewed as a mis-use of fromlist to begin with instead of necessarily a bug and a better solution is available.
What you should be doing is using importlib.import_module (available in the standard library for Python 2.7 and Python 3.1, or from PyPI with compatibility back to Python 2.3 along with being included in Django since 1.1 as django.utils.importlib). It will prevent this problem from happening, provides a better programmatic interface for importing modules, and even lets you use relative imports when you specify the package you are importing from.
If you really cannot use importlib (e.g., PyPI dependencies are not allowed even though the code you can freely copy thanks to the PSF license and it being rather short), then you should be doing __import__("some.module"); mod = sys.modules["some.module"]. That is the official, python-dev sanctioned solution to the problem (but only after you cannot use importlib).
| __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__ "module" twice?
| [
"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, and is
typically used to convert urls to
requests.
Unless overridden, this method returns
Requests with the parse() method as
their callback function, and with
dont_filter parameter enabled (see
Request class for more info).
Do you understand what this method does? And can I use makerequestsfrom_url and BaseSpider instead of SgmlLinkExtractor and CrawlSpider that is not working for me?
I am trying to crawl more than the given initial url and Scrapy is not doing that.
Thanks
A:
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.
| 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
requests.
Unless overridden, this method returns
Requests with the parse() method as
their callback function, and with
dont_filter parameter enabled (see
Request class for more info).
Do you understand what this method does? And can I use makerequestsfrom_url and BaseSpider instead of SgmlLinkExtractor and CrawlSpider that is not working for me?
I am trying to crawl more than the given initial url and Scrapy is not doing that.
Thanks
| [
"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 does?
Eg. I have read that people compare Expect with Awk and also Perl.
Could Awk and Perl do the same thing?
How about other languages like Python and Ruby?
Is Expect the de-facto automation tool or are there other solutions/languages that are more superior?
A:
There's more to it.
Bluntly, 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.
HOWEVER, at the same time, most Expect users exploit such a small fraction of Expect's capabilities that this technical superiority is a matter of indifference to them. In nearly all cases, I advise someone coming from Perl to use Expect.pm, someone familiar with Python to rely on Pexpect, and so on.
Naive comparisons of Perl with "... Awk and also Perl" are ill-founded.
In the abstract, all the common scripting languages--Lua, awk, sh, Tcl, Ruby, Perl, Python, ...--are about the same. Expect slightly but very effectively extends this common core in the direction of pty-awareness (there's a little more to the story that we can neglect for the moment). Roughly speaking, if your automation involves entering an invisible password, you want Expect. Awk and Perl do NOT build in this capability.
There are other automation tools for other contexts.
A:
Check out Expect for Perl
A:
ajsie asks, "Which other automation tools are you talking about?"
I'll answer a different question: "which other contexts do I have in mind"? The answer: any interactive environment OTHER than a stdio one. Expect is NOT for automation of GUI points-and-clicks, for example. Expect is also not available for Win* non-console applications, even if they look as though they are character-oriented (such exist).
An exciting counter-realization: Expect is for automation of wacky equipment that permits control by a term-like connection. If your diesel engine (or, more typically, telecomm iron) says it can be monitored by hooking up a telnet-like process (even through an old-style serial line, say), you're in a domain where Expect has a chance to work its magic.
A:
Check out Pexpect for Python
| 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.
Could Awk and Perl do the same thing?
How about other languages like Python and Ruby?
Is Expect the de-facto automation tool or are there other solutions/languages that are more superior?
| [
"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....any ideas to help me get it runnig again would be great. Strangely the Python Command Line opens up fine...
OS: Vista
thanks,
Baba
A:
uninstalling Python AND manually deleting the Python installation folder (which isn't removed by default when uninstalling) allowed me to re-install Python successfully
| 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 would be great. Strangely the Python Command Line opens up fine...
OS: Vista
thanks,
Baba
| [
"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 combine them into bigger launch pad. My perference would be launch pad type gui....Any ideas?
Its seems that launching scripts out of SciTE, works ok.
A:
Check joblaunch, a shell tool I made for executing interdependent jobs in parallel locally. It has more options.
| 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 launch pad. My perference would be launch pad type gui....Any ideas?
Its seems that launching scripts out of SciTE, works ok.
| [
"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 rows...but I still need to clean out the datastore to try to fix the bulk loader error.
What can I do?
A:
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.
Alternatively, if you know the keys for the entities you want to delete, you can delete them directly using db.delete() without ever needing to fetch them in the first place.
You might even be able to use the datastore viewer from the Dashboard to delete them (if you don't have many entities to delete, this might be easiest).
A:
Change your entities/models so that Districts is no longer a required property?
| 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 the bulk loader error.
What can I do?
| [
"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 a section header? I was thinking just the standard
[section]
regex1
regex2
But I just realized that [section] is a valid regex. So I'm wondering if there's a way I can format a section header so that it can ONLY be understood as a section header and not a regex.
A:
There's an unlimited ways of making an invalid regexp, but the first thing that comes to mind would be
*section*
You can't have a quantifier (*) at the start of the regexp.
(The other * is there just to satisfy my obsession for symmetry.)
A:
I don't know your problem domain, so I don't know what forms of regex you're expecting, but it seems to me you should keep your section formatting as it is. A regex that starts with [ and ends with ] and has no square brackets in between is quite unusual. It can only match a single character. So leave the section headers as they are. Strictly speaking, they are valid regexes, but they probably aren't interesting regexes.
Also, why not use ConfigParser from the standard library, and let it do the parsing for you?
A:
There are easy ways, but they all require changing your format:
Use indentation, similar to how Python source is interpreted. Leading spaces would need special handling, e.g. "(?: )abc" instead of " abc".
Use an INI format, where each item in a section requires a name=value pair.
Use some sort of list syntax. ast.literal_eval will be helpful.
section1 = [
"regex 1",
"2",
"3",
]
section2 = ["..."]
Primarily, don't invent your own format, or make it as close to a known format as you can. The third is a subset of Python syntax, for example, and you could even use raw string literals naturally.
JSON or YAML may be useful for you.
A:
As others have said, please don't invent yet another config format. Use the Python Standard Library's ConfigParser, which will be able to parse the [section] notation exactly as you have shown it.
EDIT: The allow_no_value option allows you to to just have a single entry, rather than a key/value pair. And the default dict type is OrderedDict, so it will maintain order.
| 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]
regex1
regex2
But I just realized that [section] is a valid regex. So I'm wondering if there's a way I can format a section header so that it can ONLY be understood as a section header and not a regex.
| [
"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 something similar to f.readline() for files, but on the form submission. It's entirely possible that this is incredibly easy. I'm a complete noob so any help you be greatly appreciated.
A:
Sounds like you want (have?) a text area control in your form, like the one I'm typing into now. Something like this?
<textarea name="items"></textarea>
When handling the POST request for the form, you will be able to get the value of the text area like so.
itemList = self.request.get("items")
It will post back the entire text with newline characters (with the escape code \n). The text can be split into a list of lines.
items = itemList.split("\n")
Aaaand you have a list of lines.
| 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 the form submission. It's entirely possible that this is incredibly easy. I'm a complete noob so any help you be greatly appreciated.
| [
"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 have the same interface.
How do I define one set of tests, and provide a list of the parser classes, and have the set of tests run using each parser class? The parser class would define a filename prefix so that it reads the proper input file and the desired result file.
I want all the tests to be run (it shouldn't stop when one breaks), and when one breaks it should report the parser class name.
A:
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.
A:
If you are using unittest, which has the advantage of being supported by django and installed on most systems, you can do something like:
class TestBase(unittest.TestCase)
testing_class = None
def setUp(self):
self.testObject = testing_class(foo, bar)
and then to run the tests:
for cls in [class1, class2, class3]:
testclass = type('Test'+cls.__name, (TestBase, ), {'testing_class': cls})
suite = unittest.TestLoader().loadTestsFromTestCase(testclass)
unittest.TextTestRunner(verbosity=2).run(suite)
I haven't tested this code but I've done stuff like this before.
| 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 tests, and provide a list of the parser classes, and have the set of tests run using each parser class? The parser class would define a filename prefix so that it reads the proper input file and the desired result file.
I want all the tests to be run (it shouldn't stop when one breaks), and when one breaks it should report the parser class name.
| [
"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 python script using the execfile().
In this case you will discover that Python will not be able to locate your function when it does exits, and this makes sense.
My question is how to keep this functionality in a way that does not presents this issue.
A:
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:
import os
target = os.path.join(os.path.dirname(__file__), "mytarget.py")
A:
This works for me. I created a file to be executed by another file, a.py:
$ cat a.py
import atexit
@atexit.register
def myexit():
print 'myexit in a.py'
And then b.py to call execfile:
$ cat b.py
import atexit
@atexit.register
def b_myexit():
print 'b_myexit in b.py'
execfile('a.py')
When I run b.py, both registered functions get called:
$ python b.py
myexit in a.py
b_myexit in b.py
Note that both of these scripts are in the same directory when I ran them. If your a.py is in a separate directory as Ryan Ginstrom mentioned in his answer, you will need to use the full path to it, like:
execfile('/path/to/a.py')
| 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 be able to locate your function when it does exits, and this makes sense.
My question is how to keep this functionality in a way that does not presents this issue.
| [
"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 necessary to the setup.py?
A:
I think its good, not to install the examples,
rather you can keep your examples folder with your distribution, so it may be on the same level where your setup.py,
If you want to include them, then include as separate module of package, like 'example' - and that directory holds the all example scripts, that users can refer even after installing.
package_data = {
'module_1': [files],
'module_2': [files],
'example': [files],
}
A:
Example scripts are a type of documentation, so install them in the same way you would install other documentation: as package_data.
| 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 a method I just wrote, paste it into the shell and then unit test it by hand (I'm using IDLE).
I'm just wondering if there is a way to expose all the symbols in my python code to the shell automatically, so I can debug without copying and pasting my code into the shell every time (especially when I make a modification in the code).
Cheers
A:
you can import the module that your code is in. This will expose all of the symbols prefixed with the module name.
The details for the easiest way to do it depend on your operating system but you can always do:
>>> sys.path.append('/path/to/directory/that/my/module/is/in/')
>>> import mymod #.py
later after you make a change, you can just do
>>>> reload(mymod)
and the symbols will now reference the new values. Note that from mymod import foo will break reload in the sense that foo will not be updated after a call to reload. So just use mymod.foo.
Essentially the trick is to get the directory containing the file on your PYTHONPATH environment variable. You can do this from .bashrc on linux for example. I don't know how to go about doing it on another operating system. I use virualenv with has a nice wrapper and workon command so I just have to type workon foo and it runs shell scripts (that I had to write) that add the necessary directories to my python path.
When I was just starting off though, I made one permanent addition to my PYTHONPATH env variable and kept module I wrote in there.
Another alternative is to execute your module with the -i option.
$ python -i mymod.py
This will execute the module through to completion and then leave you at the interpreter. this isn't IDLE though, it's a little rougher but you are now in your module's namespace (or rather the module's namespace is the global namespace)
A:
Check IPython. It's enhanced interactive Python shell. You can %run your script and it will automatically expose all your global objects to the shell. It's very easy to use and powerful. You can even debug your code using it.
For example, if your script is:
import numpy as np
def f(x):
return x + 1
You can do the following:
%run yourScript.py
x = np.eye(4)
y = f(x)
| 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, paste it into the shell and then unit test it by hand (I'm using IDLE).
I'm just wondering if there is a way to expose all the symbols in my python code to the shell automatically, so I can debug without copying and pasting my code into the shell every time (especially when I make a modification in the code).
Cheers
| [
"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 not overly complex is
for s in str:
r = regex.match(s)
if r:
print r.groups()
I guess I'm complaining about a pretty pedantic issue. I just miss the former syntax.
A:
How about
for r in [regex.match(s) for s in str]:
if r:
print r.groups()
or a bit more functional
for r in filter(None, map(regex.match, str)):
print r.groups()
A:
Perhaps it's a bit hacky, but using a function object's attributes to store the last result allows you to do something along these lines:
def fn(regex, s):
fn.match = regex.match(s) # save result
return fn.match
for s in strings:
if fn(regex, s):
print fn.match.groups()
Or more generically:
def cache(value):
cache.value = value
return value
for s in strings:
if cache(regex.match(s)):
print cache.value.groups()
Note that although the "value" saved can be a collection of a number of things, this approach is limited to holding only one such at a time, so more than one function may be required to handle situations where multiple values need to be saved simultaneously, such as in nested function calls, loops or other threads. So, in accordance with the DRY principle, rather than writing each one, a factory function can help:
def Cache():
def cache(value):
cache.value = value
return value
return cache
cache1 = Cache()
for s in strings:
if cache1(regex.match(s)):
# use another at same time
cache2 = Cache()
if cache2(somethingelse) != cache1.value:
process(cache2.value)
print cache1.value.groups()
...
A:
There's a recipe to make an assignment expression but it's very hacky. Your first option doesn't compile so your second option is the way to go.
## {{{ http://code.activestate.com/recipes/202234/ (r2)
import sys
def set(**kw):
assert len(kw)==1
a = sys._getframe(1)
a.f_locals.update(kw)
return kw.values()[0]
#
# sample
#
A=range(10)
while set(x=A.pop()):
print x
## end of http://code.activestate.com/recipes/202234/ }}}
As you can see, production code shouldn't touch this hack with a ten foot, double bagged stick.
A:
This might be an overly simplistic answer, but would you consider this:
for s in str:
if regex.match(s):
print regex.match(s).groups()
A:
There is no pythonic way to do something that is not pythonic. It's that way for a reason, because 1, allowing statements in the conditional part of an if statement would make the grammar pretty ugly, for instance, if you allowed assignment statements in if conditions, why not also allow if statements? how would you actually write that? C like languages don't have this problem, because they don't have assignment statements. They make do with just assignment expressions and expression statements.
the second reason is because of the way
if foo = bar:
pass
looks very similar to
if foo == bar:
pass
even if you are clever enough to type the correct one, and even if most of the members on your team are sharp enough to notice it, are you sure that the one you are looking at now is exactly what is supposed to be there? it's not unreasonable for a new dev to see this and just fix it (one way or the other) and now its definitely wrong.
A:
Whenever I find that my loop logic is getting complex I do what I would with any other bit of logic: I extract it to a function. In Python it is a lot easier than some other languages to do this cleanly.
So extract the code that just generates the items of interest:
def matching(strings, regex):
for s in strings:
r = regex.match(s)
if r: yield r
and then when you want to use it, the loop itself is as simple as they get:
for r in matching(strings, regex):
print r.groups()
A:
Yet another answer is to use the "Assign and test" recipe for allowing assigning and testing in a single statement published in O'Reilly Media's July 2002 1st edition of the Python Cookbook and also online at Activestate. It's object-oriented, the crux of which is this:
# from http://code.activestate.com/recipes/66061
class DataHolder:
def __init__(self, value=None):
self.value = value
def set(self, value):
self.value = value
return value
def get(self):
return self.value
This can optionally be modified slightly by adding the custom __call__() method shown below to provide an alternative way to retrieve instances' values -- which, while less explicit, seems like a completely logical thing for a 'DataHolder' object to do when called, I think.
def __call__(self):
return self.value
Allowing your example to be re-written:
r = DataHolder()
for s in strings:
if r.set(regex.match(s))
print r.get().groups()
# or
print r().groups()
As also noted in the original recipe, if you use it a lot, adding the class and/or an instance of it to the __builtin__ module to make it globally available is very tempting despite the potential downsides:
import __builtin__
__builtin__.DataHolder = DataHolder
__builtin__.data = DataHolder()
As I mentioned in my other answer to this question, it must be noted that this approach is limited to holding only one result/value at a time, so more than one instance is required to handle situations where multiple values need to be saved simultaneously, such as in nested function calls, loops or other threads. That doesn't mean you should use it or the other answer, just that more effort will be required.
| 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)
if r:
print r.groups()
I guess I'm complaining about a pretty pedantic issue. I just miss the former syntax.
| [
"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 hosted on
GAE, but I thought a simple
solutions might be to write / find a
s script that is able to send
pop/imap mail, and use a gmail
account. This would require me to
save the login and password in the
script, in plaintext. This seems
wrong and very insecure - I wonder
what is the better way to do this?
The webapp needs a sqlite db,
which out of the box do not provide
any security. How can i ensure that
people just cant download the whole
database file?
I imagine both of the questions above come down to file structure and permissioning - i havent been able to find a rigorous tutorial, and really curious to how people typically go about structuring webapps?
Many thanks
A:
Obviously there must not be any direct access to the file system via an HTTP request.
And 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 request to your web server gets sent to web.py, then you shouldn't have any issues, as everything is white-listed by this URL list.
http://webpy.org/tutorial3.en#urlhandling
Because of that fact I wouldn't worry about storing passwords in config files or source-code too much.
| 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
s script that is able to send
pop/imap mail, and use a gmail
account. This would require me to
save the login and password in the
script, in plaintext. This seems
wrong and very insecure - I wonder
what is the better way to do this?
The webapp needs a sqlite db,
which out of the box do not provide
any security. How can i ensure that
people just cant download the whole
database file?
I imagine both of the questions above come down to file structure and permissioning - i havent been able to find a rigorous tutorial, and really curious to how people typically go about structuring webapps?
Many thanks
| [
"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 while doing fastcgi stuff, the .pth files are not parsed, but this is only a guess. Need more official statement.
A:
After some more thorough analysis, I think I understand what's going on here.
When Python starts up, it sets up the sys.path (all as part of initializing the interpreter).
At 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 your modules installed to sys.prefix. Additionally, since easy-install.pth is probably installed to your custom prefix directory, it won't find that .pth file to be parsed.
Adding environment variables to os.environ or sys.path after the interpreter has initialized won't cause .pth files to be parsed again. This is why you're finding yourself forced to manually do what you expect Python to do naturally.
I think the correct solution is to make sure the custom path is available to the Python interpreter at the time the interpreter starts up (which is before mysite.fcgi is executed).
I looked for options to add a PYTHONPATH environment variable to mod_fastcgi, but I see no such option. Perhaps it's a general Apache option, so not documented in mod_fastcgi, or perhaps it's not possible to set a static variable in the mod_fastcgi config.
Given that, I believe you could produce a workaround with the following:
Create a wrapper script (a shell script or another Python script) that will be your new FastCGI handler.
In this wrapper script, set the PYTHONPATH environment variable to your prefix path (just as you have set in your user environment which works).
Have the wrapper script launch the Python process for your original fastcgi handler (mysite.fcgi) with the altered environment.
Although I don't have a good environment in which to test, I think a wrapper shell script would look something like:
#!/bin/sh
export PYTHONPATH=/your/local/python/path
/path/to/python /path/to/your/fastcgi/handler # this line should be similar to what was supplied to mod_fastcgi originally
There may be alternative workarounds to consider.
From mysite.fgci, cause the Python to re-process the sys.path based on a new, altered environment. I don't know how this would be done, but this might be cleaner than having a wrapper script.
Find an Apache/mod_fastcgi option that allows an environment variable (PYTHONPATH) to be specified to the fastcgi process.
A:
Programs run by or code run in a web server has a restricted environment compared with what you use interactively. Most likely, the difference stems from the difference between your interactive environment and the FastCGI environment. What I can't tell you is which difference is critical in this context.
A:
I've encountered a similar issue when running my Python applications under IIS (Windows). I've found that when running under ISAPI, eggs aren't readable because setuptools munges the permissions on zipped eggs, and because the ISAPI application runs under a limited privilege account.
You may be experiencing the same situation in FastCGI. If the FastCGI process doesn't have permission to read the eggs or expand the eggs as necessary, you may have problems. Also, I've found that setting the PYTHON_EGG_CACHE environment variable to a directory that's writable by the process is also necessary for some eggs (in particular, eggs with binary/extension modules or resources that must be accessed as files).
A:
I concur that even with the PYTHONPATH environment variable defined the .pth files do not get interpreted when python starts up in the FastCGI environment. I do not now why this is so, but I do have a suggestion for a workaround.
Use site.addsitedir. It will interpret the .pth files allowing you to then import eggs simply by name without having to add the full path to each one.
#!/user/bin/python2.6
import site
# adds a directory to sys.path and processes its .pth files
site.addsitedir('/home/mhanney/.local/lib/python2.6/site-packages/')
# avoids permissions error writing to system egg-cache
os.environ['PYTHON_EGG_CACHE'] = '/home/mhanney/.local/egg-cache'
It is not necessary to use virtual env. At my shared hosting provider I just install eggs in ~/.local using
python setup.py install --prefix=~/.local
Here is a variation on the flup 'Hello World' example to dump the environment vars, path and modules, useful for debugging FastCGI.
#!/usr/bin/python2.6
import sys, os, site, StringIO
from pprint import pprint as p
# adds a directory to sys.path and processes its .pth files
site.addsitedir('/home/mhanney/.local/lib/python2.6/site-packages/')
# avoids permissions error writing to system egg-cache
os.environ['PYTHON_EGG_CACHE'] = '/home/mhanney/.local/egg-cache'
def test_app(environ, start_response):
output = StringIO.StringIO()
output.write("Environment:\n")
for param in os.environ.keys():
output.write("%s %s\n" % (param,os.environ[param]))
output.write("\n\nsys.path:\n")
p(sys.path, output)
output.write("\n\nsys.modules:\n")
p(sys.modules, output)
start_response('200 OK', [('Content-Type', 'text/plain')])
yield output.getvalue()
if __name__ == '__main__':
from flup.server.fcgi import WSGIServer
WSGIServer(test_app).run()
| 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, but this is only a guess. Need more official statement.
| [
"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 trying to wrap my brain around WSGI and Flask, etc. Any help is appreciated.
A:
In Flask request is a thread-safe global, so you actually do import it:
from flask import request
I'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 which is valid for a single request in a similar object called flask.g:
To share data that is valid for one
request only from one function to
another, a global variable is not good
enough because it would break in
threaded environments. Flask provides
you with a special object that ensures
it is only valid for the active
request and that will return different
values for each request. In a
nutshell: it does the right thing,
like it does for request and session.
| 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 appreciated.
| [
"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 to be the most-likely to work in this situation.
Here's the server information:
Can't install mod_python
no root access
Server is SunOs 5.6
Python 2.5
Apache/2.0.46
I've installed Django (and flup) using the --prefix option (reading again I probably should've used --home, but at the moment it doesn't seem to matter)
I've added the .htaccess file and mysite.fcgi file to my root web directory as mentioned here.
When I run the mysite.fcgi script from the server I get my expected output (the correct site HTML output). But, it won't when trying to access it from a browser.
It seems that it may be a problem with the PYTHONPATH setting since I'm using the prefix option.
I've noticed that if I run mysite.fcgi from the command-line without setting the PYTHONPATH enviornment variable it throws the following error:
prompt$ python2.5 mysite.fcgi
ERROR:
No module named flup Unable to load
the flup package. In order to run
django as a FastCGI application, you
will need to get flup from
http://www.saddi.com/software/flup/
If you've already installed flup,
then make sure you have it in your
PYTHONPATH.
I've added sys.path.append(prefixpath) and os.environ['PYTHONPATH'] = prefixpath to mysite.fcgi, but if I set the enviornment variable to be empty on the command-line then run mysite.fcgi, I still get the above error.
Here are some command-line results:
>>> os.environ['PYTHONPATH'] = 'Null'
>>>
>>> os.system('echo $PYTHONPATH')
Null
>>> os.environ['PYTHONPATH'] = '/prefix/path'
>>>
>>> os.system('echo $PYTHONPATH')
/prefix/path
>>> exit()
prompt$ echo $PYTHONPATH
Null
It looks like Python is setting the variable OK, but the variable is only applicable inside of the script. Flup appears to be distributed as an .egg file, and my guess is that the egg implementation doesn't take into account variables added by os.environ['key'] = value (?) at least when installing via the --prefix option.
I'm not that familiar with .pth files, but it seems that the easy-install.pth file is the one that points to flup:
import sys; sys.__plen = len(sys.path)
./setuptools-0.6c6-py2.5.egg
./flup-1.0.1-py2.5.egg
import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sy
s.path[p:p]=new; sys.__egginsert = p+len(new)
It looks like it's doing something funky, anyway to edit this or add something to my code so it will find flup?
A:
In your settings you have to point go actual egg file, not directory where egg file is located. It should look something like:
sys.path.append('/path/to/flup/egg/flup-1.0.1-py2.5.egg')
A:
Try using a utility called virtualenv. According to the official package page, "virtualenv is a tool to create isolated Python environments."
It'll take care of the PYTHONPATH stuff for you and make it easy to correctly install Django and flup.
A:
Use site.addsitedir() not os.environ['PYTHONPATH'] or sys.path.append().
site.addsitedir interprets the .pth files. Modifying os.environ or sys.path does not. Not in a FastCGI environment anyway.
#!/user/bin/python2.6
import site
# adds a directory to sys.path and processes its .pth files
site.addsitedir('/path/to/local/prefix/site-packages/')
# avoids permissions error writing to system egg-cache
os.environ['PYTHON_EGG_CACHE'] = '/path/to/local/prefix/egg-cache'
A:
To modify the PYTHONPATH from a python script you should use:
sys.path.append("prefixpath")
Try this instead of modifying with os.environ().
And I would recommend to run Django with mod_python instead of using FastCGI...
| 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't install mod_python
no root access
Server is SunOs 5.6
Python 2.5
Apache/2.0.46
I've installed Django (and flup) using the --prefix option (reading again I probably should've used --home, but at the moment it doesn't seem to matter)
I've added the .htaccess file and mysite.fcgi file to my root web directory as mentioned here.
When I run the mysite.fcgi script from the server I get my expected output (the correct site HTML output). But, it won't when trying to access it from a browser.
It seems that it may be a problem with the PYTHONPATH setting since I'm using the prefix option.
I've noticed that if I run mysite.fcgi from the command-line without setting the PYTHONPATH enviornment variable it throws the following error:
prompt$ python2.5 mysite.fcgi
ERROR:
No module named flup Unable to load
the flup package. In order to run
django as a FastCGI application, you
will need to get flup from
http://www.saddi.com/software/flup/
If you've already installed flup,
then make sure you have it in your
PYTHONPATH.
I've added sys.path.append(prefixpath) and os.environ['PYTHONPATH'] = prefixpath to mysite.fcgi, but if I set the enviornment variable to be empty on the command-line then run mysite.fcgi, I still get the above error.
Here are some command-line results:
>>> os.environ['PYTHONPATH'] = 'Null'
>>>
>>> os.system('echo $PYTHONPATH')
Null
>>> os.environ['PYTHONPATH'] = '/prefix/path'
>>>
>>> os.system('echo $PYTHONPATH')
/prefix/path
>>> exit()
prompt$ echo $PYTHONPATH
Null
It looks like Python is setting the variable OK, but the variable is only applicable inside of the script. Flup appears to be distributed as an .egg file, and my guess is that the egg implementation doesn't take into account variables added by os.environ['key'] = value (?) at least when installing via the --prefix option.
I'm not that familiar with .pth files, but it seems that the easy-install.pth file is the one that points to flup:
import sys; sys.__plen = len(sys.path)
./setuptools-0.6c6-py2.5.egg
./flup-1.0.1-py2.5.egg
import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sy
s.path[p:p]=new; sys.__egginsert = p+len(new)
It looks like it's doing something funky, anyway to edit this or add something to my code so it will find flup?
| [
"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 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,
temperatures = db.ListProperty(float)
should work just fine (float is a Python built-in identifier, of course). What problems are you seeing when you do that?
| 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 function by the caller in the form of a callable object. If the callable is an instance of some class, I can provide the __str__ method to make it print out the name of the distance measure. But the callable can also be a function, and I have not found a way to change __str__ in that case. Some code:
def distance(v1, v2, d):
print d
dist = d(v1, v2)
print dist
return dist
If d is a function, print d will print out something like <function someFunc at 0x1b68830>. How can I change this? Just printing out the name of the function would be fine, since I usually give them readable names.
A:
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).
Functions have a func_name attribute, that returns the function's name.
If you choose to use the func_name attribute, then your callable objects would need a func_name attribute too.
Since you've already defined the class's __str__ method, you could make func_name a property to return str(self) like this:
def dfunc(v1,v2):
return 1
class FooDist(object):
def __call__(self,v1,v2):
return 1
@property
def func_name(self):
return str(self)
def __str__(self):
return 'My FooDist'
def distance(v1, v2, d):
print d.func_name
dist = d(v1, v2)
print dist
return dist
distance(1,2,dfunc)
# dfunc
distance(1,2,FooDist())
# My FooDist
A:
You can do
import types
if isinstance(d, types.FunctionType):
print "<function %s>" % d.__name__
A:
To get a function's name, see this question.
To get a class's name, see this question.
Putting them together:
def distance(v1, v2, d):
if hasattr(d, '__name__'):
print d.__name__
elif hasattr(d, '__class__'):
print d.__class__.__name__
else:
print d # unsure about this case
dist = d(v1, v2)
print dist
return dist
A:
You can uniformly give both classes and functions your own attributes:
class MyDistanceMeasure:
name = "mine"
#...
def another_distance_measure(x,y):
#...
another_distance_measure.name = "another"
then:
def distance(v1, v2, d):
print d.name
# or..
print getattr(d, 'name', "unknown")
dist = d(v1, v2)
print dist
return dist
| 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 instance of some class, I can provide the __str__ method to make it print out the name of the distance measure. But the callable can also be a function, and I have not found a way to change __str__ in that case. Some code:
def distance(v1, v2, d):
print d
dist = d(v1, v2)
print dist
return dist
If d is a function, print d will print out something like <function someFunc at 0x1b68830>. How can I change this? Just printing out the name of the function would be fine, since I usually give them readable names.
| [
"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 to be able to set expectations for myself, so based on the following requirements how long do you think it will take to get this app up and running?
Online Collection DB
Users can create accounts that are authenticated through token sent via e-mail
Once logged in, users can add items to pre-created collections (like "DVD" or "Software")
Each collection has it's own template with attributes (ie: DVD has Name, Year, Studio, Rating, Comments, etc)
Users can list all items in collections (all DVDs, all Software), sort by various attributes
Also: Yes I know there are lots of online tools like this, but I want to build it on my own with Python
A:
Assuming you're already familiar with another programming language:
Time to learn python basics: 1 week.
Total time to figure out email module: 2 days.
Total time to figure out httplib module: 1 days.
Total time to figure out creating database: 3 days.
Total time to learn about SQL: 2 weeks.
Total time to figure out that you probably don't need SQL: 1 week.
Total time writing the rest of the logic in python: 1 week.
Probably...
A:
Assuming that you don't write everything from the ground up and reuse basic components, this shouldn't be too hard. Probably the most difficult aspect will be authentication, because that requires domain specific knowledge and is hard to get right in any language. I would suggest starting with the basic functionality, even maybe learn how to get it up and running on App Engine, and then once you have the basic functionality, then you can deal with the business of authentication and users.
| 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 requirements how long do you think it will take to get this app up and running?
Online Collection DB
Users can create accounts that are authenticated through token sent via e-mail
Once logged in, users can add items to pre-created collections (like "DVD" or "Software")
Each collection has it's own template with attributes (ie: DVD has Name, Year, Studio, Rating, Comments, etc)
Users can list all items in collections (all DVDs, all Software), sort by various attributes
Also: Yes I know there are lots of online tools like this, but I want to build it on my own with Python
| [
"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 idea how to make this work:
>>> class Super(object):
name = None
def __init__(self, *args, name=None, **kwargs):
self.name = name
super().__init__(self, *args, **kwargs)
>>> class Sub(Super, int):
pass
>>> Sub(5)
5
>>> Sub(5, name="Foo")
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
Sub(5, name="Foo")
TypeError: 'name' is an invalid keyword argument for this function
(I've also tried it without the super() call, but the result was the same.)
Perhaps someone with better knowledge of multiple inheritance can point me in the right direction?
Update:
Here is the solution I ended up with, based on Alex's answer.
It's still a little hacky (by changining __new__'s signature partway through construction), but it will work as long as the superclass appears in the subclasses' MROs before the built-in type and defining __new__ this way allows me to make subclasses which work with different built-in types without adding a separate __new__ to each one.
>>> class Super(object):
name = None
def __new__(cls, *args, name=None, **kwargs):
inner = super().__new__(cls, *args, **kwargs)
inner.name = name
return inner
>>> class Sub(Super, int):
pass
>>> Sub(5)
5
>>> Sub(5, name="Foo")
5
>>> _.name
'Foo'
A:
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 middle of the Zen of Python,
Errors should never pass silently.
Unless explicitly silenced.
and in most cases, calling (e.g.) int(name='booga') would of course be an error.
If you want you weirdly-named class Super to be able to "pass on" arbitrary parameters, you must also ensure that all classes ever used as bases after it can handle that -- so, for example, int can be called with one parameter (or exactly two: a string and a base), so, if it's absolutely crucial to you that class Sub can multiply inherit from the buck-passing Super and int, you have to field that, e.g.:
class Int(int):
def __new__(cls, *a, **k):
return int.__new__(Int, a[0] if a else 0)
Note that you must override __new__, not __init__ (it does no harm if you also override the latter, but it's irrelevant anyway): int is immutable so the value has to be set at __new__ time.
Now, things like
>>> class X(Super, Int): pass
...
>>> X(23, za='zo')
23
>>>
work. But note that X must subclass from Int (our __new__-sanitizing version of int), not from int itself, which, quite properly, has an unforgiving __new__!-)
| 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=None, **kwargs):
self.name = name
super().__init__(self, *args, **kwargs)
>>> class Sub(Super, int):
pass
>>> Sub(5)
5
>>> Sub(5, name="Foo")
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
Sub(5, name="Foo")
TypeError: 'name' is an invalid keyword argument for this function
(I've also tried it without the super() call, but the result was the same.)
Perhaps someone with better knowledge of multiple inheritance can point me in the right direction?
Update:
Here is the solution I ended up with, based on Alex's answer.
It's still a little hacky (by changining __new__'s signature partway through construction), but it will work as long as the superclass appears in the subclasses' MROs before the built-in type and defining __new__ this way allows me to make subclasses which work with different built-in types without adding a separate __new__ to each one.
>>> class Super(object):
name = None
def __new__(cls, *args, name=None, **kwargs):
inner = super().__new__(cls, *args, **kwargs)
inner.name = name
return inner
>>> class Sub(Super, int):
pass
>>> Sub(5)
5
>>> Sub(5, name="Foo")
5
>>> _.name
'Foo'
| [
"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:
Try:
[\u00D8-\u00F6]
A:
Python 2.X
u'[\u00d8-\u00f6]'
Python 3.X
'[\u00d8-\u00f6]'
| 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.cssselect('tr.headlineRow'):
headline = row.cssselect('td span.headline')
print headline[0]
This will pass:
for row in doc.cssselect('tr.headlineRow'):
headline = row.cssselect('td span.headline')
for first_thing in headline:
print headline[0].text_content()
A:
I usually use the xpath method for things like this.
It returns a list of matching elements.
>>> spans = doc.xpath('//tr[@class="headlineRow"]/td/span[@class="headline"]')
>>> spans[0].text
'This is some awesome text'
A:
I tried out your example using CSSSelector and headline[0] worked fine. See below:
>>> html ="""<tr class="headlineRow">
<td>
<span class="headline">This is some awesome text</span>
</td>
</tr>"""
>>> from lxml import etree
>>> from lxml.cssselect import CSSSelector
>>> doc = etree.fromstring(html)
>>> sel1 = CSSSelector('tr.headlineRow')
>>> sel2 = CSSSelector('td span.headline')
>>> for row in sel1(doc):
headline = sel2(row)
print headline[0]
<Element span at 8f31e3c>
A:
Elements are accessed the same way you access nested lists:
>>> doc[0][0]
<Element span at ...>
Or via CSS selectors:
doc.cssselect('td span.headline')[0]
A:
Your "failing" example works perfectly for me? Either you made a mistake when trying it out, or you are using an older version of lxml that has a - now fixed - bug (I tried 2.2.6, and with 2.1.1 - the oldest I had around, and both worked)
| 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('td span.headline')
print headline[0]
This will pass:
for row in doc.cssselect('tr.headlineRow'):
headline = row.cssselect('td span.headline')
for first_thing in headline:
print headline[0].text_content()
| [
"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_template.html', 'mode':mode} ),
)
Then my view is something like this:
@render_to()
def custom_view(request, template, mg=False, login=True):
if mode:
template = template + 'x' #I add an x to the template name to advice to django I that it should use the mode_2 template.
return {'TEMPLATE':template}
My problem is when the user selects mode 2 (in my custom Configuration page), mode does not change until server is restarted (either apache or runserver.py is the same).
I think this has to do something with cache, but I can't find how to erase that cache. (each time Config.mode is changed.)
A:
Getting the mode in urls.py is not going to work. The get will only be executed once, when the file is first imported.
Do the database work in the view function, instead.
| 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':mode} ),
)
Then my view is something like this:
@render_to()
def custom_view(request, template, mg=False, login=True):
if mode:
template = template + 'x' #I add an x to the template name to advice to django I that it should use the mode_2 template.
return {'TEMPLATE':template}
My problem is when the user selects mode 2 (in my custom Configuration page), mode does not change until server is restarted (either apache or runserver.py is the same).
I think this has to do something with cache, but I can't find how to erase that cache. (each time Config.mode is changed.)
| [
"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 import a module (usually from my views file). However, it's not an issue with that module as it usually works, for example, I will get the error "Cannot import classname from module" once, then reload the page and it works fine, I would say it's about 1 in 10 page loads where this occurs and it's just random as it will happen for any page on my site.
I have tried restarting apache2, restarting the server but the issue persists. I have tried it on different client machines, clearing out the user cache, etc but the issue persists. I don't know what might be doing this, would perhaps some sort of caching help prevent this as it seems that the server is just having an issue with sometimes not being able to fully process the request. I am using a cloud set up with not much memory on the server so maybe this is the problem? Any advice is appreciated
A:
It is working most of the time because you likely have a multi process configuration and only one of the processes is affected.
You can try alternate WSGI script file as documented in:
http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html
The jury is still out as to whether the issue is the differences between development server and proper deployment systems using WSGI, or whether it is users not handling imports properly and causing order dependencies or even import cycles. Problems possibly only come up when URL visited in certain order and thus why random as to when it can happen.
| 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, I will get the error "Cannot import classname from module" once, then reload the page and it works fine, I would say it's about 1 in 10 page loads where this occurs and it's just random as it will happen for any page on my site.
I have tried restarting apache2, restarting the server but the issue persists. I have tried it on different client machines, clearing out the user cache, etc but the issue persists. I don't know what might be doing this, would perhaps some sort of caching help prevent this as it seems that the server is just having an issue with sometimes not being able to fully process the request. I am using a cloud set up with not much memory on the server so maybe this is the problem? Any advice is appreciated
| [
"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 signal
# ...
signal.signal(signal.SIGINT, thread_interrupt_handler)
_init_signals()
This works fine if everything is in the main thread. However, when the first import of git (and thus async) happens on another thread, things go boom:
ValueError: signal only works in main thread
Since all this runs inside the Django framework, I have no control over threading.
One workaround I've found is to put import async into settings.py, which is (apparently) imported on the main thread. However, this needs to be done on a per-install basis, so it's not very nice towards users of my Django app.
I tried catching the exception, but an import that raised an exception does not fully complete, so the next import async will fail as well.
Can you think of any halfway decent method to work/hack around this problem?
Update: I noticed that Apache's mod_wsgi is smart enough to ignore the signal call:
[Tue Sep 07 19:53:11 2010] [warn] mod_wsgi (pid=28595): Callback registration for signal 2 ignored.
The problem remains with the Django development server, though.
A:
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
| 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_interrupt_handler)
_init_signals()
This works fine if everything is in the main thread. However, when the first import of git (and thus async) happens on another thread, things go boom:
ValueError: signal only works in main thread
Since all this runs inside the Django framework, I have no control over threading.
One workaround I've found is to put import async into settings.py, which is (apparently) imported on the main thread. However, this needs to be done on a per-install basis, so it's not very nice towards users of my Django app.
I tried catching the exception, but an import that raised an exception does not fully complete, so the next import async will fail as well.
Can you think of any halfway decent method to work/hack around this problem?
Update: I noticed that Apache's mod_wsgi is smart enough to ignore the signal call:
[Tue Sep 07 19:53:11 2010] [warn] mod_wsgi (pid=28595): Callback registration for signal 2 ignored.
The problem remains with the Django development server, though.
| [
"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 forloop.first %}
<td>{{ documento.fecha_creacion.date }}</td>
<td>{{ cuenta.cuenta.nombre }}</td>
<td>
{% if cuenta.monto >= 0 %}
{{ cuenta.monto}}
{% endif %}
</td>
<td>
{% if cuenta.monto <= 0 %}
{{ cuenta.monto }}
{% endif %}
</td>
{% else %}
<td colspan="4"></td>
<td>{{ cuenta.cuenta.codigo }}</td>
<td>{{ cuenta.cuenta.nombre }}</td>
<td>
{% if cuenta.monto <= 0 %}
{{ cuenta.monto }}
{% endif %}
</td>
<td>
{% if cuenta.monto >= 0 %}
{{ cuenta.monto }}
{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
<tr>
<td colspan="1"></td>
<td>Document Total</td>
<td></td>
<td></td>
</tr>
{% endfor %}
This is all done using the following models, which are simplified for the purpose of this question
class Documento(models.Model):
numero_impreso = models.CharField(max_length=50)
fecha_creacion = models.DateTimeField(auto_now_add = True)
cuentas = models.ManyToManyField('CuentaContable', through = 'CuentasXDocumento', null = True)
def __unicode__(self):
return self.tipo.nombre + ": " + self.numero_impreso
class CuentasXDocumento(models.Model):
cuenta = models.ForeignKey('CuentaContable')
documento = models.ForeignKey('Documento')
monto = models.DecimalField(max_digits= 14, decimal_places = 6)
linea = models.IntegerField()
class CuentaContable(models.Model):
codigo = models.CharField(max_length=50)
nombre = models.CharField(max_length=100)
def __unicode__(self):
return self.nombre
Finally I'm sorry for the bad english :)
A:
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.
My recommendation would be to calculate the two sums you need in the view instead of the template.
That beings said, it is possible to do some work in the template using custom filters and tags. Using filters it might look like this:
<td>{% documento.cuentasxdocumento_set.all | sum_monto:"pos" %}</td>
<td>{% documento.cuentasxdocumento_set.all | sum_monto:"neg" %}</td>
Filters take two arguments, the value that you pass to the filter and an argument that you can use to control its behavior. You could use the last argument to tell sum_monto to sum the positive values or the negative values.
This is a quick untested filter implementation off the top of my head:
from django import template
register = template.Library()
@register.filter
def sum_monto(cuentas, op):
if op == "pos":
return sum(c.monto for c in cuentas if c.monto > 0)
else
return sum(c.monto for c in cuentas if c.monto < 0)
| 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>{{ documento.fecha_creacion.date }}</td>
<td>{{ cuenta.cuenta.nombre }}</td>
<td>
{% if cuenta.monto >= 0 %}
{{ cuenta.monto}}
{% endif %}
</td>
<td>
{% if cuenta.monto <= 0 %}
{{ cuenta.monto }}
{% endif %}
</td>
{% else %}
<td colspan="4"></td>
<td>{{ cuenta.cuenta.codigo }}</td>
<td>{{ cuenta.cuenta.nombre }}</td>
<td>
{% if cuenta.monto <= 0 %}
{{ cuenta.monto }}
{% endif %}
</td>
<td>
{% if cuenta.monto >= 0 %}
{{ cuenta.monto }}
{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
<tr>
<td colspan="1"></td>
<td>Document Total</td>
<td></td>
<td></td>
</tr>
{% endfor %}
This is all done using the following models, which are simplified for the purpose of this question
class Documento(models.Model):
numero_impreso = models.CharField(max_length=50)
fecha_creacion = models.DateTimeField(auto_now_add = True)
cuentas = models.ManyToManyField('CuentaContable', through = 'CuentasXDocumento', null = True)
def __unicode__(self):
return self.tipo.nombre + ": " + self.numero_impreso
class CuentasXDocumento(models.Model):
cuenta = models.ForeignKey('CuentaContable')
documento = models.ForeignKey('Documento')
monto = models.DecimalField(max_digits= 14, decimal_places = 6)
linea = models.IntegerField()
class CuentaContable(models.Model):
codigo = models.CharField(max_length=50)
nombre = models.CharField(max_length=100)
def __unicode__(self):
return self.nombre
Finally I'm sorry for the bad english :)
| [
"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 space between 2 toolbars)
However, the stretchable space produces a blank space between 2 toolbars and there is no underline for that space, hence, it looks ugly. (Please prefer to this picture to know what I mean http://i55.tinypic.com/2dlrvaa.jpg).
The underlines are supposed to be connected to each other so that they look like just one toolbar in total. They are discrete because of the stretchable space.
Is there any solution I can try to overcome this? I guess I can either remove the underlines for the toolbar, or add underline to the blank space. However I don't know how to achieve either way of these.
Here is part of my code:
# Create the top toolbar container
topToolBar = wx.BoxSizer(wx.HORIZONTAL)
# Add 2 toolbars to this sizer, with stretchable space
# We add the same toolbar for testing purpose
topToolBar.Add(toolbar1,0,wx.ALIGN_LEFT,4) # add the toolbar to the sizer
topToolBar.AddStretchSpacer()
topToolBar.Add(toolbar1,0,wx.ALIGN_RIGHT ,4)
self.SetSizer(topToolBar)
A:
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
topToolBar.Add(toolbar1,1,wx.ALIGN_LEFT,4) # note the 2nd param 'proportion' is 1
#topToolBar.AddStretchSpacer()
topToolBar.Add(toolbar1,0,wx.ALIGN_RIGHT,4)
The idea being that the first toolbar expands to fill the available space.
| 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 toolbars and there is no underline for that space, hence, it looks ugly. (Please prefer to this picture to know what I mean http://i55.tinypic.com/2dlrvaa.jpg).
The underlines are supposed to be connected to each other so that they look like just one toolbar in total. They are discrete because of the stretchable space.
Is there any solution I can try to overcome this? I guess I can either remove the underlines for the toolbar, or add underline to the blank space. However I don't know how to achieve either way of these.
Here is part of my code:
# Create the top toolbar container
topToolBar = wx.BoxSizer(wx.HORIZONTAL)
# Add 2 toolbars to this sizer, with stretchable space
# We add the same toolbar for testing purpose
topToolBar.Add(toolbar1,0,wx.ALIGN_LEFT,4) # add the toolbar to the sizer
topToolBar.AddStretchSpacer()
topToolBar.Add(toolbar1,0,wx.ALIGN_RIGHT ,4)
self.SetSizer(topToolBar)
| [
"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/Source/chap5/
| 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 Vector:
def __init__(self, x, y, z):
self.setposition(x, y, z)
def setposition(self, x, y, z):
for i in (x, y, z):
if not isinstance(i, numbers.Real):
raise TypeError("Real coordinates only")
self.__x = x
self.__y = y
self.__z = z
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
@property
def z(self):
return self.__z
...but that seems un-Pythonic.
Suggestions?
A:
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.
>>> 3.0 / 'abc'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for /: 'float' and 'str'
A:
Duck Typing is the usual way in Python. It should work with anything that behaves like a number, but not necessarily is a real number.
In most cases in Python one should not explicitly check for types. You gain flexibility because your code can be used with custom datatypes, as long as they behave correctly.
A:
The other answers already pointed out that it doesn't make much sense to check for the type here. Furthermore, your class won't be very fast if it's written in pure Python.
If you want a more pythonic solution - you could use property setters like:
@x.setter
def x(self, value):
assert isinstance(value, numbers.Real)
self.__x = value
The assert statement will be removed when you disable debugging or enable optimizing mode.
Alternatively, you could force value to floating-point in the setter. That will raise an exception if the type/value is not convertible:
@x.setter
def x(self, value):
self.__x = float(value)
A:
But there's nothing to stop one from doing the following:
I believe trying to stop someone from doing something like that is un-Pythonic. If you must, then you should check for type safety during any operations you might do using Vector, in my opinion.
To quote G.V.R:
we are all adults.
after all. See this question and its answers for more information.
I am sure more experienced Pythonistas here can give you better answers.
A:
You are not supposed to provide type safety this way. Yes, someone can deliberately break your code by supplying values for which your container won't work - but this is just the same with other languages. And even if someone put the right value for a parameter into a method or member function does not necessarily mean it's not broken: If a program expects an IP address, but you pass a hostname, it still won't work, although both may be strings.
What I am saying is: The mindset of Python is inherently different. Duck typing basically says: Hey, I'm not limited to certain types, but to the interface, or behavior of objects. If an object does act like it's the kind of object I'd expect, I don't care - just go for it.
If you try to introduce type checking, you are basically limiting one of most useful features of the language.
That being said, you really need to get into test driven development, or unit testing at least. There really is no excuse not to do it with dynamic languages - it's just moving the way (type) errors are being detected to another step in the build process, away from compile time to running a test suite multiple times a day. While this seems like added effort, it will actually reduce time spent on debugging and fixing code, as it's an inherently more powerful way to detect errors in your code.
But enough of that, I'm already rambling.
| 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__(self, x, y, z):
self.setposition(x, y, z)
def setposition(self, x, y, z):
for i in (x, y, z):
if not isinstance(i, numbers.Real):
raise TypeError("Real coordinates only")
self.__x = x
self.__y = y
self.__z = z
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
@property
def z(self):
return self.__z
...but that seems un-Pythonic.
Suggestions?
| [
"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((1, 2)))
TypeError: can't write str to text stream
But
>>> buffer.write(str((1, 2)) + u"")
6
works. I assume this is because the concatenation with a unicode string makes the result unicode as well. Is there a more elegant solution to this problem?
A:
The io package provides python3.x compatibility. In python 3, strings are unicode by default.
Your code works fine with the standard StringIO package,
>>> from StringIO import StringIO
>>> StringIO().write(str((1,2)))
>>>
If you want to do it the python 3 way, use unicode() in stead of str(). You have to be explicit here.
>>> io.StringIO().write(unicode((1,2)))
6
| 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
>>> buffer.write(str((1, 2)) + u"")
6
works. I assume this is because the concatenation with a unicode string makes the result unicode as well. Is there a more elegant solution to this problem?
| [
"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 working. There is no trace. All ideas are welcome.
The code that should sort is
a = A.proximity_fetch(A.all().filter("modified >",
timeline).filter("published =", True).filter("modified <=",
bookmark ).order("-modified") ,db.GeoPt(lat, lon),max_results=PAGESIZE
+1, max_distance=m)
All parameters appear to work except order("-modified")
Trying the suggested way sorting with lambda I get message
"TypeError: lambda() takes exactly 1 argument (2 given)"
a = A.proximity_fetch(A.all().filter("modified >", timeline).filter("published =", True).filter("modified <=", bookmark ).order("-modified") ,db.GeoPt(lat, lon),max_results=40, max_distance=m)
a = sorted(a, lambda x: x.modified, reverse=True)
A:
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.
A:
GeoModel sorts the result of the nearest to the farthest of the point.
You need to sort your result with python after have executed proximity_fetch:
result = sorted(result, key=lambda x: x.modified, reverse=True)
Edited: forget to use the 'key' argument's for sorted
| 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 are welcome.
The code that should sort is
a = A.proximity_fetch(A.all().filter("modified >",
timeline).filter("published =", True).filter("modified <=",
bookmark ).order("-modified") ,db.GeoPt(lat, lon),max_results=PAGESIZE
+1, max_distance=m)
All parameters appear to work except order("-modified")
Trying the suggested way sorting with lambda I get message
"TypeError: lambda() takes exactly 1 argument (2 given)"
a = A.proximity_fetch(A.all().filter("modified >", timeline).filter("published =", True).filter("modified <=", bookmark ).order("-modified") ,db.GeoPt(lat, lon),max_results=40, max_distance=m)
a = sorted(a, lambda x: x.modified, reverse=True)
| [
"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 schoolname;
After that I tried to download data so that I created bulkloader configuration file .It created successfully but I that default auto generated bulkloade.yaml file I have one problem(i.E)export-transform convert Primary key into string, but I need Long datatype how to achieve this.
The content of bulkloader file is
- kind: School
connector: csv
property_map:
- property: __key__
external_name: key
export_transform: transform.key_id_or_name_as_string
- property: schoolname
external_name: schoolname
How to solve this
Thanks in advance
A:
Try export_transform: datastore.Key.name
| 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 download data so that I created bulkloader configuration file .It created successfully but I that default auto generated bulkloade.yaml file I have one problem(i.E)export-transform convert Primary key into string, but I need Long datatype how to achieve this.
The content of bulkloader file is
- kind: School
connector: csv
property_map:
- property: __key__
external_name: key
export_transform: transform.key_id_or_name_as_string
- property: schoolname
external_name: schoolname
How to solve this
Thanks in advance
| [
"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 the python script while I am running the DB Units?
A:
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.
That said, IMHO this is a wrong approach to take for various reasons.
Inter-language disqualifies the tests from being described as "unit". These are functional tests. and thereby shouldn't care about code coverage (See @Ned's comment below).
If you must (unit) test the Python code then I suggest that you do it using Python. This will also solve your problem of checking for test coverage.
If you do want to function test then it would be good idea to keep Python code coverage checks away from Java. This would reduce the coupling between the Java and Python code. Tests are code after all and it is usually a good idea to reduce coupling between parts.
A:
Coverage.py has an API that you can use to start and stop coverage measurement as you need.
I'm not sure how you are invoking your Python code from your Java code, but once in the Python, you can use coverage.py to measure Python execution, and then get reports on the results.
Drop me a line if you need help.
| 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, -67333094L,
38, 4, 493.493464900383,
493.63348372593703), (15002483, 76, 20, 1394, -67333094L, 91, 3,
499.959042442434, 499.97304310494502)]
I'm trying to convert this nested tuple/list into R dataframe with RPY2 : with nine column with name, and four row of data (number of element in this nested list ))
But i don't understand how, i'm trying with taggedList (into RPY2 container library) but with no success .. It seems tagged list take one list by one list only.
Thx for help !
A:
import rpy2.robjects as ro
r=ro.r
data=[(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, 1394, -67333094L, 91, 3, 499.959042442434, 499.97304310494502)]
columns=zip(*data)
columns=[ro.FloatVector(col) for col in columns]
names=['col{i}'.format(i=i) for i in range(9)]
dataf = r['data.frame'](**dict(zip(names,columns)))
print(dataf)
# col8 col6 col7 col4 col5 col2 col3 col0 col1
# 1 493.6335 4 493.4876 -67333094 38 20 1393 15002325 24
# 2 499.9700 3 499.9585 -67333094 91 20 1393 15002339 76
# 3 493.6335 4 493.4935 -67333094 38 20 1394 15002431 24
# 4 499.9730 3 499.9590 -67333094 91 20 1394 15002483 76
Note that there is an R interface for postgresql, and this may provide a cleaner way than going through Python and rpy2.
If you need Python, another possibility is to figure out the R commands needed to load the data from postgresql, and then call them in Python using ro.r.
| 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), (15002483, 76, 20, 1394, -67333094L, 91, 3,
499.959042442434, 499.97304310494502)]
I'm trying to convert this nested tuple/list into R dataframe with RPY2 : with nine column with name, and four row of data (number of element in this nested list ))
But i don't understand how, i'm trying with taggedList (into RPY2 container library) but with no success .. It seems tagged list take one list by one list only.
Thx for help !
| [
"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 = True, null = True)
class B(models.Model):
title = models.CharField(max_length = 255, blank = True, null = True)
class C(models.Model):
b = models.OneToOneField('B', blank = True, null = True, related_name = 'c')
This is the test case:
a1 = A()
a1.save()
b1= B()
b1.save()
c1 = C()
c1.b = b1
c1.save()
b1 = B.objects.all()[0]
b1.c.delete()
b1.delete()
self.failUnlessEqual(A.objects.count(),1)
I deleted b1.c explicitly before deleting b1. When deleting b1.c, b1.c is NULL. It seems that then all entries of A were deleted where A.related is NULL.
Is this a bug? I really did not expect that all entries of all tables that have a NULL reference to model C are deleted.
I am using Postgres 8.4 and psycopg2 as DB Backend.
Best regards!
A:
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.
Workarounds are discussed elsewhere on stackoverflow.
| 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.CharField(max_length = 255, blank = True, null = True)
class C(models.Model):
b = models.OneToOneField('B', blank = True, null = True, related_name = 'c')
This is the test case:
a1 = A()
a1.save()
b1= B()
b1.save()
c1 = C()
c1.b = b1
c1.save()
b1 = B.objects.all()[0]
b1.c.delete()
b1.delete()
self.failUnlessEqual(A.objects.count(),1)
I deleted b1.c explicitly before deleting b1. When deleting b1.c, b1.c is NULL. It seems that then all entries of A were deleted where A.related is NULL.
Is this a bug? I really did not expect that all entries of all tables that have a NULL reference to model C are deleted.
I am using Postgres 8.4 and psycopg2 as DB Backend.
Best regards!
| [
"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, arg3=1):
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
kwargs = dict((key, values[key]) for key in args) # convert args list into dictionary form
return list(ooxx(**kwargs))
Is it possible to have some sort of methods to generate automatically the function "asdf"? I have lots of dynamic generated ooxx functions and I would like to have corresponding asdf functions with customized named arguments. Not sure if this is the correct requirement or right way to coding :p
A:
Your descriptions doesn't make such sense to me: You wrote a really verbose function that does this:
def asdf(arg1, arg2, arg3=1):
return list(ooxx(**locals()))
but you want to inspect the ooxx and somehow make up appropriate names for asdfs arguments? That is impossible, there is no information about this on ooxx.
If you actually have a signature and want to create a function from it you would have to resort to eval or generate function definitions to a Python file and import it.
There is also the decorator module. You can create a function with it like this:
import decorator
asdf = decorator.FunctionMaker.create(
'asdf(arg1, arg2, arg3)', # signature
'return ooxx(**locals())', # function body
{'ooxx' : ooxx}, # context for the function
('arg3', 1)) # default arguments
| 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.getargvalues(frame)
kwargs = dict((key, values[key]) for key in args) # convert args list into dictionary form
return list(ooxx(**kwargs))
Is it possible to have some sort of methods to generate automatically the function "asdf"? I have lots of dynamic generated ooxx functions and I would like to have corresponding asdf functions with customized named arguments. Not sure if this is the correct requirement or right way to coding :p
| [
"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 out to the socket, everything works great.
However, I need the ability to support chunked transfer encoding. When some of the browsers hit the uri for this, they make the request, immediately close the connection, then make the request again at which point it succeeds. Sometimes I have seen them close the connection multiple times, re-requesting multiple times, until it succeeds. Other times I have seen them close the connection and not retry.
Here is a log of the output that I am sending over the socket. The number in parentheses indicates the number of bytes that it actually attempted to send:
send(21): 'HTTP/1.1 100 Continue'
send(2): '\r\n'
send(2): '\r\n'
send(15): 'HTTP/1.1 200 OK'
send(2): '\r\n'
send(26): 'Transfer-Encoding: chunked'
send(2): '\r\n'
send(38): 'Content-Type: application/octet-stream'
send(2): '\r\n'
send(52): 'Content-Disposition: attachment; filename="test.mp3"'
send(2): '\r\n'
send(17): 'Connection: close'
send(2): '\r\n'
send(35): 'Date: Mon, 20 Sep 2010 11:38:34 GMT'
send(2): '\r\n'
send(2): '\r\n'
send(4): '4000'
send(2): '\r\n'
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 64329)
...
self.request.send("\r\n")
error: [Errno 32] Broken pipe
----------------------------------------
Note that each printed line there represents the bytes its about to send, not bytes that have actually been sent - thus it fails on that final "\r\n". Also note that sometimes it will successfully send a few chunks before the socket is closed. I can see in the browser that a few kilobytes have been received.
EDIT: Here's a request from Firefox 4 beta 6. My server was able to send back 16KB (according to FireBug) before the socket crapped out. Note that my server ignores the Range header, if that makes a difference:
GET /audios/11/download.ogg HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b6) Gecko/20100101 Firefox/4.0b6
Accept: audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Range: bytes=0-
Cookie: player-61646d696e=1; player-64617665=4; JSESSIONID=6glsv8468cbp
A:
Wild guess: the Connection:close-Header doesn't "feel" right. Actually, I think this is a request-header, not a response-header.
Edit: 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.
| 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 encoding. When some of the browsers hit the uri for this, they make the request, immediately close the connection, then make the request again at which point it succeeds. Sometimes I have seen them close the connection multiple times, re-requesting multiple times, until it succeeds. Other times I have seen them close the connection and not retry.
Here is a log of the output that I am sending over the socket. The number in parentheses indicates the number of bytes that it actually attempted to send:
send(21): 'HTTP/1.1 100 Continue'
send(2): '\r\n'
send(2): '\r\n'
send(15): 'HTTP/1.1 200 OK'
send(2): '\r\n'
send(26): 'Transfer-Encoding: chunked'
send(2): '\r\n'
send(38): 'Content-Type: application/octet-stream'
send(2): '\r\n'
send(52): 'Content-Disposition: attachment; filename="test.mp3"'
send(2): '\r\n'
send(17): 'Connection: close'
send(2): '\r\n'
send(35): 'Date: Mon, 20 Sep 2010 11:38:34 GMT'
send(2): '\r\n'
send(2): '\r\n'
send(4): '4000'
send(2): '\r\n'
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 64329)
...
self.request.send("\r\n")
error: [Errno 32] Broken pipe
----------------------------------------
Note that each printed line there represents the bytes its about to send, not bytes that have actually been sent - thus it fails on that final "\r\n". Also note that sometimes it will successfully send a few chunks before the socket is closed. I can see in the browser that a few kilobytes have been received.
EDIT: Here's a request from Firefox 4 beta 6. My server was able to send back 16KB (according to FireBug) before the socket crapped out. Note that my server ignores the Range header, if that makes a difference:
GET /audios/11/download.ogg HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b6) Gecko/20100101 Firefox/4.0b6
Accept: audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Range: bytes=0-
Cookie: player-61646d696e=1; player-64617665=4; JSESSIONID=6glsv8468cbp
| [
"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 not work
http://popcnt.org/2008/05/google-app-engine-tips.html - link to the code is broken
http://groups.google.com/group/google-appengine/browse_thread/thread/c9e8a906a88a8102 - a lot of work needed
A:
You need Appstats, which comes with the App Engine Python SDK.
| 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.html - link to the code is broken
http://groups.google.com/group/google-appengine/browse_thread/thread/c9e8a906a88a8102 - a lot of work needed
| [
"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 the interface:
void SomeUnicodeFunction(const wchar_t* string)
However, when I attempt to use the following code in Python:
SomeModule.SomeUnicodeFunction(ctypes.c_wchar_p(unicode_string))
I get this error:
ArgumentError: Python argument types in
SomeModule.SomeUnicodeFunction(SomeModule, c_wchar_p)
did not match C++ signature:
SomeUnicodeFunction(... {lvalue}, wchar_t const*)
(names have been changed).
I've tried changing wchar_t in the C++ module to Py_UNICODE with no success. How do I solve this problem?
A:
Found a hack to work around the problem:
SomeModule.SomeUnicodeFunction(str(s.encode('utf-8')))
It seems to be working fine for my purposes so far.
Update: Actually, using UTF-8 means I avoid any need for SomeUnicodeFunction and can use the standard SomeFunction without specialising for unicode. Learn something new every day I guess :).
A:
For Linux you don't have to change your API, just do:
SomeModule.SomeFunction(str(s.encode('utf-8')))
On Windows all Unicode APIs are using UTF-16 LE (Little Endian) so you have to encode it this way:
SomeModule.SomeFunctionW(str(s.encode('utf-16-le')))
Good to know: wchar_t can have different sizes on different platforms: 8, 16 or 32 bits.
| 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_t* string)
However, when I attempt to use the following code in Python:
SomeModule.SomeUnicodeFunction(ctypes.c_wchar_p(unicode_string))
I get this error:
ArgumentError: Python argument types in
SomeModule.SomeUnicodeFunction(SomeModule, c_wchar_p)
did not match C++ signature:
SomeUnicodeFunction(... {lvalue}, wchar_t const*)
(names have been changed).
I've tried changing wchar_t in the C++ module to Py_UNICODE with no success. How do I solve this problem?
| [
"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_CI_AS' (I've checked also the specific fields and they keep the same collation). I started selecting the encoding 'latin1' in the call of create_engine and that appears to work for Western European character (like French or Spanish, characters like é) but not for Easter European characters. Specifically, I have a problem with the character ć
I have been trying to select other encodings as stated on Python documentation, specifically the Microsoft ones, like cp1250 and cp1252, but I keep facing the same problem.
Does anyone knows how to solve those differences? Does the collation 'Latin1_General_CI_AS' has an equivalence on Python encodings?
The code for my current connection is the following
for sqlalchemy import *
def connect():
return pyodbc.connect('DSN=database;UID=uid;PWD=password')
engine = create_engine('mssql://', creator=connect, encoding='latin1')
connection = engine.connect()
Clarifications and comments:
This problems happens when retrieving information from the DB. I don't need to store anything.
At the beginning I didn't specify the encoding, and the result was that, whenever a non ascii character was encountered on the DB, pyodbc raises a UnicodeDecodeError. I corrected that using 'latin1' as encoding, but that doesn't solve the problem for all the characters.
I admit that the server is not on latin1, the comment is incorrect. I have been checking both the database collation and the specific fields collations and appears to be all in 'Latin1_General_CI_AS', then, how can ć be stored? Maybe I'm not correctly understanding collations.
I corrected a little the question, specifically, I have tried more encodings than latin1, also cp1250 and cp1252 (which apparently is the one used on 'Latin1_General_CI_AS', according to msdn)
UPDATE:
OK, Following these steps, I get that the encoding used by the DB appears to be cp1252: http://bytes.com/topic/sql-server/answers/142972-characters-encoding
Anyway, that appears to be a bad assumption as reflected on answers.
UPDATE2:
Anyway, after configuring properly the odbc driver, I don't need to specify the encoding on the Python code.
A:
You should stop using code pages and switch to Unicode. This is the only way of getting rid of this kind of problems.
A:
Original comment turned into an answer:
cp1250 and cp1252 are NOT "latin1 encodings". A collation is not an encoding. Re your comment: Who says that "the server is encoded in latin1"? If the server expects all input/output to be encoded in latin1 (which I doubt), then you quite simply can't get some Eastern European characters into your database (nor Russian, Chinese, Greek, etc etc).
Update:
You need to look further afield than the collation. """msdn.microsoft.com/en-us/library/ms174596(v=SQL.90).aspx suggests, for Latin1_General_CI_AS the used encoding is cp1252""" is codswallop. The table provides an LCID (locale ID), default collation, and codepage for each locale. Yes, the collation "Latin1_General_CI_AS" is listed in association with the cp1252 codepage for several locales. For two locales (Armenian and Georgian), it is listed in association with the "Unicode" codepage (!!!).
Quite simply, you need to find out what codepage the database is using.
Try to extract data from the database without specifing an encoding at all. Don't bother encoding that in whatever encoding you guess your console may be using -- that only adds another source of confusion. Instead, use print repr(data). Report back here what you get from the repr() where you expect non-Latin1 characters.
A:
Try connecting to the db with the pyodbc.connect() parameter convert_unicode=True , eg. from sqlalchemy:
engine = create_engine('mssql://yourdb', connect_args={'convert_unicode': True})
This should make sure that all the results (and not only those from nvarchar etc...) you get are unicode, correctly converted from whatever encoding is used in the db.
As for writing to the db, just always use unicode. If I'm not mistaken (will check later), pyodbc will make sure it will get written to the db correctly as well.
(of course, if the db uses an encoding that does not support the characters you want to write, you will still get errors: if you want the columns to support any kind of character, you will have to use unicode columns on the db too)
A:
OK, per http://msdn.microsoft.com/en-us/library/ms174596(v=SQL.90).aspx the encoding of Latin1_General_CI_AS is most probably cp1252. So, you'd have to use encoding='cp1252'. But this could solve only halve of the problem, because you have to output the values somehow to see, whether the characters are there or not. So if you have some_db_value, which you extracted from the database, you have to some_db_value.encode('proper-output-encoding') to have it right. proper-output-encoding depends, how you output this: on the console, it is the console encoding, which can be anything like 'cp1252', 'cp437', 'cp850' (on windows). On the web, it is the encoding of the webserver, hopefully 'utf-8'.
edit: Please read John Machin's answer, as it is not clear whether 'cp1252' is the correct database encoding
| 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 keep the same collation). I started selecting the encoding 'latin1' in the call of create_engine and that appears to work for Western European character (like French or Spanish, characters like é) but not for Easter European characters. Specifically, I have a problem with the character ć
I have been trying to select other encodings as stated on Python documentation, specifically the Microsoft ones, like cp1250 and cp1252, but I keep facing the same problem.
Does anyone knows how to solve those differences? Does the collation 'Latin1_General_CI_AS' has an equivalence on Python encodings?
The code for my current connection is the following
for sqlalchemy import *
def connect():
return pyodbc.connect('DSN=database;UID=uid;PWD=password')
engine = create_engine('mssql://', creator=connect, encoding='latin1')
connection = engine.connect()
Clarifications and comments:
This problems happens when retrieving information from the DB. I don't need to store anything.
At the beginning I didn't specify the encoding, and the result was that, whenever a non ascii character was encountered on the DB, pyodbc raises a UnicodeDecodeError. I corrected that using 'latin1' as encoding, but that doesn't solve the problem for all the characters.
I admit that the server is not on latin1, the comment is incorrect. I have been checking both the database collation and the specific fields collations and appears to be all in 'Latin1_General_CI_AS', then, how can ć be stored? Maybe I'm not correctly understanding collations.
I corrected a little the question, specifically, I have tried more encodings than latin1, also cp1250 and cp1252 (which apparently is the one used on 'Latin1_General_CI_AS', according to msdn)
UPDATE:
OK, Following these steps, I get that the encoding used by the DB appears to be cp1252: http://bytes.com/topic/sql-server/answers/142972-characters-encoding
Anyway, that appears to be a bad assumption as reflected on answers.
UPDATE2:
Anyway, after configuring properly the odbc driver, I don't need to specify the encoding on the Python code.
| [
"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
Note the difference:
X Adam Matan X
X אדם מתן X
Any ideas?
A:
You need to specify that the second string is Unicode by putting u in front of the string:
>>> str1="Adam Matan"
>>> str2=u"אדם מתן"
>>> print "X %20s X" % str1
X Adam Matan X
>>> print "X %20s X" % str2
X אדם מתן X
Doing this lets Python know that it's counting Unicode characters, not just bytes.
A:
In Python 2 unprefixed string literals are of type str, which is a byte string. It stores arbitrary bytes, not characters. UTF-8 encodes some characters with more than one bytes. str2 therefore contains more bytes than actual characters, and shows the unexpected, but perfectly valid behaviour in string formatting. If you look at the actual byte content of these strings (use repr instead of print), you'll see, that in both strings the field is actually 20 bytes (not characters!) long.
As already mentioned, the solution is to use unicode strings. When working with strings in Python, you absolutely need to understand and realize the difference between unicode and byte strings.
A:
Try this way:
>>> str1="Adam Matan"
>>> str2=unicode("אדם מתן", "utf8")
>>> print "X %20s X" % str2
X אדם מתן X
>>> print "X %20s X" % str1
X Adam Matan 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 אדם מתן X
Any ideas?
| [
"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 defining the filters in the backend (Django) that will then be applied in javascript.
The filters should look like the following:
dataobject.key operator value
Filters can also be conditional:
if dataobject.key operator value
and dataobject.key2 operator value
or dataobject.key3 operator value
And probably any combination of conditionals such as:
if (condition and condition) or condition
Some keys will have a set of allowed values, and other keys will have free text fields. This system must be usable by business-type end-users otherwise there is no point in having this system at all. The primary goal is to have a system that is fully managed by the end-users. If most of these goals can be implemented, I'll consider it a win.
Is a rule engine appropriate for this scenario? Is there a python or django framework available for implementing this behaviour or any well defined patterns?
Update (Based on S.Lott's answer):
I'm not talking about filtering the data using the Django ORM. I want to pass all the data and all the rules to javascript, so the javascript application can remain 'disconnected'.
What I need is a way of having users define these rules and combinations of rules, and storing them in a database. Then when a page is loaded, this data and all the rules are retrieved and placed onto the page. The definition of the rules is the important piece of the puzzle.
A:
Django filters can easily be piled on top of each other.
initial_query_set = SomeModel.objects.filter( ... some defaults ... )
if got_some_option_from_javascript:
query_set = initial_query_set.filter( this )
else:
query_set = initial_query_set
if got_some_other_option:
query_set = query_set.exclude( that )
if yet_more:
query_set = query_set.filter( and on and on )
That's the standard approach. If you're not talking about Django ORM query filters, please update your question.
| 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 applied in javascript.
The filters should look like the following:
dataobject.key operator value
Filters can also be conditional:
if dataobject.key operator value
and dataobject.key2 operator value
or dataobject.key3 operator value
And probably any combination of conditionals such as:
if (condition and condition) or condition
Some keys will have a set of allowed values, and other keys will have free text fields. This system must be usable by business-type end-users otherwise there is no point in having this system at all. The primary goal is to have a system that is fully managed by the end-users. If most of these goals can be implemented, I'll consider it a win.
Is a rule engine appropriate for this scenario? Is there a python or django framework available for implementing this behaviour or any well defined patterns?
Update (Based on S.Lott's answer):
I'm not talking about filtering the data using the Django ORM. I want to pass all the data and all the rules to javascript, so the javascript application can remain 'disconnected'.
What I need is a way of having users define these rules and combinations of rules, and storing them in a database. Then when a page is loaded, this data and all the rules are retrieved and placed onto the page. The definition of the rules is the important piece of the puzzle.
| [
"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 Exception, exc:
return HttpResponseRedirect(auth_sub_url()) # instead this line is executed (why?)
So I set breakpoint at last line and under debugger I see:
"exc" TokenUpgradeFailed: {'status': 403, 'body': 'html stripped', 'reason': 'Non 200 response on upgrade'}
"type(exc)" type: <class 'gdata.service.TokenUpgradeFailed'>
"exc is gdata.service.TokenUpgradeFailed" bool: False
"exc.__class__" type: <class 'gdata.service.TokenUpgradeFailed'>
"isinstance(exc, gdata.service.TokenUpgradeFailed)" bool: False
"exc.__class__.__name__" str: TokenUpgradeFailed
What I missed in python exception handling? Why isinstance(exc, gdata.service.TokenUpgradeFailed) is False?
A:
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 (hence the exception catching problem).
There may be other causes for the error but I suggest looking through your code and ensuring that everything importing the gdata.service module explicitly mentions the gdata package. Even within the gdata package itself, each module using the service module should import it from the package explicitly via from gdata import service rather than by way of the relative import: import service.
| 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(auth_sub_url()) # instead this line is executed (why?)
So I set breakpoint at last line and under debugger I see:
"exc" TokenUpgradeFailed: {'status': 403, 'body': 'html stripped', 'reason': 'Non 200 response on upgrade'}
"type(exc)" type: <class 'gdata.service.TokenUpgradeFailed'>
"exc is gdata.service.TokenUpgradeFailed" bool: False
"exc.__class__" type: <class 'gdata.service.TokenUpgradeFailed'>
"isinstance(exc, gdata.service.TokenUpgradeFailed)" bool: False
"exc.__class__.__name__" str: TokenUpgradeFailed
What I missed in python exception handling? Why isinstance(exc, gdata.service.TokenUpgradeFailed) is False?
| [
"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 string" & Null ==> "Some string"
This hidden feature allows for the first line of code I wrote to include a comma and space between the required LastName and the optional FirstName values. If FirstName is Null (Null is the VB/VBA equiv of Python's None), FullName will be set to LastName with no trailing comma.
Is there a one-line idiomatic way to do this in Python?
Technical Note:
gnibbler's and eumiro's answers are not strictly the equivalent of VB/VBA's + and &. Using their approaches, if FirstName is an empty string ("") rather than None, there will be no trailing comma. In almost all cases this would be preferable to VB/VBA's result which would be to add the trailing comma with a blank FirstName.
A:
The following line can be used to concatenate more not-None elements:
FullName = ', '.join(filter(None, (LastName, FirstName)))
A:
FullName = LastName + (", " + FirstName if FirstName else "")
A:
Simple ternary operator would do:
>>> s1, s
('abc', None)
>>> print(s if s is None else s1 + s)
None
>>> print(s1 if s is None else s1 + s)
abc
| 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 for the first line of code I wrote to include a comma and space between the required LastName and the optional FirstName values. If FirstName is Null (Null is the VB/VBA equiv of Python's None), FullName will be set to LastName with no trailing comma.
Is there a one-line idiomatic way to do this in Python?
Technical Note:
gnibbler's and eumiro's answers are not strictly the equivalent of VB/VBA's + and &. Using their approaches, if FirstName is an empty string ("") rather than None, there will be no trailing comma. In almost all cases this would be preferable to VB/VBA's result which would be to add the trailing comma with a blank FirstName.
| [
"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 AddUserPermission(
LPSTR szUserAlias,
LPMAPISESSION lpSession,
LPEXCHANGEMODIFYTABLE lpExchModTbl,
ACLRIGHTS frights)
{
HRESULT hr = S_OK;
LPADRBOOK lpAdrBook;
ULONG cbEid;
LPENTRYID lpEid = NULL;
SPropValue prop[2] = {0};
ROWLIST rowList = {0};
char szExName[MAX_PATH];
// Replace with "/o=OrganizationName/ou=SiteName/cn=Recipients/cn="
char* szServerDN = "/o=org/ou=site/cn=Recipients/cn=";
strcpy(szExName, szServerDN);
strcat(szExName, szUserAlias);
// Open the address book.
hr = lpSession->OpenAddressBook(0,
0,
MAPI_ACCESS_MODIFY,
&lpAdrBook );
if ( FAILED( hr ) ) goto cleanup;
// Obtain the entry ID for the recipient.
hr = HrCreateDirEntryIdEx(lpAdrBook,
szExName,
&cbEid,
&lpEid);
if ( FAILED( hr ) ) goto cleanup;
prop[0].ulPropTag = PR_MEMBER_ENTRYID;
prop[0].Value.bin.cb = cbEid;
prop[0].Value.bin.lpb = (BYTE*)lpEid;
prop[1].ulPropTag = PR_MEMBER_RIGHTS;
prop[1].Value.l = frights;
rowList.cEntries = 1;
rowList.aEntries->ulRowFlags = ROW_ADD;
rowList.aEntries->cValues = 2;
rowList.aEntries->rgPropVals = &prop[0];
hr = lpExchModTbl->ModifyTable(0, &rowList);
if(FAILED(hr)) goto cleanup;
printf("Added user permission. \n");
cleanup:
if (lpAdrBook)
lpAdrBook->Release();
return hr;
}
I can open the Address Book, but HrCreateDirEntryIdEx is not provided in the pywin32 mapi. I found it in the exchange extension, which does not compile on my system, the missing library problem. Do you have any idea to retrieve the users entry ID?
Thank.
Patrick
A:
I got this piece of code and it works fine
from binascii import b2a_hex, a2b_hex
import active_directory as ad
# entry_type, see http://msdn.microsoft.com/en-us/library/cc840018.aspx
# + AB_DT_CONTAINER 0x000000100
# + AB_DT_TEMPLATE 0x000000101
# + AB_DT_OOUSER 0x000000102
# + AB_DT_SEARCH 0x000000200
# ab_flags, maybe see here: https://svn.openchange.org/openchange/trunk/libmapi/mapidefs.h
def gen_exchange_entry_id(user_id, ab_flags=0, entry_type = 0):
muidEMSAB = "DCA740C8C042101AB4B908002B2FE182"
version = 1
# Find user and bail out if it's not there
ad_obj = ad.find_user(user_id)
if not ad_obj:
return None
return "%08X%s%08X%08X%s00" % (
ab_flags,
muidEMSAB,
version,
entry_type,
b2a_hex(ad_obj.legacyExchangeDN.upper()).upper(),
)
data = gen_exchange_entry_id("myusername")
print data
print len(a2b_hex(data))
| 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,
LPMAPISESSION lpSession,
LPEXCHANGEMODIFYTABLE lpExchModTbl,
ACLRIGHTS frights)
{
HRESULT hr = S_OK;
LPADRBOOK lpAdrBook;
ULONG cbEid;
LPENTRYID lpEid = NULL;
SPropValue prop[2] = {0};
ROWLIST rowList = {0};
char szExName[MAX_PATH];
// Replace with "/o=OrganizationName/ou=SiteName/cn=Recipients/cn="
char* szServerDN = "/o=org/ou=site/cn=Recipients/cn=";
strcpy(szExName, szServerDN);
strcat(szExName, szUserAlias);
// Open the address book.
hr = lpSession->OpenAddressBook(0,
0,
MAPI_ACCESS_MODIFY,
&lpAdrBook );
if ( FAILED( hr ) ) goto cleanup;
// Obtain the entry ID for the recipient.
hr = HrCreateDirEntryIdEx(lpAdrBook,
szExName,
&cbEid,
&lpEid);
if ( FAILED( hr ) ) goto cleanup;
prop[0].ulPropTag = PR_MEMBER_ENTRYID;
prop[0].Value.bin.cb = cbEid;
prop[0].Value.bin.lpb = (BYTE*)lpEid;
prop[1].ulPropTag = PR_MEMBER_RIGHTS;
prop[1].Value.l = frights;
rowList.cEntries = 1;
rowList.aEntries->ulRowFlags = ROW_ADD;
rowList.aEntries->cValues = 2;
rowList.aEntries->rgPropVals = &prop[0];
hr = lpExchModTbl->ModifyTable(0, &rowList);
if(FAILED(hr)) goto cleanup;
printf("Added user permission. \n");
cleanup:
if (lpAdrBook)
lpAdrBook->Release();
return hr;
}
I can open the Address Book, but HrCreateDirEntryIdEx is not provided in the pywin32 mapi. I found it in the exchange extension, which does not compile on my system, the missing library problem. Do you have any idea to retrieve the users entry ID?
Thank.
Patrick
| [
"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 not supported in
HTTP.
--08:42:17-- http://svn.zope.org/checkout/zc.buildout/trunk/bootstrap/bootstrap.py
=> `bootstrap.py' Resolving svn.zope.org... 74.84.203.155
Connecting to
svn.zope.org|74.84.203.155|:80...
connected. HTTP request sent, awaiting
response... 200 OK Length: unspecified
[text/x-python]
[ <=> ] 2,572 --.--K/s
08:42:17 (122.64 MB/s) -
`bootstrap.py' saved [2572]
You can see there a warning message. I do not know what it means and if I should wary about it. Any way, I tried to continue.
python bootstrap.py init
vi buildout.cfg
In the buildout.cfg I put the following:
[buildout]
parts = sqlite
[sqlite]
recipe = zc.recipe.egg
eggs = pysqlite
interpreter = mypython
And then I execute:
./bin/buildout
At that stage I have problems:
Getting distribution for
'zc.recipe.egg'. Got zc.recipe.egg
1.2.2. Installing sqlite. Getting distribution for 'pysqlite'. In file
included from src/module.c:24:
src/connection.h:33:21: error:
sqlite3.h: No such file or directory
In file included from src/module.c:24:
src/connection.h:38: error: expected
specifier-qualifier-list before
‘sqlite3’ In file included from
src/module.c:25: src/statement.h:37:
error: expected
specifier-qualifier-list before
‘sqlite3’ src/module.c: In function
‘module_complete’: src/module.c:99:
warning: implicit declaration of
function ‘sqlite3_complete’
src/module.c: At top level:
src/module.c:265: error: ‘SQLITE_OK’
undeclared here (not in a function)
src/module.c:266: error: ‘SQLITE_DENY’
undeclared here (not in a function)
src/module.c:267: error:
‘SQLITE_IGNORE’ undeclared here (not
in a function) src/module.c:268:
error: ‘SQLITE_CREATE_INDEX’
undeclared here (not in a function)
src/module.c:269: error:
‘SQLITE_CREATE_TABLE’ undeclared here
(not in a function) src/module.c:270:
error: ‘SQLITE_CREATE_TEMP_INDEX’
undeclared here (not in a function)
src/module.c:271: error:
‘SQLITE_CREATE_TEMP_TABLE’ undeclared
here (not in a function)
src/module.c:272: error:
‘SQLITE_CREATE_TEMP_TRIGGER’
undeclared here (not in a function)
src/module.c:273: error:
‘SQLITE_CREATE_TEMP_VIEW’ undeclared
here (not in a function)
src/module.c:274: error:
‘SQLITE_CREATE_TRIGGER’ undeclared
here (not in a function)
src/module.c:275: error:
‘SQLITE_CREATE_VIEW’ undeclared here
(not in a function) src/module.c:276:
error: ‘SQLITE_DELETE’ undeclared here
(not in a function) src/module.c:277:
error: ‘SQLITE_DROP_INDEX’ undeclared
here (not in a function)
src/module.c:278: error:
‘SQLITE_DROP_TABLE’ undeclared here
(not in a function) src/module.c:279:
error: ‘SQLITE_DROP_TEMP_INDEX’
undeclared here (not in a function)
src/module.c:280: error:
‘SQLITE_DROP_TEMP_TABLE’ undeclared
here (not in a function)
src/module.c:281: error:
‘SQLITE_DROP_TEMP_TRIGGER’ undeclared
here (not in a function)
src/module.c:282: error:
‘SQLITE_DROP_TEMP_VIEW’ undeclared
here (not in a function)
src/module.c:283: error:
‘SQLITE_DROP_TRIGGER’ undeclared here
(not in a function) src/module.c:284:
error: ‘SQLITE_DROP_VIEW’ undeclared
here (not in a function)
src/module.c:285: error:
‘SQLITE_INSERT’ undeclared here (not
in a function) src/module.c:286:
error: ‘SQLITE_PRAGMA’ undeclared here
(not in a function) src/module.c:287:
error: ‘SQLITE_READ’ undeclared here
(not in a function) src/module.c:288:
error: ‘SQLITE_SELECT’ undeclared here
(not in a function) src/module.c:289:
error: ‘SQLITE_TRANSACTION’ undeclared
here (not in a function)
src/module.c:290: error:
‘SQLITE_UPDATE’ undeclared here (not
in a function) src/module.c:291:
error: ‘SQLITE_ATTACH’ undeclared here
(not in a function) src/module.c:292:
error: ‘SQLITE_DETACH’ undeclared here
(not in a function) src/module.c: In
function ‘init_sqlite’:
src/module.c:419: warning: implicit
declaration of function
‘sqlite3_libversion’ src/module.c:419:
warning: passing argument 1 of
‘PyString_FromString’ makes pointer
from integer without a cast error:
Setup script exited with error:
command 'gcc' failed with exit status
1 An error occured when trying to
install pysqlite 2.5.5.Look above this
message for any errors thatwere output
by easy_install. While: Installing
sqlite. Getting distribution for
'pysqlite'. Error: Couldn't install:
pysqlite 2.5.5
Can anybody tell me, pleas, what these error messages means and how the above problem can be solved?
A:
You need install sqlite develop library.
In ubuntu or debian, run:
sudo apt-get install libsqlite3-dev
A:
You need to have sqlite installed before you start installing the python bindings.
| 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/checkout/zc.buildout/trunk/bootstrap/bootstrap.py
=> `bootstrap.py' Resolving svn.zope.org... 74.84.203.155
Connecting to
svn.zope.org|74.84.203.155|:80...
connected. HTTP request sent, awaiting
response... 200 OK Length: unspecified
[text/x-python]
[ <=> ] 2,572 --.--K/s
08:42:17 (122.64 MB/s) -
`bootstrap.py' saved [2572]
You can see there a warning message. I do not know what it means and if I should wary about it. Any way, I tried to continue.
python bootstrap.py init
vi buildout.cfg
In the buildout.cfg I put the following:
[buildout]
parts = sqlite
[sqlite]
recipe = zc.recipe.egg
eggs = pysqlite
interpreter = mypython
And then I execute:
./bin/buildout
At that stage I have problems:
Getting distribution for
'zc.recipe.egg'. Got zc.recipe.egg
1.2.2. Installing sqlite. Getting distribution for 'pysqlite'. In file
included from src/module.c:24:
src/connection.h:33:21: error:
sqlite3.h: No such file or directory
In file included from src/module.c:24:
src/connection.h:38: error: expected
specifier-qualifier-list before
‘sqlite3’ In file included from
src/module.c:25: src/statement.h:37:
error: expected
specifier-qualifier-list before
‘sqlite3’ src/module.c: In function
‘module_complete’: src/module.c:99:
warning: implicit declaration of
function ‘sqlite3_complete’
src/module.c: At top level:
src/module.c:265: error: ‘SQLITE_OK’
undeclared here (not in a function)
src/module.c:266: error: ‘SQLITE_DENY’
undeclared here (not in a function)
src/module.c:267: error:
‘SQLITE_IGNORE’ undeclared here (not
in a function) src/module.c:268:
error: ‘SQLITE_CREATE_INDEX’
undeclared here (not in a function)
src/module.c:269: error:
‘SQLITE_CREATE_TABLE’ undeclared here
(not in a function) src/module.c:270:
error: ‘SQLITE_CREATE_TEMP_INDEX’
undeclared here (not in a function)
src/module.c:271: error:
‘SQLITE_CREATE_TEMP_TABLE’ undeclared
here (not in a function)
src/module.c:272: error:
‘SQLITE_CREATE_TEMP_TRIGGER’
undeclared here (not in a function)
src/module.c:273: error:
‘SQLITE_CREATE_TEMP_VIEW’ undeclared
here (not in a function)
src/module.c:274: error:
‘SQLITE_CREATE_TRIGGER’ undeclared
here (not in a function)
src/module.c:275: error:
‘SQLITE_CREATE_VIEW’ undeclared here
(not in a function) src/module.c:276:
error: ‘SQLITE_DELETE’ undeclared here
(not in a function) src/module.c:277:
error: ‘SQLITE_DROP_INDEX’ undeclared
here (not in a function)
src/module.c:278: error:
‘SQLITE_DROP_TABLE’ undeclared here
(not in a function) src/module.c:279:
error: ‘SQLITE_DROP_TEMP_INDEX’
undeclared here (not in a function)
src/module.c:280: error:
‘SQLITE_DROP_TEMP_TABLE’ undeclared
here (not in a function)
src/module.c:281: error:
‘SQLITE_DROP_TEMP_TRIGGER’ undeclared
here (not in a function)
src/module.c:282: error:
‘SQLITE_DROP_TEMP_VIEW’ undeclared
here (not in a function)
src/module.c:283: error:
‘SQLITE_DROP_TRIGGER’ undeclared here
(not in a function) src/module.c:284:
error: ‘SQLITE_DROP_VIEW’ undeclared
here (not in a function)
src/module.c:285: error:
‘SQLITE_INSERT’ undeclared here (not
in a function) src/module.c:286:
error: ‘SQLITE_PRAGMA’ undeclared here
(not in a function) src/module.c:287:
error: ‘SQLITE_READ’ undeclared here
(not in a function) src/module.c:288:
error: ‘SQLITE_SELECT’ undeclared here
(not in a function) src/module.c:289:
error: ‘SQLITE_TRANSACTION’ undeclared
here (not in a function)
src/module.c:290: error:
‘SQLITE_UPDATE’ undeclared here (not
in a function) src/module.c:291:
error: ‘SQLITE_ATTACH’ undeclared here
(not in a function) src/module.c:292:
error: ‘SQLITE_DETACH’ undeclared here
(not in a function) src/module.c: In
function ‘init_sqlite’:
src/module.c:419: warning: implicit
declaration of function
‘sqlite3_libversion’ src/module.c:419:
warning: passing argument 1 of
‘PyString_FromString’ makes pointer
from integer without a cast error:
Setup script exited with error:
command 'gcc' failed with exit status
1 An error occured when trying to
install pysqlite 2.5.5.Look above this
message for any errors thatwere output
by easy_install. While: Installing
sqlite. Getting distribution for
'pysqlite'. Error: Couldn't install:
pysqlite 2.5.5
Can anybody tell me, pleas, what these error messages means and how the above problem can be solved?
| [
"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 proxy in order to send some HTTP requests:
import socket
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.connect(( "10.10.1.100", 9401 ))
s.send("GET /index.html HTTP/1.1\r\nHost: aorotos.com\r\n\r\n")
d = s.recv(1024)
print d
s.close()
I get an exception (113, "No route to host") during the connect. Now here is the weird part—I can browse the web using these same proxy settings, and if check the currently connected sockets via netstat -tna I see an ACTIVE connection to 10.10.1.100:9401.
I tried a simple command like export http_proxy='10.10.1.100:9401' && wget aorotos.com/index.html and even that works! If I enable the debug option (-d) in wget, I can even get the socket's file descriptor.
I went through the wget source code, and from what I can see it too uses a normal connect statement and does not set any special socket options (I'll go through it more throughly later). I've tried the same code in C, and it too fails.
The routing table provided via route is
Destination Gateway Genmask Flags Metric Ref Use Iface
default * 0.0.0.0 U 0 0 0 gprs0
Does anyone have any idea what might be wrong?
EDIT: Currently my IP is 10.16.82.250. And that is all that is there in the route output. If you're interested my external IP is 203.8.8.2.
ifconfig gprs0 -
gprs0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
inet addr:10.17.221.94 P-t-P:10.17.221.94 Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MTU:1400 Metric:1
RX packets:1832 errors:0 dropped:0 overruns:0 frame:0
TX packets:1844 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:10
RX bytes:1878364 (1.7 MiB) TX bytes:224746 (219.4 KiB)
EDIT 2 :
I landed up installing tcpdump and going through it's manual, and finally installing wireshark ( I'm on my N900 ) only to realize, from the packet dump, that I've been using the port 4901 instead of 9401 in both in C program and the python script! Doh! I blame the small screen and, well, myself.
Is there any way to close this question with a "I'm an idiot" or something? :P
Sorry for taking up your time! ( I've spent over a week on this. I can't believe I went through most of wget's source code! )
A:
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.
| 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 requests:
import socket
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.connect(( "10.10.1.100", 9401 ))
s.send("GET /index.html HTTP/1.1\r\nHost: aorotos.com\r\n\r\n")
d = s.recv(1024)
print d
s.close()
I get an exception (113, "No route to host") during the connect. Now here is the weird part—I can browse the web using these same proxy settings, and if check the currently connected sockets via netstat -tna I see an ACTIVE connection to 10.10.1.100:9401.
I tried a simple command like export http_proxy='10.10.1.100:9401' && wget aorotos.com/index.html and even that works! If I enable the debug option (-d) in wget, I can even get the socket's file descriptor.
I went through the wget source code, and from what I can see it too uses a normal connect statement and does not set any special socket options (I'll go through it more throughly later). I've tried the same code in C, and it too fails.
The routing table provided via route is
Destination Gateway Genmask Flags Metric Ref Use Iface
default * 0.0.0.0 U 0 0 0 gprs0
Does anyone have any idea what might be wrong?
EDIT: Currently my IP is 10.16.82.250. And that is all that is there in the route output. If you're interested my external IP is 203.8.8.2.
ifconfig gprs0 -
gprs0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
inet addr:10.17.221.94 P-t-P:10.17.221.94 Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MTU:1400 Metric:1
RX packets:1832 errors:0 dropped:0 overruns:0 frame:0
TX packets:1844 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:10
RX bytes:1878364 (1.7 MiB) TX bytes:224746 (219.4 KiB)
EDIT 2 :
I landed up installing tcpdump and going through it's manual, and finally installing wireshark ( I'm on my N900 ) only to realize, from the packet dump, that I've been using the port 4901 instead of 9401 in both in C program and the python script! Doh! I blame the small screen and, well, myself.
Is there any way to close this question with a "I'm an idiot" or something? :P
Sorry for taking up your time! ( I've spent over a week on this. I can't believe I went through most of wget's source code! )
| [
"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 it. The pylons framework isn't making it easy for me to interact with the python-openid classes, which are basically looking for instances of python's HTTPServer and SimpleCookie classes...
Any assistance available? Has anyone solved this problem? TIA.
A:
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#
| 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 easy for me to interact with the python-openid classes, which are basically looking for instances of python's HTTPServer and SimpleCookie classes...
Any assistance available? Has anyone solved this problem? TIA.
| [
"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 use oAuth?
Thanks,
Joel
A:
Tweepy has an oAuth module which works very well. See here: http://packages.python.org/tweepy/html/auth_tutorial.html
| 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 both implementations.
Mergesort:
#Merges two sorted lists into one sorted list. recursively
def merge(left, right):
if len(left) == 0 and len(right) == 0:
return []
elif len(left) == 0:
return right
elif len(right) == 0:
return left
else:
if left[0] <= right[0]:
return left[:1] + merge(left[1:],right)
else:
return right[:1] + merge(left,right[1:])
#Splits a list in half and returns the halves
def halve(list):
return list[:len(list)//2],list[len(list)//2:]
#Mergesort
def mergesort(list):
if len(list) <= 1:
return list
left,right = halve(list)
left,right = mergesort(left),mergesort(right)
return merge(left,right)
Quicksort:
#Three-way QuickSort in Python
def quicksort(a):
if len(a) == 0:
return []
p = a[(len(a)-1)//2]
less = quicksort([x for x in a if x < p])
greater = quicksort([x for x in a if x > p])
equal = [x for x in a if x == p]
return less + equal + greater
Can someone come up with an explanation or maybe even a fix?
A:
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:
You 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 creates like N**2 intermediate lists. The quicksort on the other hand uses very fast LCs instead and creates less lists (I think like 2N or so).
Try using extend instead of the +, maybe that helps.
A:
A recursive mergesort is not really the best way to do things. You should get better performance with a straight iterative approach. I'm not very conversant with Python, so I'll give you the C-like pseudocode.
ileft = 0 // index into left array
iright = 0 // index into right array
iresult = 0 // index into result array
while (ileft < left.length && iright < right.length)
{
if (left[ileft] <= right[iright])
result[iresult++] = left[ileft++]
else
result[iresult++] = right[iright++]
}
// now clean up the remaining list
while (ileft < left.length)
result[iresult++] = left[ileft++]
while (iright < right.length)
result[iresult++] = right[iright++]
A:
Explanation:
Typically, quicksort is significantly
faster in practice than other Θ(nlogn)
algorithms, because its inner loop can
be efficiently implemented on most
architectures, and in most real-world
data, it is possible to make design
choices which minimize the probability
of requiring quadratic time.
A:
Just out of curiosity, I wrote a quick implementation using generators (could be cleaner). How does this compare with those in the original method?
def merge(listA,listB):
iterA, iterB = iter(listA), iter(listB)
valA, valB = iterA.next(), iterB.next()
while True:
if valA <= valB:
yield valA
try:
valA = iterA.next()
except StopIteration:
yield valB
try:
while True:
yield iterB.next()
except StopIteration:
return
else:
yield valB
try:
valB = iterB.next()
except StopIteration:
yield valA
try:
while True:
yield iterA.next()
except StopIteration:
return
| 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 sorted lists into one sorted list. recursively
def merge(left, right):
if len(left) == 0 and len(right) == 0:
return []
elif len(left) == 0:
return right
elif len(right) == 0:
return left
else:
if left[0] <= right[0]:
return left[:1] + merge(left[1:],right)
else:
return right[:1] + merge(left,right[1:])
#Splits a list in half and returns the halves
def halve(list):
return list[:len(list)//2],list[len(list)//2:]
#Mergesort
def mergesort(list):
if len(list) <= 1:
return list
left,right = halve(list)
left,right = mergesort(left),mergesort(right)
return merge(left,right)
Quicksort:
#Three-way QuickSort in Python
def quicksort(a):
if len(a) == 0:
return []
p = a[(len(a)-1)//2]
less = quicksort([x for x in a if x < p])
greater = quicksort([x for x in a if x > p])
equal = [x for x in a if x == p]
return less + equal + greater
Can someone come up with an explanation or maybe even a fix?
| [
"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 example,
bookmarks = soup.findAll('bookmark')
then beautifulsoupcommand(bookmarks[0]) would return:
[<folder name="folder1">,<folder name="folder2">]
I'd also want to know when the ending tags hit too. Any ideas?
Thanks in advance!
A:
Here is my stab at it:
>>> from BeautifulSoup import BeautifulSoup
>>> html = """<folder name="folder1">
<folder name="folder2">
<bookmark href="link.html">
</folder>
</folder>
"""
>>> soup = BeautifulSoup(html)
>>> bookmarks = soup.find_all('bookmark')
>>> [p.get('name') for p in bookmarks[0].find_all_previous(name = 'folder')]
[u'folder2', u'folder1']
The key difference from @eumiro's answer is that I am using find_all_previous instead of find_parents. When I tested @eumiro's solution I found that find_parents only returns the first (immediate) parent as the name of the parent and grandparent are the same.
>>> [p.get('name') for p in bookmarks[0].find_parents('folder')]
[u'folder2']
>>> [p.get('name') for p in bookmarks[0].find_parents()]
[u'folder2', None]
It does return two generations of parents if the parent and grandparent are differently named.
>>> html = """<folder name="folder1">
<folder_parent name="folder2">
<bookmark href="link.html">
</folder_parent>
</folder>
"""
>>> soup = BeautifulSoup(html)
>>> bookmarks = soup.find_all('bookmark')
>>> [p.get('name') for p in bookmarks[0].find_parents()]
[u'folder2', u'folder1', None]
A:
bookmarks[0].findParents('folder') will return you a list of all parent nodes. You can then iterate over them and use their name attribute.
| 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 beautifulsoupcommand(bookmarks[0]) would return:
[<folder name="folder1">,<folder name="folder2">]
I'd also want to know when the ending tags hit too. Any ideas?
Thanks in advance!
| [
"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.