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:
Easiest way of unit testing C code with Python
I've got a pile of C code that I'd like to unit test using Python's unittest library (in Windows), but I'm trying to work out the best way of interfacing the C code so that Python can execute it (and get the results back). Does anybody have any experience in the easiest way to do it?
Some ideas include:
Wrapping the code as a Python C extension using the Python API
Wrap the C code using SWIG
Add a DLL wrapper to the C code and load it into Python using ctypes
Add a small XML-RPC server to the c-code and call it using xmlrpclib (yes, I know this seems a bit far-out!)
Is there a canonical way of doing this? I'm going to be doing this quite a lot, with different C modules, so I'd like to find a way which is least effort.
A:
Using ctypes would be my first instinct, though I must admit that if I was testing C code that was not going to be interfaced from Python in the first place, I would just use check. Check has the strong advantage of being able to properly report test cases that segfault. This is because it runs each test case in a separate process.
Now if you are going to create a python wrapper for the C code anyway, I would simply unittest the wrapper. In addition to the methods you listed above, you could also use Cython to write such a wrapper with python-like code and then unittest it from Python.
A:
I think that the exact solution depends on your code. Not all libraries are easily suitable for wrapping as a DLL. If your is, then ctypes is certainly the easiest way - just make a DLL out of your library and then test it with ctypes. An added bonus is that you now have your library conveniently wrapped as a standalone DLL which helps to decouple your application.
Sometimes, however, a more thorough interaction will be required between your C code and the testing Python code. Then, it's probably best to hook it as an extension, for which SWIG is a pretty good tool that will automate away most things you'll find boring about the process.
|
Easiest way of unit testing C code with Python
|
I've got a pile of C code that I'd like to unit test using Python's unittest library (in Windows), but I'm trying to work out the best way of interfacing the C code so that Python can execute it (and get the results back). Does anybody have any experience in the easiest way to do it?
Some ideas include:
Wrapping the code as a Python C extension using the Python API
Wrap the C code using SWIG
Add a DLL wrapper to the C code and load it into Python using ctypes
Add a small XML-RPC server to the c-code and call it using xmlrpclib (yes, I know this seems a bit far-out!)
Is there a canonical way of doing this? I'm going to be doing this quite a lot, with different C modules, so I'd like to find a way which is least effort.
|
[
"Using ctypes would be my first instinct, though I must admit that if I was testing C code that was not going to be interfaced from Python in the first place, I would just use check. Check has the strong advantage of being able to properly report test cases that segfault. This is because it runs each test case in a separate process.\nNow if you are going to create a python wrapper for the C code anyway, I would simply unittest the wrapper. In addition to the methods you listed above, you could also use Cython to write such a wrapper with python-like code and then unittest it from Python.\n",
"I think that the exact solution depends on your code. Not all libraries are easily suitable for wrapping as a DLL. If your is, then ctypes is certainly the easiest way - just make a DLL out of your library and then test it with ctypes. An added bonus is that you now have your library conveniently wrapped as a standalone DLL which helps to decouple your application.\nSometimes, however, a more thorough interaction will be required between your C code and the testing Python code. Then, it's probably best to hook it as an extension, for which SWIG is a pretty good tool that will automate away most things you'll find boring about the process.\n"
] |
[
12,
8
] |
[] |
[] |
[
"c",
"python",
"swig",
"unit_testing"
] |
stackoverflow_0002482270_c_python_swig_unit_testing.txt
|
Q:
Performance Wise, Python VS JAVA For File Based Processing
I need to create daemon that will monitor certain directory and will process every file that's written to that particular path.
My choice is either java or python.
Did you guys have any experience using both technology? what is the best one?
EDIT 1: files that will be processed is simple text file (one line with tab separated fields).
I just need to move it to buffer and send to further to my php file.
EDIT 2: It's for freebsd server
A:
Performance-wise, for an I/O - syscall bound task such as you're mentioning, it's going to be a wash, most likely, depending a bit on the platform. Java tends to have better CPU usage (partly because a JVM can effectively use multiple cores on a multicore CPU on different threads, with CPython having problems with that; partly because of strong JIT abilities), but typically pays for them with higher RAM footprints (no big deal if you have 64GB of RAM laying around and not much else to do on the machine, say, but often an issue in other circumstances).
If you specify the platform (Linux vs Windows vs ...), we might be able to offer more help.
Edit: with processing required as light as the OP's mentioned in the Q's edit, there's really nothing either way in the CPU-load part of the task. Unfortunately I don't know what freebsd offers for "directory watching" (like Linux's inotify, etc).
|
Performance Wise, Python VS JAVA For File Based Processing
|
I need to create daemon that will monitor certain directory and will process every file that's written to that particular path.
My choice is either java or python.
Did you guys have any experience using both technology? what is the best one?
EDIT 1: files that will be processed is simple text file (one line with tab separated fields).
I just need to move it to buffer and send to further to my php file.
EDIT 2: It's for freebsd server
|
[
"Performance-wise, for an I/O - syscall bound task such as you're mentioning, it's going to be a wash, most likely, depending a bit on the platform. Java tends to have better CPU usage (partly because a JVM can effectively use multiple cores on a multicore CPU on different threads, with CPython having problems with that; partly because of strong JIT abilities), but typically pays for them with higher RAM footprints (no big deal if you have 64GB of RAM laying around and not much else to do on the machine, say, but often an issue in other circumstances).\nIf you specify the platform (Linux vs Windows vs ...), we might be able to offer more help.\nEdit: with processing required as light as the OP's mentioned in the Q's edit, there's really nothing either way in the CPU-load part of the task. Unfortunately I don't know what freebsd offers for \"directory watching\" (like Linux's inotify, etc).\n"
] |
[
0
] |
[] |
[] |
[
"file_io",
"java",
"python"
] |
stackoverflow_0002490291_file_io_java_python.txt
|
Q:
Best/Fastest Way to Test Python CGI locally?
Just wondering whats the best way to test Python CGI while developing a site?
(I'm used to PHP for web dev so bear with me :P)
A:
The Python standard library's CGIHTTPServer module is a simple, quick-and-dirty way to locally test CGI scripts!
A:
There are a number of Python web frameworks which make this easier for you. Django, for example, has a built-in web server designed for testing out your application.
However, if you're already using CGI, the easiest way to test it would be to run Apache. Configuring CGI for Apache is straightforward and there is a lot of good documentation.
|
Best/Fastest Way to Test Python CGI locally?
|
Just wondering whats the best way to test Python CGI while developing a site?
(I'm used to PHP for web dev so bear with me :P)
|
[
"The Python standard library's CGIHTTPServer module is a simple, quick-and-dirty way to locally test CGI scripts!\n",
"There are a number of Python web frameworks which make this easier for you. Django, for example, has a built-in web server designed for testing out your application.\nHowever, if you're already using CGI, the easiest way to test it would be to run Apache. Configuring CGI for Apache is straightforward and there is a lot of good documentation.\n"
] |
[
6,
0
] |
[] |
[] |
[
"cgi",
"python"
] |
stackoverflow_0002490150_cgi_python.txt
|
Q:
My method is being recognized within my own program. Newbie mistake probably
Here's my code:
sentenceToTranslate = raw_input("Please write in the sentence you want to translate: ")
words = sentenceToTranslate.split(" ")
for word in words:
if isVowel(word[0]):
print "TEST"
def isVowel(letter):
if letter.lower() == "a" or letter.lower() == "e" or letter.lower() == "i" or letter.lower() == "o" or letter.lower() == "u":
return True
else:
return False
The error I get is:
NameError: name 'isVowel' is not defined
What am I doing wrong?
A:
The function hasn't been defined yet, so the name 'isVowel' doesn't have a function bound to it: that only happens at the time when you say "def".
Solution: move your code below the def isVowel(letter).
A:
Put the def isVowel definition at top.
You defined the function after it had already been called.
Since, the source code is not compiled and interpreted at run-time, it does not check for this error.
Also, you can redefine the function as
def isVowel(letter):
if letter.lower() in "aeiou":
return True
else:
return False
A:
Python executes all the statements that you put in your module when it encounters them, from top to bottom. What happens is that you try to call isVowel before you have defined that function. The python interpreter has not reached that code yet.
If you put the definition of isVowel at the top of your file you will be able to call it.
A:
At the risk of being downvoted again, here is some further insight into these "define before use" requirements.
Note that the body of a function is not processed for the existence of symbols in until that function gets called. So you could write code like this:
def A():
# calls B - even though B is defined later in the module
B()
def B():
# calls A
A()
And this works just fine. The interpreter/compiler works top-down through the module, but when it sees a function or class definition, it processes the definition of the function, but not the function itself.
The reason your code failed was because the reference to isVowel was not within a function, but was at module scope. Code in the module that is not within a function is executed immediately, so the interpreter needs to be able to resolve any names based on what it has seen so far.
A:
I think you need to define the function first, then call it after it has been defined.
def isVowel(letter):
if letter.lower() == "a" or letter.lower() == "e" or letter.lower() == "i" or letter.lower() == "o" or letter.lower() == "u":
return True
else:
return False
sentenceToTranslate = raw_input("Please write in the sentence you want to translate: ")
words = sentenceToTranslate.split(" ")
for word in words:
if isVowel(word[0]):
print "TEST"
Often you will put the function definitions in another file, and import them to avoid these problems.
A:
Here are a couple of other points to make for a newbie Pythoner:
1) What is the point of writing this?
def isVowel():
if boolean-expression:
return True
else:
return False
You already have the True/False-ness captured in the value of the boolean expression, just:
def isVowel():
return boolean-expression
2) Function calls are performance killers. Especially when you have such a limited set of items to check for, instead of calling .lower() so that you can check against "aeiou", check the character itself against both the lower and upper case letters, "aeiouAEIOU". Even though this is twice the length string to test for membership, it saves us the call to the lower() function.
Here are some performance test results:
import time
import string
time.clock()
reps = 100000
testString = (string.uppercase + string.lowercase) * reps
start = time.clock()
for c in testString:
answer = c.lower() in "aeiou"
end = time.clock()
print end-start
start = time.clock()
for c in testString:
answer = c in "aeiouAEIOU"
end = time.clock()
print end-start
start = time.clock()
for c in testString:
pass
end = time.clock()
Prints:
3.27782246068
1.76839123408
0.713913919227
The third loop shows the time it takes just to iterate over the testString itself, so the time spent in the body of the loop (assuming pass takes negligible time) is:
2.563908541
1.054477315
By avoiding the lower() call, the second technique is more than twice as fast.
|
My method is being recognized within my own program. Newbie mistake probably
|
Here's my code:
sentenceToTranslate = raw_input("Please write in the sentence you want to translate: ")
words = sentenceToTranslate.split(" ")
for word in words:
if isVowel(word[0]):
print "TEST"
def isVowel(letter):
if letter.lower() == "a" or letter.lower() == "e" or letter.lower() == "i" or letter.lower() == "o" or letter.lower() == "u":
return True
else:
return False
The error I get is:
NameError: name 'isVowel' is not defined
What am I doing wrong?
|
[
"The function hasn't been defined yet, so the name 'isVowel' doesn't have a function bound to it: that only happens at the time when you say \"def\".\nSolution: move your code below the def isVowel(letter).\n",
"\nPut the def isVowel definition at top.\n\nYou defined the function after it had already been called.\nSince, the source code is not compiled and interpreted at run-time, it does not check for this error.\nAlso, you can redefine the function as\ndef isVowel(letter):\n if letter.lower() in \"aeiou\":\n return True\n else:\n return False\n\n",
"Python executes all the statements that you put in your module when it encounters them, from top to bottom. What happens is that you try to call isVowel before you have defined that function. The python interpreter has not reached that code yet. \nIf you put the definition of isVowel at the top of your file you will be able to call it.\n",
"At the risk of being downvoted again, here is some further insight into these \"define before use\" requirements.\nNote that the body of a function is not processed for the existence of symbols in until that function gets called. So you could write code like this:\ndef A():\n # calls B - even though B is defined later in the module\n B()\n\ndef B():\n # calls A\n A()\n\nAnd this works just fine. The interpreter/compiler works top-down through the module, but when it sees a function or class definition, it processes the definition of the function, but not the function itself. \nThe reason your code failed was because the reference to isVowel was not within a function, but was at module scope. Code in the module that is not within a function is executed immediately, so the interpreter needs to be able to resolve any names based on what it has seen so far.\n",
"I think you need to define the function first, then call it after it has been defined. \ndef isVowel(letter):\n if letter.lower() == \"a\" or letter.lower() == \"e\" or letter.lower() == \"i\" or letter.lower() == \"o\" or letter.lower() == \"u\":\n return True\n else:\n return False\n\nsentenceToTranslate = raw_input(\"Please write in the sentence you want to translate: \")\nwords = sentenceToTranslate.split(\" \")\n\nfor word in words:\n if isVowel(word[0]):\n print \"TEST\"\n\nOften you will put the function definitions in another file, and import them to avoid these problems.\n",
"Here are a couple of other points to make for a newbie Pythoner:\n1) What is the point of writing this?\ndef isVowel():\n if boolean-expression:\n return True\n else:\n return False\n\nYou already have the True/False-ness captured in the value of the boolean expression, just:\ndef isVowel():\n return boolean-expression\n\n2) Function calls are performance killers. Especially when you have such a limited set of items to check for, instead of calling .lower() so that you can check against \"aeiou\", check the character itself against both the lower and upper case letters, \"aeiouAEIOU\". Even though this is twice the length string to test for membership, it saves us the call to the lower() function.\nHere are some performance test results:\nimport time\nimport string\ntime.clock()\n\nreps = 100000\ntestString = (string.uppercase + string.lowercase) * reps\n\nstart = time.clock()\nfor c in testString:\n answer = c.lower() in \"aeiou\"\nend = time.clock()\nprint end-start\n\nstart = time.clock()\nfor c in testString:\n answer = c in \"aeiouAEIOU\"\nend = time.clock()\nprint end-start\n\nstart = time.clock()\nfor c in testString:\n pass\nend = time.clock()\n\nPrints:\n3.27782246068\n1.76839123408\n0.713913919227\n\nThe third loop shows the time it takes just to iterate over the testString itself, so the time spent in the body of the loop (assuming pass takes negligible time) is:\n2.563908541\n1.054477315\n\nBy avoiding the lower() call, the second technique is more than twice as fast.\n"
] |
[
5,
2,
1,
1,
0,
0
] |
[] |
[] |
[
"function",
"python"
] |
stackoverflow_0002489273_function_python.txt
|
Q:
Will Python 3 ever catch on?
I have been learning a bit of Python 2 and Python 3 and it seems like Python 2 is overall better than Python 3. So that's where my question comes in. Are there any good reasons to actually switch over to python 3?
A:
On the whole, and even in most details, Python3 is better than Python2.
The only area where Python 3 is lagging is with regards to 3rd party libraries. What makes Python great is not only its intrinsic characteristics as a language and its rather extensive standard library, but also the existence of a whole "eco-system" of libraries which support so many specific applications of the language.
Several such libraries are, at the moment not fully ported to Python 3.x and this sometimes results in keeping people developing under Python 2.x.
This situation may seem a bit like a chicken and egg problem: Application developers won't move to 3.x till the libraries "get there", libraries developers would rather only maintain one branch and are waiting in an attempt to time the porting to Py3k in a way that they can put the their Py2.x branches in maintenance shortly thereafter.
This situation is somewhat of a testimony the satisfaction people have of Python 2.x (or phrased more negatively, to the lack of truly compelling incentives for a move to 3.x; while Py3k is better and poised for better things yet, as-is, it doesn't have any features that would prompt a move to 3.x "en masse".) This said, I believe the momentum is effectively in favor of Python 3.
To back this up, I was about to mention the likelihood that Unladen Swallow be only ported to Py3k-only, providing some strong incentive for the move. But Alex Martelli has started answering this question, and is using this example. Obviously Alex speaks first-hand of these roadmap questions, please get it from the Master!
A word of caution regarding Py3k versions: Be sure to use the most recent version (currently 3.1.2, soon 3.2.x will replace it as the most recent stable version). Beware that some folks (like me) occasionally use the expression "3.0" to reference the generic name for all Py3k (or even for the current version thereof). The short lived 3.0 version per-se is now "defunct" and of no interest but maybe forensic specialists ;-)
A:
As other answers mention, the only real (and crucial) current advantage of Python 2 over Python 3 is that the former already has a huge wealth of third-party extensions (and auxiliary tools, such as IDEs and the like), which the latter is only gradually moving towards. This is a situation that's gradually improving, as existing extensions are ported to support Python 3; sooner or later somebody will release a Py3-only extension or tool that's important to you, and that might tip you over to actually using Py3 for a new project (and that will happen for many different values of "you";-).
Python core development has mostly shifted to the Python 3 area -- while Python 2.7 will be out soon, I'm not sure how many future important enhancements, if any, will keep getting backported to Python 2 versions. In particular, I doubt that Unladen Swallow will be -- if that's the case, then at some point CPython 3 will gain an important speed advantage over CPython 2, which will be the tipping-over factor for other new projects (and ports of existing projects) yet.
Not sure what gives you the impression that "Python 2 is over all better than Python 3", in terms, of course, of just "Python proper", i.e., the parts that the Python Software Foundation is releasing (core code, libraries, docs...): I strongly disagree with this assessment. Python 3 is better in terms of simplicity (cruft removal) and in having a few features that enable future third-party extensions and tools (such as better metaclass interaction, and syntax for parameter annoutation); I cannot find, in fact, any advantages for Python 2 in terms of "Python proper". The "ecosystem" around Python, as already discussed, is another thing, but that's already progressing (at its own pace, of course, which is definitely not under the control of the Python Software Foundation, but rather of many external groups of developers and a few firms).
For example, PyQt is already available for Python 3 (as well as 2), and you can use PostgreSQL (a splendid open-source SQL database engine, much more standard than MySql) via py-postgresql. So, if the third party extensions you're pining for are (say) wxpython and mysqldb, perhaps you can try these alternatives (I'm biased, of course, since I've long preferred Qt to wxWidgets, and PostgreSQL to MySQL, on purely technical grounds -- but the prompt porting of the related Python extensions to Python 3 does also hint that these extensions are being more actively and vigorously developed, so that might be another nudge to try them;-).
A:
Python 3 is going to be the new standard going forward.
As no major sweeping changes are planned to Python 3 anytime soon, more people will eventually be moving to it. So... although there are many Python 2 applications around now, eventually many of these applications will be migrated up. There is even at tool for this, 2to3.
Also, what makes you say that python 2 is better than 3? There were many language improvements made in Python 3, and even IDLE is improved. One major reason to upgrade is that unladen-swallow is coming to python 3, which will vastly improve performance.
A:
The main thing holding Python 3.x back right now is the lack of third-party libraries. I'll be converting my code as soon as SciPy gets ported.
A:
More iterators (in things like dict.keys()) will be a big boost for web applications.
The core team will put more work into the new version. New books might focus on python 3 (see Dive into Python), but the real work is still done in python 2.
Sooner or later, the big libraries (numpy, wx, django) will be ported. Until those big three switch, I can't see many people using python 3. But those aren't impossible projects to port.
Once the big libraries are ported, the community will face a real choice. That's when it will start to catch on.
|
Will Python 3 ever catch on?
|
I have been learning a bit of Python 2 and Python 3 and it seems like Python 2 is overall better than Python 3. So that's where my question comes in. Are there any good reasons to actually switch over to python 3?
|
[
"On the whole, and even in most details, Python3 is better than Python2.\nThe only area where Python 3 is lagging is with regards to 3rd party libraries. What makes Python great is not only its intrinsic characteristics as a language and its rather extensive standard library, but also the existence of a whole \"eco-system\" of libraries which support so many specific applications of the language.\nSeveral such libraries are, at the moment not fully ported to Python 3.x and this sometimes results in keeping people developing under Python 2.x.\nThis situation may seem a bit like a chicken and egg problem: Application developers won't move to 3.x till the libraries \"get there\", libraries developers would rather only maintain one branch and are waiting in an attempt to time the porting to Py3k in a way that they can put the their Py2.x branches in maintenance shortly thereafter.\nThis situation is somewhat of a testimony the satisfaction people have of Python 2.x (or phrased more negatively, to the lack of truly compelling incentives for a move to 3.x; while Py3k is better and poised for better things yet, as-is, it doesn't have any features that would prompt a move to 3.x \"en masse\".) This said, I believe the momentum is effectively in favor of Python 3. \nTo back this up, I was about to mention the likelihood that Unladen Swallow be only ported to Py3k-only, providing some strong incentive for the move. But Alex Martelli has started answering this question, and is using this example. Obviously Alex speaks first-hand of these roadmap questions, please get it from the Master!\nA word of caution regarding Py3k versions: Be sure to use the most recent version (currently 3.1.2, soon 3.2.x will replace it as the most recent stable version). Beware that some folks (like me) occasionally use the expression \"3.0\" to reference the generic name for all Py3k (or even for the current version thereof). The short lived 3.0 version per-se is now \"defunct\" and of no interest but maybe forensic specialists ;-)\n",
"As other answers mention, the only real (and crucial) current advantage of Python 2 over Python 3 is that the former already has a huge wealth of third-party extensions (and auxiliary tools, such as IDEs and the like), which the latter is only gradually moving towards. This is a situation that's gradually improving, as existing extensions are ported to support Python 3; sooner or later somebody will release a Py3-only extension or tool that's important to you, and that might tip you over to actually using Py3 for a new project (and that will happen for many different values of \"you\";-).\nPython core development has mostly shifted to the Python 3 area -- while Python 2.7 will be out soon, I'm not sure how many future important enhancements, if any, will keep getting backported to Python 2 versions. In particular, I doubt that Unladen Swallow will be -- if that's the case, then at some point CPython 3 will gain an important speed advantage over CPython 2, which will be the tipping-over factor for other new projects (and ports of existing projects) yet.\nNot sure what gives you the impression that \"Python 2 is over all better than Python 3\", in terms, of course, of just \"Python proper\", i.e., the parts that the Python Software Foundation is releasing (core code, libraries, docs...): I strongly disagree with this assessment. Python 3 is better in terms of simplicity (cruft removal) and in having a few features that enable future third-party extensions and tools (such as better metaclass interaction, and syntax for parameter annoutation); I cannot find, in fact, any advantages for Python 2 in terms of \"Python proper\". The \"ecosystem\" around Python, as already discussed, is another thing, but that's already progressing (at its own pace, of course, which is definitely not under the control of the Python Software Foundation, but rather of many external groups of developers and a few firms).\nFor example, PyQt is already available for Python 3 (as well as 2), and you can use PostgreSQL (a splendid open-source SQL database engine, much more standard than MySql) via py-postgresql. So, if the third party extensions you're pining for are (say) wxpython and mysqldb, perhaps you can try these alternatives (I'm biased, of course, since I've long preferred Qt to wxWidgets, and PostgreSQL to MySQL, on purely technical grounds -- but the prompt porting of the related Python extensions to Python 3 does also hint that these extensions are being more actively and vigorously developed, so that might be another nudge to try them;-).\n",
"Python 3 is going to be the new standard going forward. \nAs no major sweeping changes are planned to Python 3 anytime soon, more people will eventually be moving to it. So... although there are many Python 2 applications around now, eventually many of these applications will be migrated up. There is even at tool for this, 2to3.\nAlso, what makes you say that python 2 is better than 3? There were many language improvements made in Python 3, and even IDLE is improved. One major reason to upgrade is that unladen-swallow is coming to python 3, which will vastly improve performance.\n",
"The main thing holding Python 3.x back right now is the lack of third-party libraries. I'll be converting my code as soon as SciPy gets ported.\n",
"More iterators (in things like dict.keys()) will be a big boost for web applications.\nThe core team will put more work into the new version. New books might focus on python 3 (see Dive into Python), but the real work is still done in python 2.\nSooner or later, the big libraries (numpy, wx, django) will be ported. Until those big three switch, I can't see many people using python 3. But those aren't impossible projects to port.\nOnce the big libraries are ported, the community will face a real choice. That's when it will start to catch on.\n"
] |
[
32,
18,
7,
6,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0002489299_python_python_3.x.txt
|
Q:
Unit testing in python?
Hey - I'm new to python , and I'm having a hard time grasping the concept of Unit testing in python.
I'm coming from Java - so unit testing makes sense because - well , there you actually have a unit - A Class. But a Python class is not necessarily the same as a Java class , and the way I use Python - as a scripting language - is more functional then OOP - So what do you "unit test" in Python ? A flow?
Thanks!
A:
Python has a unit test module that I like. You can also read unit test section of Dive Into Python.
Heres a basic example from the (linked) documentation:
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
if __name__ == '__main__':
unittest.main()
A:
If you make functional programming then the unit is the function and I would recommend to unit test your functions
A:
For quick and simple testing, you might like to have a look at doctests.
To write the tests, you place things that look like interactive interpreter sessions in a docstring:
def my_function(n):
"""Return n + 5
>>> my_function(500)
505"""
return n + 5
to run the test, you import doctest and run doctest.testmod() which will run all the doctests in the module. You can also use doctest.testfile("...") to run all the tests in some other file.
If you check the documentation for doctests you will find ways to make a test expect exceptions, lists, etc -- anything the interpreter would output, plus some wildcards for brevity.
This is a quick way to write tests in Python modules, there isn't a lot of boilerplate code, and IMO it's easier to keep them up to date (the test is right there in the function!). But I also find them a little ugly.
A:
I wrote a post about unit testing in IronPython - it works same as in other Python flavors as well.
Have a look at these projects as well:
unittest — Unit testing framework
python-nose - Test discovery tool
|
Unit testing in python?
|
Hey - I'm new to python , and I'm having a hard time grasping the concept of Unit testing in python.
I'm coming from Java - so unit testing makes sense because - well , there you actually have a unit - A Class. But a Python class is not necessarily the same as a Java class , and the way I use Python - as a scripting language - is more functional then OOP - So what do you "unit test" in Python ? A flow?
Thanks!
|
[
"Python has a unit test module that I like. You can also read unit test section of Dive Into Python.\nHeres a basic example from the (linked) documentation:\nimport random\nimport unittest\n\nclass TestSequenceFunctions(unittest.TestCase):\n\n def setUp(self):\n self.seq = range(10)\n\n def test_shuffle(self):\n # make sure the shuffled sequence does not lose any elements\n random.shuffle(self.seq)\n self.seq.sort()\n self.assertEqual(self.seq, range(10))\n\n # should raise an exception for an immutable sequence\n self.assertRaises(TypeError, random.shuffle, (1,2,3))\n\n def test_choice(self):\n element = random.choice(self.seq)\n self.assertTrue(element in self.seq)\n\n def test_sample(self):\n with self.assertRaises(ValueError):\n random.sample(self.seq, 20)\n for element in random.sample(self.seq, 5):\n self.assertTrue(element in self.seq)\n\nif __name__ == '__main__':\n unittest.main()\n\n",
"If you make functional programming then the unit is the function and I would recommend to unit test your functions\n",
"For quick and simple testing, you might like to have a look at doctests.\nTo write the tests, you place things that look like interactive interpreter sessions in a docstring:\ndef my_function(n):\n \"\"\"Return n + 5\n\n >>> my_function(500)\n 505\"\"\"\n return n + 5\n\nto run the test, you import doctest and run doctest.testmod() which will run all the doctests in the module. You can also use doctest.testfile(\"...\") to run all the tests in some other file.\nIf you check the documentation for doctests you will find ways to make a test expect exceptions, lists, etc -- anything the interpreter would output, plus some wildcards for brevity.\nThis is a quick way to write tests in Python modules, there isn't a lot of boilerplate code, and IMO it's easier to keep them up to date (the test is right there in the function!). But I also find them a little ugly.\n",
"I wrote a post about unit testing in IronPython - it works same as in other Python flavors as well.\nHave a look at these projects as well:\n\nunittest — Unit testing framework\npython-nose - Test discovery tool\n\n"
] |
[
9,
5,
5,
3
] |
[] |
[] |
[
"python",
"unit_testing"
] |
stackoverflow_0002490715_python_unit_testing.txt
|
Q:
Python: Retrieve Image from MSSQL
I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image!
The following is my code:
#!/usr/bin/python
import _mssql
mssql=_mssql.connect('<ServerIP>','<UserID>','<Password>')
mssql.select_db('<Database>')
x=1
while x==1:
query="select TOP 1 * from table;"
if mssql.query(query):
rows=mssql.fetch_array()
rowNumbers = rows[0][1]
#print "Number of rows fetched: " + str(rowNumbers)
for row in rows:
for i in range(rowNumbers):
FILE=open('/home/images/' + str(row[2][i][1]) + '-' + str(row[2][i][2]).strip() + ' (' + str(row[2][i][0]) + ').jpg','wb')
FILE.write(row[2][i][4])
FILE.close()
print 'Successfully downloaded image: ' + str(row[2][i][0]) + '\t' + str(row[2][i][2]).strip() + '\t' + str(row[2][i][1])
else:
print mssql.errmsg()
print mssql.stdmsg()
mssql.close()
A:
It's kind of hard to tell what the problem is when you're using a database like this. Your query isn't explicitly selecting any columns, so we have no idea what your table structure is, or what types the columns are. I suspect the table format is not what you're expecting, or the columntype is incorrect for your data.
Also your code doesn't even look like it would run. You have "for row in rows:" and then don't indent after that. Maybe post your schema?
A:
If your using freetds (I think you are): Search in your freetds.conf for the 'text size' setting.. standard its at 63 kb
|
Python: Retrieve Image from MSSQL
|
I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image!
The following is my code:
#!/usr/bin/python
import _mssql
mssql=_mssql.connect('<ServerIP>','<UserID>','<Password>')
mssql.select_db('<Database>')
x=1
while x==1:
query="select TOP 1 * from table;"
if mssql.query(query):
rows=mssql.fetch_array()
rowNumbers = rows[0][1]
#print "Number of rows fetched: " + str(rowNumbers)
for row in rows:
for i in range(rowNumbers):
FILE=open('/home/images/' + str(row[2][i][1]) + '-' + str(row[2][i][2]).strip() + ' (' + str(row[2][i][0]) + ').jpg','wb')
FILE.write(row[2][i][4])
FILE.close()
print 'Successfully downloaded image: ' + str(row[2][i][0]) + '\t' + str(row[2][i][2]).strip() + '\t' + str(row[2][i][1])
else:
print mssql.errmsg()
print mssql.stdmsg()
mssql.close()
|
[
"It's kind of hard to tell what the problem is when you're using a database like this. Your query isn't explicitly selecting any columns, so we have no idea what your table structure is, or what types the columns are. I suspect the table format is not what you're expecting, or the columntype is incorrect for your data.\nAlso your code doesn't even look like it would run. You have \"for row in rows:\" and then don't indent after that. Maybe post your schema?\n",
"If your using freetds (I think you are): Search in your freetds.conf for the 'text size' setting.. standard its at 63 kb\n"
] |
[
1,
0
] |
[] |
[] |
[
"file_io",
"python",
"sql_server"
] |
stackoverflow_0000691288_file_io_python_sql_server.txt
|
Q:
Consecutive, Overlapping Subsets of Array (NumPy, Python)
I have a NumPy array [1,2,3,4,5,6,7,8,9,10,11,12,13,14] and want to have an array structured like [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]].
Sure this is possible by looping over the large array and adding arrays of length four to the new array, but I'm curious if there is some secret 'magic' Python method doing just this :)
A:
You should use stride_tricks. When I first saw this, the word 'magic' did spring to mind. It's simple and is by far the fastest method.
>>> as_strided = numpy.lib.stride_tricks.as_strided
>>> a = numpy.arange(1,15)
>>> a
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
>>> b = as_strided(a, (11,4), a.strides*2)
>>> b
array([[ 1, 2, 3, 4],
[ 2, 3, 4, 5],
[ 3, 4, 5, 6],
[ 4, 5, 6, 7],
[ 5, 6, 7, 8],
[ 6, 7, 8, 9],
[ 7, 8, 9, 10],
[ 8, 9, 10, 11],
[ 9, 10, 11, 12],
[10, 11, 12, 13],
[11, 12, 13, 14]])
Be aware that the values in array b are those in a, just viewed differently. Do a .copy() on b if you plan to modify it.
I saw this at a SciPy conference. Here are the slides for more explanation.
A:
The fastest way seems to be to preallocate the array, given as option 7 right at the bottom of this answer.
>>> import numpy as np
>>> A=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14])
>>> A
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
>>> np.array(zip(A,A[1:],A[2:],A[3:]))
array([[ 1, 2, 3, 4],
[ 2, 3, 4, 5],
[ 3, 4, 5, 6],
[ 4, 5, 6, 7],
[ 5, 6, 7, 8],
[ 6, 7, 8, 9],
[ 7, 8, 9, 10],
[ 8, 9, 10, 11],
[ 9, 10, 11, 12],
[10, 11, 12, 13],
[11, 12, 13, 14]])
>>>
You can easily adapt this to do it for variable chunk size.
>>> n=5
>>> np.array(zip(*(A[i:] for i in range(n))))
array([[ 1, 2, 3, 4, 5],
[ 2, 3, 4, 5, 6],
[ 3, 4, 5, 6, 7],
[ 4, 5, 6, 7, 8],
[ 5, 6, 7, 8, 9],
[ 6, 7, 8, 9, 10],
[ 7, 8, 9, 10, 11],
[ 8, 9, 10, 11, 12],
[ 9, 10, 11, 12, 13],
[10, 11, 12, 13, 14]])
You may wish to compare performance between this and using itertools.islice.
>>> from itertools import islice
>>> n=4
>>> np.array(zip(*[islice(A,i,None) for i in range(n)]))
array([[ 1, 2, 3, 4],
[ 2, 3, 4, 5],
[ 3, 4, 5, 6],
[ 4, 5, 6, 7],
[ 5, 6, 7, 8],
[ 6, 7, 8, 9],
[ 7, 8, 9, 10],
[ 8, 9, 10, 11],
[ 9, 10, 11, 12],
[10, 11, 12, 13],
[11, 12, 13, 14]])
My timing results:
1. timeit np.array(zip(A,A[1:],A[2:],A[3:]))
10000 loops, best of 3: 92.9 us per loop
2. timeit np.array(zip(*(A[i:] for i in range(4))))
10000 loops, best of 3: 101 us per loop
3. timeit np.array(zip(*[islice(A,i,None) for i in range(4)]))
10000 loops, best of 3: 101 us per loop
4. timeit numpy.array([ A[i:i+4] for i in range(len(A)-3) ])
10000 loops, best of 3: 37.8 us per loop
5. timeit numpy.array(list(chunks(A, 4)))
10000 loops, best of 3: 43.2 us per loop
6. timeit numpy.array(byN(A, 4))
10000 loops, best of 3: 100 us per loop
# Does preallocation of the array help? (11 is from len(A)+1-4)
7. timeit B=np.zeros(shape=(11, 4),dtype=np.int32)
100000 loops, best of 3: 2.19 us per loop
timeit for i in range(4):B[:,i]=A[i:11+i]
10000 loops, best of 3: 20.9 us per loop
total 23.1us per loop
As len(A) increases (20000) 4 and 5 converge to be equivalent speed (44 ms). 1,2,3 and 6 all remain about 3 times slower (135 ms). 7 is much faster (1.36 ms).
A:
Quick&dirty solution:
>>> a = numpy.arange(1,15)
>>> numpy.array([ a[i:i+4] for i in range(len(a)-3) ])
array([[ 1, 2, 3, 4],
[ 2, 3, 4, 5],
[ 3, 4, 5, 6],
[ 4, 5, 6, 7],
[ 5, 6, 7, 8],
[ 6, 7, 8, 9],
[ 7, 8, 9, 10],
[ 8, 9, 10, 11],
[ 9, 10, 11, 12],
[10, 11, 12, 13],
[11, 12, 13, 14]])
A:
Using itertools, and assuming Python 2.6:
import itertools
def byN(iterable, N):
itrs = itertools.tee(iter(iterable), N)
for n in range(N):
for i in range(n):
next(itrs[n], None)
return zip(*itrs)
aby4 = numpy.array(byN(thearray, 4))
A:
Broadcast!
from numpy import ogrid
def stretch(N=5,M=15):
x, y = ogrid[0:M,0:N]
return x+y+1
Note that ogrid does give things like:
>> ogrid[0:5,0:5]
>>
[array([[0],
[1],
[2],
[3],
[4]]),
array([[0, 1, 2, 3, 4]])]
Let's compare with another solution given here:
def zipping(N=5,M=15):
A = numpy.arange(1, M+1)
return numpy.array(zip(*(A[i:] for i in range(N))))
comparison (python 2.6, 32 bit, 1Go RAM) gives
>>> %timeit stretch(5,15)
10000 loops, best of 3: 61.2 us per loop
>>> %timeit zipping(5,15)
10000 loops, best of 3: 72.5 us per loop
>>> %timeit stretch(5,1e3)
10000 loops, best of 3: 128 us per loop
>>> %timeit zipping(5,1e3)
100 loops, best of 3: 4.25 ms per loop
The 40-fold speed-up is kind of consistant to scaling.
A:
I know of no Python stdlib function that quite does that. It's easy enough to do. Here is a generator that basically does it:
def chunks(sequence, length):
for index in xrange(0, len(sequence) - length + 1):
yield sequence[index:index + length]
You could use it like so
>>> import numpy
>>> a = numpy.arange(1, 15)
>>> a
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
>>> numpy.array(list(chunks(a, 4)))
array([[ 1, 2, 3, 4],
[ 2, 3, 4, 5],
[ 3, 4, 5, 6],
[ 4, 5, 6, 7],
[ 5, 6, 7, 8],
[ 6, 7, 8, 9],
[ 7, 8, 9, 10],
[ 8, 9, 10, 11],
[ 9, 10, 11, 12],
[10, 11, 12, 13],
[11, 12, 13, 14]])
The only weird thing about this code is that I called list on the result of chunks(a, 4). This is since numpy.array does not accept an arbitrary iterable, such as the generator chunks returns. If you just want to iterate over these chunks, you don't need to bother. If you really need to put the result into an array you can do it this way or some more efficient ways.
A:
The efficient NumPy way to do this is given here, which is somewhat too long to reproduce here. It boils down to using some stride tricks, and is much faster than itertools for largish window sizes. For example, using a method essentially the same as that of of Alex Martelli's:
In [16]: def windowed(sequence, length):
seqs = tee(sequence, length)
[ seq.next() for i, seq in enumerate(seqs) for j in xrange(i) ]
return zip(*seqs)
We get:
In [19]: data = numpy.random.randint(0, 2, 1000000)
In [20]: %timeit windowed(data, 2)
100000 loops, best of 3: 6.62 us per loop
In [21]: %timeit windowed(data, 10)
10000 loops, best of 3: 29.3 us per loop
In [22]: %timeit windowed(data, 100)
1000 loops, best of 3: 1.41 ms per loop
In [23]: %timeit segment_axis(data, 2, 1)
10000 loops, best of 3: 30.1 us per loop
In [24]: %timeit segment_axis(data, 10, 9)
10000 loops, best of 3: 30.2 us per loop
In [25]: %timeit segment_axis(data, 100, 99)
10000 loops, best of 3: 30.5 us per loop
|
Consecutive, Overlapping Subsets of Array (NumPy, Python)
|
I have a NumPy array [1,2,3,4,5,6,7,8,9,10,11,12,13,14] and want to have an array structured like [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]].
Sure this is possible by looping over the large array and adding arrays of length four to the new array, but I'm curious if there is some secret 'magic' Python method doing just this :)
|
[
"You should use stride_tricks. When I first saw this, the word 'magic' did spring to mind. It's simple and is by far the fastest method.\n>>> as_strided = numpy.lib.stride_tricks.as_strided\n>>> a = numpy.arange(1,15)\n>>> a\narray([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])\n>>> b = as_strided(a, (11,4), a.strides*2)\n>>> b\narray([[ 1, 2, 3, 4],\n [ 2, 3, 4, 5],\n [ 3, 4, 5, 6],\n [ 4, 5, 6, 7],\n [ 5, 6, 7, 8],\n [ 6, 7, 8, 9],\n [ 7, 8, 9, 10],\n [ 8, 9, 10, 11],\n [ 9, 10, 11, 12],\n [10, 11, 12, 13],\n [11, 12, 13, 14]])\n\nBe aware that the values in array b are those in a, just viewed differently. Do a .copy() on b if you plan to modify it.\nI saw this at a SciPy conference. Here are the slides for more explanation.\n",
"The fastest way seems to be to preallocate the array, given as option 7 right at the bottom of this answer.\n>>> import numpy as np\n>>> A=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n>>> A\narray([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])\n>>> np.array(zip(A,A[1:],A[2:],A[3:]))\narray([[ 1, 2, 3, 4],\n [ 2, 3, 4, 5],\n [ 3, 4, 5, 6],\n [ 4, 5, 6, 7],\n [ 5, 6, 7, 8],\n [ 6, 7, 8, 9],\n [ 7, 8, 9, 10],\n [ 8, 9, 10, 11],\n [ 9, 10, 11, 12],\n [10, 11, 12, 13],\n [11, 12, 13, 14]])\n>>> \n\nYou can easily adapt this to do it for variable chunk size.\n>>> n=5\n>>> np.array(zip(*(A[i:] for i in range(n))))\narray([[ 1, 2, 3, 4, 5],\n [ 2, 3, 4, 5, 6],\n [ 3, 4, 5, 6, 7],\n [ 4, 5, 6, 7, 8],\n [ 5, 6, 7, 8, 9],\n [ 6, 7, 8, 9, 10],\n [ 7, 8, 9, 10, 11],\n [ 8, 9, 10, 11, 12],\n [ 9, 10, 11, 12, 13],\n [10, 11, 12, 13, 14]])\n\nYou may wish to compare performance between this and using itertools.islice.\n>>> from itertools import islice\n>>> n=4\n>>> np.array(zip(*[islice(A,i,None) for i in range(n)]))\narray([[ 1, 2, 3, 4],\n [ 2, 3, 4, 5],\n [ 3, 4, 5, 6],\n [ 4, 5, 6, 7],\n [ 5, 6, 7, 8],\n [ 6, 7, 8, 9],\n [ 7, 8, 9, 10],\n [ 8, 9, 10, 11],\n [ 9, 10, 11, 12],\n [10, 11, 12, 13],\n [11, 12, 13, 14]])\n\nMy timing results:\n1. timeit np.array(zip(A,A[1:],A[2:],A[3:]))\n10000 loops, best of 3: 92.9 us per loop\n\n2. timeit np.array(zip(*(A[i:] for i in range(4))))\n10000 loops, best of 3: 101 us per loop\n\n3. timeit np.array(zip(*[islice(A,i,None) for i in range(4)]))\n10000 loops, best of 3: 101 us per loop\n\n4. timeit numpy.array([ A[i:i+4] for i in range(len(A)-3) ])\n10000 loops, best of 3: 37.8 us per loop\n\n5. timeit numpy.array(list(chunks(A, 4)))\n10000 loops, best of 3: 43.2 us per loop\n\n6. timeit numpy.array(byN(A, 4))\n10000 loops, best of 3: 100 us per loop\n\n# Does preallocation of the array help? (11 is from len(A)+1-4)\n7. timeit B=np.zeros(shape=(11, 4),dtype=np.int32)\n100000 loops, best of 3: 2.19 us per loop\n timeit for i in range(4):B[:,i]=A[i:11+i]\n10000 loops, best of 3: 20.9 us per loop\ntotal 23.1us per loop\n\nAs len(A) increases (20000) 4 and 5 converge to be equivalent speed (44 ms). 1,2,3 and 6 all remain about 3 times slower (135 ms). 7 is much faster (1.36 ms).\n",
"Quick&dirty solution:\n>>> a = numpy.arange(1,15)\n>>> numpy.array([ a[i:i+4] for i in range(len(a)-3) ])\narray([[ 1, 2, 3, 4],\n [ 2, 3, 4, 5],\n [ 3, 4, 5, 6],\n [ 4, 5, 6, 7],\n [ 5, 6, 7, 8],\n [ 6, 7, 8, 9],\n [ 7, 8, 9, 10],\n [ 8, 9, 10, 11],\n [ 9, 10, 11, 12],\n [10, 11, 12, 13],\n [11, 12, 13, 14]])\n\n",
"Using itertools, and assuming Python 2.6:\nimport itertools\n\ndef byN(iterable, N):\n itrs = itertools.tee(iter(iterable), N)\n for n in range(N):\n for i in range(n):\n next(itrs[n], None)\n return zip(*itrs)\n\naby4 = numpy.array(byN(thearray, 4))\n\n",
"Broadcast!\nfrom numpy import ogrid\ndef stretch(N=5,M=15):\n x, y = ogrid[0:M,0:N]\n return x+y+1\n\nNote that ogrid does give things like:\n>> ogrid[0:5,0:5]\n>> \n[array([[0],\n [1],\n [2],\n [3],\n [4]]),\n array([[0, 1, 2, 3, 4]])]\n\nLet's compare with another solution given here:\ndef zipping(N=5,M=15):\n A = numpy.arange(1, M+1)\n return numpy.array(zip(*(A[i:] for i in range(N))))\n\ncomparison (python 2.6, 32 bit, 1Go RAM) gives\n>>> %timeit stretch(5,15)\n10000 loops, best of 3: 61.2 us per loop\n\n>>> %timeit zipping(5,15)\n10000 loops, best of 3: 72.5 us per loop\n\n>>> %timeit stretch(5,1e3)\n10000 loops, best of 3: 128 us per loop\n\n>>> %timeit zipping(5,1e3)\n100 loops, best of 3: 4.25 ms per loop\n\nThe 40-fold speed-up is kind of consistant to scaling.\n",
"I know of no Python stdlib function that quite does that. It's easy enough to do. Here is a generator that basically does it:\ndef chunks(sequence, length):\n for index in xrange(0, len(sequence) - length + 1):\n yield sequence[index:index + length]\n\nYou could use it like so\n>>> import numpy\n>>> a = numpy.arange(1, 15)\n>>> a\narray([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])\n>>> numpy.array(list(chunks(a, 4)))\narray([[ 1, 2, 3, 4],\n [ 2, 3, 4, 5],\n [ 3, 4, 5, 6],\n [ 4, 5, 6, 7],\n [ 5, 6, 7, 8],\n [ 6, 7, 8, 9],\n [ 7, 8, 9, 10],\n [ 8, 9, 10, 11],\n [ 9, 10, 11, 12],\n [10, 11, 12, 13],\n [11, 12, 13, 14]])\n\nThe only weird thing about this code is that I called list on the result of chunks(a, 4). This is since numpy.array does not accept an arbitrary iterable, such as the generator chunks returns. If you just want to iterate over these chunks, you don't need to bother. If you really need to put the result into an array you can do it this way or some more efficient ways.\n",
"The efficient NumPy way to do this is given here, which is somewhat too long to reproduce here. It boils down to using some stride tricks, and is much faster than itertools for largish window sizes. For example, using a method essentially the same as that of of Alex Martelli's:\nIn [16]: def windowed(sequence, length):\n seqs = tee(sequence, length)\n [ seq.next() for i, seq in enumerate(seqs) for j in xrange(i) ]\n return zip(*seqs)\n\nWe get:\nIn [19]: data = numpy.random.randint(0, 2, 1000000)\n\nIn [20]: %timeit windowed(data, 2)\n100000 loops, best of 3: 6.62 us per loop\nIn [21]: %timeit windowed(data, 10)\n10000 loops, best of 3: 29.3 us per loop\nIn [22]: %timeit windowed(data, 100)\n1000 loops, best of 3: 1.41 ms per loop\nIn [23]: %timeit segment_axis(data, 2, 1)\n10000 loops, best of 3: 30.1 us per loop\nIn [24]: %timeit segment_axis(data, 10, 9)\n10000 loops, best of 3: 30.2 us per loop\nIn [25]: %timeit segment_axis(data, 100, 99)\n10000 loops, best of 3: 30.5 us per loop\n\n"
] |
[
31,
17,
4,
1,
1,
0,
0
] |
[] |
[] |
[
"numpy",
"python",
"scipy"
] |
stackoverflow_0002485669_numpy_python_scipy.txt
|
Q:
Python/Django application with dynamic model name (application reuse)
excuse me in advance if this is not the right title for the problem but here it is:
You have application that works with pre defined model. What happens if you want to
use this application one more time in your project but pointing to different model (same structure but differen name).
For example - you have a "News" application that is fully working but you want to have also and articles the do the same job but you want it in different table.
I'm pretty sure that copying the whole application and renaming the Model isn`t the "pythonic" way so if someone knows how this is done please share your knowledge.
thanks in advance,
Ilian Iliev
A:
This is what abstract models are for. Define once, and all children will acquire the fields in the abstract model, plus be able to define additional fields.
|
Python/Django application with dynamic model name (application reuse)
|
excuse me in advance if this is not the right title for the problem but here it is:
You have application that works with pre defined model. What happens if you want to
use this application one more time in your project but pointing to different model (same structure but differen name).
For example - you have a "News" application that is fully working but you want to have also and articles the do the same job but you want it in different table.
I'm pretty sure that copying the whole application and renaming the Model isn`t the "pythonic" way so if someone knows how this is done please share your knowledge.
thanks in advance,
Ilian Iliev
|
[
"This is what abstract models are for. Define once, and all children will acquire the fields in the abstract model, plus be able to define additional fields.\n"
] |
[
2
] |
[] |
[] |
[
"code_reuse",
"django",
"models",
"python"
] |
stackoverflow_0002490759_code_reuse_django_models_python.txt
|
Q:
Use string as input to re.compile
I want to use a variable in a regex, like this:
variables = ['variableA','variableB']
for i in range(len(variables)):
regex = r"'('+variables[i]+')[:|=|\(](-?\d+(?:\.\d+)?)(?:\))?'"
pattern_variable = re.compile(regex)
match = re.search(pattern_variable, line)
The problem is that python adds an extra backslash character for each backslash character in my regex string (ipython), and makes my regex invalid:
In [76]: regex
Out[76]: "'('+variables[i]+')[:|=|\\(](-?\\d+(?:\\.\\d+)?)(?:\\))?'"
Any tips on how I can avoid this?
A:
No, it only displays extra backslashes so that the string could be read in again and have the correct number of backslashes. Try
print regex
and you will see the difference.
A:
There is no problem there. What you're seeing is the output of the repr() of the string. Since the repr is supposed to be more-or-less reversible back into the original object, it doubles up all backslashes, as well as escaping the type of quote used at the ends of the repr.
|
Use string as input to re.compile
|
I want to use a variable in a regex, like this:
variables = ['variableA','variableB']
for i in range(len(variables)):
regex = r"'('+variables[i]+')[:|=|\(](-?\d+(?:\.\d+)?)(?:\))?'"
pattern_variable = re.compile(regex)
match = re.search(pattern_variable, line)
The problem is that python adds an extra backslash character for each backslash character in my regex string (ipython), and makes my regex invalid:
In [76]: regex
Out[76]: "'('+variables[i]+')[:|=|\\(](-?\\d+(?:\\.\\d+)?)(?:\\))?'"
Any tips on how I can avoid this?
|
[
"No, it only displays extra backslashes so that the string could be read in again and have the correct number of backslashes. Try\nprint regex\n\nand you will see the difference.\n",
"There is no problem there. What you're seeing is the output of the repr() of the string. Since the repr is supposed to be more-or-less reversible back into the original object, it doubles up all backslashes, as well as escaping the type of quote used at the ends of the repr.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002491196_python_regex.txt
|
Q:
Enforce "spaces" or "tabs" only in python files?
In Python, is there a mean to enforce the use of spaces or tabs indentation with a per file basis ?
Well, perhaps "enforce" is too strong, more like a "recommendation".
I keep receiving patch files with mixed indentation and this is annoying... (to say the least) Python itself can tell when there is a problem, but I am searching something to do that at the editor level, like it exists for the charset.
Edit : Ok, my question wasn't clear, I am asking this because I keep receiving corrections and patches in any mix of tab/space you can imagine. I am using Mercurial as a DVCS, perhaps something exists at this level ?
A:
Tim Peters has written a nifty script called reindent.py which converts .py files to use 4-space indents and no tabs. It is available here, but check your distribution first -- it may have come bundled in an Examples or Tools directory. (On the latest LTS Ubuntu, it is provided by the python2.7-examples package.)
If you can set up a Mercurial hook you should be able to run all files through reindent.py.
By the way, if you are using unix, then your system may also have the expand (and unexpand) command, which convert all tabs to spaces (and spaces to tabs). However, in this case, I think reindent.py is the right tool.
A:
Look at the tabnanny module: — Detection of ambiguous indentation.
A:
This is something your editor should do for you. Most editors (try Notepad++ for example, it's free) will let you set whether hitting tab enters a tab character or a number of spaces. I'd recommend using two spaces instead of tab in all files (I find 4 is too much). Using spaces instead of tabs is better as it means that you can indent stuff using both the space & tab keys without worrying about messing up your files.
If you have files that have a mix it isn't hard to write your own script to convert tabs to spaces
A:
As explicited in PEP 8, never mix tabs and space. However, a file with both may just run...
As it says there:
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively.
When invoking the Python command line interpreter with the -t option, it issues
warnings about code that illegally mixes tabs and spaces. When using -tt
these warnings become errors. These options are highly recommended!
the solution is therefore to use as a default:
python -t my_mixed_code.py
To answer at the editor level, this depends on the editor, please specify!
|
Enforce "spaces" or "tabs" only in python files?
|
In Python, is there a mean to enforce the use of spaces or tabs indentation with a per file basis ?
Well, perhaps "enforce" is too strong, more like a "recommendation".
I keep receiving patch files with mixed indentation and this is annoying... (to say the least) Python itself can tell when there is a problem, but I am searching something to do that at the editor level, like it exists for the charset.
Edit : Ok, my question wasn't clear, I am asking this because I keep receiving corrections and patches in any mix of tab/space you can imagine. I am using Mercurial as a DVCS, perhaps something exists at this level ?
|
[
"Tim Peters has written a nifty script called reindent.py which converts .py files to use 4-space indents and no tabs. It is available here, but check your distribution first -- it may have come bundled in an Examples or Tools directory. (On the latest LTS Ubuntu, it is provided by the python2.7-examples package.)\nIf you can set up a Mercurial hook you should be able to run all files through reindent.py. \nBy the way, if you are using unix, then your system may also have the expand (and unexpand) command, which convert all tabs to spaces (and spaces to tabs). However, in this case, I think reindent.py is the right tool.\n",
"Look at the tabnanny module: — Detection of ambiguous indentation.\n",
"This is something your editor should do for you. Most editors (try Notepad++ for example, it's free) will let you set whether hitting tab enters a tab character or a number of spaces. I'd recommend using two spaces instead of tab in all files (I find 4 is too much). Using spaces instead of tabs is better as it means that you can indent stuff using both the space & tab keys without worrying about messing up your files.\nIf you have files that have a mix it isn't hard to write your own script to convert tabs to spaces\n",
"As explicited in PEP 8, never mix tabs and space. However, a file with both may just run...\nAs it says there:\n\nThe most popular way of indenting Python is with spaces only. The\nsecond-most popular way is with tabs only. Code indented with a mixture\nof tabs and spaces should be converted to using spaces exclusively.\nWhen invoking the Python command line interpreter with the -t option, it issues\nwarnings about code that illegally mixes tabs and spaces. When using -tt\nthese warnings become errors. These options are highly recommended!\n\n\nthe solution is therefore to use as a default:\npython -t my_mixed_code.py\n\nTo answer at the editor level, this depends on the editor, please specify!\n"
] |
[
9,
5,
2,
2
] |
[] |
[] |
[
"indentation",
"python",
"spaces",
"tabs"
] |
stackoverflow_0002490686_indentation_python_spaces_tabs.txt
|
Q:
Django Template Error : Template u'base.html' cannot be extended
I get this error when I run a django app (dpaste)
Template error
In template c:\python\projects\mycms\dpaste\templates\dpaste\base.html, error at line 1
Template u'base.html' cannot be extended, because it doesn't exist
1 {% extends "base.html" %}
But the "base.html" do exist in the template directory and it has this one line in it:
{% extends "base.html" %}
What is wrong with that?
A:
Your base.html template cannot extend itself. The problem lies there. Remove that line and replace it with valid html or other Django template tags (or extend some other template).
A:
A template can't extend itself.
A:
If you meant to say that:
{% extends "base.html" %}
is the only line in the including template, not the base template, then maybe your problem is that "base.html" is relative to the template root.
So if in settings you have:
TEMPLATE_DIRS = ("/home/me/mysite/mytemplates")
and the including template is:
/home/me/mysite/mytemplates/myapp/page.html
and the base template is:
/home/me/mysite/mytemplates/myapp/base.html
then you want to use:
{% extends "myapp/base.html" %}
At least that's what my problem was when I found this page.
|
Django Template Error : Template u'base.html' cannot be extended
|
I get this error when I run a django app (dpaste)
Template error
In template c:\python\projects\mycms\dpaste\templates\dpaste\base.html, error at line 1
Template u'base.html' cannot be extended, because it doesn't exist
1 {% extends "base.html" %}
But the "base.html" do exist in the template directory and it has this one line in it:
{% extends "base.html" %}
What is wrong with that?
|
[
"Your base.html template cannot extend itself. The problem lies there. Remove that line and replace it with valid html or other Django template tags (or extend some other template).\n",
"A template can't extend itself. \n",
"If you meant to say that:\n{% extends \"base.html\" %}\n\nis the only line in the including template, not the base template, then maybe your problem is that \"base.html\" is relative to the template root.\nSo if in settings you have:\nTEMPLATE_DIRS = (\"/home/me/mysite/mytemplates\")\n\nand the including template is:\n/home/me/mysite/mytemplates/myapp/page.html\n\nand the base template is:\n/home/me/mysite/mytemplates/myapp/base.html\n\nthen you want to use:\n{% extends \"myapp/base.html\" %}\n\nAt least that's what my problem was when I found this page.\n"
] |
[
3,
1,
1
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0001138106_django_django_templates_python.txt
|
Q:
why my code print this when i read and write
def sss(request):
handle=open('b.txt','r+')
handle.write("I AM NEW FILE")
var=handle.read();
return HttpResponse(var)
urlpatterns = patterns('',
('^$',sss),
)
1.my b.txt has nothing
2.when i run my code ,it print this :
I AM NEW FILE7 鸸?; ??x 鸸鸸v1鸸pZ€0 鸸鸸燛?鸸8N鸸鸸p 坮 愵) 犭 ?`16鸸鸸 S6鸸鸸榑 鸸? 鸸@ 鸸鸸p叠 {鸸€1鸸鸸 V 鸸鸸 @+ 爏 鸸 职 鑮 鸸鸸鸸`埤 >?) ?鸸鸸@? Z!x`%鸸p?鸸? 鸸鸸鄧鸸鸸@?`7鸸鸸鸸`? 柜 鸸鸸鑎1X 鸸鸸鸸鸸鸸?#鸸餷?鸸€0鸸(Q?鸸H?鸸P?#鸸 ' 鸸(5 ?, 7鸸啵6H宏 0??+噌? k%8除 `烋 鸸爐"繳` 鸸埻 鸸0?郤 鸸鸸鸸?爛/啊 鸸鸸鸸睾8S1`?`?鸸鸸悀0鸸 ?`??鸸繧爅 鸸餡 鸸些 鸸鸸鸸鸸鸸@]鄡HE,鸸鸸?瘅+?+鸸鸸鸸p戙 @O鸸?? 鸸鸸 37€P6蠯7鸸@= 鸸嘣 囗 ?+xP?x?如?70暡 鸸鸸鸸鸸鸸鸸 €鸸鸸鸸€ h *??x 纙1鸸鸸鸸€K 叠 鸸鹞8? ?鸸 鸸萰 鸸`?辣 @?饆 鸸鸸鸸鸸? 鸸€?鸸鸸鸸鸸鸸鄧鸸8(鸸P⒊ ?鸸? p(0B?鸸鸸嗨鸸鸸鸸鸸李 鸸鸸鸸邪 P?鸸鸸鸫 爛/爦+鸸蜣 9 鸸 楈 ?鸸鸸怱1鸸鸸恏鸸鸸鸸鸸袖 ; 鸸€?鸸€札 `?(?鸸ㄈ 鸸鸸+ 鸸栉0鸸愵 鸸鸸恾谿6 ?1谹,鸸鸸鸸 {0鸸鸸? X?鸸€D 鸸&?€?` 鸸H{ ?鸸葉Xw鸸鸸鸸皢 鸸狑 鸸鄩0缊0堩)€Q 鸸? ?鸸 ④ @?鸸鸸鸸鸸鸸 ?XA6鸸鸸? O 鸸0 h 鸸 鸸鸸李 鸸 ? j鸸鸸鸸鸸0昌 57極7@?H+ 鸸鸩 尛 `?鸸 18戙 鸸P ?噍6嗤0鸸鸸鸸楧6鸸坆 鸸a 鸸` 鸸鸸鸸鸸鸸鸸鸸惍砾 pG8s鸸鸸鸸@ ? (, 蠵 ( 鄭? 鸸╒&鸸缞鸸鐽圡7鸸繮!0[ 0m 鸸鸸鸸鸸@?発0鸸鸸鸸鸸鸸? ?鸸饗 p?pZ爦+鸸@?€\1鸸犎 0如 ?艾 鸸棱? 鸸€;鸸? 鸸鸸`? 褶 ? 鸸鸸鸸给*`7鸸@嵀 6 R 恈鸸鸸鸸鸸p?鸸饇鸸埪00^#燽 鸸鸸8褶 h €,h ? 鸸鸸x+ 鸸鸸€37鸸鸸鸸鸸`+鸸P?鸸 1 杞 鸸鸸鸸鸸惥*鸸郔6鸸李 鸸鸸h: 鸸鸸83 ? 哀犎鸸鸸0s 鸸鸸鸸鸸? 蝎p篆 鸸鸸鸸鸸鸸纞" s找( ??x Q s l??x ndies".
* If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy".
* If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies".
u ,i u i ( RE RG R5 R3 R4 ( R R< R t singular_suffixt
plural_suffix( ( s? D:\Python25\lib\site-packages\django\template\defaultfilters.pyt pluralize4 s$
c C s d d k l } | | ? S( sD Takes a phone number and converts it in to its numerical equivalent.i( t
phone2numeric( Rc R ( R R
why?
thanks
A:
The only way I can repro this is to open an existing non-empty file using 'r+' (Are you absolutely sure it's empty?). In any event, opening the file in the 'w+' mode truncates it.
A:
What middle-ware are you using? I guess that you have a lot of middle-ware installed, which explains some of the garbage.
For debugging, use a logging module to log what var was. Otherwise you can't isolate the problem, right?
Also, should you convert the string to unicode before sending it off to HttpResponse?
|
why my code print this when i read and write
|
def sss(request):
handle=open('b.txt','r+')
handle.write("I AM NEW FILE")
var=handle.read();
return HttpResponse(var)
urlpatterns = patterns('',
('^$',sss),
)
1.my b.txt has nothing
2.when i run my code ,it print this :
I AM NEW FILE7 鸸?; ??x 鸸鸸v1鸸pZ€0 鸸鸸燛?鸸8N鸸鸸p 坮 愵) 犭 ?`16鸸鸸 S6鸸鸸榑 鸸? 鸸@ 鸸鸸p叠 {鸸€1鸸鸸 V 鸸鸸 @+ 爏 鸸 职 鑮 鸸鸸鸸`埤 >?) ?鸸鸸@? Z!x`%鸸p?鸸? 鸸鸸鄧鸸鸸@?`7鸸鸸鸸`? 柜 鸸鸸鑎1X 鸸鸸鸸鸸鸸?#鸸餷?鸸€0鸸(Q?鸸H?鸸P?#鸸 ' 鸸(5 ?, 7鸸啵6H宏 0??+噌? k%8除 `烋 鸸爐"繳` 鸸埻 鸸0?郤 鸸鸸鸸?爛/啊 鸸鸸鸸睾8S1`?`?鸸鸸悀0鸸 ?`??鸸繧爅 鸸餡 鸸些 鸸鸸鸸鸸鸸@]鄡HE,鸸鸸?瘅+?+鸸鸸鸸p戙 @O鸸?? 鸸鸸 37€P6蠯7鸸@= 鸸嘣 囗 ?+xP?x?如?70暡 鸸鸸鸸鸸鸸鸸 €鸸鸸鸸€ h *??x 纙1鸸鸸鸸€K 叠 鸸鹞8? ?鸸 鸸萰 鸸`?辣 @?饆 鸸鸸鸸鸸? 鸸€?鸸鸸鸸鸸鸸鄧鸸8(鸸P⒊ ?鸸? p(0B?鸸鸸嗨鸸鸸鸸鸸李 鸸鸸鸸邪 P?鸸鸸鸫 爛/爦+鸸蜣 9 鸸 楈 ?鸸鸸怱1鸸鸸恏鸸鸸鸸鸸袖 ; 鸸€?鸸€札 `?(?鸸ㄈ 鸸鸸+ 鸸栉0鸸愵 鸸鸸恾谿6 ?1谹,鸸鸸鸸 {0鸸鸸? X?鸸€D 鸸&?€?` 鸸H{ ?鸸葉Xw鸸鸸鸸皢 鸸狑 鸸鄩0缊0堩)€Q 鸸? ?鸸 ④ @?鸸鸸鸸鸸鸸 ?XA6鸸鸸? O 鸸0 h 鸸 鸸鸸李 鸸 ? j鸸鸸鸸鸸0昌 57極7@?H+ 鸸鸩 尛 `?鸸 18戙 鸸P ?噍6嗤0鸸鸸鸸楧6鸸坆 鸸a 鸸` 鸸鸸鸸鸸鸸鸸鸸惍砾 pG8s鸸鸸鸸@ ? (, 蠵 ( 鄭? 鸸╒&鸸缞鸸鐽圡7鸸繮!0[ 0m 鸸鸸鸸鸸@?発0鸸鸸鸸鸸鸸? ?鸸饗 p?pZ爦+鸸@?€\1鸸犎 0如 ?艾 鸸棱? 鸸€;鸸? 鸸鸸`? 褶 ? 鸸鸸鸸给*`7鸸@嵀 6 R 恈鸸鸸鸸鸸p?鸸饇鸸埪00^#燽 鸸鸸8褶 h €,h ? 鸸鸸x+ 鸸鸸€37鸸鸸鸸鸸`+鸸P?鸸 1 杞 鸸鸸鸸鸸惥*鸸郔6鸸李 鸸鸸h: 鸸鸸83 ? 哀犎鸸鸸0s 鸸鸸鸸鸸? 蝎p篆 鸸鸸鸸鸸鸸纞" s找( ??x Q s l??x ndies".
* If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy".
* If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies".
u ,i u i ( RE RG R5 R3 R4 ( R R< R t singular_suffixt
plural_suffix( ( s? D:\Python25\lib\site-packages\django\template\defaultfilters.pyt pluralize4 s$
c C s d d k l } | | ? S( sD Takes a phone number and converts it in to its numerical equivalent.i( t
phone2numeric( Rc R ( R R
why?
thanks
|
[
"The only way I can repro this is to open an existing non-empty file using 'r+' (Are you absolutely sure it's empty?). In any event, opening the file in the 'w+' mode truncates it.\n",
"What middle-ware are you using? I guess that you have a lot of middle-ware installed, which explains some of the garbage.\nFor debugging, use a logging module to log what var was. Otherwise you can't isolate the problem, right?\nAlso, should you convert the string to unicode before sending it off to HttpResponse? \n"
] |
[
3,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002491511_django_python.txt
|
Q:
Find multiple regex in each line and skip result if one of the regex doesn't match
I have a list of variables:
variables = ['VariableA', 'VariableB','VariableC']
which I'm going to search for, line by line
ifile = open("temp.txt",'r')
d = {}
match = zeros(len(variables))
for line in ifile:
emptyCells=0
for i in range(len(variables)):
regex = r'('+variables[i]+r')[:|=|\(](-?\d+(?:\.\d+)?)(?:\))?'
pattern_variable = re.compile(regex)
match[i] = re.findall(pattern_variable, line)
if match[j] == []:
emptyCells = emptyCells+1
if emptyCells == 0:
for k, v in match[j]:
d.setdefault(k, []).append(v)
The requirement is that I will only keep the lines where all the regex'es matches!
I want to collect all results for each variable in a dictionary where the variable name is the key, and the value becomes a list of all matches.
The code provided is only what I've found out so far, and is not working perfectly yet...
A:
Can you edit your question to give an example of the source file, so we could test our solutions against it?
Anyway here's a quick hack:
from collections import defaultdict
import re
variables = ['VariableA', 'VariableB', 'VariableC']
regexes = [re.compile(r'(%s)[:|=|\(](-?\d+(?:\.\d+)?)(?:\))?' % (variable,))
for variable in variables]
d = defaultdict(list)
with open("temp.txt") as f:
for line in f:
results = [regex.search(line) for regex in regexes]
if all(results):
for m in results:
k, v = m.groups()
d[k].append(v)
print d
|
Find multiple regex in each line and skip result if one of the regex doesn't match
|
I have a list of variables:
variables = ['VariableA', 'VariableB','VariableC']
which I'm going to search for, line by line
ifile = open("temp.txt",'r')
d = {}
match = zeros(len(variables))
for line in ifile:
emptyCells=0
for i in range(len(variables)):
regex = r'('+variables[i]+r')[:|=|\(](-?\d+(?:\.\d+)?)(?:\))?'
pattern_variable = re.compile(regex)
match[i] = re.findall(pattern_variable, line)
if match[j] == []:
emptyCells = emptyCells+1
if emptyCells == 0:
for k, v in match[j]:
d.setdefault(k, []).append(v)
The requirement is that I will only keep the lines where all the regex'es matches!
I want to collect all results for each variable in a dictionary where the variable name is the key, and the value becomes a list of all matches.
The code provided is only what I've found out so far, and is not working perfectly yet...
|
[
"Can you edit your question to give an example of the source file, so we could test our solutions against it?\nAnyway here's a quick hack:\nfrom collections import defaultdict\nimport re\n\nvariables = ['VariableA', 'VariableB', 'VariableC']\nregexes = [re.compile(r'(%s)[:|=|\\(](-?\\d+(?:\\.\\d+)?)(?:\\))?' % (variable,))\n for variable in variables]\nd = defaultdict(list)\n\nwith open(\"temp.txt\") as f:\n for line in f:\n results = [regex.search(line) for regex in regexes]\n if all(results):\n for m in results:\n k, v = m.groups()\n d[k].append(v)\n\nprint d\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002491778_python_regex.txt
|
Q:
Use URL Fetch of Google App Engine just to call a php script
I wanto call a PHP script using Google App Engine. I just want to execute the script. The script updates a couple of databases on my webhost. But I guess Google App waits for the response. Is there a way by which I can start the script.
The script takes some time and Google App might die during that time.
A:
Can you not modify the PHP script to simply execute a background task, and return a 200 confirmation? In any case, if simply issuing a GET to that script will start a task, you can do that with AppEngine with an asynchronous URLFetch (http://code.google.com/appengine/docs/python/urlfetch/asynchronousrequests.html) and simply wrap the call in a try/except and ignore the exception.
A:
Just do a URLFetch request. If the PHP page takes longer than 10 seconds to return, that doesn't matter (presuming you don't care about the response) - it'll complete execution anyway.
If you wish, you can do an asynchronous http request to avoid waiting for completion.
A:
Why not rewrite what your php script does in python?
Php is a awful scripting language, and considering your thinking about calling it from inside a very powerful language, why not do it all in python
|
Use URL Fetch of Google App Engine just to call a php script
|
I wanto call a PHP script using Google App Engine. I just want to execute the script. The script updates a couple of databases on my webhost. But I guess Google App waits for the response. Is there a way by which I can start the script.
The script takes some time and Google App might die during that time.
|
[
"Can you not modify the PHP script to simply execute a background task, and return a 200 confirmation? In any case, if simply issuing a GET to that script will start a task, you can do that with AppEngine with an asynchronous URLFetch (http://code.google.com/appengine/docs/python/urlfetch/asynchronousrequests.html) and simply wrap the call in a try/except and ignore the exception.\n",
"Just do a URLFetch request. If the PHP page takes longer than 10 seconds to return, that doesn't matter (presuming you don't care about the response) - it'll complete execution anyway.\nIf you wish, you can do an asynchronous http request to avoid waiting for completion.\n",
"Why not rewrite what your php script does in python?\nPhp is a awful scripting language, and considering your thinking about calling it from inside a very powerful language, why not do it all in python\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002490592_google_app_engine_python.txt
|
Q:
How App Engine application can get a list of instance developers
How Google App instance can get the list of developers (like in Administration > Developers).
Hard-coding developer's email is a bad idea because nothing lasts forever.
I would like to get a solution in python (because I don't know java).
A:
There's no way to do this programmatically, currently. If you only need to email all the admins, however, you can use send_mail_to_admins.
|
How App Engine application can get a list of instance developers
|
How Google App instance can get the list of developers (like in Administration > Developers).
Hard-coding developer's email is a bad idea because nothing lasts forever.
I would like to get a solution in python (because I don't know java).
|
[
"There's no way to do this programmatically, currently. If you only need to email all the admins, however, you can use send_mail_to_admins.\n"
] |
[
2
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002488910_google_app_engine_python.txt
|
Q:
Python XML + Java XML interoperability
I need a recommendation for a pythonic library that can marshall python objects to XML(let it be a file).
I need to be able read that XML later on with Java (JAXB) and unmarshall it.
I know JAXB has some issues that makes it not play nice with .NET XML libraries so a recommendation on something that actually works would be great.
A:
As Ignacio says, XML is XML. On the python side, I recommend using lxml, unless you have more specific needs that are better met by another library. If you are restricted to the standard library, look at ElementTree or cElementTree, which are also excellent, and which inspired (and are functionally mostly equivalent to) lxml.etree.
Edit: On closer look, it seems you are not just looking for XML, but for XML representations of objects. For this, check out lxml.objectify, or Amara. I haven't tried using them for interoperability with Java, but they're worth a try. If you're just looking for a way to do data exchange, you might also try custom JSON objects.
A:
The issue your are probably having is the default format of the Python and Java libraries you are using to marshal your objects. Any decent libraries including JAXB allows customisation of how objects should be represented in XML.
You need to decide what the structure of your XML should be then use your libraries features to consume and emit your XML structure rather than relying on the defaults which would never be the same across different libraries in different programming languages.
|
Python XML + Java XML interoperability
|
I need a recommendation for a pythonic library that can marshall python objects to XML(let it be a file).
I need to be able read that XML later on with Java (JAXB) and unmarshall it.
I know JAXB has some issues that makes it not play nice with .NET XML libraries so a recommendation on something that actually works would be great.
|
[
"As Ignacio says, XML is XML. On the python side, I recommend using lxml, unless you have more specific needs that are better met by another library. If you are restricted to the standard library, look at ElementTree or cElementTree, which are also excellent, and which inspired (and are functionally mostly equivalent to) lxml.etree.\nEdit: On closer look, it seems you are not just looking for XML, but for XML representations of objects. For this, check out lxml.objectify, or Amara. I haven't tried using them for interoperability with Java, but they're worth a try. If you're just looking for a way to do data exchange, you might also try custom JSON objects.\n",
"The issue your are probably having is the default format of the Python and Java libraries you are using to marshal your objects. Any decent libraries including JAXB allows customisation of how objects should be represented in XML.\nYou need to decide what the structure of your XML should be then use your libraries features to consume and emit your XML structure rather than relying on the defaults which would never be the same across different libraries in different programming languages. \n"
] |
[
1,
0
] |
[] |
[] |
[
"interop",
"java",
"marshalling",
"python",
"xml"
] |
stackoverflow_0002492490_interop_java_marshalling_python_xml.txt
|
Q:
meaning of the returned list of python json
I'm new to python so I really don't know the language very well.
the following example was taken from here http://docs.python.org/library/json.html
>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
what does the u mean? and how do i know which elements are available in the dictionary?
A:
It's a unicode. Iterating over the dict yields its keys:
for k in D:
print k, D[k]
A:
Ignacio's answer a bit more verbose (no upvotes to me)
u'something' means that 'something' is a unicode string, and not for instance an ascii string. Generally text is encoded as 8-bit characters, and you need an encoding to properly interpret/display it. Unicode is 16-bit and doesn't need seperate encodings for the various locale dependent characters.
In a dictionary (enclosed by {}) the key is the part before the ":" and the value comes after.
You got a list, with elements:
foo, a Unicode string
a dictionary containing:
a key (unicode) "bar", and accessible through that key a list with values
unicode string baz,
None
a float 1.0
an integer 2
A:
The python type function can be useful here.
>>> import json
>>> data = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
>>> data
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> type(data)
<type 'list'>
>>> type(data[0])
<type 'unicode'>
>>> type(data[1])
<type 'dict'>
|
meaning of the returned list of python json
|
I'm new to python so I really don't know the language very well.
the following example was taken from here http://docs.python.org/library/json.html
>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
what does the u mean? and how do i know which elements are available in the dictionary?
|
[
"It's a unicode. Iterating over the dict yields its keys:\nfor k in D:\n print k, D[k]\n\n",
"Ignacio's answer a bit more verbose (no upvotes to me)\nu'something' means that 'something' is a unicode string, and not for instance an ascii string. Generally text is encoded as 8-bit characters, and you need an encoding to properly interpret/display it. Unicode is 16-bit and doesn't need seperate encodings for the various locale dependent characters.\nIn a dictionary (enclosed by {}) the key is the part before the \":\" and the value comes after.\nYou got a list, with elements:\n\nfoo, a Unicode string\na dictionary containing:\n\n\na key (unicode) \"bar\", and accessible through that key a list with values\n\n\nunicode string baz,\nNone\na float 1.0\nan integer 2\n\n\n\n",
"The python type function can be useful here.\n>>> import json\n>>> data = json.loads('[\"foo\", {\"bar\":[\"baz\", null, 1.0, 2]}]')\n>>> data\n[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]\n>>> type(data)\n<type 'list'>\n>>> type(data[0])\n<type 'unicode'>\n>>> type(data[1])\n<type 'dict'>\n\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"json",
"python"
] |
stackoverflow_0002492099_json_python.txt
|
Q:
django / python get image from url and display on site
Given a url to an image is there a way in Django/Python to pull this image in and then display it on my site (resized if possible)
Thanks
A:
If you just want to hotlink it print out the html snippet(<img src="http://example.com/img.png" width="100" height="100" />).
If you want to store in at your server and resize it on the server-side you might want to look into ImageMagick or PIL for processing and urllib or pycurl for downloading.
|
django / python get image from url and display on site
|
Given a url to an image is there a way in Django/Python to pull this image in and then display it on my site (resized if possible)
Thanks
|
[
"If you just want to hotlink it print out the html snippet(<img src=\"http://example.com/img.png\" width=\"100\" height=\"100\" />).\nIf you want to store in at your server and resize it on the server-side you might want to look into ImageMagick or PIL for processing and urllib or pycurl for downloading.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"python",
"python_imaging_library"
] |
stackoverflow_0002492703_django_python_python_imaging_library.txt
|
Q:
Python Daemon Subprocess not working at boot
I am attempting to write a python daemon that will launch at boot. The goal of the script is to receive a job from our gearman load balancing server and complete the job. I am using the python-daemon module from pypi (http://pypi.python.org/pypi/python-daemon/). The nature of the job that it is completing is converting images in the orf (olympus raw image format) to jpeg. In order to accomplish this an outside program is used, ufraw in this case. The problem comes in when I start the daemon at boot, if I launch from the shell it runs perfectly and completes the work. When it starts at boot it is unable to launch the subprocess command.
commandString = '/usr/bin/ufraw-batch --interpolation=four-color --wb=camera --compression=100 --output="' + outfile + '" --out-type=jpg --overwrite "' + infile + '"'
args = shlex.split(commandString)
process = subprocess.Popen(args).wait()
I am not sure what I am doing wrong. Thanks for any help.
A:
The issue is not related to python but rather related to the ubuntu init.d daemon. I assumed that the python script was being as a user turns out that it is not. To remedy the problem I added a sudo command to the init.d script and the subprocess starts successfully now.
|
Python Daemon Subprocess not working at boot
|
I am attempting to write a python daemon that will launch at boot. The goal of the script is to receive a job from our gearman load balancing server and complete the job. I am using the python-daemon module from pypi (http://pypi.python.org/pypi/python-daemon/). The nature of the job that it is completing is converting images in the orf (olympus raw image format) to jpeg. In order to accomplish this an outside program is used, ufraw in this case. The problem comes in when I start the daemon at boot, if I launch from the shell it runs perfectly and completes the work. When it starts at boot it is unable to launch the subprocess command.
commandString = '/usr/bin/ufraw-batch --interpolation=four-color --wb=camera --compression=100 --output="' + outfile + '" --out-type=jpg --overwrite "' + infile + '"'
args = shlex.split(commandString)
process = subprocess.Popen(args).wait()
I am not sure what I am doing wrong. Thanks for any help.
|
[
"The issue is not related to python but rather related to the ubuntu init.d daemon. I assumed that the python script was being as a user turns out that it is not. To remedy the problem I added a sudo command to the init.d script and the subprocess starts successfully now.\n"
] |
[
0
] |
[] |
[] |
[
"daemon",
"gearman",
"imagemagick",
"python"
] |
stackoverflow_0002480339_daemon_gearman_imagemagick_python.txt
|
Q:
GAE, Python 2.5, Python 2.6 Side-by-side on windows
On my development system, I have Python 2.6, Django 1.1 and GAE.
I have three projects running on Python 2.6 and Django 1.1.
I have 1 project using GAE, Python 2.6 and Django 1.1.
I have heard that my set-up for running GAE using Python 2.6 may create some head-scratching problems while deploying it on the production server, because GAE supports only Python 2.5, and using 2.6 is not recommended.
Can I develop GAE application using Python 2.6? If not, what should I do? I am using Windows Vista as my development system.
Please note : I don't want to disturb my other projects in development, which uses Python 2.6 and Django 1.1.
A:
Use virtualenv to isolate your development environments, so you can have one running 2.5 and the others running 2.6.
Edited to add: once 2.5 is installed, you can initialize your virtualenv to use it with the -p option:
virtualenv -p /path/to/python2.5/python.exe destination_dir
A:
Unless you are using python 2.6 specific syntax/code your application is safe to run on GAE.
A:
Re virtualenv question above: virtualenv have a parameter
--python=PYTHON_EXE that you can point to the interpreter you'd like
it to use. Running virtualenv without parameters or with an --help
option whill show you which options you may pass it.
|
GAE, Python 2.5, Python 2.6 Side-by-side on windows
|
On my development system, I have Python 2.6, Django 1.1 and GAE.
I have three projects running on Python 2.6 and Django 1.1.
I have 1 project using GAE, Python 2.6 and Django 1.1.
I have heard that my set-up for running GAE using Python 2.6 may create some head-scratching problems while deploying it on the production server, because GAE supports only Python 2.5, and using 2.6 is not recommended.
Can I develop GAE application using Python 2.6? If not, what should I do? I am using Windows Vista as my development system.
Please note : I don't want to disturb my other projects in development, which uses Python 2.6 and Django 1.1.
|
[
"Use virtualenv to isolate your development environments, so you can have one running 2.5 and the others running 2.6.\nEdited to add: once 2.5 is installed, you can initialize your virtualenv to use it with the -p option:\nvirtualenv -p /path/to/python2.5/python.exe destination_dir\n\n",
"Unless you are using python 2.6 specific syntax/code your application is safe to run on GAE.\n",
"Re virtualenv question above: virtualenv have a parameter\n--python=PYTHON_EXE that you can point to the interpreter you'd like\nit to use. Running virtualenv without parameters or with an --help\noption whill show you which options you may pass it.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django",
"google_app_engine",
"python"
] |
stackoverflow_0002491280_django_google_app_engine_python.txt
|
Q:
GAE AttributeError
My GAE app runs fine from my computer, but when I upload it, I start getting an AttributeError, specifically:
AttributeError: 'dict' object has no attribute 'item'
I am using the pylast interface (an API for last.fm--link). Specifically, I am accessing a list of variables of this type:
SimilarItem = _namedtuple("SimilarItem", ["item", "match"])
I have a variable of this type, call it sim, and I am trying to access sim.item when I get the attribute error.
I should note that I am using Python 2.6 on my computer, and I understand that GAE runs on Python 2.5. Would that make a difference here? I thought they were backwards-compatible.
Lastly, I think it could be a possible problem with the modules that pylast imports--maybe they don't work with GAE or something? I did some research but I didn't get any results. Here are the imports:
import hashlib
import httplib
import urllib
import threading
from xml.dom import minidom
import xml.dom
import time
import shelve
import tempfile
import sys
import htmlentitydefs
I would appreciate any help with this frustrating issue. Thanks in advance.
A:
Yep, Python 2.6 is mostly backwards-compatible to 2.5 -- this means that what runs in 2.5 will mostly run in 2.6. But you seem to misunderstand what backwards means -- it's the antonym of forwards, meaning that it's perfectly possible that what runs in 2.6 (if it uses new features that are in 2.6 but were not in 2.5) will not run in 2.5 (or previous versions). Surely you see that the only way to avoid that would be to never, ever add any new features in new versions of Python -- a pretty dire remedy!-)
So I don't think you're well advised to use 2.6 for your local GAE development, since you know that 2.5 is what the production version will be using. Why not download and install a Python 2.5 from python.org (or your linux distro's specific repos, if you're on Linux) and point your GAE SDK to use that version, instead of 2.6? That would make your life substantially easier!
A:
Python 2.5 doesn't have namedtuple. It was added in 2.6.
Edit: It looks like the _namedtuple function is provided by pylast and will use a real namedtuple in Python 2.6+ but will fall back to a plain old dict in Python 2.5 or older. That means that you'll have to use sim['item'] or sim.get('item') when running in production.
Here's the source for that function:
def _namedtuple(name, children):
"""
collections.namedtuple is available in (python >= 2.6)
"""
v = sys.version_info
if v[1] >= 6 and v[0] < 3:
return collections.namedtuple(name, children)
else:
def fancydict(*args):
d = {}
i = 0
for child in children:
d[child.strip()] = args[i]
i += 1
return d
return fancydict
|
GAE AttributeError
|
My GAE app runs fine from my computer, but when I upload it, I start getting an AttributeError, specifically:
AttributeError: 'dict' object has no attribute 'item'
I am using the pylast interface (an API for last.fm--link). Specifically, I am accessing a list of variables of this type:
SimilarItem = _namedtuple("SimilarItem", ["item", "match"])
I have a variable of this type, call it sim, and I am trying to access sim.item when I get the attribute error.
I should note that I am using Python 2.6 on my computer, and I understand that GAE runs on Python 2.5. Would that make a difference here? I thought they were backwards-compatible.
Lastly, I think it could be a possible problem with the modules that pylast imports--maybe they don't work with GAE or something? I did some research but I didn't get any results. Here are the imports:
import hashlib
import httplib
import urllib
import threading
from xml.dom import minidom
import xml.dom
import time
import shelve
import tempfile
import sys
import htmlentitydefs
I would appreciate any help with this frustrating issue. Thanks in advance.
|
[
"Yep, Python 2.6 is mostly backwards-compatible to 2.5 -- this means that what runs in 2.5 will mostly run in 2.6. But you seem to misunderstand what backwards means -- it's the antonym of forwards, meaning that it's perfectly possible that what runs in 2.6 (if it uses new features that are in 2.6 but were not in 2.5) will not run in 2.5 (or previous versions). Surely you see that the only way to avoid that would be to never, ever add any new features in new versions of Python -- a pretty dire remedy!-)\nSo I don't think you're well advised to use 2.6 for your local GAE development, since you know that 2.5 is what the production version will be using. Why not download and install a Python 2.5 from python.org (or your linux distro's specific repos, if you're on Linux) and point your GAE SDK to use that version, instead of 2.6? That would make your life substantially easier!\n",
"Python 2.5 doesn't have namedtuple. It was added in 2.6. \nEdit: It looks like the _namedtuple function is provided by pylast and will use a real namedtuple in Python 2.6+ but will fall back to a plain old dict in Python 2.5 or older. That means that you'll have to use sim['item'] or sim.get('item') when running in production.\nHere's the source for that function:\ndef _namedtuple(name, children):\n \"\"\"\n collections.namedtuple is available in (python >= 2.6)\n \"\"\"\n\n v = sys.version_info\n if v[1] >= 6 and v[0] < 3:\n return collections.namedtuple(name, children)\n else:\n def fancydict(*args):\n d = {}\n i = 0\n for child in children:\n d[child.strip()] = args[i]\n i += 1\n return d\n\n return fancydict\n\n"
] |
[
4,
3
] |
[] |
[] |
[
"attributeerror",
"google_app_engine",
"python"
] |
stackoverflow_0002493072_attributeerror_google_app_engine_python.txt
|
Q:
Renaming a pylons controller
Is there an automatic way I can use to rename a pylons controller? If I have to rename the controller manually which all files and filenames do I have to change. Thank you much!
A:
You need to rename the file containing the controller, as well as the name of the controller class itself within the file. As far as I know there is no automatic way to do this, although if you have many controllers to rename it might be worth the time to write a special script to do it for you.
As discussed on the pylons-discuss group, it would be nice if the class within the controller file was generic, so it did not also have to be changed:
controllers/__init__.py
controllers/foo.py:
class Controller...
controllers/bar.py:
class Controller...
|
Renaming a pylons controller
|
Is there an automatic way I can use to rename a pylons controller? If I have to rename the controller manually which all files and filenames do I have to change. Thank you much!
|
[
"You need to rename the file containing the controller, as well as the name of the controller class itself within the file. As far as I know there is no automatic way to do this, although if you have many controllers to rename it might be worth the time to write a special script to do it for you.\nAs discussed on the pylons-discuss group, it would be nice if the class within the controller file was generic, so it did not also have to be changed:\n\ncontrollers/__init__.py\ncontrollers/foo.py:\n class Controller...\ncontrollers/bar.py:\n class Controller...\n\n"
] |
[
1
] |
[] |
[] |
[
"pylons",
"python"
] |
stackoverflow_0002492692_pylons_python.txt
|
Q:
download mbox files over https using python
I was trying to find the right module for downloading kernel patches from
kernel.org site
For example,to download the file at https://patchwork.kernel.org/patch/62948/mbox/
I understand urlgrabber has a problem with https on debian. urllib2 seems to have problem with this url as well (says getaddrinfo failed, even though there are no problems reaching other urls)
Any help would be appreciated
A:
Curious, this url should work fine (though I've tried it on Mac OS X only). I used this very simple test in my code:
import urllib
get_url = lambda url : urllib.urlopen(url).read()
data = get_url('https://patchwork.kernel.org/patch/62948/mbox/')
Of course, this loads the result into memory - but it does work. What version of Python are you using? The only thing I can think of is that your Python socket module has been compiled without SSL support.
A:
Hmm, maybe you need redirect handling?
|
download mbox files over https using python
|
I was trying to find the right module for downloading kernel patches from
kernel.org site
For example,to download the file at https://patchwork.kernel.org/patch/62948/mbox/
I understand urlgrabber has a problem with https on debian. urllib2 seems to have problem with this url as well (says getaddrinfo failed, even though there are no problems reaching other urls)
Any help would be appreciated
|
[
"Curious, this url should work fine (though I've tried it on Mac OS X only). I used this very simple test in my code:\nimport urllib\nget_url = lambda url : urllib.urlopen(url).read()\ndata = get_url('https://patchwork.kernel.org/patch/62948/mbox/')\n\nOf course, this loads the result into memory - but it does work. What version of Python are you using? The only thing I can think of is that your Python socket module has been compiled without SSL support.\n",
"Hmm, maybe you need redirect handling?\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"urllib2"
] |
stackoverflow_0002493394_python_urllib2.txt
|
Q:
Dictionaries with tuples that have lists as values
How can i have a tuple that has a list as a value.
F.x. if i want to have a structure like this.
( Somechar , Somelist[] )
And how would i iterate through a dictionary of these things?
A:
You can add a list to a tuple just like any other element. From a dictionary, you can access each element of the tuple by indexing it like so: d[key][0] and d[key][1]. Here is an example:
>>> d = {}
>>> d["b"] = ('b', [2])
>>> d["a"] = ('a', [1])
>>> for k in d:
... print(d[k][0], d[k][1])
...
('a', [1])
('b', [2])
A:
A tuple can contain anything you like. It just works the same as a nested list.
>>> myvar = ('d', [1, 2])
>>> myvar[0]
'd'
>>> myvar[1]
[1, 2]
>>> myvar[1][1]
2
A:
Here's a simple example:
>> a = ('a', ['a list'])
>> a
('a', ['a list'])
>> b = dict((a,))
{'a': ['a list']}
for i, j in b.iteritems():
print i, j
a ['a list']
Does that answer your question? The dict constructor takes a list/tuple of (key, value) tuples. Also keep in mind the ',' character is constructor for a tuple (not just the () ).
|
Dictionaries with tuples that have lists as values
|
How can i have a tuple that has a list as a value.
F.x. if i want to have a structure like this.
( Somechar , Somelist[] )
And how would i iterate through a dictionary of these things?
|
[
"You can add a list to a tuple just like any other element. From a dictionary, you can access each element of the tuple by indexing it like so: d[key][0] and d[key][1]. Here is an example:\n\n>>> d = {}\n>>> d[\"b\"] = ('b', [2])\n>>> d[\"a\"] = ('a', [1])\n>>> for k in d:\n... print(d[k][0], d[k][1])\n...\n('a', [1])\n('b', [2])\n\n",
"A tuple can contain anything you like. It just works the same as a nested list.\n>>> myvar = ('d', [1, 2])\n>>> myvar[0]\n'd'\n>>> myvar[1]\n[1, 2]\n>>> myvar[1][1]\n2\n\n",
"Here's a simple example:\n>> a = ('a', ['a list'])\n>> a\n('a', ['a list'])\n>> b = dict((a,))\n{'a': ['a list']}\n\nfor i, j in b.iteritems():\n print i, j\n\na ['a list']\n\nDoes that answer your question? The dict constructor takes a list/tuple of (key, value) tuples. Also keep in mind the ',' character is constructor for a tuple (not just the () ).\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"dictionary",
"list",
"python",
"tuples"
] |
stackoverflow_0002493425_dictionary_list_python_tuples.txt
|
Q:
How to make Twisted use Python logging?
I've got a project where I'm using Twisted for my web server. When exceptions occur (such as network errors), it's printing to the console.
I've already got logging through Python's built-in log module - is there any way to tell the reactor to use that instead?
What's the usual pattern for this?
A:
Found it. It's actually quite easy:
from twisted.python import log
observer = log.PythonLoggingObserver(loggerName='logname')
observer.start()
You just set loggerName to the same logger name that you're using in logging.getLogger().
A:
You can use twisted.python.log. For example:
from twisted.python import log
log.msg('Hello, world.')
|
How to make Twisted use Python logging?
|
I've got a project where I'm using Twisted for my web server. When exceptions occur (such as network errors), it's printing to the console.
I've already got logging through Python's built-in log module - is there any way to tell the reactor to use that instead?
What's the usual pattern for this?
|
[
"Found it. It's actually quite easy:\nfrom twisted.python import log\nobserver = log.PythonLoggingObserver(loggerName='logname')\nobserver.start()\n\nYou just set loggerName to the same logger name that you're using in logging.getLogger().\n",
"You can use twisted.python.log. For example:\nfrom twisted.python import log\nlog.msg('Hello, world.')\n\n"
] |
[
25,
1
] |
[] |
[] |
[
"python",
"twisted"
] |
stackoverflow_0002493644_python_twisted.txt
|
Q:
Resulting .exe from PyInstaller with wxPython crashing
I'm trying to compile a very simple wxPython script into an executable by using PyInstaller on Windows Vista.
The Python script is nothing but a Hello World in wxPython. I'm trying to get that up and running as a Windows executable before I add any of the features that the program needs to have. But I'm already stuck.
I've jumped through some loops in regards to MSVCR90.DLL, MSVCP90.DLL and MSVCPM90.DLL, which I ended up copying from my Visual Studio installation (C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT).
As according to the instructions for PyInstaller, I run:
Command:
Configure.py
Output:
I: computing EXE_dependencies
I: Finding TCL/TK...
I: could not find TCL/TK
I: testing for Zlib...
I: ... Zlib available
I: Testing for ability to set icons, version resources...
I: ... resource update available
I: Testing for Unicode support...
I: ... Unicode available
I: testing for UPX...
I: ...UPX available
I: computing PYZ dependencies...
So far, so good. I continue.
Command:
Makespec.py -F guitest.py
Output:
wrote C:\Code\PromoUSB\guitest.spec
now run Build.py to build the executable
Then there's the final command.
Command:
Build.py guitest.spec
Output:
checking Analysis
building Analysis because out0.toc non existent
running Analysis out0.toc
Analyzing: C:\Python26\pyinstaller-1.3\support\_mountzlib.py
Analyzing: C:\Python26\pyinstaller-1.3\support\useUnicode.py
Analyzing: guitest.py
Warnings written to C:\Code\PromoUSB\warnguitest.txt
checking PYZ
rebuilding out1.toc because out1.pyz is missing
building PYZ out1.toc
checking PKG
rebuilding out3.toc because out3.pkg is missing
building PKG out3.pkg
checking ELFEXE
rebuilding out2.toc because guitest.exe missing
building ELFEXE out2.toc
I get the resulting 'guitest.exe' file, but upon execution, it "simply crashes"... and there is no debug info. It's just one of those standard Windows Vista crashes.
The script itself, guitest.py runs just fine by itself. It only crashes as an executable, and I'm completely lost. I don't even know what to look for, since nothing I've tried has returned any relevant results.
Another file is generated as a result of the compilation process, called 'warnguitest.txt'. Here are its contents.
W: no module named posix (conditional import by os)
W: no module named optik.__all__ (top-level import by optparse)
W: no module named readline (delayed, conditional import by cmd)
W: no module named readline (delayed import by pdb)
W: no module named pwd (delayed, conditional import by posixpath)
W: no module named org (top-level import by pickle)
W: no module named posix (delayed, conditional import by iu)
W: no module named fcntl (conditional import by subprocess)
W: no module named org (top-level import by copy)
W: no module named _emx_link (conditional import by os)
W: no module named optik.__version__ (top-level import by optparse)
W: no module named fcntl (top-level import by tempfile)
W: __all__ is built strangely at line 0 - collections (C:\Python26\lib\collections.pyc)
W: delayed exec statement detected at line 0 - collections (C:\Python26\lib\collections.pyc)
W: delayed conditional __import__ hack detected at line 0 - doctest (C:\Python26\lib\doctest.pyc)
W: delayed exec statement detected at line 0 - doctest (C:\Python26\lib\doctest.pyc)
W: delayed conditional __import__ hack detected at line 0 - doctest (C:\Python26\lib\doctest.pyc)
W: delayed __import__ hack detected at line 0 - encodings (C:\Python26\lib\encodings\__init__.pyc)
W: __all__ is built strangely at line 0 - optparse (C:\Python26\pyinstaller-1.3\optparse.pyc)
W: __all__ is built strangely at line 0 - dis (C:\Python26\lib\dis.pyc)
W: delayed eval hack detected at line 0 - os (C:\Python26\lib\os.pyc)
W: __all__ is built strangely at line 0 - __future__ (C:\Python26\lib\__future__.pyc)
W: delayed conditional __import__ hack detected at line 0 - unittest (C:\Python26\lib\unittest.pyc)
W: delayed conditional __import__ hack detected at line 0 - unittest (C:\Python26\lib\unittest.pyc)
W: __all__ is built strangely at line 0 - tokenize (C:\Python26\lib\tokenize.pyc)
W: __all__ is built strangely at line 0 - wx (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.pyc)
W: __all__ is built strangely at line 0 - wx (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.pyc)
W: delayed exec statement detected at line 0 - bdb (C:\Python26\lib\bdb.pyc)
W: delayed eval hack detected at line 0 - bdb (C:\Python26\lib\bdb.pyc)
W: delayed eval hack detected at line 0 - bdb (C:\Python26\lib\bdb.pyc)
W: delayed __import__ hack detected at line 0 - pickle (C:\Python26\lib\pickle.pyc)
W: delayed __import__ hack detected at line 0 - pickle (C:\Python26\lib\pickle.pyc)
W: delayed conditional exec statement detected at line 0 - iu (C:\Python26\pyinstaller-1.3\iu.pyc)
W: delayed conditional exec statement detected at line 0 - iu (C:\Python26\pyinstaller-1.3\iu.pyc)
W: delayed eval hack detected at line 0 - gettext (C:\Python26\lib\gettext.pyc)
W: delayed __import__ hack detected at line 0 - optik.option_parser (C:\Python26\pyinstaller-1.3\optik\option_parser.pyc)
W: delayed conditional eval hack detected at line 0 - warnings (C:\Python26\lib\warnings.pyc)
W: delayed conditional __import__ hack detected at line 0 - warnings (C:\Python26\lib\warnings.pyc)
W: __all__ is built strangely at line 0 - optik (C:\Python26\pyinstaller-1.3\optik\__init__.pyc)
W: delayed exec statement detected at line 0 - pdb (C:\Python26\lib\pdb.pyc)
W: delayed conditional eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc)
W: delayed eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc)
W: delayed conditional eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc)
W: delayed eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc)
I don't know what the heck to make of any of that. Again, my searches have been fruitless.
A:
On windows I have found Py2exe to be more stable and easier to use, have you tried that.
A:
I found the solution to this problem on the PyInstaller mailing list, and it's remarkably simple, only undocumented.
PyInstaller doesn't yet support Python 2.6. The solution is to get a patch from a page which can now be found in the compilation process that I was trying, if one tries to compile using Python 2.6.
Thanks everyone though!
EDIT: The page used to be hosted at http://svn.pyinstaller.org/branches/py26win but it no longer exists.
|
Resulting .exe from PyInstaller with wxPython crashing
|
I'm trying to compile a very simple wxPython script into an executable by using PyInstaller on Windows Vista.
The Python script is nothing but a Hello World in wxPython. I'm trying to get that up and running as a Windows executable before I add any of the features that the program needs to have. But I'm already stuck.
I've jumped through some loops in regards to MSVCR90.DLL, MSVCP90.DLL and MSVCPM90.DLL, which I ended up copying from my Visual Studio installation (C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT).
As according to the instructions for PyInstaller, I run:
Command:
Configure.py
Output:
I: computing EXE_dependencies
I: Finding TCL/TK...
I: could not find TCL/TK
I: testing for Zlib...
I: ... Zlib available
I: Testing for ability to set icons, version resources...
I: ... resource update available
I: Testing for Unicode support...
I: ... Unicode available
I: testing for UPX...
I: ...UPX available
I: computing PYZ dependencies...
So far, so good. I continue.
Command:
Makespec.py -F guitest.py
Output:
wrote C:\Code\PromoUSB\guitest.spec
now run Build.py to build the executable
Then there's the final command.
Command:
Build.py guitest.spec
Output:
checking Analysis
building Analysis because out0.toc non existent
running Analysis out0.toc
Analyzing: C:\Python26\pyinstaller-1.3\support\_mountzlib.py
Analyzing: C:\Python26\pyinstaller-1.3\support\useUnicode.py
Analyzing: guitest.py
Warnings written to C:\Code\PromoUSB\warnguitest.txt
checking PYZ
rebuilding out1.toc because out1.pyz is missing
building PYZ out1.toc
checking PKG
rebuilding out3.toc because out3.pkg is missing
building PKG out3.pkg
checking ELFEXE
rebuilding out2.toc because guitest.exe missing
building ELFEXE out2.toc
I get the resulting 'guitest.exe' file, but upon execution, it "simply crashes"... and there is no debug info. It's just one of those standard Windows Vista crashes.
The script itself, guitest.py runs just fine by itself. It only crashes as an executable, and I'm completely lost. I don't even know what to look for, since nothing I've tried has returned any relevant results.
Another file is generated as a result of the compilation process, called 'warnguitest.txt'. Here are its contents.
W: no module named posix (conditional import by os)
W: no module named optik.__all__ (top-level import by optparse)
W: no module named readline (delayed, conditional import by cmd)
W: no module named readline (delayed import by pdb)
W: no module named pwd (delayed, conditional import by posixpath)
W: no module named org (top-level import by pickle)
W: no module named posix (delayed, conditional import by iu)
W: no module named fcntl (conditional import by subprocess)
W: no module named org (top-level import by copy)
W: no module named _emx_link (conditional import by os)
W: no module named optik.__version__ (top-level import by optparse)
W: no module named fcntl (top-level import by tempfile)
W: __all__ is built strangely at line 0 - collections (C:\Python26\lib\collections.pyc)
W: delayed exec statement detected at line 0 - collections (C:\Python26\lib\collections.pyc)
W: delayed conditional __import__ hack detected at line 0 - doctest (C:\Python26\lib\doctest.pyc)
W: delayed exec statement detected at line 0 - doctest (C:\Python26\lib\doctest.pyc)
W: delayed conditional __import__ hack detected at line 0 - doctest (C:\Python26\lib\doctest.pyc)
W: delayed __import__ hack detected at line 0 - encodings (C:\Python26\lib\encodings\__init__.pyc)
W: __all__ is built strangely at line 0 - optparse (C:\Python26\pyinstaller-1.3\optparse.pyc)
W: __all__ is built strangely at line 0 - dis (C:\Python26\lib\dis.pyc)
W: delayed eval hack detected at line 0 - os (C:\Python26\lib\os.pyc)
W: __all__ is built strangely at line 0 - __future__ (C:\Python26\lib\__future__.pyc)
W: delayed conditional __import__ hack detected at line 0 - unittest (C:\Python26\lib\unittest.pyc)
W: delayed conditional __import__ hack detected at line 0 - unittest (C:\Python26\lib\unittest.pyc)
W: __all__ is built strangely at line 0 - tokenize (C:\Python26\lib\tokenize.pyc)
W: __all__ is built strangely at line 0 - wx (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.pyc)
W: __all__ is built strangely at line 0 - wx (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.pyc)
W: delayed exec statement detected at line 0 - bdb (C:\Python26\lib\bdb.pyc)
W: delayed eval hack detected at line 0 - bdb (C:\Python26\lib\bdb.pyc)
W: delayed eval hack detected at line 0 - bdb (C:\Python26\lib\bdb.pyc)
W: delayed __import__ hack detected at line 0 - pickle (C:\Python26\lib\pickle.pyc)
W: delayed __import__ hack detected at line 0 - pickle (C:\Python26\lib\pickle.pyc)
W: delayed conditional exec statement detected at line 0 - iu (C:\Python26\pyinstaller-1.3\iu.pyc)
W: delayed conditional exec statement detected at line 0 - iu (C:\Python26\pyinstaller-1.3\iu.pyc)
W: delayed eval hack detected at line 0 - gettext (C:\Python26\lib\gettext.pyc)
W: delayed __import__ hack detected at line 0 - optik.option_parser (C:\Python26\pyinstaller-1.3\optik\option_parser.pyc)
W: delayed conditional eval hack detected at line 0 - warnings (C:\Python26\lib\warnings.pyc)
W: delayed conditional __import__ hack detected at line 0 - warnings (C:\Python26\lib\warnings.pyc)
W: __all__ is built strangely at line 0 - optik (C:\Python26\pyinstaller-1.3\optik\__init__.pyc)
W: delayed exec statement detected at line 0 - pdb (C:\Python26\lib\pdb.pyc)
W: delayed conditional eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc)
W: delayed eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc)
W: delayed conditional eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc)
W: delayed eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc)
I don't know what the heck to make of any of that. Again, my searches have been fruitless.
|
[
"On windows I have found Py2exe to be more stable and easier to use, have you tried that. \n",
"I found the solution to this problem on the PyInstaller mailing list, and it's remarkably simple, only undocumented.\nPyInstaller doesn't yet support Python 2.6. The solution is to get a patch from a page which can now be found in the compilation process that I was trying, if one tries to compile using Python 2.6.\nThanks everyone though!\nEDIT: The page used to be hosted at http://svn.pyinstaller.org/branches/py26win but it no longer exists.\n"
] |
[
0,
0
] |
[] |
[] |
[
"pyinstaller",
"python",
"wxpython"
] |
stackoverflow_0002480480_pyinstaller_python_wxpython.txt
|
Q:
Determine cluster size of file system in Python
I would like to calculate the "size on disk" of a file in Python. Therefore I would like to determine the cluster size of the file system where the file is stored.
How do I determine the cluster size in Python?
Or another built-in method that calculates the "size on disk" will also work.
I looked at os.path.getsize but it returns the file size in bytes, not taking the FS's block size into consideration.
I am hoping that this can be done in an OS independent way...
A:
On UNIX/Linux platforms, use Python's built-in os.statvfs. On Windows, unless you can find a third-party library that does it, you'll need to use ctypes to call the Win32 function GetDiskFreeSpace, like this:
import ctypes
sectorsPerCluster = ctypes.c_ulonglong(0)
bytesPerSector = ctypes.c_ulonglong(0)
rootPathName = ctypes.c_wchar_p(u"C:\\")
ctypes.windll.kernel32.GetDiskFreeSpaceW(rootPathName,
ctypes.pointer(sectorsPerCluster),
ctypes.pointer(bytesPerSector),
None,
None,
)
print(sectorsPerCluster.value, bytesPerSector.value)
Note that ctypes only became part of the Python stdlib in 2.5 or 2.6 (can't remember which).
I put this sort of thing in a function that first checks whether the UNIX variant is present, and falls back to ctypes if (presumably because it's running on Windows) not. That way, if Python ever does implement statvfs on Windows, it will just use that.
A:
Use statvfs, at least if you're aiming for a pre-3.0 version of Python. Not sure what it has been replaced with.
I also think you're going to have to do the maths yourself, Python doesn't seem to expose the "size in blocks" of files.
|
Determine cluster size of file system in Python
|
I would like to calculate the "size on disk" of a file in Python. Therefore I would like to determine the cluster size of the file system where the file is stored.
How do I determine the cluster size in Python?
Or another built-in method that calculates the "size on disk" will also work.
I looked at os.path.getsize but it returns the file size in bytes, not taking the FS's block size into consideration.
I am hoping that this can be done in an OS independent way...
|
[
"On UNIX/Linux platforms, use Python's built-in os.statvfs. On Windows, unless you can find a third-party library that does it, you'll need to use ctypes to call the Win32 function GetDiskFreeSpace, like this:\nimport ctypes\n\nsectorsPerCluster = ctypes.c_ulonglong(0)\nbytesPerSector = ctypes.c_ulonglong(0)\nrootPathName = ctypes.c_wchar_p(u\"C:\\\\\")\n\nctypes.windll.kernel32.GetDiskFreeSpaceW(rootPathName,\n ctypes.pointer(sectorsPerCluster),\n ctypes.pointer(bytesPerSector),\n None,\n None,\n)\n\nprint(sectorsPerCluster.value, bytesPerSector.value)\n\nNote that ctypes only became part of the Python stdlib in 2.5 or 2.6 (can't remember which).\nI put this sort of thing in a function that first checks whether the UNIX variant is present, and falls back to ctypes if (presumably because it's running on Windows) not. That way, if Python ever does implement statvfs on Windows, it will just use that.\n",
"Use statvfs, at least if you're aiming for a pre-3.0 version of Python. Not sure what it has been replaced with.\nI also think you're going to have to do the maths yourself, Python doesn't seem to expose the \"size in blocks\" of files.\n"
] |
[
6,
2
] |
[] |
[] |
[
"filesystems",
"python"
] |
stackoverflow_0002493172_filesystems_python.txt
|
Q:
Evaluating for loops in python, containing an array with an embedded for loop
I was looking at the following code in python:
for ob in [ob for ob in context.scene.objects if ob.is_visible()]:
pass
Obviously, it's a for each loop, saying for each object in foo array. However, I'm having a bit of trouble reading the array. If it just had:
[for ob in context.scene.objects if ob.is_visible()]
that would make some sense, granted the use of different objects with the same name ob seems odd to me, but it looks readable enough, saying that the array consists of every element in that loop. However, the use of 'ob', before the for loop makes little sense, is there some syntax that isn't in what I've seen in the documentation?
Thank you
A:
That is the syntax for list comprehension.
A:
The first ob is an expression, take this simple example:
>>>> [ x**2 for x in range(10) if x%2 == 0 ]
[0, 4, 16, 36, 64]
Which reads, create a list from range(10), if x is even then square it. Discard any odd value of x.
A:
It's a list comprehension. You can read it as:
create a list with [some_new_value for the_current_value in source_list_of_values if matches_criteria]
Think of:
[n*2 for n in [1,2,3,4]]
This means, for every item, n, create an entry in a new list with a value of n*2. So, this will yield:
[2,4,6,8]
In your case since the value ob is not modified, it's just filtering the list based on ob.is_visible(). So you're getting a new list of all ob's that are visible.
A:
It might help you see what's going on to rewrite your example code into this equivalent code:
temp_list = [ob for ob in context.scene.objects if ob.is_visible()]
for ob in temp_list:
pass
|
Evaluating for loops in python, containing an array with an embedded for loop
|
I was looking at the following code in python:
for ob in [ob for ob in context.scene.objects if ob.is_visible()]:
pass
Obviously, it's a for each loop, saying for each object in foo array. However, I'm having a bit of trouble reading the array. If it just had:
[for ob in context.scene.objects if ob.is_visible()]
that would make some sense, granted the use of different objects with the same name ob seems odd to me, but it looks readable enough, saying that the array consists of every element in that loop. However, the use of 'ob', before the for loop makes little sense, is there some syntax that isn't in what I've seen in the documentation?
Thank you
|
[
"That is the syntax for list comprehension.\n",
"The first ob is an expression, take this simple example:\n>>>> [ x**2 for x in range(10) if x%2 == 0 ]\n[0, 4, 16, 36, 64]\n\nWhich reads, create a list from range(10), if x is even then square it. Discard any odd value of x.\n",
"It's a list comprehension. You can read it as:\ncreate a list with [some_new_value for the_current_value in source_list_of_values if matches_criteria]\nThink of:\n[n*2 for n in [1,2,3,4]]\n\nThis means, for every item, n, create an entry in a new list with a value of n*2. So, this will yield:\n[2,4,6,8]\n\nIn your case since the value ob is not modified, it's just filtering the list based on ob.is_visible(). So you're getting a new list of all ob's that are visible.\n",
"It might help you see what's going on to rewrite your example code into this equivalent code:\ntemp_list = [ob for ob in context.scene.objects if ob.is_visible()]\nfor ob in temp_list:\n pass\n\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"arrays",
"foreach",
"list",
"python"
] |
stackoverflow_0002494141_arrays_foreach_list_python.txt
|
Q:
ctypes and pointer manipulation
I am dealing with image buffers, and I want to be able to access data a few lines into my image for analysis with a c library. I have created my 8-bit pixel buffer in Python using create_string_buffer. Is there a way to get a pointer to a location within that buffer without re-creating a new buffer? My goal is to analyze and change data within that buffer in chunks, without having to do a lot of buffer creation and data copying.
In this case, ultimately, the C library is doing all the manipulation of the buffer, so I don't actually have to change values within the buffer using Python. I just need to give my C function access to data within the buffer.
A:
create_string_buffer gives you a ctypes object (an array of chars), then byref, and I quote,
Returns a light-weight pointer to obj,
which must be an instance of a ctypes
type. offset defaults to zero, and
must be an integer that will be added
to the internal pointer value.
The offset argument has been added in 2.6, so if you're stuck with an older version you will unfortunately need more work.
A:
You can also use ctypes.cast(buf, ctypes.c_void_p)
|
ctypes and pointer manipulation
|
I am dealing with image buffers, and I want to be able to access data a few lines into my image for analysis with a c library. I have created my 8-bit pixel buffer in Python using create_string_buffer. Is there a way to get a pointer to a location within that buffer without re-creating a new buffer? My goal is to analyze and change data within that buffer in chunks, without having to do a lot of buffer creation and data copying.
In this case, ultimately, the C library is doing all the manipulation of the buffer, so I don't actually have to change values within the buffer using Python. I just need to give my C function access to data within the buffer.
|
[
"create_string_buffer gives you a ctypes object (an array of chars), then byref, and I quote,\n\nReturns a light-weight pointer to obj,\n which must be an instance of a ctypes\n type. offset defaults to zero, and\n must be an integer that will be added\n to the internal pointer value.\n\nThe offset argument has been added in 2.6, so if you're stuck with an older version you will unfortunately need more work.\n",
"You can also use ctypes.cast(buf, ctypes.c_void_p)\n"
] |
[
8,
0
] |
[] |
[] |
[
"ctypes",
"python"
] |
stackoverflow_0002494288_ctypes_python.txt
|
Q:
Modify default queryset in django
I have added a 'cancelled' field to my model, is there a way to modify the model default query to something like cancelled=False ? without having to modify all my filter/exclude queries ?
A:
You can do this with a custom model manager and override the get_queryset function to always filter canceled=False.
class CustomManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(canceled=False)
class MyModel(models.Model):
# Blah blah
objects = CustomManager()
Then when calling MyModel.objects.all() it will always exclude canceled objects. Here is a blog post I found helpful on the subject. http://www.b-list.org/weblog/2006/aug/18/django-tips-using-properties-models-and-managers/
EDIT:
Perhaps a better approach with a custom manager would be to attach it to another property, other than objects, such as:
class MyModel(models.Model):
# Blah blah
active = CustomManager()
And in your views your queries would look like MyModel.active.all().
EDIT2:
Updated method spelling from get_query_set to get_queryset for modern versions of django.
A:
You could write custom query manager, but I don't believe this is the right way to go. This would make an implicit, hidden condition for a filter, which would make code unreadable. Remember Zen of Python: Explicit is better than implicit. Detect places, where you need to add cancelled=False and just add this, that's the way you should do this.
|
Modify default queryset in django
|
I have added a 'cancelled' field to my model, is there a way to modify the model default query to something like cancelled=False ? without having to modify all my filter/exclude queries ?
|
[
"You can do this with a custom model manager and override the get_queryset function to always filter canceled=False.\nclass CustomManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(canceled=False)\n\nclass MyModel(models.Model):\n # Blah blah\n objects = CustomManager()\n\nThen when calling MyModel.objects.all() it will always exclude canceled objects. Here is a blog post I found helpful on the subject. http://www.b-list.org/weblog/2006/aug/18/django-tips-using-properties-models-and-managers/\nEDIT:\nPerhaps a better approach with a custom manager would be to attach it to another property, other than objects, such as:\nclass MyModel(models.Model):\n # Blah blah\n active = CustomManager()\n\nAnd in your views your queries would look like MyModel.active.all().\nEDIT2:\nUpdated method spelling from get_query_set to get_queryset for modern versions of django.\n",
"You could write custom query manager, but I don't believe this is the right way to go. This would make an implicit, hidden condition for a filter, which would make code unreadable. Remember Zen of Python: Explicit is better than implicit. Detect places, where you need to add cancelled=False and just add this, that's the way you should do this.\n"
] |
[
48,
3
] |
[] |
[] |
[
"django",
"django_models",
"metaprogramming",
"python"
] |
stackoverflow_0002494501_django_django_models_metaprogramming_python.txt
|
Q:
ssh-rsa public key validation using a regular expression
What regular expression can I use (if any) to validate that a given string is a legal ssh rsa public key?
I only need to validate the actual key - I don't care about the key type the precedes it or the username comment after it.
Ideally, someone will also provide the python code to run the regex validation.
Thanks.
A:
A "good enough" check is to see if the key starts with the correct header.
The data portion of the keyfile should decode from base64, or it will fail with a base64.binascii.Error
Unpack the first 4 bytes (an int), which should be 7. This is the
length of the following string (I guess this could be different, but you're only concerned with ssh-rsa).
openssh_pubkey = open('keyfile').read()
type, key_string, comment = openssh_pubkey.split()
data = base64.decodestring(key_string)
int_len = 4
str_len = struct.unpack('>I', data[:int_len])[0] # this should return 7
data[int_len:int_len+str_len] == type
Alternatively, you could forgo the binary checks, and look for AAAAB3NzaC1yc2EA at the start of an ssh-rsa key, bit I would still verify it's valid base64.
[edit] Clarification:
Via the specification, the first part if the key is a length prefixed string. The length is packed as a big-endian unsigned int ('>I' for a python struct). It's a 7 here, because the following string, 'ssh-rsa', is 7 bytes long. data[4:11] is the next 7 bytes (per the length prefix), but I edited the code above to use some descriptive variables to try and make this more clear. If you want to be thorough, you should also check for ssh-dss, and possibly pgp-sign-rsa, and pgp-sign-dss, but they are far less common.
A:
Based on the references to "key type that precedes it" and "username comment after it", I assume you're talking about public keys stored in ssh2 keyfile format.
In that format, the key is stored in base64 format, so a simple check would be to verify that the string contains only valid base64 characters.
If you want to go a little further, you could note that the first few bytes of the encoded key specify the key type, and match on that. See this post, which says:
If you base64-decode the first bit of
that text (AAAAB3NzaC1yc2EA) you'll
find that it starts with bytes 00 00
00 07 (indicating that a 7-character
string follows) and then the seven
characters "ssh-rsa", which is the key
type. DSA keys start with the
slightly different string
`AAAAB3NzaC1kc3MA', which decodes
similarly to the string "ssh-dss".
|
ssh-rsa public key validation using a regular expression
|
What regular expression can I use (if any) to validate that a given string is a legal ssh rsa public key?
I only need to validate the actual key - I don't care about the key type the precedes it or the username comment after it.
Ideally, someone will also provide the python code to run the regex validation.
Thanks.
|
[
"A \"good enough\" check is to see if the key starts with the correct header.\nThe data portion of the keyfile should decode from base64, or it will fail with a base64.binascii.Error\nUnpack the first 4 bytes (an int), which should be 7. This is the\nlength of the following string (I guess this could be different, but you're only concerned with ssh-rsa).\nopenssh_pubkey = open('keyfile').read()\ntype, key_string, comment = openssh_pubkey.split()\ndata = base64.decodestring(key_string)\nint_len = 4\nstr_len = struct.unpack('>I', data[:int_len])[0] # this should return 7\ndata[int_len:int_len+str_len] == type\n\nAlternatively, you could forgo the binary checks, and look for AAAAB3NzaC1yc2EA at the start of an ssh-rsa key, bit I would still verify it's valid base64.\n[edit] Clarification:\nVia the specification, the first part if the key is a length prefixed string. The length is packed as a big-endian unsigned int ('>I' for a python struct). It's a 7 here, because the following string, 'ssh-rsa', is 7 bytes long. data[4:11] is the next 7 bytes (per the length prefix), but I edited the code above to use some descriptive variables to try and make this more clear. If you want to be thorough, you should also check for ssh-dss, and possibly pgp-sign-rsa, and pgp-sign-dss, but they are far less common.\n",
"Based on the references to \"key type that precedes it\" and \"username comment after it\", I assume you're talking about public keys stored in ssh2 keyfile format.\nIn that format, the key is stored in base64 format, so a simple check would be to verify that the string contains only valid base64 characters.\nIf you want to go a little further, you could note that the first few bytes of the encoded key specify the key type, and match on that. See this post, which says:\n\nIf you base64-decode the first bit of\n that text (AAAAB3NzaC1yc2EA) you'll\n find that it starts with bytes 00 00 \n 00 07 (indicating that a 7-character\n string follows) and then the seven\n characters \"ssh-rsa\", which is the key\n type. DSA keys start with the\n slightly different string\n `AAAAB3NzaC1kc3MA', which decodes \n similarly to the string \"ssh-dss\".\n\n"
] |
[
11,
2
] |
[] |
[] |
[
"python",
"regex",
"ssh_keys",
"validation"
] |
stackoverflow_0002494450_python_regex_ssh_keys_validation.txt
|
Q:
How to implement a hub in Python
Dear all, I need to implement a TCP server in Python which receives some data from a client and then sends this data to another client. I've tried many different implementations but no way to make it run. Any help would be really appreciated.
Below is my code:
import SocketServer
import sys
import threading
buffer_size = 8182
ports = {'toserver': int(sys.argv[1]), 'fromserver': int(sys.argv[2])}
class ConnectionHandler(SocketServer.BaseRequestHandler):
def handle(self):
# I need to send the data received from the client connected to port 'toserver'
# to the client connected to port 'fromserver' - see variable 'ports' above
class TwoWayConnectionServer(threading.Thread):
def __init__(self):
self.to_server = SocketServer.ThreadingTCPServer(("", ports['toserver']), ConnectionHandler)
self.from_server = SocketServer.ThreadingTCPServer(("", ports['fromserver']), ConnectionHandler)
threading.Thread.__init__(self)
def run(self):
while (1):
self.to_server.handle_request()
self.from_server.handle_request()
def serve_non_blocking():
server = TwoWayConnectionServer()
server.run()
if __name__ == '__main__':
serve_non_blocking()
A:
See the Twisted tutorial, and also twisted.protocols.portforward. I think that portforward module does something slightly different from what you want, it opens an outgoing connection to the destination port rather than waiting for the second client to connect, but you should be able to work from there.
A:
Can you be more specific about what you tried and what didn't work? There are lots of ways to do this. Probably the easiest would be to use the socket library - maybe looking at some examples will help:
http://docs.python.org/library/socket.html#example
|
How to implement a hub in Python
|
Dear all, I need to implement a TCP server in Python which receives some data from a client and then sends this data to another client. I've tried many different implementations but no way to make it run. Any help would be really appreciated.
Below is my code:
import SocketServer
import sys
import threading
buffer_size = 8182
ports = {'toserver': int(sys.argv[1]), 'fromserver': int(sys.argv[2])}
class ConnectionHandler(SocketServer.BaseRequestHandler):
def handle(self):
# I need to send the data received from the client connected to port 'toserver'
# to the client connected to port 'fromserver' - see variable 'ports' above
class TwoWayConnectionServer(threading.Thread):
def __init__(self):
self.to_server = SocketServer.ThreadingTCPServer(("", ports['toserver']), ConnectionHandler)
self.from_server = SocketServer.ThreadingTCPServer(("", ports['fromserver']), ConnectionHandler)
threading.Thread.__init__(self)
def run(self):
while (1):
self.to_server.handle_request()
self.from_server.handle_request()
def serve_non_blocking():
server = TwoWayConnectionServer()
server.run()
if __name__ == '__main__':
serve_non_blocking()
|
[
"See the Twisted tutorial, and also twisted.protocols.portforward. I think that portforward module does something slightly different from what you want, it opens an outgoing connection to the destination port rather than waiting for the second client to connect, but you should be able to work from there.\n",
"Can you be more specific about what you tried and what didn't work? There are lots of ways to do this. Probably the easiest would be to use the socket library - maybe looking at some examples will help:\nhttp://docs.python.org/library/socket.html#example\n"
] |
[
1,
0
] |
[] |
[] |
[
"client",
"python",
"sockets",
"tcp"
] |
stackoverflow_0002493888_client_python_sockets_tcp.txt
|
Q:
Django URL regex question
I had a quick question about Django URL configuration, and I guess REGEX as well. I have a small configuration application that takes in environments and artifacts in the following way:
url(r'^env/(?P<env>\w+)/artifact/(?P<artifact>\w+)/$', 'config.views.ipview', name="bothlist"),
Now, this works fine, but what I would like to do is have it be able to have additional parameters that are optional, such as a verbose mode or no formating mode. I know how to do this just fine in the views, but I can't wrap my head around the regex.
the call would be something like
GET /env/<env>/artifact/<artifact>/<opt:verbose>/<opt:noformat>
Any help would be appreciated, thanks!
-Shawn
A:
I wouldn't put such options into the URL. As you said, these are optional options, they might only change the output. They don't belong in an URL.
Your initial regex should match URLs like:
/env/<env>/artifact/<artifact>?verbose=1&noformat=1
Imho this is a much better usage of URLs
|
Django URL regex question
|
I had a quick question about Django URL configuration, and I guess REGEX as well. I have a small configuration application that takes in environments and artifacts in the following way:
url(r'^env/(?P<env>\w+)/artifact/(?P<artifact>\w+)/$', 'config.views.ipview', name="bothlist"),
Now, this works fine, but what I would like to do is have it be able to have additional parameters that are optional, such as a verbose mode or no formating mode. I know how to do this just fine in the views, but I can't wrap my head around the regex.
the call would be something like
GET /env/<env>/artifact/<artifact>/<opt:verbose>/<opt:noformat>
Any help would be appreciated, thanks!
-Shawn
|
[
"I wouldn't put such options into the URL. As you said, these are optional options, they might only change the output. They don't belong in an URL.\nYour initial regex should match URLs like:\n/env/<env>/artifact/<artifact>?verbose=1&noformat=1\n\nImho this is a much better usage of URLs\n"
] |
[
9
] |
[] |
[] |
[
"django",
"python",
"regex"
] |
stackoverflow_0002494821_django_python_regex.txt
|
Q:
How do I retrieve Hotmail contacts with python
How can I retrieve contacts from hotmail with python?
Is there any example?
A:
Hotmail: Windows Live Contacts API
If a python interface doesn't exist you may have to resort to screen scraping.
A:
use octazen, but you have to pay for it
|
How do I retrieve Hotmail contacts with python
|
How can I retrieve contacts from hotmail with python?
Is there any example?
|
[
"Hotmail: Windows Live Contacts API\nIf a python interface doesn't exist you may have to resort to screen scraping.\n",
"use octazen, but you have to pay for it\n"
] |
[
1,
0
] |
[
"IIRC Hotmail has POP access, so just use the poplib library.\nUsage is something like this (NOT tested):\nhotmail = poplib.POP3_SSL('pop3.live.com', 995)\nhotmail.user(USERNAME)\nhotmail.pass_(PASSWORD)\n\nmessage_count = len(hotmail.list()[1])\n\nfor i in range(message_count):\n for message in hotmail.retr(i+1)[1]\n print message\n\nSome connectivity info here (might be old).\n"
] |
[
-1
] |
[
"hotmail",
"python"
] |
stackoverflow_0002165517_hotmail_python.txt
|
Q:
Can't call a webservice method using SOAPpy
I am trying to call a webservice using SOAPpy:
from SOAPpy import SOAPProxy
url = 'http://www.webservicex.net/WeatherForecast.asmx'
server = SOAPProxy(url);
print server.GetWeatherByPlaceName('Dallas');
print server.GetWeatherByZipCode ('33126');
The server call fails:
Traceback (most recent call last):
File "soap_test.py", line 6, in <module>
print server.GetWeatherByPlaceName('Dallas');
File "C:\usr\bin\Python26\lib\site-packages\SOAPpy\Client.py", line 451, in __call__
return self.__r_call(*args, **kw)
File "C:\usr\bin\Python26\lib\site-packages\SOAPpy\Client.py", line 473, in __r_call
self.__hd, self.__ma)
File "C:\usr\bin\Python26\lib\site-packages\SOAPpy\Client.py", line 387, in __call
raise p
SOAPpy.Types.faultType: <Fault soap:Client: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: GetWeatherByPlaceName.
at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing): >
What am I doing wrong?
A:
When consuming .NET webservices, you can add a soap action override to the call. Like the following. Confirmed working code.
import SOAPpy
ns = 'http://www.webservicex.net'
url = '%s/WeatherForecast.asmx' % ns
server = SOAPpy.SOAPProxy( url, namespace=ns )
#following is required for .NET
server.config.buildWithNamespacePrefix = 0
#adding the soapaction is required for .NET
print server._sa( '%s/GetWeatherByPlaceName' %ns ).GetWeatherByPlaceName( PlaceName='Dallas' )
print server._sa( '%s/GetWeatherByZipCode' %ns ).GetWeatherByZipCode( ZipCode='33126' )
Someone wrote a class to do something similar.
A modified version of the above wrapper for .Net:
import SOAPpy
class SOAPProxy( SOAPpy.SOAPProxy ):
"""Wrapper class for SOAPpy.SOAPProxy
Designed so it will prepend the namespace to the action in the
SOAPAction HTTP headers.
"""
def __call( self, name, args, kw, ns=None, sa=None, hd=None, ma=None ):
sa = sa or self.soapaction
ns = ns or self.namespace
self.config.buildWithNamespacePrefix = 0
# Only prepend namespace if no soapaction was given.
if ns and not sa:
if ns.endswith( '/' ):
sa = '%s%s' % ( ns , name )
else:
sa = '%s/%s' % ( ns , name )
#fixup boolean args - .net wants lowercase
for arg in kw:
if isinstance( kw[ arg ], types.BooleanType ):
kw[ arg ] = SOAPpy.Types.booleanType( kw[ arg ] )
return SOAPpy.SOAPProxy.__call( self, name, args, kw, ns, sa, hd, ma )
if __name__ == '__main__':
print __doc__
A:
As error message states, SOAPpy doesn't add SOAPAction HTTP header. That's why SOAPpy won't work for many services. Try suds, here is a working example:
from suds.client import Client
url = 'http://www.webservicex.net/WeatherForecast.asmx?WSDL'
client = Client(url)
print client.service.GetWeatherByPlaceName('Dallas')
print client.service.GetWeatherByZipCode ('33126')
|
Can't call a webservice method using SOAPpy
|
I am trying to call a webservice using SOAPpy:
from SOAPpy import SOAPProxy
url = 'http://www.webservicex.net/WeatherForecast.asmx'
server = SOAPProxy(url);
print server.GetWeatherByPlaceName('Dallas');
print server.GetWeatherByZipCode ('33126');
The server call fails:
Traceback (most recent call last):
File "soap_test.py", line 6, in <module>
print server.GetWeatherByPlaceName('Dallas');
File "C:\usr\bin\Python26\lib\site-packages\SOAPpy\Client.py", line 451, in __call__
return self.__r_call(*args, **kw)
File "C:\usr\bin\Python26\lib\site-packages\SOAPpy\Client.py", line 473, in __r_call
self.__hd, self.__ma)
File "C:\usr\bin\Python26\lib\site-packages\SOAPpy\Client.py", line 387, in __call
raise p
SOAPpy.Types.faultType: <Fault soap:Client: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: GetWeatherByPlaceName.
at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing): >
What am I doing wrong?
|
[
"When consuming .NET webservices, you can add a soap action override to the call. Like the following. Confirmed working code. \nimport SOAPpy\n\nns = 'http://www.webservicex.net'\nurl = '%s/WeatherForecast.asmx' % ns\n\nserver = SOAPpy.SOAPProxy( url, namespace=ns )\n#following is required for .NET\nserver.config.buildWithNamespacePrefix = 0\n#adding the soapaction is required for .NET\nprint server._sa( '%s/GetWeatherByPlaceName' %ns ).GetWeatherByPlaceName( PlaceName='Dallas' )\nprint server._sa( '%s/GetWeatherByZipCode' %ns ).GetWeatherByZipCode( ZipCode='33126' )\n\nSomeone wrote a class to do something similar.\nA modified version of the above wrapper for .Net:\nimport SOAPpy\n\nclass SOAPProxy( SOAPpy.SOAPProxy ):\n \"\"\"Wrapper class for SOAPpy.SOAPProxy\n\n Designed so it will prepend the namespace to the action in the\n SOAPAction HTTP headers.\n \"\"\"\n\n def __call( self, name, args, kw, ns=None, sa=None, hd=None, ma=None ):\n sa = sa or self.soapaction\n ns = ns or self.namespace\n self.config.buildWithNamespacePrefix = 0\n\n # Only prepend namespace if no soapaction was given.\n if ns and not sa:\n if ns.endswith( '/' ):\n sa = '%s%s' % ( ns , name )\n else:\n sa = '%s/%s' % ( ns , name )\n\n #fixup boolean args - .net wants lowercase\n for arg in kw:\n if isinstance( kw[ arg ], types.BooleanType ):\n kw[ arg ] = SOAPpy.Types.booleanType( kw[ arg ] )\n\n\n return SOAPpy.SOAPProxy.__call( self, name, args, kw, ns, sa, hd, ma )\n\nif __name__ == '__main__':\n print __doc__\n\n",
"As error message states, SOAPpy doesn't add SOAPAction HTTP header. That's why SOAPpy won't work for many services. Try suds, here is a working example:\nfrom suds.client import Client\n\nurl = 'http://www.webservicex.net/WeatherForecast.asmx?WSDL'\nclient = Client(url)\n\nprint client.service.GetWeatherByPlaceName('Dallas')\nprint client.service.GetWeatherByZipCode ('33126')\n\n"
] |
[
7,
4
] |
[] |
[] |
[
".net",
"python",
"soap",
"soappy",
"web_services"
] |
stackoverflow_0001768185_.net_python_soap_soappy_web_services.txt
|
Q:
Writing Strings to files in python
I'm getting the following error when trying to write a string to a file in pythion:
Traceback (most recent call last):
File "export_off.py", line 264, in execute
save_off(self.properties.path, context)
File "export_off.py", line 244, in save_off
primary.write(file)
File "export_off.py", line 181, in write
variable.write(file)
File "export_off.py", line 118, in write
file.write(self.value)
TypeError: must be bytes or buffer, not str
I basically have a string class, which contains a string:
class _off_str(object):
__slots__ = 'value'
def __init__(self, val=""):
self.value=val
def get_size(self):
return SZ_SHORT
def write(self,file):
file.write(self.value)
def __str__(self):
return str(self.value)
Furthermore, I'm calling that class like this (where variable is an array of _off_str objects:
def write(self, file):
for variable in self.variables:
variable.write(file)
I have no idea what is going on. I've seen other python programs writing strings to files, so why can't this one?
Thank you very much for your help.
Edit: It looks like I needed to state how I opened the file, here is how:
file = open(filename, 'wb')
primary.write(file)
file.close()
A:
What version of Python are you using? In Python 3.x a string contains Unicode text in no particular encoding. To write it out to a stream of bytes (a file) you must convert it to a byte encoding such as UTF-8, UTF-16, and so on. Fortunately this is easily done with the encode() method:
Python 3.1.1 (...)
>>> s = 'This is a Unicode string'
>>> print(s.encode('utf-8'))
Another example, writing UTF-16 to a file:
>>> f = open('output.txt', 'wb')
>>> f.write(s.encode('utf-16'))
Finally, you can use Python 3's "automagic" text mode, which will automatically convert your str to the encoding you specify:
>>> f = open('output.txt', 'wt', encoding='utf-8')
>>> f.write(s)
A:
I suspect you are using Python 3 and have opened the file in binary mode, which will only accept bytes or buffers to be written into it.
Any chance we could see the code that opens up the file for writing?
edit: Looks like that is indeed the culprit.
A:
I'm not seeing you open the file first:
file_handler = open(path)
file_handler.write(string)
file_handler.close()
A:
I see in you comment you mentioned that you did
file = open('xxx.xxx' ,'wb')
That means you're opening the file to write in binary (so just leave out the b flag).
A:
How did you open the file ?
According to the error message, I'll guess :
f = open("file", "wb") # b for binary mode
If you want to use strings, you must use :
f = open("file", "w")
If you use "b", files will expect binary data, and you are writing self.value which is a string.
By the way, don't use file" as a variable name as it hides the file built-in Python object.
|
Writing Strings to files in python
|
I'm getting the following error when trying to write a string to a file in pythion:
Traceback (most recent call last):
File "export_off.py", line 264, in execute
save_off(self.properties.path, context)
File "export_off.py", line 244, in save_off
primary.write(file)
File "export_off.py", line 181, in write
variable.write(file)
File "export_off.py", line 118, in write
file.write(self.value)
TypeError: must be bytes or buffer, not str
I basically have a string class, which contains a string:
class _off_str(object):
__slots__ = 'value'
def __init__(self, val=""):
self.value=val
def get_size(self):
return SZ_SHORT
def write(self,file):
file.write(self.value)
def __str__(self):
return str(self.value)
Furthermore, I'm calling that class like this (where variable is an array of _off_str objects:
def write(self, file):
for variable in self.variables:
variable.write(file)
I have no idea what is going on. I've seen other python programs writing strings to files, so why can't this one?
Thank you very much for your help.
Edit: It looks like I needed to state how I opened the file, here is how:
file = open(filename, 'wb')
primary.write(file)
file.close()
|
[
"What version of Python are you using? In Python 3.x a string contains Unicode text in no particular encoding. To write it out to a stream of bytes (a file) you must convert it to a byte encoding such as UTF-8, UTF-16, and so on. Fortunately this is easily done with the encode() method:\nPython 3.1.1 (...)\n>>> s = 'This is a Unicode string'\n>>> print(s.encode('utf-8'))\n\nAnother example, writing UTF-16 to a file:\n>>> f = open('output.txt', 'wb')\n>>> f.write(s.encode('utf-16'))\n\nFinally, you can use Python 3's \"automagic\" text mode, which will automatically convert your str to the encoding you specify:\n>>> f = open('output.txt', 'wt', encoding='utf-8')\n>>> f.write(s)\n\n",
"I suspect you are using Python 3 and have opened the file in binary mode, which will only accept bytes or buffers to be written into it.\nAny chance we could see the code that opens up the file for writing?\n\nedit: Looks like that is indeed the culprit.\n",
"I'm not seeing you open the file first:\nfile_handler = open(path)\nfile_handler.write(string)\nfile_handler.close()\n\n",
"I see in you comment you mentioned that you did\nfile = open('xxx.xxx' ,'wb')\n\nThat means you're opening the file to write in binary (so just leave out the b flag).\n",
"How did you open the file ?\nAccording to the error message, I'll guess :\nf = open(\"file\", \"wb\") # b for binary mode\n\nIf you want to use strings, you must use :\nf = open(\"file\", \"w\") \n\nIf you use \"b\", files will expect binary data, and you are writing self.value which is a string.\nBy the way, don't use file\" as a variable name as it hides the file built-in Python object.\n"
] |
[
23,
9,
2,
1,
0
] |
[] |
[] |
[
"file",
"io",
"python",
"python_3.x",
"string"
] |
stackoverflow_0002495290_file_io_python_python_3.x_string.txt
|
Q:
Finding longest non-repeating path through connected nodes
I've been working on this for a couple of days now without success. Basically, I have a bunch of nodes arranged in a 2D matrix. Every node has four neighbors, except for the nodes on the sides and corners of the matrix, which have 3 and 2 neighbors, respectively. Imagine a bunch of square cards laid out side by side in a rectangular area--the project is actually simulating a sort of card/board game.
Each node may or may not be connected to the nodes around it. Each node has a function (get_connections()), that returns the nodes immediately around it that it is connected to (so anywhere from 0 to 4 nodes are returned). Each node also has an "index" property, that contains it's position on the board matrix (eg '1, 4' -> row 1, col 4). What I am trying to do is find the longest non-repeating path of connected nodes given a particular "start" node.
I've uploaded a couple of images that should give a good idea of what I'm trying to do:
(source: necessarygames.com)
(source: necessarygames.com)
In both images, the highlighted red cards are supposedly the longest path of connected cards containing the most upper-left card. However, you can see in both images that a couple of cards that should be in the path have been left out (Romania and Maldova in the first image, Greece and Turkey in the second)
Here's the recursive function that I am using currently to find the longest path, given a starting node/card:
def get_longest_trip(self, board, processed_connections = list(),
processed_countries = list()):
#Append this country to the processed countries list,
#so we don't re-double over it
processed_countries.append(self)
possible_trips = dict()
if self.get_connections(board):
for i, card in enumerate(self.get_connections(board)):
if card not in processed_countries:
processed_connections.append((self, card))
possible_trips[i] = card.get_longest_trip(board,
processed_connections,
processed_countries)
if possible_trips:
longest_trip = []
for i, trip in possible_trips.iteritems():
trip_length = len(trip)
if trip_length > len(longest_trip):
longest_trip = trip
longest_trip.append(self)
return longest_trip
else:
print
card_list = []
card_list.append(self)
return card_list
else:
#If no connections from start_card, just return the start card
#as the longest trip
card_list = []
card_list.append(board.start_card)
return card_list
The problem here has to do with the processed_countries list: if you look at my first screenshot, you can see that what has happened is that when Ukraine came around, it looked at its two possible choices for longest path (Maldova-Romania, or Turkey, Bulgaria), saw that they were both equal, and chose one indiscriminantly. Now when Hungary comes around, it can't attempt to make a path through Romania (where the longest path would actually be), because Romania has been added to the processed_countries list by Ukraine.
Any help on this is EXTREMELY appreciated. If you can find me a solution to this, recursive or not, I'd be happy to donate some $$ to you.
I've uploaded my full source code (Python 2.6, Pygame 1.9 required) to:
http://www.necessarygames.com/junk/planes_trains.zip
The relevant code is in src/main.py, which is all set to run.
A:
You do know the longest path problem in a graph with cycles is NP-hard?
A:
...Romania has been added to the processed_countries list by Ukraine.
Use separate processed_countries lists for each graph path. They say one code example is worth thousand words, so I've changed your code a little (untested):
def get_longest_trip(self, board, processed_countries = list()):
# see https://stackoverflow.com/questions/576988/python-specific-antipatterns-and-bad-practices/577198#577198
processed_countries = list(processed_countries)
processed_countries.append(self)
longest_trip = list()
if self.get_connections(board):
possible_trips = list()
for card in self.get_connections(board):
if card not in processed_countries:
possible_trips.append(card.get_longest_trip(board,
processed_countries))
if possible_trips:
longest_trip = max(possible_trips, key=len)
longest_trip.append(self)
if not longest_trip:
longest_trip.append(self)
return longest_trip
Unrelated matters:
Traceback (most recent call last):
File "main.py", line 1171, in <module>
main()
File "main.py", line 1162, in main
interface = Interface(continent, screen, ev_manager)
File "main.py", line 72, in __init__
self.deck = Deck(ev_manager, continent)
File "main.py", line 125, in __init__
self.rebuild(continent)
File "main.py", line 148, in rebuild
self.stack.append(CountryCard(country, self.ev_manager))
File "main.py", line 1093, in __init__
Card.__init__(self, COUNTRY, country.name, country.image, country.color, ev_manager)
File "main.py", line 693, in __init__
self.set_text(text)
File "main.py", line 721, in set_text
self.rendered_text = self.render_text_rec(text)
File "main.py", line 817, in render_text_rec
return render_textrect(text, self.font, text_rect, self.text_color, self.text_bgcolor, 1)
File "/home/vasi/Desktop/Planes and Trains/src/textrect.py", line 47, in render_textrect
raise TextRectException, "The word " + word + " is too long to fit in the rect passed."
textrect.TextRectException: The word Montenegro is too long to fit in the rect passed.
There are 16 different bak files in your source package. Sixteen. Sixteeeen. Think about it and start to use version control.
A:
Brute force method:
Create a depth first connected list. Store List L and its Length T.
For each connection of this list:
Push Whole Diagram
Delete connection.
Create a depth first connected list.
If list is longer than T: set T to length and list to L then recursive call 2.
Pop Whole Diagram.
return
This should create a flood fill style solution of all the possible ways of connecting these nodes.
|
Finding longest non-repeating path through connected nodes
|
I've been working on this for a couple of days now without success. Basically, I have a bunch of nodes arranged in a 2D matrix. Every node has four neighbors, except for the nodes on the sides and corners of the matrix, which have 3 and 2 neighbors, respectively. Imagine a bunch of square cards laid out side by side in a rectangular area--the project is actually simulating a sort of card/board game.
Each node may or may not be connected to the nodes around it. Each node has a function (get_connections()), that returns the nodes immediately around it that it is connected to (so anywhere from 0 to 4 nodes are returned). Each node also has an "index" property, that contains it's position on the board matrix (eg '1, 4' -> row 1, col 4). What I am trying to do is find the longest non-repeating path of connected nodes given a particular "start" node.
I've uploaded a couple of images that should give a good idea of what I'm trying to do:
(source: necessarygames.com)
(source: necessarygames.com)
In both images, the highlighted red cards are supposedly the longest path of connected cards containing the most upper-left card. However, you can see in both images that a couple of cards that should be in the path have been left out (Romania and Maldova in the first image, Greece and Turkey in the second)
Here's the recursive function that I am using currently to find the longest path, given a starting node/card:
def get_longest_trip(self, board, processed_connections = list(),
processed_countries = list()):
#Append this country to the processed countries list,
#so we don't re-double over it
processed_countries.append(self)
possible_trips = dict()
if self.get_connections(board):
for i, card in enumerate(self.get_connections(board)):
if card not in processed_countries:
processed_connections.append((self, card))
possible_trips[i] = card.get_longest_trip(board,
processed_connections,
processed_countries)
if possible_trips:
longest_trip = []
for i, trip in possible_trips.iteritems():
trip_length = len(trip)
if trip_length > len(longest_trip):
longest_trip = trip
longest_trip.append(self)
return longest_trip
else:
print
card_list = []
card_list.append(self)
return card_list
else:
#If no connections from start_card, just return the start card
#as the longest trip
card_list = []
card_list.append(board.start_card)
return card_list
The problem here has to do with the processed_countries list: if you look at my first screenshot, you can see that what has happened is that when Ukraine came around, it looked at its two possible choices for longest path (Maldova-Romania, or Turkey, Bulgaria), saw that they were both equal, and chose one indiscriminantly. Now when Hungary comes around, it can't attempt to make a path through Romania (where the longest path would actually be), because Romania has been added to the processed_countries list by Ukraine.
Any help on this is EXTREMELY appreciated. If you can find me a solution to this, recursive or not, I'd be happy to donate some $$ to you.
I've uploaded my full source code (Python 2.6, Pygame 1.9 required) to:
http://www.necessarygames.com/junk/planes_trains.zip
The relevant code is in src/main.py, which is all set to run.
|
[
"You do know the longest path problem in a graph with cycles is NP-hard?\n",
"\n...Romania has been added to the processed_countries list by Ukraine. \n\nUse separate processed_countries lists for each graph path. They say one code example is worth thousand words, so I've changed your code a little (untested):\ndef get_longest_trip(self, board, processed_countries = list()):\n # see https://stackoverflow.com/questions/576988/python-specific-antipatterns-and-bad-practices/577198#577198\n processed_countries = list(processed_countries)\n processed_countries.append(self)\n\n longest_trip = list()\n if self.get_connections(board):\n possible_trips = list()\n for card in self.get_connections(board):\n if card not in processed_countries:\n possible_trips.append(card.get_longest_trip(board, \n processed_countries))\n if possible_trips:\n longest_trip = max(possible_trips, key=len)\n longest_trip.append(self)\n\n if not longest_trip:\n longest_trip.append(self)\n return longest_trip\n\nUnrelated matters:\nTraceback (most recent call last):\n File \"main.py\", line 1171, in <module>\n main()\n File \"main.py\", line 1162, in main\n interface = Interface(continent, screen, ev_manager) \n File \"main.py\", line 72, in __init__\n self.deck = Deck(ev_manager, continent)\n File \"main.py\", line 125, in __init__\n self.rebuild(continent) \n File \"main.py\", line 148, in rebuild\n self.stack.append(CountryCard(country, self.ev_manager))\n File \"main.py\", line 1093, in __init__\n Card.__init__(self, COUNTRY, country.name, country.image, country.color, ev_manager) \n File \"main.py\", line 693, in __init__\n self.set_text(text)\n File \"main.py\", line 721, in set_text\n self.rendered_text = self.render_text_rec(text) \n File \"main.py\", line 817, in render_text_rec\n return render_textrect(text, self.font, text_rect, self.text_color, self.text_bgcolor, 1) \n File \"/home/vasi/Desktop/Planes and Trains/src/textrect.py\", line 47, in render_textrect\n raise TextRectException, \"The word \" + word + \" is too long to fit in the rect passed.\"\ntextrect.TextRectException: The word Montenegro is too long to fit in the rect passed.\n\nThere are 16 different bak files in your source package. Sixteen. Sixteeeen. Think about it and start to use version control.\n",
"Brute force method:\n\nCreate a depth first connected list. Store List L and its Length T.\nFor each connection of this list:\n\nPush Whole Diagram\nDelete connection.\nCreate a depth first connected list.\nIf list is longer than T: set T to length and list to L then recursive call 2.\nPop Whole Diagram.\nreturn\n\n\nThis should create a flood fill style solution of all the possible ways of connecting these nodes.\n"
] |
[
6,
2,
0
] |
[] |
[] |
[
"pygame",
"python"
] |
stackoverflow_0002495306_pygame_python.txt
|
Q:
Variable alpha blending in pylab
How does one control the transparency over a 2D image in pylab? I'd like to give two sets of values (X,Y,Z,T) where X,Y are arrays of positions, Z is the color value, and T is the transparency to a function like imshow but it seems that the function only takes alpha as a scalar. As a concrete example, consider the code below that attempts to display two Gaussians. The closer the value is to zero, the more transparent I'd like the plot to be.
from pylab import *
side = linspace(-1,1,100)
X,Y = meshgrid(side,side)
extent = (-1,1,-1,1)
Z1 = exp(-((X+.5)**2+Y**2))
Z2 = exp(-((X-.5)**2+(Y+.2)**2))
imshow(Z1, cmap=cm.hsv, alpha=.6, extent=extent)
imshow(Z2, cmap=cm.hsv, alpha=.6, extent=extent)
show()
Note: I am not looking for a plot of Z1+Z2 (that would be trivial) but for a general way to specify the alpha blending across an image.
A:
One thing that you can do is modify what you put into imshow. The first variable can be grayscale values as you have used or it can be RGB or RGBA values. If you RGB/RGBA values then the cmap is ignored. So for instance,
imshow(Z1, cmap=cm.hsv, alpha=.6, extent=extent)
will generate the same image as
imshow(cm.hsv(Z1), alpha=.6, extent=extent)
because cm.hsv()just returns RGBA values. If you take a look at the values it returns, they all have 1.0 as the A value (the transparency). So one way to make variable transparency would be something like this:
def mycmap(x):
tmp = cm.hsv(x)
for i in xrange(tmp.shape[0]):
for j in xrange(tmp.shape[0]):
tmp[i,j][3] = somefunction of x[i,j] that generates the transparency
return tmp
imshow(mycmap(Z1), extent=extent)
imshow(mycmap(Z2), extent=extent)
You might find a little more elegant way of doing this, but hopefully you get the idea.
|
Variable alpha blending in pylab
|
How does one control the transparency over a 2D image in pylab? I'd like to give two sets of values (X,Y,Z,T) where X,Y are arrays of positions, Z is the color value, and T is the transparency to a function like imshow but it seems that the function only takes alpha as a scalar. As a concrete example, consider the code below that attempts to display two Gaussians. The closer the value is to zero, the more transparent I'd like the plot to be.
from pylab import *
side = linspace(-1,1,100)
X,Y = meshgrid(side,side)
extent = (-1,1,-1,1)
Z1 = exp(-((X+.5)**2+Y**2))
Z2 = exp(-((X-.5)**2+(Y+.2)**2))
imshow(Z1, cmap=cm.hsv, alpha=.6, extent=extent)
imshow(Z2, cmap=cm.hsv, alpha=.6, extent=extent)
show()
Note: I am not looking for a plot of Z1+Z2 (that would be trivial) but for a general way to specify the alpha blending across an image.
|
[
"One thing that you can do is modify what you put into imshow. The first variable can be grayscale values as you have used or it can be RGB or RGBA values. If you RGB/RGBA values then the cmap is ignored. So for instance,\nimshow(Z1, cmap=cm.hsv, alpha=.6, extent=extent)\n\nwill generate the same image as\nimshow(cm.hsv(Z1), alpha=.6, extent=extent)\n\nbecause cm.hsv()just returns RGBA values. If you take a look at the values it returns, they all have 1.0 as the A value (the transparency). So one way to make variable transparency would be something like this:\ndef mycmap(x):\n tmp = cm.hsv(x)\n for i in xrange(tmp.shape[0]):\n for j in xrange(tmp.shape[0]):\n tmp[i,j][3] = somefunction of x[i,j] that generates the transparency\n return tmp\n\nimshow(mycmap(Z1), extent=extent)\nimshow(mycmap(Z2), extent=extent)\n\nYou might find a little more elegant way of doing this, but hopefully you get the idea.\n"
] |
[
8
] |
[] |
[] |
[
"alphablending",
"matplotlib",
"python"
] |
stackoverflow_0002495656_alphablending_matplotlib_python.txt
|
Q:
Check if a MediaWiki page exists (Python)
I'm working on a Python script that transforms this:
foo
bar
Into this:
[[Component foo]]
[[bar]]
The script checks (per input line) if the page "Component foo" exists. If it exists then a link to that page is created, if it doesn't exist then a direct link is created.
The problem is that I need a quick & cheap way to check if a lot of wiki pages exist.I don't want to (try to) download all the 'Component' pages.
I already figured out a fast way to do this by hand: Edit a new wiki page. paste all the 'component' links into the page, press preview, and then save the resulting preview HTML page. The resulting HTML file contains a different link for existing pages than for non-existing pages.
So to rephrase my question: How can I save a mediawiki preview page in Python?
(I don't have local access to the database.)
A:
You can definitely use the API to check if a page exists:
# assuming words is a list of words you wish to query for
import urllib
# replace en.wikipedia.org with the address of the wiki you want to access
query = "http://en.wikipedia.org/w/api.php?action=query&titles=%s&format=xml" % "|".join(words)
pages = urllib.urlopen(query)
Now pages you will contain xml like this:
<?xml version="1.0"?><api><query><pages>
<page ns="0" title="DOESNOTEXIST" missing="" />
<page pageid="600799" ns="0" title="FOO" />
<page pageid="11178" ns="0" title="Foobar" />
</pages></query></api>
Pages which don't exist will appear here but they have the missing="" attribute set, as can be seen above. You can also check for the invalid attribute to be on the save side.
Now you can use your favorite xml parser to check for these attributes and react accordingly.
See also: http://www.mediawiki.org/wiki/API:Query
A:
Use Pywikibot to interact with the MediaWiki software. It's probably the most powerful bot framework available.
The Python Wikipediabot Framework (pywikipedia or PyWikipediaBot) is a
collection of tools that automate work on MediaWiki sites. Originally
designed for Wikipedia, it is now used throughout the Wikimedia
Foundation's projects and on many other MediaWiki wikis. It's written
in Python, which is a free, cross-platform programming language. This
page provides links to general information for people who want to use
the bot software.
A:
If you have local access to the wiki database, it might be easiest to do a query against the database to see whether each page exists.
If you only have HTTP access, you might try the mechanize library which lets you programmatically automate tasks that would otherwise require a browser.
A:
You should be able to use the MediaWiki API.
http://www.mediawiki.org/wiki/API (maybe under Queries or Creating/Editing)
I'm not too familiar with it, but for example, you could compare the output of an existing page with a nonexistent page.
http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Bill_Gates&rvprop=timestamp
http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=NONEXISTENT_PAGE&rvprop=timestamp
|
Check if a MediaWiki page exists (Python)
|
I'm working on a Python script that transforms this:
foo
bar
Into this:
[[Component foo]]
[[bar]]
The script checks (per input line) if the page "Component foo" exists. If it exists then a link to that page is created, if it doesn't exist then a direct link is created.
The problem is that I need a quick & cheap way to check if a lot of wiki pages exist.I don't want to (try to) download all the 'Component' pages.
I already figured out a fast way to do this by hand: Edit a new wiki page. paste all the 'component' links into the page, press preview, and then save the resulting preview HTML page. The resulting HTML file contains a different link for existing pages than for non-existing pages.
So to rephrase my question: How can I save a mediawiki preview page in Python?
(I don't have local access to the database.)
|
[
"You can definitely use the API to check if a page exists:\n# assuming words is a list of words you wish to query for\nimport urllib\n\n# replace en.wikipedia.org with the address of the wiki you want to access\nquery = \"http://en.wikipedia.org/w/api.php?action=query&titles=%s&format=xml\" % \"|\".join(words)\npages = urllib.urlopen(query)\n\nNow pages you will contain xml like this:\n<?xml version=\"1.0\"?><api><query><pages>\n\n <page ns=\"0\" title=\"DOESNOTEXIST\" missing=\"\" />\n\n <page pageid=\"600799\" ns=\"0\" title=\"FOO\" />\n\n <page pageid=\"11178\" ns=\"0\" title=\"Foobar\" />\n\n</pages></query></api>\n\nPages which don't exist will appear here but they have the missing=\"\" attribute set, as can be seen above. You can also check for the invalid attribute to be on the save side.\nNow you can use your favorite xml parser to check for these attributes and react accordingly.\nSee also: http://www.mediawiki.org/wiki/API:Query\n",
"Use Pywikibot to interact with the MediaWiki software. It's probably the most powerful bot framework available.\n\nThe Python Wikipediabot Framework (pywikipedia or PyWikipediaBot) is a\n collection of tools that automate work on MediaWiki sites. Originally\n designed for Wikipedia, it is now used throughout the Wikimedia\n Foundation's projects and on many other MediaWiki wikis. It's written\n in Python, which is a free, cross-platform programming language. This\n page provides links to general information for people who want to use\n the bot software.\n\n",
"If you have local access to the wiki database, it might be easiest to do a query against the database to see whether each page exists.\nIf you only have HTTP access, you might try the mechanize library which lets you programmatically automate tasks that would otherwise require a browser.\n",
"You should be able to use the MediaWiki API. \nhttp://www.mediawiki.org/wiki/API (maybe under Queries or Creating/Editing)\nI'm not too familiar with it, but for example, you could compare the output of an existing page with a nonexistent page.\nhttp://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Bill_Gates&rvprop=timestamp\nhttp://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=NONEXISTENT_PAGE&rvprop=timestamp\n"
] |
[
10,
5,
2,
1
] |
[] |
[] |
[
"mediawiki",
"python"
] |
stackoverflow_0002439824_mediawiki_python.txt
|
Q:
Displaying a list of items vertically in a table instead of horizontally
I have a list of items sorted alphabetically:
mylist = [a,b,c,d,e,f,g,h,i,j]
I'm able to output the list in an html table horizonally like so:
| a , b , c , d |
| e , f , g , h |
| i , j , , |
What's the algorithm to create the table vertically like this:
| a , d , g , j |
| b , e , h , |
| c , f , i , |
I'm using python, but your answer can be in any language or even pseudo-code.
A:
>>> l = [1,2,3,4,5,6,7,8,9,10]
>>> [l[i::3] for i in xrange(3)]
[[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]
Replace 3 by the number of lines you want as a result:
>>> [l[i::5] for i in xrange(5)]
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
A:
import itertools
def grouper(n, iterable, fillvalue=None):
# Source: http://docs.python.org/library/itertools.html#recipes
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
return itertools.izip_longest(*[iter(iterable)]*n,fillvalue=fillvalue)
def format_table(L):
result=[]
for row in L:
result.append('| '+', '.join(row)+' |')
return '\n'.join(result)
L = ['a','b','c','d','e','f','g','h','i','j']
L_in_rows=list(grouper(3,L,fillvalue=' '))
L_in_columns=zip(*L_in_rows)
print(format_table(L_in_columns))
# | a, d, g, j |
# | b, e, h, |
# | c, f, i, |
A:
Here's a rough solution that works (prints numbers from 0 to N-1 inclusive):
import math
NROWS = 3
N = 22
for nr in xrange(NROWS):
for nc in xrange(int(math.ceil(1.0 * N/NROWS))):
num = nc * NROWS + nr
if num < N:
print num,
print ''
This just print numbers, for example with NROWS = 3 and N = 22:
0 3 6 9 12 15 18 21
1 4 7 10 13 16 19
2 5 8 11 14 17 20
You can easily adapt it to print anything you want of course and add the required formatting.
A:
This is how I'd do it. Given the list of l (of integers, in the example).
Decide the number of columns (or rows) and,
Calculate the number of rows (or columns) needed.
Then loop through them, row by row and print the corresponding value.
See code below:
import math
l = [0,1,2,3,4,5,6,7,8,9]
num_cols=4
num_rows=int(math.ceil(1.0*len(l)/num_cols))
for r in range(num_rows):
for c in range(num_cols):
i = num_rows*c + r
if i<len(l):
print '%3d ' % l[i],
else:
print ' - ', # no value
print # linebreak
Best,
Philip
A:
>>> import numpy as np
>>> L=['a','b','c','d','e','f','g','h','i','j']
>>> width=4
>>> height = (len(L)-1)/width+1
>>> L=L+[' ']*(width*height-len(L)) #Pad to be even multiple of width
>>> A = np.array([L])
>>> A.shape=(width,height)
>>> A.transpose()
array([['a', 'd', 'g', 'j'],
['b', 'e', 'h', ' '],
['c', 'f', 'i', ' ']],
dtype='|S1')
|
Displaying a list of items vertically in a table instead of horizontally
|
I have a list of items sorted alphabetically:
mylist = [a,b,c,d,e,f,g,h,i,j]
I'm able to output the list in an html table horizonally like so:
| a , b , c , d |
| e , f , g , h |
| i , j , , |
What's the algorithm to create the table vertically like this:
| a , d , g , j |
| b , e , h , |
| c , f , i , |
I'm using python, but your answer can be in any language or even pseudo-code.
|
[
">>> l = [1,2,3,4,5,6,7,8,9,10]\n>>> [l[i::3] for i in xrange(3)]\n[[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]\n\nReplace 3 by the number of lines you want as a result:\n>>> [l[i::5] for i in xrange(5)]\n[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]\n\n",
"import itertools\ndef grouper(n, iterable, fillvalue=None):\n # Source: http://docs.python.org/library/itertools.html#recipes\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n return itertools.izip_longest(*[iter(iterable)]*n,fillvalue=fillvalue)\n\ndef format_table(L):\n result=[]\n for row in L:\n result.append('| '+', '.join(row)+' |')\n return '\\n'.join(result)\n\nL = ['a','b','c','d','e','f','g','h','i','j']\nL_in_rows=list(grouper(3,L,fillvalue=' '))\nL_in_columns=zip(*L_in_rows)\nprint(format_table(L_in_columns))\n# | a, d, g, j |\n# | b, e, h, |\n# | c, f, i, |\n\n",
"Here's a rough solution that works (prints numbers from 0 to N-1 inclusive):\nimport math\n\nNROWS = 3\nN = 22\n\nfor nr in xrange(NROWS):\n for nc in xrange(int(math.ceil(1.0 * N/NROWS))):\n num = nc * NROWS + nr\n if num < N:\n print num,\n print ''\n\nThis just print numbers, for example with NROWS = 3 and N = 22:\n0 3 6 9 12 15 18 21 \n1 4 7 10 13 16 19 \n2 5 8 11 14 17 20 \n\nYou can easily adapt it to print anything you want of course and add the required formatting.\n",
"This is how I'd do it. Given the list of l (of integers, in the example).\n\nDecide the number of columns (or rows) and,\nCalculate the number of rows (or columns) needed.\nThen loop through them, row by row and print the corresponding value.\n\nSee code below:\nimport math\nl = [0,1,2,3,4,5,6,7,8,9]\nnum_cols=4\nnum_rows=int(math.ceil(1.0*len(l)/num_cols))\n\nfor r in range(num_rows):\n for c in range(num_cols):\n i = num_rows*c + r\n if i<len(l):\n print '%3d ' % l[i],\n else:\n print ' - ', # no value\n print # linebreak\n\nBest,\nPhilip\n",
">>> import numpy as np\n>>> L=['a','b','c','d','e','f','g','h','i','j']\n>>> width=4\n>>> height = (len(L)-1)/width+1\n>>> L=L+[' ']*(width*height-len(L)) #Pad to be even multiple of width \n>>> A = np.array([L])\n>>> A.shape=(width,height)\n>>> A.transpose()\narray([['a', 'd', 'g', 'j'],\n ['b', 'e', 'h', ' '],\n ['c', 'f', 'i', ' ']], \n dtype='|S1')\n\n"
] |
[
9,
1,
0,
0,
0
] |
[
"int array_size = 26;\nint col_size = 4;\n\nfor (int i = 0; i <= array_size/col_size; ++i) {\n for (int j = i; j < array_size; j += col_size-1) {\n print (a[j]);\n }\n print(\"\\n\");\n}\n\n"
] |
[
-1
] |
[
"html",
"python",
"tabular"
] |
stackoverflow_0002495046_html_python_tabular.txt
|
Q:
Filtering documents against a dictionary key in MongoDB
I have a collection of articles in MongoDB that has the following structure:
{
'category': 'Legislature',
'updated': datetime.datetime(2010, 3, 19, 15, 32, 22, 107000),
'byline': None,
'tags': {
'party': ['Peter Hoekstra', 'Virg Bernero', 'Alma Smith', 'Mike Bouchard', 'Tom George', 'Rick Snyder'],
'geography': ['Michigan', 'United States', 'North America']
},
'headline': '2 Mich. gubernatorial candidates speak to students',
'text': [
'BEVERLY HILLS, Mich. (AP) \u2014 Two Democratic and Republican gubernatorial candidates found common ground while speaking to private school students in suburban Detroit',
"Democratic House Speaker state Rep. Andy Dillon and Republican U.S. Rep. Pete Hoekstra said Friday a more business-friendly government can help reduce Michigan's nation-leading unemployment rate.",
"The candidates were invited to Detroit Country Day Upper School in Beverly Hills to offer ideas for Michigan's future.",
'Besides Dillon, the Democratic field includes Lansing Mayor Virg Bernero and state Rep. Alma Wheeler Smith. Other Republicans running are Oakland County Sheriff Mike Bouchard, Attorney General Mike Cox, state Sen. Tom George and Ann Arbor business leader Rick Snyder.',
'Former Republican U.S. Rep. Joe Schwarz is considering running as an independent.'
],
'dateline': 'BEVERLY HILLS, Mich.',
'published': datetime.datetime(2010, 3, 19, 8, 0, 31),
'keywords': "Governor's Race",
'_id': ObjectId('4ba39721e0e16cb25fadbb40'),
'article_id': 'urn:publicid:ap.org:0611e36fb084458aa620c0187999db7e',
'slug': "BC-MI--Governor's Race,2nd Ld-Writethr"
}
If I wanted to write a query that looked for all articles that had at least 1 geography tag, how would I do that? I have tried writing db.articles.find( {'tags': 'geography'} ), but that doesn't appear to work. I've also thought about changing the search parameter to 'tags.geography', but am having a devil of a time figuring out what the search predicate would be.
A:
If the "geography" field doesn't exist when there aren't any tags in it (i.e., it's created when you add a location), you could do:
db.articles.find({tags.geography : {$exists : true}})
If it does exists and is empty (i.e., "geography" : []) you should add a geography_size field or something and do:
db.articles.find({tags.geography_size : {$gte : 1}})
There's more info on queries at http://www.mongodb.org/display/DOCS/Advanced+Queries
|
Filtering documents against a dictionary key in MongoDB
|
I have a collection of articles in MongoDB that has the following structure:
{
'category': 'Legislature',
'updated': datetime.datetime(2010, 3, 19, 15, 32, 22, 107000),
'byline': None,
'tags': {
'party': ['Peter Hoekstra', 'Virg Bernero', 'Alma Smith', 'Mike Bouchard', 'Tom George', 'Rick Snyder'],
'geography': ['Michigan', 'United States', 'North America']
},
'headline': '2 Mich. gubernatorial candidates speak to students',
'text': [
'BEVERLY HILLS, Mich. (AP) \u2014 Two Democratic and Republican gubernatorial candidates found common ground while speaking to private school students in suburban Detroit',
"Democratic House Speaker state Rep. Andy Dillon and Republican U.S. Rep. Pete Hoekstra said Friday a more business-friendly government can help reduce Michigan's nation-leading unemployment rate.",
"The candidates were invited to Detroit Country Day Upper School in Beverly Hills to offer ideas for Michigan's future.",
'Besides Dillon, the Democratic field includes Lansing Mayor Virg Bernero and state Rep. Alma Wheeler Smith. Other Republicans running are Oakland County Sheriff Mike Bouchard, Attorney General Mike Cox, state Sen. Tom George and Ann Arbor business leader Rick Snyder.',
'Former Republican U.S. Rep. Joe Schwarz is considering running as an independent.'
],
'dateline': 'BEVERLY HILLS, Mich.',
'published': datetime.datetime(2010, 3, 19, 8, 0, 31),
'keywords': "Governor's Race",
'_id': ObjectId('4ba39721e0e16cb25fadbb40'),
'article_id': 'urn:publicid:ap.org:0611e36fb084458aa620c0187999db7e',
'slug': "BC-MI--Governor's Race,2nd Ld-Writethr"
}
If I wanted to write a query that looked for all articles that had at least 1 geography tag, how would I do that? I have tried writing db.articles.find( {'tags': 'geography'} ), but that doesn't appear to work. I've also thought about changing the search parameter to 'tags.geography', but am having a devil of a time figuring out what the search predicate would be.
|
[
"If the \"geography\" field doesn't exist when there aren't any tags in it (i.e., it's created when you add a location), you could do:\ndb.articles.find({tags.geography : {$exists : true}})\n\nIf it does exists and is empty (i.e., \"geography\" : []) you should add a geography_size field or something and do:\ndb.articles.find({tags.geography_size : {$gte : 1}})\n\nThere's more info on queries at http://www.mongodb.org/display/DOCS/Advanced+Queries\n"
] |
[
10
] |
[] |
[] |
[
"mongodb",
"pymongo",
"python"
] |
stackoverflow_0002495932_mongodb_pymongo_python.txt
|
Q:
Django - provide additional information in template
I am building an app to learn Django and have started with a Contact system that currently stores Contacts and Addresses. C's are a many to many relationship with A's, but rather than use Django's models.ManyToManyField() I've created my own link-table providing additional information about the link, such as what the address type is to the that contact (home, work etc). What I'm trying to do is pass this information out to a view, so in my full view of a contact I can do this:
def contact_view_full(request, contact_id):
c = get_object_or_404(Contact, id=contact_id)
a = []
links = ContactAddressLink.objects.filter(ContactID=c.id)
for link in links:
b = Address.objects.get(id=link.AddressID_id)
a.append(b)
return render_to_response('contact_full.html', {'contact_item': c, 'addresses' : a }, context_instance=RequestContext(request))
And so I can do the equivalent of c.Addresses.all() or however the ManyToManyField works. What I'm interested to know is how can I pass out information about the link in the link object with the 'addresses' : a information, so that when my template does this:
{% for address in addresses %}
<!-- ... -->
{% endfor %}
and properly associate the correct link object data with the address.
So what's the best way to achieve this? I'm thinking a union of two objects might be an idea but I haven't enough experience with Django to know if that's considered the best way of doing it. Suggestions?
Thanks in advance.
Nf
A:
In order to add extra information, you should use a ManyToMany relationship with a 'trough' extra-field :
http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships
This will lead to this code:
def contact_view_full(request, contact_id):
c = get_object_or_404(Contact, id=contact_id)
a = c.addresses.all()
return render_to_response('contact_full.html', {'contact_item': c, 'addresses' : a }, context_instance=RequestContext(request))
|
Django - provide additional information in template
|
I am building an app to learn Django and have started with a Contact system that currently stores Contacts and Addresses. C's are a many to many relationship with A's, but rather than use Django's models.ManyToManyField() I've created my own link-table providing additional information about the link, such as what the address type is to the that contact (home, work etc). What I'm trying to do is pass this information out to a view, so in my full view of a contact I can do this:
def contact_view_full(request, contact_id):
c = get_object_or_404(Contact, id=contact_id)
a = []
links = ContactAddressLink.objects.filter(ContactID=c.id)
for link in links:
b = Address.objects.get(id=link.AddressID_id)
a.append(b)
return render_to_response('contact_full.html', {'contact_item': c, 'addresses' : a }, context_instance=RequestContext(request))
And so I can do the equivalent of c.Addresses.all() or however the ManyToManyField works. What I'm interested to know is how can I pass out information about the link in the link object with the 'addresses' : a information, so that when my template does this:
{% for address in addresses %}
<!-- ... -->
{% endfor %}
and properly associate the correct link object data with the address.
So what's the best way to achieve this? I'm thinking a union of two objects might be an idea but I haven't enough experience with Django to know if that's considered the best way of doing it. Suggestions?
Thanks in advance.
Nf
|
[
"In order to add extra information, you should use a ManyToMany relationship with a 'trough' extra-field :\nhttp://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships\nThis will lead to this code:\ndef contact_view_full(request, contact_id):\n c = get_object_or_404(Contact, id=contact_id)\n a = c.addresses.all()\n return render_to_response('contact_full.html', {'contact_item': c, 'addresses' : a }, context_instance=RequestContext(request))\n\n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_templates",
"django_views",
"python"
] |
stackoverflow_0002495985_django_django_templates_django_views_python.txt
|
Q:
How do I parse timezones with UTC offsets in Python?
Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this:
datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", etc) but I don't see anything that can parse "-04".
A:
Maybe you could use dateutil.parser.parse? That method is also mentioned on wiki.python.org/WorkingWithTime.
>>> from dateutil.parser import parse
>>> parse("2009-08-18 13:52:54-04")
datetime.datetime(2009, 8, 18, 13, 52, 54, tzinfo=tzoffset(None, -14400))
(is this question a duplicate?)
A:
use Babel, specifically parse_datetime.
A:
You can do that directrly on the constructor: class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]), tzinfo being a datetime.tzinfo dervided object.
tzinfo is an abstract base clase, meaning that this class should not be instantiated directly. You need to derive a concrete subclass, and (at least) supply implementations of the standard tzinfo methods needed by the datetime methods you use. The datetime module does not supply any concrete subclasses of tzinfo.
What you need to override is the utcoffset(self, dt) method.
Return offset of local time from UTC, in minutes east of UTC. If local time is west of UTC, this should be negative. Note that this is intended to be the total offset from UTC; for example, if a tzinfo object represents both time zone and DST adjustments, utcoffset() should return their sum. If the UTC offset isn't known, return None. Else the value returned must be a timedelta object specifying a whole number of minutes in the range -1439 to 1439 inclusive (1440 = 24*60; the magnitude of the offset must be less than one day). Most implementations of utcoffset() will probably look like one of these two:
return CONSTANT # fixed-offset class
return CONSTANT + self.dst(dt) # daylight-aware class
If utcoffset() does not return None, dst() should not return None either.
The default implementation of utcoffset() raises NotImplementedError.
A:
I ran across the same issue recently and worked around it using this code:
gmt_offset_str = time_string[-3:]
gmt_offset_seconds = int(gmt_offset_str)*60*60
timestamp = time.strptime(time_string[:-4], '%Y-%m-%d %H:%M:%S')
return time.localtime(time.mktime(timestamp)-gmt_offset_seconds)
I would also be interested in a more elegant solution.
|
How do I parse timezones with UTC offsets in Python?
|
Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this:
datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", etc) but I don't see anything that can parse "-04".
|
[
"Maybe you could use dateutil.parser.parse? That method is also mentioned on wiki.python.org/WorkingWithTime.\n>>> from dateutil.parser import parse\n>>> parse(\"2009-08-18 13:52:54-04\")\ndatetime.datetime(2009, 8, 18, 13, 52, 54, tzinfo=tzoffset(None, -14400))\n\n\n(is this question a duplicate?)\n",
"use Babel, specifically parse_datetime.\n",
"You can do that directrly on the constructor: class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]), tzinfo being a datetime.tzinfo dervided object.\n\ntzinfo is an abstract base clase, meaning that this class should not be instantiated directly. You need to derive a concrete subclass, and (at least) supply implementations of the standard tzinfo methods needed by the datetime methods you use. The datetime module does not supply any concrete subclasses of tzinfo.\n\nWhat you need to override is the utcoffset(self, dt) method.\n\nReturn offset of local time from UTC, in minutes east of UTC. If local time is west of UTC, this should be negative. Note that this is intended to be the total offset from UTC; for example, if a tzinfo object represents both time zone and DST adjustments, utcoffset() should return their sum. If the UTC offset isn't known, return None. Else the value returned must be a timedelta object specifying a whole number of minutes in the range -1439 to 1439 inclusive (1440 = 24*60; the magnitude of the offset must be less than one day). Most implementations of utcoffset() will probably look like one of these two:\nreturn CONSTANT # fixed-offset class\nreturn CONSTANT + self.dst(dt) # daylight-aware class\nIf utcoffset() does not return None, dst() should not return None either.\n\nThe default implementation of utcoffset() raises NotImplementedError.\n",
"I ran across the same issue recently and worked around it using this code:\ngmt_offset_str = time_string[-3:]\ngmt_offset_seconds = int(gmt_offset_str)*60*60\ntimestamp = time.strptime(time_string[:-4], '%Y-%m-%d %H:%M:%S')\nreturn time.localtime(time.mktime(timestamp)-gmt_offset_seconds)\n\nI would also be interested in a more elegant solution.\n"
] |
[
24,
3,
0,
0
] |
[] |
[] |
[
"datetime",
"python"
] |
stackoverflow_0001302161_datetime_python.txt
|
Q:
Exception_Record in python2.5 problem
I'm using Python2.5 & the following code produce 2 errors.
Can any body help me?
class EXCEPTION_RECORD(Structure):
_fields_ = [
("ExceptionCode", DWORD),
("ExceptionFlags", DWORD),
("ExceptionRecord", POINTER(EXCEPTION_RECORD)),
("ExceptionAddress", LPVOID),
("NumberParameters", DWORD),
("ExceptionInformation", ULONG_PTR * EXCEPTION_MAXIMUM_PARAMETERS)]
Python Error:
Traceback (most recent call last):
File "E:\Python25\my_debugger_defines.py", line 70, in <module>
class EXCEPTION_RECORD(Structure):
File "E:\Python25\my_debugger_defines.py", line 74, in EXCEPTION_RECORD
("ExceptionRecord", POINTER(EXCEPTION_RECORD)),
NameError: name 'EXCEPTION_RECORD' is not defined
Microsoft Document:
The EXCEPTION_RECORD structure describes an exception.
typedef struct _EXCEPTION_RECORD { // exr
DWORD ExceptionCode;
DWORD ExceptionFlags;
struct _EXCEPTION_RECORD *ExceptionRecord;
PVOID ExceptionAddress;
DWORD NumberParameters;
DWORD ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
} EXCEPTION_RECORD;
Thanks in advance
A:
Apparently, you can't refer to a class type while defining a class, e.g.:
>>> class C:
f = C
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
class C:
File "<pyshell#17>", line 2, in C
f = C
NameError: name 'C' is not defined
However, you can work around that by doing this:
>>> class C:
pass
>>> C.f = C
I would re-write your code as follows:
class EXCEPTION_RECORD(Structure):
pass
EXCEPTION_RECORD._fields_ = [
("ExceptionCode", DWORD),
("ExceptionFlags", DWORD),
("ExceptionRecord", POINTER(EXCEPTION_RECORD)),
("ExceptionAddress", LPVOID),
("NumberParameters", DWORD),
("ExceptionInformation", ULONG_PTR * EXCEPTION_MAXIMUM_PARAMETERS)]
A:
Looks like you've done a from ctypes import * (terrible practice, as one is reduced to guess where all those identifiers like DWORD are actually coming from!-) but missed a crucial short passage in ctypes.Structure's docs:
It is possible to define the fields
class variable after the class
statement that defines the Structure
subclass, this allows to create data
types that directly or indirectly
reference themselves:
class List(Structure):
pass
List._fields_ = [("pnext", POINTER(List)),
...
]
The fields class variable must,
however, be defined before the type is
first used (an instance is created,
sizeof() is called on it, and so on).
Later assignments to the fields
class variable will raise an
AttributeError.
So, simply applying this bit of the docs to your code, you need to change that code into:
class EXCEPTION_RECORD(Structure):
pass
EXCEPTION_RECORD._fields_ = [
("ExceptionCode", DWORD),
("ExceptionFlags", DWORD),
("ExceptionRecord", POINTER(EXCEPTION_RECORD)),
("ExceptionAddress", LPVOID),
("NumberParameters", DWORD),
("ExceptionInformation", ULONG_PTR * EXCEPTION_MAXIMUM_PARAMETERS)]
A:
A class can reference itself in the __new__ or __init__ methods.
class Test(object):
def __new__(cls):
inst = object.__new__(cls)
inst.me = Test
return inst
or:
class Test(object):
def __init__(self):
super(Test, self).__init__()
self.me = Test
Or, if you wanted to really get fancy you could use a __metaclass__.
|
Exception_Record in python2.5 problem
|
I'm using Python2.5 & the following code produce 2 errors.
Can any body help me?
class EXCEPTION_RECORD(Structure):
_fields_ = [
("ExceptionCode", DWORD),
("ExceptionFlags", DWORD),
("ExceptionRecord", POINTER(EXCEPTION_RECORD)),
("ExceptionAddress", LPVOID),
("NumberParameters", DWORD),
("ExceptionInformation", ULONG_PTR * EXCEPTION_MAXIMUM_PARAMETERS)]
Python Error:
Traceback (most recent call last):
File "E:\Python25\my_debugger_defines.py", line 70, in <module>
class EXCEPTION_RECORD(Structure):
File "E:\Python25\my_debugger_defines.py", line 74, in EXCEPTION_RECORD
("ExceptionRecord", POINTER(EXCEPTION_RECORD)),
NameError: name 'EXCEPTION_RECORD' is not defined
Microsoft Document:
The EXCEPTION_RECORD structure describes an exception.
typedef struct _EXCEPTION_RECORD { // exr
DWORD ExceptionCode;
DWORD ExceptionFlags;
struct _EXCEPTION_RECORD *ExceptionRecord;
PVOID ExceptionAddress;
DWORD NumberParameters;
DWORD ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
} EXCEPTION_RECORD;
Thanks in advance
|
[
"Apparently, you can't refer to a class type while defining a class, e.g.:\n>>> class C:\n f = C\n\n\n\nTraceback (most recent call last):\n File \"<pyshell#17>\", line 1, in <module>\n class C:\n File \"<pyshell#17>\", line 2, in C\n f = C\nNameError: name 'C' is not defined\n\nHowever, you can work around that by doing this:\n>>> class C:\n pass\n\n>>> C.f = C \n\nI would re-write your code as follows:\nclass EXCEPTION_RECORD(Structure):\n pass\n\nEXCEPTION_RECORD._fields_ = [\n (\"ExceptionCode\", DWORD),\n (\"ExceptionFlags\", DWORD),\n (\"ExceptionRecord\", POINTER(EXCEPTION_RECORD)),\n (\"ExceptionAddress\", LPVOID),\n (\"NumberParameters\", DWORD),\n (\"ExceptionInformation\", ULONG_PTR * EXCEPTION_MAXIMUM_PARAMETERS)]\n\n",
"Looks like you've done a from ctypes import * (terrible practice, as one is reduced to guess where all those identifiers like DWORD are actually coming from!-) but missed a crucial short passage in ctypes.Structure's docs:\n\nIt is possible to define the fields\n class variable after the class\n statement that defines the Structure\n subclass, this allows to create data\n types that directly or indirectly\n reference themselves:\n\nclass List(Structure):\n pass\nList._fields_ = [(\"pnext\", POINTER(List)),\n ...\n ]\n\n\nThe fields class variable must,\n however, be defined before the type is\n first used (an instance is created,\n sizeof() is called on it, and so on).\n Later assignments to the fields\n class variable will raise an\n AttributeError.\n\nSo, simply applying this bit of the docs to your code, you need to change that code into:\nclass EXCEPTION_RECORD(Structure):\n pass\nEXCEPTION_RECORD._fields_ = [\n (\"ExceptionCode\", DWORD),\n (\"ExceptionFlags\", DWORD),\n (\"ExceptionRecord\", POINTER(EXCEPTION_RECORD)),\n (\"ExceptionAddress\", LPVOID),\n (\"NumberParameters\", DWORD),\n (\"ExceptionInformation\", ULONG_PTR * EXCEPTION_MAXIMUM_PARAMETERS)]\n\n",
"A class can reference itself in the __new__ or __init__ methods.\nclass Test(object):\n def __new__(cls):\n inst = object.__new__(cls)\n inst.me = Test\n return inst\n\nor:\nclass Test(object):\n def __init__(self):\n super(Test, self).__init__()\n self.me = Test\n\nOr, if you wanted to really get fancy you could use a __metaclass__.\n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"python",
"winapi"
] |
stackoverflow_0002496258_python_winapi.txt
|
Q:
SelfReferenceProperty vs. ListProperty Google App Engine
I am experimenting with the Google App Engine and have a question.
For the sake of simplicity, let's say my app is modeling a computer network (a fairly large corporate network with 10,000 nodes). I am trying to model my Node class as follows:
class Node(db.Model):
name = db.StringProperty()
neighbors = db.SelfReferenceProperty()
Let's suppose, for a minute, that I cannot use a ListProperty(). Based on my experiments to date, I can assign only a single entity to 'neighbors' - and I cannot use the "virtual" collection (node_set) to access the list of Node neighbors.
So... my questions are:
Does SelfReferenceProperty limit you to a single entity that you can reference?
If I instead use a ListProperty, I believe I am limited to 5,000 keys, which I need to exceed.
Update
All wrapped up in my shorts as I was, I forgot the *ReferenceReleationship is "backwards" --- the "list" of things points back to the one side of the relationship. The SelfReferenceProperty works as I thought it would. My bad. I'll still need to deal with the large "many" side of the relationship - and I don't think a ListProperty will do the trick, but I'll post what I find.
Thanks,
John
A:
Re 1, yes (if I understand correctly what you're asking): for each property in a model, each instance of the model (AKA "entity") has one value for that property. So e.g. an IntegerProperty has one integer value for a given entity, a SelfReferenceProperty has one value (internally a key string) for a given entity, and so forth. Not a single value for all instances of the module, of course, but I don't believe that's what you mean.
Re 2, the 5000 limit (wow, that's a lot of neighbors for a single node graph that only has 10000 nodes in all!) I believe you're referring to is on indices for an entity -- this article explains the limitation better.
One possible workaround is to have no neighbors property at all on the nodes, but rather a separate Connection model to represent the connection from one node to another (with ReferenceProperty properties, in the Connection, that each refer to a Node). You'll need something extra in the Connection (e.g., progressive counts of incoming and outgoing connections for the affected nodes) to be able to fetch many thousands of them, of course (in multiple queries, given the 1000-at-a-time limitation).
|
SelfReferenceProperty vs. ListProperty Google App Engine
|
I am experimenting with the Google App Engine and have a question.
For the sake of simplicity, let's say my app is modeling a computer network (a fairly large corporate network with 10,000 nodes). I am trying to model my Node class as follows:
class Node(db.Model):
name = db.StringProperty()
neighbors = db.SelfReferenceProperty()
Let's suppose, for a minute, that I cannot use a ListProperty(). Based on my experiments to date, I can assign only a single entity to 'neighbors' - and I cannot use the "virtual" collection (node_set) to access the list of Node neighbors.
So... my questions are:
Does SelfReferenceProperty limit you to a single entity that you can reference?
If I instead use a ListProperty, I believe I am limited to 5,000 keys, which I need to exceed.
Update
All wrapped up in my shorts as I was, I forgot the *ReferenceReleationship is "backwards" --- the "list" of things points back to the one side of the relationship. The SelfReferenceProperty works as I thought it would. My bad. I'll still need to deal with the large "many" side of the relationship - and I don't think a ListProperty will do the trick, but I'll post what I find.
Thanks,
John
|
[
"Re 1, yes (if I understand correctly what you're asking): for each property in a model, each instance of the model (AKA \"entity\") has one value for that property. So e.g. an IntegerProperty has one integer value for a given entity, a SelfReferenceProperty has one value (internally a key string) for a given entity, and so forth. Not a single value for all instances of the module, of course, but I don't believe that's what you mean.\nRe 2, the 5000 limit (wow, that's a lot of neighbors for a single node graph that only has 10000 nodes in all!) I believe you're referring to is on indices for an entity -- this article explains the limitation better.\nOne possible workaround is to have no neighbors property at all on the nodes, but rather a separate Connection model to represent the connection from one node to another (with ReferenceProperty properties, in the Connection, that each refer to a Node). You'll need something extra in the Connection (e.g., progressive counts of incoming and outgoing connections for the affected nodes) to be able to fetch many thousands of them, of course (in multiple queries, given the 1000-at-a-time limitation).\n"
] |
[
1
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002495709_google_app_engine_python.txt
|
Q:
Asynchronous background processes in Python?
I have been using this as a reference, but not able to accomplish exactly what I need: Calling an external command in Python
I also was reading this: http://www.python.org/dev/peps/pep-3145/
For our project, we have 5 svn checkouts that need to update before we can deploy our application. In my dev environment, where speedy deployments are a bit more important for productivity than a production deployment, I have been working on speeding up the process.
I have a bash script that has been working decently but has some limitations. I fire up multiple 'svn updates' with the following bash command:
(svn update /repo1) & (svn update /repo2) & (svn update /repo3) &
These all run in parallel and it works pretty well. I also use this pattern in the rest of the build script for firing off each ant build, then moving the wars to Tomcat.
However, I have no control over stopping deployment if one of the updates or a build fails.
I'm re-writing my bash script with Python so I have more control over branches and the deployment process.
I am using subprocess.call() to fire off the 'svn update /repo' commands, but each one is acting sequentially. I try '(svn update /repo) &' and those all fire off, but the result code returns immediately. So I have no way to determine if a particular command fails or not in the asynchronous mode.
import subprocess
subprocess.call( 'svn update /repo1', shell=True )
subprocess.call( 'svn update /repo2', shell=True )
subprocess.call( 'svn update /repo3', shell=True )
I'd love to find a way to have Python fire off each Unix command, and if any of the calls fails at any time the entire script stops.
A:
Don't use shell=True. It will needlessy invoke the shell to call your svn program, and that will give you the shell's return code instead of svn's.
repos = ['/repo1', '/repo2', '/repo3']
# launch 3 async calls:
procs = [subprocess.Popen(['svn', 'update', repo]) for repo in repos]
# wait.
for proc in procs:
proc.wait()
# check for results:
if any(proc.returncode != 0 for proc in procs):
print 'Something failed'
|
Asynchronous background processes in Python?
|
I have been using this as a reference, but not able to accomplish exactly what I need: Calling an external command in Python
I also was reading this: http://www.python.org/dev/peps/pep-3145/
For our project, we have 5 svn checkouts that need to update before we can deploy our application. In my dev environment, where speedy deployments are a bit more important for productivity than a production deployment, I have been working on speeding up the process.
I have a bash script that has been working decently but has some limitations. I fire up multiple 'svn updates' with the following bash command:
(svn update /repo1) & (svn update /repo2) & (svn update /repo3) &
These all run in parallel and it works pretty well. I also use this pattern in the rest of the build script for firing off each ant build, then moving the wars to Tomcat.
However, I have no control over stopping deployment if one of the updates or a build fails.
I'm re-writing my bash script with Python so I have more control over branches and the deployment process.
I am using subprocess.call() to fire off the 'svn update /repo' commands, but each one is acting sequentially. I try '(svn update /repo) &' and those all fire off, but the result code returns immediately. So I have no way to determine if a particular command fails or not in the asynchronous mode.
import subprocess
subprocess.call( 'svn update /repo1', shell=True )
subprocess.call( 'svn update /repo2', shell=True )
subprocess.call( 'svn update /repo3', shell=True )
I'd love to find a way to have Python fire off each Unix command, and if any of the calls fails at any time the entire script stops.
|
[
"Don't use shell=True. It will needlessy invoke the shell to call your svn program, and that will give you the shell's return code instead of svn's.\nrepos = ['/repo1', '/repo2', '/repo3']\n# launch 3 async calls:\nprocs = [subprocess.Popen(['svn', 'update', repo]) for repo in repos]\n# wait.\nfor proc in procs:\n proc.wait()\n# check for results:\nif any(proc.returncode != 0 for proc in procs):\n print 'Something failed'\n\n"
] |
[
18
] |
[] |
[] |
[
"asynchronous",
"background_process",
"python"
] |
stackoverflow_0002496772_asynchronous_background_process_python.txt
|
Q:
Python.expat can't parse XML file with bad symbols. How to go around?
I'm trying to parse an XML file (OSM data) with expat, and there are lines with some Unicode characters that expat can't parse:
<tag k="name"
v="абвгдежзиклмнопр�?туфхцчшщьыъ�?ю�?�?БВГДЕЖЗИКЛМ�?ОПРСТУФХЦЧШЩЬЫЪЭЮЯ" />
<tag k="name" v="Cin\x8e? Rex" />
(XML file encoding in the opening line is "UTF-8")
The file is quite old, and there must have been errors. In modern files I don't see UTF-8 errors, and they are parsed fine. But what if my program meets a broken symbol, what workaround can I make? Is it possible to join bz2 codec (I parse a compressed file) and utf-8 codec to ignore the broken characters, or change them to "?"?
A:
Not sure if '�' characters were introduced by copy-pasting string here,
but if you have them in original data, then it seems to be generator
problem which introduced \uFFFD charactes as:
"used to replace an incoming character whose value is unknown or
unrepresentable in Unicode"
citied from:
http://www.fileformat.info/info/unicode/char/fffd/index.htm
Workaround? Just idea for extension:
good = True
buf = None
while True:
if good:
buf = f.read(buf_size)
else:
# try again with cleaned buffer
pass
try:
xp.Parse(buf, len(buf) == 0)
if (len(buf) == 0):
break
good = True
except ExpatError:
if xp.ErrorCode == XML_ERROR_BAD_CHAR_REF:
# look at ErrorByteIndex (or nearby)
# for 0xEF 0xBF 0xBD (UTF8 replacement char) and remove it
good = False
else:
# other errors processing
pass
Or clean input buffer instead + corner cases (partial sequence at the buffer end).
I can't recall if python's expat allows to assign custom error handler.
That would be easier then.
If i clean yours sample from '�' characters it's processed ok.
\xd1 does not fail.
OSM data?
|
Python.expat can't parse XML file with bad symbols. How to go around?
|
I'm trying to parse an XML file (OSM data) with expat, and there are lines with some Unicode characters that expat can't parse:
<tag k="name"
v="абвгдежзиклмнопр�?туфхцчшщьыъ�?ю�?�?БВГДЕЖЗИКЛМ�?ОПРСТУФХЦЧШЩЬЫЪЭЮЯ" />
<tag k="name" v="Cin\x8e? Rex" />
(XML file encoding in the opening line is "UTF-8")
The file is quite old, and there must have been errors. In modern files I don't see UTF-8 errors, and they are parsed fine. But what if my program meets a broken symbol, what workaround can I make? Is it possible to join bz2 codec (I parse a compressed file) and utf-8 codec to ignore the broken characters, or change them to "?"?
|
[
"Not sure if '�' characters were introduced by copy-pasting string here,\nbut if you have them in original data, then it seems to be generator\nproblem which introduced \\uFFFD charactes as:\n\"used to replace an incoming character whose value is unknown or\nunrepresentable in Unicode\"\ncitied from:\nhttp://www.fileformat.info/info/unicode/char/fffd/index.htm\nWorkaround? Just idea for extension:\ngood = True\nbuf = None\nwhile True:\nif good:\n buf = f.read(buf_size)\n else:\n # try again with cleaned buffer\n pass\n try:\n xp.Parse(buf, len(buf) == 0)\n if (len(buf) == 0):\n break\n good = True\n except ExpatError:\n if xp.ErrorCode == XML_ERROR_BAD_CHAR_REF:\n # look at ErrorByteIndex (or nearby)\n # for 0xEF 0xBF 0xBD (UTF8 replacement char) and remove it\n good = False\n else:\n # other errors processing\n pass\n\nOr clean input buffer instead + corner cases (partial sequence at the buffer end).\nI can't recall if python's expat allows to assign custom error handler.\nThat would be easier then.\nIf i clean yours sample from '�' characters it's processed ok.\n\\xd1 does not fail.\nOSM data?\n"
] |
[
1
] |
[] |
[] |
[
"expat_parser",
"python",
"unicode",
"xml"
] |
stackoverflow_0002495538_expat_parser_python_unicode_xml.txt
|
Q:
add/remove items in a list
I'm trying to create a player who can add and remove items from their inventory. I have everything working, I just have 1 small problem. Every time it prints the inventory, 'None' also appears. I've been messing with it to try and remove that, but no matter what I do, 'None' always appears in the program! I know I'm just missing something simple, but I can't figure it out for the life of me.
class Player(object):
def __init__(self, name, max_items, items):
self.name=name
self.max_items=max_items
self.items=items
def inventory(self):
for item in self.items:
print item
def take(self, new_item):
if len(self.items)<self.max_items:
self.items.append(new_item)
else:
print "You can't carry any more items!"
def drop(self, old_item):
if old_item in self.items:
self.items.remove(old_item)
else:
print "You don't have that item."
def main():
player=Player("Jimmy", 5, ['sword', 'shield', 'ax'])
print "Max items:", player.max_items
print "Inventory:", player.inventory()
choice=None
while choice!="0":
print \
"""
Inventory Man
0 - Quit
1 - Add an item to inventory
2 - Remove an item from inventory
"""
choice=raw_input("Choice: ")
print
if choice=="0":
print "Good-bye."
elif choice=="1":
new_item=raw_input("What item would you like to add to your inventory?")
player.take(new_item)
print "Inventory:", player.inventory()
elif choice=="2":
old_item=raw_input("What item would you like to remove from your inventory?")
player.drop(old_item)
print "Inventory:", player.inventory()
else:
print "\nSorry, but", choice, "isn't a valid choice."
main()
raw_input("Press enter to exit.")
A:
The problem is this statement:
print "Inventory:", player.inventory()
You're telling Python to print the value returned from player.inventory(). But your inventory() method just prints the inventory, it doesn't return anything - so the return value is implicitly None.
You probably want to explicitly choose either this:
print "Inventory:"
player.print_inventory()
Or alternatively you could have it return a string and do this:
print "Inventory:", player.inventory_as_str()
A:
Would you mind replacing the function:
def inventory(self):
for item in self.items:
print item
with this:
def inventory(self):
print self.items
and then call:
print "Inventory"
player.inventory()
Or you could have the function:
def print_inventory(self):
print "Inventory:"
for item in self.items:
print item
|
add/remove items in a list
|
I'm trying to create a player who can add and remove items from their inventory. I have everything working, I just have 1 small problem. Every time it prints the inventory, 'None' also appears. I've been messing with it to try and remove that, but no matter what I do, 'None' always appears in the program! I know I'm just missing something simple, but I can't figure it out for the life of me.
class Player(object):
def __init__(self, name, max_items, items):
self.name=name
self.max_items=max_items
self.items=items
def inventory(self):
for item in self.items:
print item
def take(self, new_item):
if len(self.items)<self.max_items:
self.items.append(new_item)
else:
print "You can't carry any more items!"
def drop(self, old_item):
if old_item in self.items:
self.items.remove(old_item)
else:
print "You don't have that item."
def main():
player=Player("Jimmy", 5, ['sword', 'shield', 'ax'])
print "Max items:", player.max_items
print "Inventory:", player.inventory()
choice=None
while choice!="0":
print \
"""
Inventory Man
0 - Quit
1 - Add an item to inventory
2 - Remove an item from inventory
"""
choice=raw_input("Choice: ")
print
if choice=="0":
print "Good-bye."
elif choice=="1":
new_item=raw_input("What item would you like to add to your inventory?")
player.take(new_item)
print "Inventory:", player.inventory()
elif choice=="2":
old_item=raw_input("What item would you like to remove from your inventory?")
player.drop(old_item)
print "Inventory:", player.inventory()
else:
print "\nSorry, but", choice, "isn't a valid choice."
main()
raw_input("Press enter to exit.")
|
[
"The problem is this statement:\nprint \"Inventory:\", player.inventory()\n\nYou're telling Python to print the value returned from player.inventory(). But your inventory() method just prints the inventory, it doesn't return anything - so the return value is implicitly None.\nYou probably want to explicitly choose either this:\nprint \"Inventory:\"\nplayer.print_inventory()\n\nOr alternatively you could have it return a string and do this:\nprint \"Inventory:\", player.inventory_as_str()\n\n",
"Would you mind replacing the function:\ndef inventory(self):\n for item in self.items:\n print item\n\nwith this:\ndef inventory(self):\n print self.items\n\nand then call:\nprint \"Inventory\"\nplayer.inventory()\n\nOr you could have the function:\ndef print_inventory(self):\n print \"Inventory:\"\n for item in self.items:\n print item\n\n"
] |
[
4,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002496926_python.txt
|
Q:
python duration of a file object in an argument list
In the pickle module documentation there is a snippet of example code:
reader = pickle.load(open('save.p', 'rb'))
which upon first read looked like it would allocate a system file descriptor, read its contents and then "leak" the open descriptor for there isn't any handle accessible to call close() upon. This got me wondering if there was any hidden magic that takes care of this case.
Diving into the source, I found in Modules/_fileio.c that file descriptors are closed by the fileio_dealloc() destructor which led to the real question.
What is the duration of the file object used by the example code above? After that statement executes does the object indeed become unreferenced and therefore will the fd be subject to a real close(2) call at some future garbage collection sweep? If so, is the example line good practice, or should one not count on the fd being released thus risking kernel per-process descriptor table exhaustion?
A:
What is the duration of the file
object returned by the example code
above?
That code does not return the file object (as the Q's title correctly says, it receives it as an argument).
In current CPython, the file will be closed at the time the function return (since the function doesn't stash away any references to the file object to more durable places). In other implementations, the file will be closed "eventually" but there's no precise time specified.
Depending on CPython's immediate-closure semantics (which may change when a future CPython moves to better garbage-collection mechanisms), while a very traditional approach, is not best practice.
Rather, best practice is to use the with statement:
with open(...) as f:
reader = pickle.load(f)
With this use, the file's immediate closure (as soon as the body of the with statement ends) is guaranteed in all implementations.
Note that, in Python 2.5, you need a from __future__ import with_statement to use with. In 2.6 or better, such an "import from the future" is not required for this purpose (it's innocuous, but if you know you're never going to be running under 2.5 it's redundant and better removed).
|
python duration of a file object in an argument list
|
In the pickle module documentation there is a snippet of example code:
reader = pickle.load(open('save.p', 'rb'))
which upon first read looked like it would allocate a system file descriptor, read its contents and then "leak" the open descriptor for there isn't any handle accessible to call close() upon. This got me wondering if there was any hidden magic that takes care of this case.
Diving into the source, I found in Modules/_fileio.c that file descriptors are closed by the fileio_dealloc() destructor which led to the real question.
What is the duration of the file object used by the example code above? After that statement executes does the object indeed become unreferenced and therefore will the fd be subject to a real close(2) call at some future garbage collection sweep? If so, is the example line good practice, or should one not count on the fd being released thus risking kernel per-process descriptor table exhaustion?
|
[
"\nWhat is the duration of the file\n object returned by the example code\n above?\n\nThat code does not return the file object (as the Q's title correctly says, it receives it as an argument).\nIn current CPython, the file will be closed at the time the function return (since the function doesn't stash away any references to the file object to more durable places). In other implementations, the file will be closed \"eventually\" but there's no precise time specified.\nDepending on CPython's immediate-closure semantics (which may change when a future CPython moves to better garbage-collection mechanisms), while a very traditional approach, is not best practice.\nRather, best practice is to use the with statement:\nwith open(...) as f:\n reader = pickle.load(f)\n\nWith this use, the file's immediate closure (as soon as the body of the with statement ends) is guaranteed in all implementations.\nNote that, in Python 2.5, you need a from __future__ import with_statement to use with. In 2.6 or better, such an \"import from the future\" is not required for this purpose (it's innocuous, but if you know you're never going to be running under 2.5 it's redundant and better removed).\n"
] |
[
3
] |
[] |
[] |
[
"internals",
"python"
] |
stackoverflow_0002496983_internals_python.txt
|
Q:
How to disable Excel's auto recognition of numbers and text
I used Python to generate a CSV file. But when I open it in Excel, Excel will auto recognize a string into a number if it could be converted.
e.g.33E105 becomes 33*10^105, which is actually an ID, not a number.
How to disable this in Excel while opening a CSV file? Or I need to resort to a excel-python library to output a excel file and specify the format myself?
I also found a similar question without good answers on the web.
Thanks!
A:
You could precede it with a single quote, forcing it to text.
A fun answer is you could keep the first eight rows blank (it only processes the first eight rows to determine data type), although I think this may blank all your data entirely. You could hide those empty rows.
A:
You have 3 options:
Output a specially formatted XML file that Excel can read. I don't recall any details but if interested, I can dig them up. We did that with our Perl code. I don't know if excel-python does just that.
Place ' (apostrophe) before each string.
Use a library which outputs native Excel file with proper formatting. No clue if such exists for Python, but it is kind of an overkill variant of the first option on any case.
A:
I think you can put a single ' in front to stop numeric strings being turned into ints
Eg.
...,"'33E105",...
OpenXML is a more flexible (and complicated) option, but only works with Office2003 or newer and is overkill for this problem. More suited to cases when you need highlighting of cells/multiple sheets, etc.
A:
To write actual .xls files in Python, rather than .csv ones that Excel might misinterpret, you can use the xlwt third-party Python package.
A:
If you dont' want to change how you're writing the CSV file you can use the Text Import Wizard in Excel to specify how you want the individual columns to be treated. There is one step in the wizard that lets you select what type of data is in each column. Set the column(s) you want to Text and it will treat it as a string.
|
How to disable Excel's auto recognition of numbers and text
|
I used Python to generate a CSV file. But when I open it in Excel, Excel will auto recognize a string into a number if it could be converted.
e.g.33E105 becomes 33*10^105, which is actually an ID, not a number.
How to disable this in Excel while opening a CSV file? Or I need to resort to a excel-python library to output a excel file and specify the format myself?
I also found a similar question without good answers on the web.
Thanks!
|
[
"You could precede it with a single quote, forcing it to text.\nA fun answer is you could keep the first eight rows blank (it only processes the first eight rows to determine data type), although I think this may blank all your data entirely. You could hide those empty rows.\n",
"You have 3 options:\n\nOutput a specially formatted XML file that Excel can read. I don't recall any details but if interested, I can dig them up. We did that with our Perl code. I don't know if excel-python does just that.\nPlace ' (apostrophe) before each string.\nUse a library which outputs native Excel file with proper formatting. No clue if such exists for Python, but it is kind of an overkill variant of the first option on any case.\n\n",
"I think you can put a single ' in front to stop numeric strings being turned into ints\nEg.\n...,\"'33E105\",...\n\nOpenXML is a more flexible (and complicated) option, but only works with Office2003 or newer and is overkill for this problem. More suited to cases when you need highlighting of cells/multiple sheets, etc.\n",
"To write actual .xls files in Python, rather than .csv ones that Excel might misinterpret, you can use the xlwt third-party Python package.\n",
"If you dont' want to change how you're writing the CSV file you can use the Text Import Wizard in Excel to specify how you want the individual columns to be treated. There is one step in the wizard that lets you select what type of data is in each column. Set the column(s) you want to Text and it will treat it as a string.\n"
] |
[
4,
3,
2,
1,
0
] |
[] |
[] |
[
"excel",
"python"
] |
stackoverflow_0002496990_excel_python.txt
|
Q:
convert a binary file in a list (python)
I'd like to be able to open a binary file, and make a list (kind of array) with all the chars in, like : "\x21\x23\x22\x21\x22\x31" to ["\x21","\x23","\x22","\x21","\x22","\x31"]
What would be the best solution to convert it ?
Thanks !
A:
You need to understand that "\x21" and "!" are two ways of representing the same thing
so "\x21\x23\x22\x21\x22\x31" is the same as '!#"!"1'
>>> "\x21\x23\x22\x21\x22\x31" == '!#"!"1'
True
>>> infile = open('infile.txt', 'rb')
>>> list(infile.read())
['!', '#', '"', '!', '"', '1']
>>> ['!', '#', '"', '!', '"', '1'] == ["\x21","\x23","\x22","\x21","\x22","\x31"]
True
So you see they are the same thing, but python always tries to pick the most user friendly way to display the characters
A:
You can read the binary data into a string just like you would do with text data, just make sure to open the file in binary mode (the b flag in the call to open()):
with open('file.bin', 'rb') as f:
data = f.read()
data now contains the characters from the file as a string, like "\x21\x23\x22\x21\x22\x31".
A:
Assume that myfile.txt has 'abcdef\n' in it...
>>> fh = open('myfile.txt', 'rb')
>>> list(fh.read())
['a', 'b', 'c', 'd', 'e', 'f', '\n']
A:
To make "a kind of array" of characters, an extremely efficient way (more than using a list!) is to use Python's standard library array module:
res = array.array('c')
with open('binaryfile', 'rb') as f:
while True:
try: res.fromfile(f, 1024 * 1024)
except EOFError: break
This reads no more than a megabyte at a time (that's the 1024 * 1024), but keeps going until the file's all done -- you can tweak that behavior as you prefer, of course.
|
convert a binary file in a list (python)
|
I'd like to be able to open a binary file, and make a list (kind of array) with all the chars in, like : "\x21\x23\x22\x21\x22\x31" to ["\x21","\x23","\x22","\x21","\x22","\x31"]
What would be the best solution to convert it ?
Thanks !
|
[
"You need to understand that \"\\x21\" and \"!\" are two ways of representing the same thing\nso \"\\x21\\x23\\x22\\x21\\x22\\x31\" is the same as '!#\"!\"1'\n>>> \"\\x21\\x23\\x22\\x21\\x22\\x31\" == '!#\"!\"1'\nTrue\n\n>>> infile = open('infile.txt', 'rb')\n>>> list(infile.read())\n['!', '#', '\"', '!', '\"', '1']\n>>> ['!', '#', '\"', '!', '\"', '1'] == [\"\\x21\",\"\\x23\",\"\\x22\",\"\\x21\",\"\\x22\",\"\\x31\"]\nTrue\n\nSo you see they are the same thing, but python always tries to pick the most user friendly way to display the characters\n",
"You can read the binary data into a string just like you would do with text data, just make sure to open the file in binary mode (the b flag in the call to open()):\nwith open('file.bin', 'rb') as f:\n data = f.read()\n\ndata now contains the characters from the file as a string, like \"\\x21\\x23\\x22\\x21\\x22\\x31\".\n",
"Assume that myfile.txt has 'abcdef\\n' in it...\n>>> fh = open('myfile.txt', 'rb')\n>>> list(fh.read())\n['a', 'b', 'c', 'd', 'e', 'f', '\\n']\n\n",
"To make \"a kind of array\" of characters, an extremely efficient way (more than using a list!) is to use Python's standard library array module:\nres = array.array('c')\nwith open('binaryfile', 'rb') as f:\n while True:\n try: res.fromfile(f, 1024 * 1024)\n except EOFError: break\n\nThis reads no more than a megabyte at a time (that's the 1024 * 1024), but keeps going until the file's all done -- you can tweak that behavior as you prefer, of course.\n"
] |
[
4,
2,
1,
1
] |
[] |
[] |
[
"binary",
"list",
"python"
] |
stackoverflow_0002496854_binary_list_python.txt
|
Q:
Can I create class properties during __new__ or __init__?
I want to do something like this, but I haven't had much success so far. I would like to make each attr a property that computes _lazy_eval only when accessed:
class Base(object):
def __init__(self):
for attr in self._myattrs:
setattr(self, attr, property(lambda self: self._lazy_eval(attr)))
def _lazy_eval(self, attr):
#Do complex stuff here
return attr
class Child(Base):
_myattrs = ['foo', 'bar']
me = Child()
print me.foo
print me.bar
#desired output:
#"foo"
#"bar"
** UPDATE **
This doesn't work either:
class Base(object):
def __new__(cls):
for attr in cls._myattrs:
setattr(cls, attr, property(lambda self: self._lazy_eval(attr)))
return object.__new__(cls)
#Actual output (it sets both .foo and .bar equal to "bar"??)
#bar
#bar
** UPDATE 2 **
Used the __metaclass__ solution, but stuck it in Base.__new__ instead. It looks like it needed a better defined closure -- "prop()" -- to form the property correctly:
class Base(object):
def __new__(cls):
def prop(x):
return property(lambda self: self._lazy_eval(x))
for attr in cls._myattrs:
setattr(cls, attr, prop(attr))
return object.__new__(cls)
#Actual output! It works!
#foo
#bar
A:
Descriptors (such as instances of the property type) are only meaningful when they're held in the class object, not the instance object. So, you need to change the class, not the instance, and (in Python 2.6 or better) a class decorator is very handy for that purpose:
class Base(object):
def _lazy_eval(self, attr):
#Do complex stuff here
return attr
def lazyclass(cls):
for attr in cls._myattrs:
setattr(cls, attr, property(lambda self: self._lazy_eval(attr)))
return cls
@lazyclass
class Child(Base):
_myattrs = ['foo', 'bar']
If you're stuck with Python 2.5 or earlier, the decorator syntax doesn't apply to classes, but it's easy to get the same effect, just with less nifty syntax -- change the last 3 rows to:
class Child(Base):
_myattrs = ['foo', 'bar']
Child = lazyclass(Child)
which has the same semantics as the class decorator syntax.
A:
You can access class attributes through the __ class __ dict
self.__class__.attr
A:
Technically you want a metaclass:
class LazyMeta(type):
def __init__(cls, name, bases, attr):
super(LazyMeta, cls).__init__(name, bases, attr)
def prop( x ):
return property(lambda self: self._lazy_eval(x))
for x in attr['lazyattrs']:
setattr(cls, x, prop(x))
class Base(object):
__metaclass__ = LazyMeta
lazyattrs = []
def _lazy_eval(self, attr):
#Do complex stuff here
return attr
class Child(Base):
lazyattrs = ['foo', 'bar']
me = Child()
print me.foo
print me.bar
A:
You could consider using __getattr__() instead:
class Base(object):
def __getattr__(self, attr):
if attr not in self._myattrs:
raise AttributeError
return self._lazy_eval(attr)
def _lazy_eval(self, attr):
#Do complex stuff here
return attr
class Child(Base):
_myattrs = ['foo', 'bar']
me = Child()
print me.foo
print me.bar
|
Can I create class properties during __new__ or __init__?
|
I want to do something like this, but I haven't had much success so far. I would like to make each attr a property that computes _lazy_eval only when accessed:
class Base(object):
def __init__(self):
for attr in self._myattrs:
setattr(self, attr, property(lambda self: self._lazy_eval(attr)))
def _lazy_eval(self, attr):
#Do complex stuff here
return attr
class Child(Base):
_myattrs = ['foo', 'bar']
me = Child()
print me.foo
print me.bar
#desired output:
#"foo"
#"bar"
** UPDATE **
This doesn't work either:
class Base(object):
def __new__(cls):
for attr in cls._myattrs:
setattr(cls, attr, property(lambda self: self._lazy_eval(attr)))
return object.__new__(cls)
#Actual output (it sets both .foo and .bar equal to "bar"??)
#bar
#bar
** UPDATE 2 **
Used the __metaclass__ solution, but stuck it in Base.__new__ instead. It looks like it needed a better defined closure -- "prop()" -- to form the property correctly:
class Base(object):
def __new__(cls):
def prop(x):
return property(lambda self: self._lazy_eval(x))
for attr in cls._myattrs:
setattr(cls, attr, prop(attr))
return object.__new__(cls)
#Actual output! It works!
#foo
#bar
|
[
"Descriptors (such as instances of the property type) are only meaningful when they're held in the class object, not the instance object. So, you need to change the class, not the instance, and (in Python 2.6 or better) a class decorator is very handy for that purpose:\nclass Base(object):\n def _lazy_eval(self, attr):\n #Do complex stuff here\n return attr\n\ndef lazyclass(cls):\n for attr in cls._myattrs:\n setattr(cls, attr, property(lambda self: self._lazy_eval(attr)))\n return cls\n\n@lazyclass\nclass Child(Base):\n _myattrs = ['foo', 'bar']\n\nIf you're stuck with Python 2.5 or earlier, the decorator syntax doesn't apply to classes, but it's easy to get the same effect, just with less nifty syntax -- change the last 3 rows to:\nclass Child(Base):\n _myattrs = ['foo', 'bar']\nChild = lazyclass(Child)\n\nwhich has the same semantics as the class decorator syntax.\n",
"You can access class attributes through the __ class __ dict\nself.__class__.attr\n\n",
"Technically you want a metaclass:\nclass LazyMeta(type):\n def __init__(cls, name, bases, attr):\n super(LazyMeta, cls).__init__(name, bases, attr)\n def prop( x ):\n return property(lambda self: self._lazy_eval(x))\n for x in attr['lazyattrs']:\n setattr(cls, x, prop(x))\n\nclass Base(object):\n __metaclass__ = LazyMeta\n lazyattrs = []\n def _lazy_eval(self, attr):\n #Do complex stuff here\n return attr\n\nclass Child(Base):\n lazyattrs = ['foo', 'bar']\n\nme = Child()\n\nprint me.foo\nprint me.bar\n\n",
"You could consider using __getattr__() instead:\n\nclass Base(object):\n def __getattr__(self, attr):\n if attr not in self._myattrs:\n raise AttributeError\n return self._lazy_eval(attr)\n\n def _lazy_eval(self, attr):\n #Do complex stuff here\n return attr\n\n\nclass Child(Base):\n _myattrs = ['foo', 'bar']\n\nme = Child()\nprint me.foo\nprint me.bar\n\n"
] |
[
5,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002496930_python.txt
|
Q:
Python: Dynamic attribute name generation without exec() or eval()
I'm trying to dynamically create buttons at runtime with PyQT4.7
However, this being my first python program I'm not sure how to get the functionality I want.
I would like to be able to substitute a text string for an attribute name:
i.e.
for each in xrange(4):
myname = "tab1_button%s" % each #tab1_button0, tab1_button1, tab1_button2
#self.ui.tab1_button0 = QtGui.QPushButton(self.ui.tab) <--normal code to create a named button
setattr(self.ui,myname,QtGui.QPushButton(self.ui.tab)) #rewrite of line above to dynamicly generate a button
#here's where I get stuck. this code isn't valid, but it shows what i want to do
self.ui.gridLayout.addWidget(self.ui.%s) % myname
#I need to have %s be tab1_button1, tab1_button2, etc. I know the % is for string substituion but how can I substitute the dynamically generated attribute name into that statement?
I assume there's a basica language construct I'm missing that allows this. Since it's my first program, please take it easy on me ;)
A:
If I interpreted this correctly, I think what you want is this:
self.ui.gridLayout.addWidget(getattr(self.ui,myname))
Give that a go. In Python the following two statements are functionally equivalent (from the link below):
value = obj.attribute
value = getattr(obj, "attribute-name")
For extra context:
http://effbot.org/zone/python-getattr.htm
A:
Just assign the button to a variable so you can both set the attribute and add the widget.
for i in range(4):
name = 'button%d' % i
button = QtGui.QPushButton(...)
setattr(self, name, button)
self.ui.gridLayout.addWidget(button)
Personally I would add the buttons to a list instead of giving them different names.
A:
I think you might benefit from knowledge of lists (commonly called arrays in other languages)
self.buttons = [None, None, None, None]
for each in xrange(4):
self.buttons[each] = QtGui.QPushButton(self.ui.tab)
self.ui.gridLayout.addWidget(self.buttons[each])
For a tutorial on Python lists:
http://effbot.org/zone/python-list.htm
|
Python: Dynamic attribute name generation without exec() or eval()
|
I'm trying to dynamically create buttons at runtime with PyQT4.7
However, this being my first python program I'm not sure how to get the functionality I want.
I would like to be able to substitute a text string for an attribute name:
i.e.
for each in xrange(4):
myname = "tab1_button%s" % each #tab1_button0, tab1_button1, tab1_button2
#self.ui.tab1_button0 = QtGui.QPushButton(self.ui.tab) <--normal code to create a named button
setattr(self.ui,myname,QtGui.QPushButton(self.ui.tab)) #rewrite of line above to dynamicly generate a button
#here's where I get stuck. this code isn't valid, but it shows what i want to do
self.ui.gridLayout.addWidget(self.ui.%s) % myname
#I need to have %s be tab1_button1, tab1_button2, etc. I know the % is for string substituion but how can I substitute the dynamically generated attribute name into that statement?
I assume there's a basica language construct I'm missing that allows this. Since it's my first program, please take it easy on me ;)
|
[
"If I interpreted this correctly, I think what you want is this:\nself.ui.gridLayout.addWidget(getattr(self.ui,myname))\nGive that a go. In Python the following two statements are functionally equivalent (from the link below):\nvalue = obj.attribute\nvalue = getattr(obj, \"attribute-name\")\n\nFor extra context:\nhttp://effbot.org/zone/python-getattr.htm\n",
"Just assign the button to a variable so you can both set the attribute and add the widget.\nfor i in range(4):\n name = 'button%d' % i\n button = QtGui.QPushButton(...)\n setattr(self, name, button)\n self.ui.gridLayout.addWidget(button)\n\nPersonally I would add the buttons to a list instead of giving them different names.\n",
"I think you might benefit from knowledge of lists (commonly called arrays in other languages)\nself.buttons = [None, None, None, None]\nfor each in xrange(4):\n self.buttons[each] = QtGui.QPushButton(self.ui.tab)\n self.ui.gridLayout.addWidget(self.buttons[each])\n\nFor a tutorial on Python lists:\nhttp://effbot.org/zone/python-list.htm\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"pyqt4",
"python"
] |
stackoverflow_0002497168_pyqt4_python.txt
|
Q:
read a binary file (python)
I cant read a file, and I dont understand why:
f = open("test/test.pdf", "r")
data = list(f.read())
print data
Returns : []
I would like to open a PDF, and extract every bytes, and put it in a List.
What's wrong with my code ? :(
Thanks,
A:
f = open("test/test.pdf", "rb")
You must include the pseudo-mode "b" for binary when reading and writing on Windows. Otherwise the OS silently translates what it considers to be "line endings", causing i/o corruption.
A:
Jonathan is correct that you should be opening the file in binary mode if you are on windows.
However, a PDF file will start with "%PDF-", which would at least be read in regardless of whether you are using binary mode or not.
So it appears to me that your "test/test.pdf" is an empty file
A:
As best as I understand the pdf format, a pdf file shouldn't be a binary file. It should be a text file that may contain lots of binary blobs. I could be wrong.
On Windows, if you are opening a binary file, you need to include b in the mode of your file, i.e. open(filename, "rb").
On Unix-like systems, the b doesn't hurt anything, though it does not mean anything.
Always use a context manager with your files. That is to say, instead of writing f = open("test/test.pdf", "rb"), say with open("test/test.pdf", "r") as f:. This will assure your file always gets closed.
list(f.read()) is not likely to be useful code very often. f.read() reaurns a str and calling list on it makes a list of the characters (one-byte strings). This is very seldom needed.
Binary or text or whatever, read should work. Are you positive that there is anything in test/test.pdf? Python does not seem to think there is.
A:
What platform are you running on?
Using python 2.6 on Windows XP, I get:
f = open("14500lf.pdf", "r")
data = list(f.read())
print data
['%', 'P', 'D', 'F', '-', '1', '.', '5', '\r', '%', '\xe2', '\xe3', '\xcf', '\xd3', '\n', '1', ' ', '0', ' ', 'o', 'b', 'j', '<', '<', '/', 'C', 'o', 'n', 't', 'e', 'n', 't', 's', ' ', '3', ' ', '0', ' ', 'R', '/', 'T', 'y', 'p', 'e', '/', 'P', 'a', 'g', 'e', '/', 'P', 'a', 'r', 'e', 'n', 't', ' ', '8', '7', ' ', '0', ' ', 'R', '/', 'T', 'h', 'u', 'm', 'b', ' ', '7', '1', ' ', '0', ' ', 'R', '/', 'R', 'o', 't', 'a', 't', 'e', ' ', '0', '/', 'M', 'e', 'd', 'i', 'a', 'B', 'o', 'x', '[', '0', ' ', '0', ' ', '6', '1', '2', ' ', '7', '9', '2', ']', '/', 'C', 'r', 'o', 'p', 'B', 'o', 'x', '[', '0', ' ', '0', ' ', '6', '1', '2', ' ',
'7', '9', '2', ']', '/', 'R', 'e', 's', 'o', 'u', 'r', 'c', 'e', 's', ' ', '2', ' ', '0', ' ', 'R', '>', '>', '\r', 'e', 'n', 'd', 'o', 'b', 'j', '\r', '2', ' ', '0', ' ', 'o', 'b', 'j', '<', '<', '/', 'C', 'o', 'l', 'o', 'r', 'S', 'p', 'a', 'c', 'e', '<', '<', '/', 'D', 'e', 'f', 'a', 'u', 'l', 't', 'R', 'G', 'B', ' ', '1', '0', '0', ' ', '0', ' ', 'R', '>', '>', '/', 'F', 'o', 'n', 't', '<', '<', '/', 'F', '5', ' ', '9', '6', ' ', '0', ' ', 'R', '/', 'F', '7', ' ', '9', '7', ' ', '0', ' ', 'R', '/', 'F', '9', ' ', '1', '0', '6', ' ', '0', ' ', 'R', '/', 'F', '1', '1', ' ', '1', '0', '7', ' ', '0', ' ', 'R', '/', 'F', '1', '4', ' ', '1', '1', '1', ' ', '0', ' ', 'R', '/', 'F', '1', '6', ' ', '1', '1', '6', ' ', '0', ' ', 'R', '/', 'F', '1', '7', ' ',
'1', '1', '7', ' ', '0', ' ', 'R', '/', 'F', '1', '3', ' ', '1', '1', '2', ' ', '0', ' ', 'R', '>', '>', '/', 'P', 'r', 'o', 'c', 'S', 'e', 't', '[', '/', 'P', 'D', 'F', '/', 'T', 'e', 'x', 't', ']', '>', '>', '\r', 'e', 'n', 'd', 'o', 'b', 'j', '\r', '3', ' ', '0', ' ', 'o', 'b', 'j', '<', '<', '/', 'L', 'e', 'n', 'g', 't', 'h', ' ', '4', ' ', '0', ' ', 'R', '/', 'F', 'i', 'l', 't', 'e', 'r', '/', 'F', 'l', 'a', 't', 'e', 'D', 'e', 'c', 'o', 'd', 'e', '>', '>', 's', 't', 'r', 'e', 'a', 'm', '\n', 'H',
'\x89', '\xa4', 'W', '\xd9', 'r', 'T', '\xc9', '\x11', '\xfd', '\x82', '\xfb', '\x0f', '\xf5', '\xd8', '\n', '\x8f', '\x8a', '\xda', '\x97', 'G', '!', '\x04', '\x06', '\x03']
On a PDF I happen to have on my desktop (Its a IC Datasheet LTC1450)
Using "rb" (Read Binary):
f = open("14500lf.pdf", "rb")
data = list(f.read())
print data
['%', 'P', 'D', 'F', '-', '1', '.', '5', '\r', '%', '\xe2', '\xe3', '\xcf', '\xd3', '\r', '\n', '1', ' ', '0', ' ', 'o', 'b', 'j', '<', '<', '/', 'C', 'o', 'n', 't', 'e', 'n', 't', 's', ' ', '3', ' ', '0', ' ', 'R', '/', 'T', 'y', 'p', 'e', '/', 'P', 'a', 'g', 'e', '/', 'P', 'a', 'r', 'e', 'n', 't', ' ', '8', '7', ' ', '0', ' ', 'R', '/', 'T', 'h', 'u', 'm', 'b', ' ', '7', '1',
' ', '0', ' ', 'R', '/', 'R', 'o', 't', 'a', 't', 'e', ' ', '0', '/', 'M', 'e', 'd', 'i', 'a', 'B', 'o', 'x', '[', '0', ' ', '0', ' ', '6', '1', '2', ' ', '7', '9', '2', ']', '/', 'C', 'r', 'o', 'p', 'B', 'o', 'x', '[', '0', ' ', '0', ' ', '6', '1', '2', ' ', '7', '9', '2', ']', '/', 'R', 'e', 's', 'o', 'u', 'r', 'c', 'e', 's', ' ', '2', ' ', '0', ' ', 'R', '>', '>', '\r', 'e',
....Snip a few thousand lines...
'9', '1', ' ', '0', ' ', 'R', '/', 'I', 'D', '[', '<', 'd', 'd', '3', 'd', '2', '8',
'5', 'e', '1', 'd', '9', '0', '4', '6', 'e', '1', 'f', '6', 'e', '7', '0', '8', 'b', 'd', '8', 'e', '4', 'f', '9', 'b', '1', '3', '>', '<', '4', '3', '8', 'a', '7', '7', '2', '3', 'f', 'b', '2', '9', 'e', '7', '4', '6', 'a', '4', 'd', '4', '1', '6', 'a', 'f', '7', '6', '2', 'd', '8', '0', '9', '5', '>', ']', '>', '>', '\r', '\n', 's', 't', 'a', 'r', 't', 'x', 'r', 'e', 'f', '\r', '\n', '2', '9', '0', '2', '6', '9', '\r', '\n', '%', '%', 'E', 'O', 'F', '\r', '\n']
|
read a binary file (python)
|
I cant read a file, and I dont understand why:
f = open("test/test.pdf", "r")
data = list(f.read())
print data
Returns : []
I would like to open a PDF, and extract every bytes, and put it in a List.
What's wrong with my code ? :(
Thanks,
|
[
"f = open(\"test/test.pdf\", \"rb\")\n\nYou must include the pseudo-mode \"b\" for binary when reading and writing on Windows. Otherwise the OS silently translates what it considers to be \"line endings\", causing i/o corruption.\n",
"Jonathan is correct that you should be opening the file in binary mode if you are on windows.\nHowever, a PDF file will start with \"%PDF-\", which would at least be read in regardless of whether you are using binary mode or not.\nSo it appears to me that your \"test/test.pdf\" is an empty file\n",
"\nAs best as I understand the pdf format, a pdf file shouldn't be a binary file. It should be a text file that may contain lots of binary blobs. I could be wrong.\nOn Windows, if you are opening a binary file, you need to include b in the mode of your file, i.e. open(filename, \"rb\").\n\n\nOn Unix-like systems, the b doesn't hurt anything, though it does not mean anything.\n\nAlways use a context manager with your files. That is to say, instead of writing f = open(\"test/test.pdf\", \"rb\"), say with open(\"test/test.pdf\", \"r\") as f:. This will assure your file always gets closed.\nlist(f.read()) is not likely to be useful code very often. f.read() reaurns a str and calling list on it makes a list of the characters (one-byte strings). This is very seldom needed.\nBinary or text or whatever, read should work. Are you positive that there is anything in test/test.pdf? Python does not seem to think there is.\n\n",
"What platform are you running on?\nUsing python 2.6 on Windows XP, I get:\n\n\n\nf = open(\"14500lf.pdf\", \"r\")\n data = list(f.read())\n print data\n ['%', 'P', 'D', 'F', '-', '1', '.', '5', '\\r', '%', '\\xe2', '\\xe3', '\\xcf', '\\xd3', '\\n', '1', ' ', '0', ' ', 'o', 'b', 'j', '<', '<', '/', 'C', 'o', 'n', 't', 'e', 'n', 't', 's', ' ', '3', ' ', '0', ' ', 'R', '/', 'T', 'y', 'p', 'e', '/', 'P', 'a', 'g', 'e', '/', 'P', 'a', 'r', 'e', 'n', 't', ' ', '8', '7', ' ', '0', ' ', 'R', '/', 'T', 'h', 'u', 'm', 'b', ' ', '7', '1', ' ', '0', ' ', 'R', '/', 'R', 'o', 't', 'a', 't', 'e', ' ', '0', '/', 'M', 'e', 'd', 'i', 'a', 'B', 'o', 'x', '[', '0', ' ', '0', ' ', '6', '1', '2', ' ', '7', '9', '2', ']', '/', 'C', 'r', 'o', 'p', 'B', 'o', 'x', '[', '0', ' ', '0', ' ', '6', '1', '2', ' ',\n '7', '9', '2', ']', '/', 'R', 'e', 's', 'o', 'u', 'r', 'c', 'e', 's', ' ', '2', ' ', '0', ' ', 'R', '>', '>', '\\r', 'e', 'n', 'd', 'o', 'b', 'j', '\\r', '2', ' ', '0', ' ', 'o', 'b', 'j', '<', '<', '/', 'C', 'o', 'l', 'o', 'r', 'S', 'p', 'a', 'c', 'e', '<', '<', '/', 'D', 'e', 'f', 'a', 'u', 'l', 't', 'R', 'G', 'B', ' ', '1', '0', '0', ' ', '0', ' ', 'R', '>', '>', '/', 'F', 'o', 'n', 't', '<', '<', '/', 'F', '5', ' ', '9', '6', ' ', '0', ' ', 'R', '/', 'F', '7', ' ', '9', '7', ' ', '0', ' ', 'R', '/', 'F', '9', ' ', '1', '0', '6', ' ', '0', ' ', 'R', '/', 'F', '1', '1', ' ', '1', '0', '7', ' ', '0', ' ', 'R', '/', 'F', '1', '4', ' ', '1', '1', '1', ' ', '0', ' ', 'R', '/', 'F', '1', '6', ' ', '1', '1', '6', ' ', '0', ' ', 'R', '/', 'F', '1', '7', ' ',\n '1', '1', '7', ' ', '0', ' ', 'R', '/', 'F', '1', '3', ' ', '1', '1', '2', ' ', '0', ' ', 'R', '>', '>', '/', 'P', 'r', 'o', 'c', 'S', 'e', 't', '[', '/', 'P', 'D', 'F', '/', 'T', 'e', 'x', 't', ']', '>', '>', '\\r', 'e', 'n', 'd', 'o', 'b', 'j', '\\r', '3', ' ', '0', ' ', 'o', 'b', 'j', '<', '<', '/', 'L', 'e', 'n', 'g', 't', 'h', ' ', '4', ' ', '0', ' ', 'R', '/', 'F', 'i', 'l', 't', 'e', 'r', '/', 'F', 'l', 'a', 't', 'e', 'D', 'e', 'c', 'o', 'd', 'e', '>', '>', 's', 't', 'r', 'e', 'a', 'm', '\\n', 'H',\n '\\x89', '\\xa4', 'W', '\\xd9', 'r', 'T', '\\xc9', '\\x11', '\\xfd', '\\x82', '\\xfb', '\\x0f', '\\xf5', '\\xd8', '\\n', '\\x8f', '\\x8a', '\\xda', '\\x97', 'G', '!', '\\x04', '\\x06', '\\x03']\n\n\n\nOn a PDF I happen to have on my desktop (Its a IC Datasheet LTC1450)\nUsing \"rb\" (Read Binary):\n\n\n\nf = open(\"14500lf.pdf\", \"rb\")\n data = list(f.read())\n print data\n ['%', 'P', 'D', 'F', '-', '1', '.', '5', '\\r', '%', '\\xe2', '\\xe3', '\\xcf', '\\xd3', '\\r', '\\n', '1', ' ', '0', ' ', 'o', 'b', 'j', '<', '<', '/', 'C', 'o', 'n', 't', 'e', 'n', 't', 's', ' ', '3', ' ', '0', ' ', 'R', '/', 'T', 'y', 'p', 'e', '/', 'P', 'a', 'g', 'e', '/', 'P', 'a', 'r', 'e', 'n', 't', ' ', '8', '7', ' ', '0', ' ', 'R', '/', 'T', 'h', 'u', 'm', 'b', ' ', '7', '1',\n ' ', '0', ' ', 'R', '/', 'R', 'o', 't', 'a', 't', 'e', ' ', '0', '/', 'M', 'e', 'd', 'i', 'a', 'B', 'o', 'x', '[', '0', ' ', '0', ' ', '6', '1', '2', ' ', '7', '9', '2', ']', '/', 'C', 'r', 'o', 'p', 'B', 'o', 'x', '[', '0', ' ', '0', ' ', '6', '1', '2', ' ', '7', '9', '2', ']', '/', 'R', 'e', 's', 'o', 'u', 'r', 'c', 'e', 's', ' ', '2', ' ', '0', ' ', 'R', '>', '>', '\\r', 'e',\n....Snip a few thousand lines...\n'9', '1', ' ', '0', ' ', 'R', '/', 'I', 'D', '[', '<', 'd', 'd', '3', 'd', '2', '8',\n '5', 'e', '1', 'd', '9', '0', '4', '6', 'e', '1', 'f', '6', 'e', '7', '0', '8', 'b', 'd', '8', 'e', '4', 'f', '9', 'b', '1', '3', '>', '<', '4', '3', '8', 'a', '7', '7', '2', '3', 'f', 'b', '2', '9', 'e', '7', '4', '6', 'a', '4', 'd', '4', '1', '6', 'a', 'f', '7', '6', '2', 'd', '8', '0', '9', '5', '>', ']', '>', '>', '\\r', '\\n', 's', 't', 'a', 'r', 't', 'x', 'r', 'e', 'f', '\\r', '\\n', '2', '9', '0', '2', '6', '9', '\\r', '\\n', '%', '%', 'E', 'O', 'F', '\\r', '\\n']\n\n\n\n"
] |
[
12,
1,
1,
0
] |
[] |
[] |
[
"file",
"io",
"python"
] |
stackoverflow_0002497027_file_io_python.txt
|
Q:
How to make python_select work for '$>python' command?
I installed a couple of pythons in different versions with macports, and the apple python 2.6 is also working. Now I need to run a program which requires MySQLdb package support in python, and this package was installed to the python I installed by macports. The program tells me that there is no MySQLdb installed, so I guess it is the apple python working for that program.
I searched for some help and found python_select for switching between pythons. However after the command
$>sudo python_select python25
told me that it selected the version "python25" for python, when I type
$>python
it is still apple python 2.6 that launches.
The question is that how can I make python25(the one with MySQLdb) work for the program rather than apple python?
Another important thing, the program is NOT a .py file and needs to be compiled before running. So do I need to re-install this program? My Mac OS version is Snow Leopard 10.6.
Any answer is appreciated.
A:
By default, MacPorts installs user programs (or links to them) in /opt/local/bin. The MacPorts select_python command selects which python instance is linked to /opt/local/bin/python. It has no effect (nor should it) on what Apple installs in /usr/bin, which is where the Apple-supplied python and python2.x commands are.
To invoke the MacPorts python2.5, you either need to ensure that /opt/local/bin precedes /usr/bin on your shell $PATH (you can do this by modifying your .bash_profile or other shell initialization script) or you can simply invoke the desired python with an absolute path reference:
$ /usr/bin/python your-program.py
to use the Apple-supplied default python;
$ /opt/local/bin/python your-program.py
to use the version selected with python_select, or:
$ /opt/local/bin/python2.5 your-program.py
to explicitly select the MacPorts 2.5 one.
EDIT:
To modify your search PATH to use MacPorts, add this line to .bash_profile:
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
A:
First, I am not sure with Mac, coz I never use it before.
but in Linux, when I do whereis python
It will show like /usr/bin/python /usr/local/bin/python ....etc
in my .bashrc file, I just export PATH=/usr/local/bin:/usr/bin:$PATH when I want /usr/local/bin more priority
or you still can run like
/usr/bin/python yourpython.py
or
/usr/local/bin/python yourpython.py
depends on your python install locations
just my 2 cents. sorry if my answer dont make you any helps.
A:
'python' in the Mac is just a link. Do a 'which python', 'cd' to the directory in which 'python' resides, and then do an 'ls -a py*'. You shall see where python is pointing too. If you want that python to point to your different version of python, just make it link to the right version.
|
How to make python_select work for '$>python' command?
|
I installed a couple of pythons in different versions with macports, and the apple python 2.6 is also working. Now I need to run a program which requires MySQLdb package support in python, and this package was installed to the python I installed by macports. The program tells me that there is no MySQLdb installed, so I guess it is the apple python working for that program.
I searched for some help and found python_select for switching between pythons. However after the command
$>sudo python_select python25
told me that it selected the version "python25" for python, when I type
$>python
it is still apple python 2.6 that launches.
The question is that how can I make python25(the one with MySQLdb) work for the program rather than apple python?
Another important thing, the program is NOT a .py file and needs to be compiled before running. So do I need to re-install this program? My Mac OS version is Snow Leopard 10.6.
Any answer is appreciated.
|
[
"By default, MacPorts installs user programs (or links to them) in /opt/local/bin. The MacPorts select_python command selects which python instance is linked to /opt/local/bin/python. It has no effect (nor should it) on what Apple installs in /usr/bin, which is where the Apple-supplied python and python2.x commands are.\nTo invoke the MacPorts python2.5, you either need to ensure that /opt/local/bin precedes /usr/bin on your shell $PATH (you can do this by modifying your .bash_profile or other shell initialization script) or you can simply invoke the desired python with an absolute path reference:\n$ /usr/bin/python your-program.py\n\nto use the Apple-supplied default python;\n$ /opt/local/bin/python your-program.py\n\nto use the version selected with python_select, or:\n$ /opt/local/bin/python2.5 your-program.py\n\nto explicitly select the MacPorts 2.5 one.\nEDIT:\nTo modify your search PATH to use MacPorts, add this line to .bash_profile:\nexport PATH=/opt/local/bin:/opt/local/sbin:$PATH\n\n",
"First, I am not sure with Mac, coz I never use it before.\nbut in Linux, when I do whereis python\nIt will show like /usr/bin/python /usr/local/bin/python ....etc\nin my .bashrc file, I just export PATH=/usr/local/bin:/usr/bin:$PATH when I want /usr/local/bin more priority \nor you still can run like\n/usr/bin/python yourpython.py\n\nor\n/usr/local/bin/python yourpython.py \n\ndepends on your python install locations\njust my 2 cents. sorry if my answer dont make you any helps.\n",
"'python' in the Mac is just a link. Do a 'which python', 'cd' to the directory in which 'python' resides, and then do an 'ls -a py*'. You shall see where python is pointing too. If you want that python to point to your different version of python, just make it link to the right version.\n"
] |
[
7,
0,
0
] |
[] |
[] |
[
"macos",
"mysql",
"python"
] |
stackoverflow_0001768881_macos_mysql_python.txt
|
Q:
I am currently serving my static files in Django. How do I use Apache2 to do this?
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
As you can see, I have a directory called "media" under my Django project.
I would like to delete this line in my urls.py and instead us Apache to serve my static files. What do I do to my Apache configs (which files do I change) in order to do this?
By the way, I installed Apache2 like normal:
sudo aptitude install apache2
A:
I would read Django's official static files docs and apache mod_python documentation.
This example sets up Django at the
site root but explicitly disables
Django for the media subdirectory and
any URL that ends with .jpg, .gif or
.png:
<Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
</Location>
<Location "/media">
SetHandler None
</Location>
<LocationMatch "\.(jpg|gif|png)$">
SetHandler None
</LocationMatch>
|
I am currently serving my static files in Django. How do I use Apache2 to do this?
|
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
As you can see, I have a directory called "media" under my Django project.
I would like to delete this line in my urls.py and instead us Apache to serve my static files. What do I do to my Apache configs (which files do I change) in order to do this?
By the way, I installed Apache2 like normal:
sudo aptitude install apache2
|
[
"I would read Django's official static files docs and apache mod_python documentation.\n\nThis example sets up Django at the\n site root but explicitly disables\n Django for the media subdirectory and\n any URL that ends with .jpg, .gif or\n .png:\n\n<Location \"/\">\n SetHandler python-program\n PythonHandler django.core.handlers.modpython\n SetEnv DJANGO_SETTINGS_MODULE mysite.settings\n</Location>\n\n<Location \"/media\">\n SetHandler None\n</Location>\n\n<LocationMatch \"\\.(jpg|gif|png)$\">\n SetHandler None\n</LocationMatch>\n\n"
] |
[
4
] |
[] |
[] |
[
"apache",
"django",
"linux",
"python",
"unix"
] |
stackoverflow_0002497485_apache_django_linux_python_unix.txt
|
Q:
I'm making a simulated tv
I need to make a tv that shows the user the channel and the volume, and shows whether or not the television is on. I have the majority of the code made, but for some reason the channels won't switch. I'm fairly unfamiliar with how properties work, and I think that's what my problem here is. Help please.
class Television(object):
def __init__(self, __channel=1, volume=1, is_on=0):
self.__channel=__channel
self.volume=volume
self.is_on=is_on
def __str__(self):
if self.is_on==1:
print "The tv is on"
print self.__channel
print self.volume
else:
print "The television is off."
def toggle_power(self):
if self.is_on==1:
self.is_on=0
return self.is_on
if self.is_on==0:
self.is_on=1
return self.is_on
def get_channel(self):
return channel
def set_channel(self, choice):
if self.is_on==1:
if choice>=0 and choice<=499:
channel=self.__channel
else:
print "Invalid channel!"
else:
print "The television isn't on!"
channel=property(get_channel, set_channel)
def raise_volume(self, up=1):
if self.is_on==1:
self.volume+=up
if self.volume>=10:
self.volume=10
print "Max volume!"
else:
print "The television isn't on!"
def lower_volume(self, down=1):
if self.is_on==1:
self.volume-=down
if self.volume<=0:
self.volume=0
print "Muted!"
else:
print "The television isn't on!"
def main():
tv=Television()
choice=None
while choice!="0":
print \
"""
Television
0 - Exit
1 - Toggle Power
2 - Change Channel
3 - Raise Volume
4 - Lower Volume
"""
choice=raw_input("Choice: ")
print
if choice=="0":
print "Good-bye."
elif choice=="1":
tv.toggle_power()
tv.__str__()
elif choice=="2":
change=raw_input("What would you like to change the channel to?")
tv.set_channel(change)
tv.__str__()
elif choice=="3":
tv.raise_volume()
tv.__str__()
elif choice=="4":
tv.lower_volume()
tv.__str__()
else:
print "\nSorry, but", choice, "isn't a valid choice."
main()
raw_input("Press enter to exit.")
A:
The channel number is integer, but raw_input returns string. Should be:
change = int(raw_input("What would you like to change the channel to?"))
also your set_channel function has this:
channel=self.__channel
When it should be:
self.__channel = choice
Those two changes make it work.
A:
EXTRA HINTS:
Posting this as community wiki so everybody can help with ideas and hints.
Don't name your attributes starting with two underscores. It doesn't mean private. If you want some private name, use a single underscore.
You're not really using the channel property you created.
Use True and False instead of 1 and 0 for the is_on
__str__ method should return a string, not print one. And then you don't invoke it directly, you just print the instance and it will be invoked by python (usually you don't invoke methods that start and end with two underscores yourself)
Code using hints above:
class Television(object):
def __init__(self, channel=1, volume=1, is_on=False):
self._channel= channel
self.volume = volume
self.is_on = is_on
def __str__(self):
volume = self.volume
if not volume:
volume = 'muted'
elif volume == 10:
volume = 'max'
if self.is_on:
return "The TV is on, channel {0}, volume {1}".format(self.channel, volume)
else:
return "The TV is off."
def toggle_power(self):
self.is_on = not self.is_on
return self.is_on
def get_channel(self):
return self._channel
def set_channel(self, choice):
self._check_on()
if 0 <= choice <= 499:
self._channel = choice
else:
raise ValueError('Invalid channel')
channel = property(get_channel, set_channel)
def _check_on(self):
if not self.is_on:
raise ValueError("The television isn't on")
def raise_volume(self, up=1):
self._check_on()
self.volume += up
if self.volume >= 10:
self.volume = 10
def lower_volume(self, down=1):
self._check_on()
self.volume -= down
if self.volume <= 0:
self.volume = 0
def main():
tv = Television()
while True:
print 'Status:', tv
print \
"""
Television
0 - Exit
1 - Toggle Power
2 - Change Channel
3 - Raise Volume
4 - Lower Volume
"""
choice=raw_input("Choice: ")
try:
if choice=="0":
break
elif choice=="1":
tv.toggle_power()
elif choice=="2":
change=int(raw_input("What would you like to change the channel to? "))
tv.set_channel(change)
elif choice=="3":
tv.raise_volume()
elif choice=="4":
tv.lower_volume()
else:
raise ValueError("Sorry, but {0} isn't a valid choice.".format(choice))
except ValueError as e:
print '\n\n *** ERROR: {0}\n'.format(e)
main()
raw_input("Press enter to exit.")
|
I'm making a simulated tv
|
I need to make a tv that shows the user the channel and the volume, and shows whether or not the television is on. I have the majority of the code made, but for some reason the channels won't switch. I'm fairly unfamiliar with how properties work, and I think that's what my problem here is. Help please.
class Television(object):
def __init__(self, __channel=1, volume=1, is_on=0):
self.__channel=__channel
self.volume=volume
self.is_on=is_on
def __str__(self):
if self.is_on==1:
print "The tv is on"
print self.__channel
print self.volume
else:
print "The television is off."
def toggle_power(self):
if self.is_on==1:
self.is_on=0
return self.is_on
if self.is_on==0:
self.is_on=1
return self.is_on
def get_channel(self):
return channel
def set_channel(self, choice):
if self.is_on==1:
if choice>=0 and choice<=499:
channel=self.__channel
else:
print "Invalid channel!"
else:
print "The television isn't on!"
channel=property(get_channel, set_channel)
def raise_volume(self, up=1):
if self.is_on==1:
self.volume+=up
if self.volume>=10:
self.volume=10
print "Max volume!"
else:
print "The television isn't on!"
def lower_volume(self, down=1):
if self.is_on==1:
self.volume-=down
if self.volume<=0:
self.volume=0
print "Muted!"
else:
print "The television isn't on!"
def main():
tv=Television()
choice=None
while choice!="0":
print \
"""
Television
0 - Exit
1 - Toggle Power
2 - Change Channel
3 - Raise Volume
4 - Lower Volume
"""
choice=raw_input("Choice: ")
print
if choice=="0":
print "Good-bye."
elif choice=="1":
tv.toggle_power()
tv.__str__()
elif choice=="2":
change=raw_input("What would you like to change the channel to?")
tv.set_channel(change)
tv.__str__()
elif choice=="3":
tv.raise_volume()
tv.__str__()
elif choice=="4":
tv.lower_volume()
tv.__str__()
else:
print "\nSorry, but", choice, "isn't a valid choice."
main()
raw_input("Press enter to exit.")
|
[
"\nThe channel number is integer, but raw_input returns string. Should be:\nchange = int(raw_input(\"What would you like to change the channel to?\"))\n\nalso your set_channel function has this:\nchannel=self.__channel\n\nWhen it should be:\nself.__channel = choice\n\n\nThose two changes make it work.\n",
"EXTRA HINTS:\nPosting this as community wiki so everybody can help with ideas and hints.\n\nDon't name your attributes starting with two underscores. It doesn't mean private. If you want some private name, use a single underscore.\nYou're not really using the channel property you created.\nUse True and False instead of 1 and 0 for the is_on\n__str__ method should return a string, not print one. And then you don't invoke it directly, you just print the instance and it will be invoked by python (usually you don't invoke methods that start and end with two underscores yourself)\n\n\nCode using hints above:\nclass Television(object):\n def __init__(self, channel=1, volume=1, is_on=False):\n self._channel= channel\n self.volume = volume\n self.is_on = is_on\n\n def __str__(self):\n volume = self.volume\n if not volume:\n volume = 'muted'\n elif volume == 10:\n volume = 'max'\n if self.is_on:\n return \"The TV is on, channel {0}, volume {1}\".format(self.channel, volume)\n else:\n return \"The TV is off.\"\n\n def toggle_power(self):\n self.is_on = not self.is_on\n return self.is_on\n\n def get_channel(self):\n return self._channel\n\n def set_channel(self, choice):\n self._check_on()\n if 0 <= choice <= 499:\n self._channel = choice\n else:\n raise ValueError('Invalid channel')\n\n channel = property(get_channel, set_channel)\n\n def _check_on(self):\n if not self.is_on:\n raise ValueError(\"The television isn't on\")\n\n def raise_volume(self, up=1):\n self._check_on()\n self.volume += up\n if self.volume >= 10:\n self.volume = 10\n\n def lower_volume(self, down=1):\n self._check_on()\n self.volume -= down\n if self.volume <= 0:\n self.volume = 0\n\ndef main():\n tv = Television()\n while True:\n print 'Status:', tv\n print \\\n \"\"\"\n Television\n\n 0 - Exit\n 1 - Toggle Power\n 2 - Change Channel\n 3 - Raise Volume\n 4 - Lower Volume\n \"\"\"\n choice=raw_input(\"Choice: \")\n\n try:\n if choice==\"0\":\n break\n elif choice==\"1\":\n tv.toggle_power()\n elif choice==\"2\":\n change=int(raw_input(\"What would you like to change the channel to? \"))\n tv.set_channel(change)\n elif choice==\"3\":\n tv.raise_volume()\n elif choice==\"4\":\n tv.lower_volume()\n else:\n raise ValueError(\"Sorry, but {0} isn't a valid choice.\".format(choice))\n except ValueError as e:\n print '\\n\\n *** ERROR: {0}\\n'.format(e)\n\nmain()\nraw_input(\"Press enter to exit.\")\n\n"
] |
[
5,
3
] |
[] |
[] |
[
"class",
"properties",
"python"
] |
stackoverflow_0002497525_class_properties_python.txt
|
Q:
How can I tell [G]vim where to look for python26.dll?
I have a version of Vim compiled with python 2.6 support enabled (from here). however vim cannot find the python26.dll.
:version confirms +python/dyn
:version and gvim.exe confirms DYNAMIC_PYTHON_DLL="python26.dll"
echo PATH confirms python26.dll is in the search path.
(both c:\windows\system32, and C:\python26)
What could I be missing? Did I skip something silly?
UPDATE Nevermind. I just saw it. Vim is x86 and python is x64. Sorry to waste your time. Score 1 for Dependancy Walker
A:
Be sure that any dll you try to load is compiled for the same architecture as the exe.
e.g. If you have x86 Vim installed. Make sure that the python dll you are loading is not x64, or vice-versa.
|
How can I tell [G]vim where to look for python26.dll?
|
I have a version of Vim compiled with python 2.6 support enabled (from here). however vim cannot find the python26.dll.
:version confirms +python/dyn
:version and gvim.exe confirms DYNAMIC_PYTHON_DLL="python26.dll"
echo PATH confirms python26.dll is in the search path.
(both c:\windows\system32, and C:\python26)
What could I be missing? Did I skip something silly?
UPDATE Nevermind. I just saw it. Vim is x86 and python is x64. Sorry to waste your time. Score 1 for Dependancy Walker
|
[
"Be sure that any dll you try to load is compiled for the same architecture as the exe. \ne.g. If you have x86 Vim installed. Make sure that the python dll you are loading is not x64, or vice-versa.\n"
] |
[
8
] |
[] |
[] |
[
"python",
"vim"
] |
stackoverflow_0002497551_python_vim.txt
|
Q:
Updating section in ConfigParser (or an alternative)
I am making a plugin for another program and so I am trying to make thing as lightweight as possible.
What i need to do is be able to update the name of a section in the ConfigParser's config file.
[project name]
author:john doe
email: spam@example.com
year: 2010
I then have text fields where user can edit project's name, author, email and year.
I don't think changing [project name] is possible, so I have thought of two solutions:
1 -Have my config file like this:
[0]
projectname: foobar
author:john doe
email: spam@example.com
year: 2010
that way i can change project's name just like another option. But the problem is, i would need the section # to be auto incremented ([0], [1], etc). And to do this i would have to get every section, sort of, and figure out what the next number should be.
The other option would be to delete the entire section and its value, and re-add it with the updated values which would require a little more work as well, such as passing a variable that holds the old section name through functions, etc, but i wouldn't mind if it's faster.
Which of the two is best? or is there another way?
I am willing to go with the fastest/lightweight solution possible, doesn't matter if it requires more work or not.
A:
ini files are probably best suited for configuring applications, with well-defined inputs and so forth. It sounds like you want a more generic serialization tool; JSON would probably work well for this. Perhaps you want to store a JSON representation of a list (hence your incrementing indices) of dicts with those fields?
The usage of the json module in the stdlib is pretty simple. For example, to store a couple records you would
import json
projects = []
projects.append({'project_name': 'foobar',
'author': 'John Doe',
'email': 'spam@example.com',
'year': '2010'})
projects.append({'project_name': 'baz',
'author': 'Cat Stevens',
'email': 'cs@example.com',
'year': '2009'})
with open('projects.json', 'w') as f:
json.dump(projects, f)
Similarly you would recover the serialized data from the file with json.load(f), where you have opened f in read mode.
|
Updating section in ConfigParser (or an alternative)
|
I am making a plugin for another program and so I am trying to make thing as lightweight as possible.
What i need to do is be able to update the name of a section in the ConfigParser's config file.
[project name]
author:john doe
email: spam@example.com
year: 2010
I then have text fields where user can edit project's name, author, email and year.
I don't think changing [project name] is possible, so I have thought of two solutions:
1 -Have my config file like this:
[0]
projectname: foobar
author:john doe
email: spam@example.com
year: 2010
that way i can change project's name just like another option. But the problem is, i would need the section # to be auto incremented ([0], [1], etc). And to do this i would have to get every section, sort of, and figure out what the next number should be.
The other option would be to delete the entire section and its value, and re-add it with the updated values which would require a little more work as well, such as passing a variable that holds the old section name through functions, etc, but i wouldn't mind if it's faster.
Which of the two is best? or is there another way?
I am willing to go with the fastest/lightweight solution possible, doesn't matter if it requires more work or not.
|
[
"ini files are probably best suited for configuring applications, with well-defined inputs and so forth. It sounds like you want a more generic serialization tool; JSON would probably work well for this. Perhaps you want to store a JSON representation of a list (hence your incrementing indices) of dicts with those fields?\nThe usage of the json module in the stdlib is pretty simple. For example, to store a couple records you would \nimport json\n\nprojects = []\nprojects.append({'project_name': 'foobar', \n 'author': 'John Doe', \n 'email': 'spam@example.com', \n 'year': '2010'})\nprojects.append({'project_name': 'baz', \n 'author': 'Cat Stevens', \n 'email': 'cs@example.com', \n 'year': '2009'})\n\nwith open('projects.json', 'w') as f:\n json.dump(projects, f)\n\nSimilarly you would recover the serialized data from the file with json.load(f), where you have opened f in read mode.\n"
] |
[
2
] |
[] |
[] |
[
"configparser",
"python"
] |
stackoverflow_0002497717_configparser_python.txt
|
Q:
Python overriding class (not instance) special methods
How do I override a class special method?
I want to be able to call the __str__() method of the class without creating an instance. Example:
class Foo:
def __str__(self):
return 'Bar'
class StaticFoo:
@staticmethod
def __str__():
return 'StaticBar'
class ClassFoo:
@classmethod
def __str__(cls):
return 'ClassBar'
if __name__ == '__main__':
print(Foo)
print(Foo())
print(StaticFoo)
print(StaticFoo())
print(ClassFoo)
print(ClassFoo())
produces:
<class '__main__.Foo'>
Bar
<class '__main__.StaticFoo'>
StaticBar
<class '__main__.ClassFoo'>
ClassBar
should be:
Bar
Bar
StaticBar
StaticBar
ClassBar
ClassBar
Even if I use the @staticmethod or @classmethod the __str__ is still using the built-in Python definition for __str__. It's only working when it's Foo().__str__() instead of Foo.__str__().
A:
Special method __str__ defined in a class works only for the instances of that class, to have the different behavior for class objects you will have to do it in a metaclass of that class e.g. (python 2.5)
class Meta(type):
def __str__(self):
return "Klass"
class A(object):
__metaclass__ = Meta
def __str__(self):
return "instance"
print A
print A()
output:
Klass
instance
A:
Why do you want to abuse the meaning of __str__? That method name (like many dunder method names) is special in Python, being an instance method with the meaning "return a string representation of this instance of the class".
If you want a function that just returns a static string, it would be better to have that as a separate function not inside a class.
If you want a constructor that returns a new string, name it something else so it's not clobbering the special __str__ name.
If you want a method for printing a representation of the class, you should not use the name __str__ for that. That name is – as the dunder-style name implies – expected to have particular behaviour as defined in the Python documentation. Choose some (non-dunder) name which you can give your special meaning, and don't forget to make it a class method.
A:
I'm not sure what you are trying to do, exactly. Let me just add a bit of random information.
First, add this class:
class FooNew(object):
def __str__(self):
return 'Fubar'
Print this instead:
if __name__ == '__main__':
print "You are calling type for an old style class"
print(Foo)
print(type.__str__(Foo))
print(Foo())
print("But my Python 2.6 didn't match your output for print(Foo)")
print("You are calling object.str() for a new style class")
print(FooNew)
print(object.__str__(FooNew))
print(FooNew())
print("Why do you want to change this?")
To get this:
You are calling type for an old style class
__main__.Foo
<class __main__.Foo at 0xb73c9f5c>
Bar
But my Python 2.6 didn't match your output for print(Foo)
You are calling object.str() for a new style class
<class '__main__.FooNew'>
<class '__main__.FooNew'>
Fubar
Why do you want to change this?
Are you absolutely sure you don't want to call a classmethod?
|
Python overriding class (not instance) special methods
|
How do I override a class special method?
I want to be able to call the __str__() method of the class without creating an instance. Example:
class Foo:
def __str__(self):
return 'Bar'
class StaticFoo:
@staticmethod
def __str__():
return 'StaticBar'
class ClassFoo:
@classmethod
def __str__(cls):
return 'ClassBar'
if __name__ == '__main__':
print(Foo)
print(Foo())
print(StaticFoo)
print(StaticFoo())
print(ClassFoo)
print(ClassFoo())
produces:
<class '__main__.Foo'>
Bar
<class '__main__.StaticFoo'>
StaticBar
<class '__main__.ClassFoo'>
ClassBar
should be:
Bar
Bar
StaticBar
StaticBar
ClassBar
ClassBar
Even if I use the @staticmethod or @classmethod the __str__ is still using the built-in Python definition for __str__. It's only working when it's Foo().__str__() instead of Foo.__str__().
|
[
"Special method __str__ defined in a class works only for the instances of that class, to have the different behavior for class objects you will have to do it in a metaclass of that class e.g. (python 2.5)\nclass Meta(type):\n def __str__(self):\n return \"Klass\"\n\nclass A(object):\n __metaclass__ = Meta\n\n def __str__(self):\n return \"instance\"\n\nprint A\nprint A()\n\noutput:\nKlass\ninstance\n\n",
"Why do you want to abuse the meaning of __str__? That method name (like many dunder method names) is special in Python, being an instance method with the meaning \"return a string representation of this instance of the class\".\nIf you want a function that just returns a static string, it would be better to have that as a separate function not inside a class.\nIf you want a constructor that returns a new string, name it something else so it's not clobbering the special __str__ name.\nIf you want a method for printing a representation of the class, you should not use the name __str__ for that. That name is – as the dunder-style name implies – expected to have particular behaviour as defined in the Python documentation. Choose some (non-dunder) name which you can give your special meaning, and don't forget to make it a class method.\n",
"I'm not sure what you are trying to do, exactly. Let me just add a bit of random information.\nFirst, add this class:\nclass FooNew(object):\ndef __str__(self):\n return 'Fubar'\n\nPrint this instead:\nif __name__ == '__main__':\n print \"You are calling type for an old style class\"\n print(Foo)\n print(type.__str__(Foo))\n print(Foo())\n print(\"But my Python 2.6 didn't match your output for print(Foo)\")\n print(\"You are calling object.str() for a new style class\")\n print(FooNew)\n print(object.__str__(FooNew))\n print(FooNew())\n print(\"Why do you want to change this?\")\n\nTo get this:\nYou are calling type for an old style class\n__main__.Foo\n<class __main__.Foo at 0xb73c9f5c>\nBar\nBut my Python 2.6 didn't match your output for print(Foo)\nYou are calling object.str() for a new style class\n<class '__main__.FooNew'>\n<class '__main__.FooNew'>\nFubar\nWhy do you want to change this?\n\nAre you absolutely sure you don't want to call a classmethod?\n"
] |
[
20,
1,
0
] |
[] |
[] |
[
"class",
"overriding",
"python"
] |
stackoverflow_0002497790_class_overriding_python.txt
|
Q:
creating matrix with probabilities
I want to generate a matrix of NxN to test some code that I have where each row contains floats as the elements and has to add up to 1 (i.e. a row with a set of probabilities).
Where it gets tricky is that I want to make sure that randomly some of the elements should be 0 (in fact most of the elements should be 0 except for some random ones to be the probabilities). I need the probabilities to be 1/m where m is the number of elements that are not 0 within a single row. I tried to think of ways to output this, but essentially I would need this stored in a C++ array. So even if I output to a file I would still have the issue of not having it in array as I need it. At the end of it all I need that array because I want to generate a Market Matrix file. I found an implementation in C++ to take an array and convert it to the market matrix file, so this is what I am basing my findings on. My input for the rest of the code takes in this market matrix file so I need that to be the primary form of output. The language does not matter, I just want to generate the file at the end (I found a way mmwrite and mmread in python as well)
Please help, I am stuck and not really sure how to implement this.
A:
import random
N = 10
matrix = []
for j in range(N):
t = [int(random.random()<0.6) for i in range(N)]
ones = t.count(1)
row = [float(x)/ones for x in t] if ones else t
matrix.append(row)
for r in matrix:
print r
A:
By C++ array, do you mean a C array or a STL vector<vector< > >? The latter would be cleaner, but here's an example using C arrays:
#include <stdlib.h>
#include <stdio.h>
float* makeProbabilityMatrix(int N, float zeroProbability)
{
float* matrix = (float*)malloc(N*N*sizeof(float));
for (int ii = 0; ii < N; ii++)
{
int m = 0;
for (int jj = 0; jj < N; jj++)
{
int val = (rand() / (RAND_MAX*1.0) < zeroProbability) ? 0 : 1;
matrix[ii*N+jj] = val;
m += val;
}
for (int jj = 0; jj < N; jj++)
{
matrix[ii*N+jj] /= m;
}
}
return matrix;
}
int main()
{
srand(234);
int N = 10;
float* matrix = makeProbabilityMatrix(N, 0.70);
for (int ii = 0; ii < N; ii++)
{
for (int jj = 0; jj < N; jj++)
{
printf("%.2f ", matrix[ii*N+jj]);
}
printf("\n");
}
free(matrix);
return 0;
};
Output:
0.00 0.20 0.20 0.00 0.00 0.00 0.00 0.20 0.20 0.20
0.25 0.00 0.00 0.00 0.00 0.25 0.00 0.25 0.25 0.00
0.00 0.33 0.33 0.33 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.50 0.00 0.00 0.50 0.00
0.25 0.25 0.00 0.00 0.00 0.00 0.25 0.00 0.25 0.00
0.00 0.25 0.00 0.00 0.00 0.25 0.25 0.00 0.25 0.00
0.00 0.00 0.33 0.00 0.33 0.00 0.00 0.00 0.33 0.00
0.00 0.20 0.20 0.20 0.20 0.00 0.00 0.20 0.00 0.00
0.20 0.00 0.20 0.00 0.00 0.00 0.00 0.20 0.20 0.20
0.00 0.00 0.00 0.00 0.00 0.50 0.00 0.50 0.00 0.00
|
creating matrix with probabilities
|
I want to generate a matrix of NxN to test some code that I have where each row contains floats as the elements and has to add up to 1 (i.e. a row with a set of probabilities).
Where it gets tricky is that I want to make sure that randomly some of the elements should be 0 (in fact most of the elements should be 0 except for some random ones to be the probabilities). I need the probabilities to be 1/m where m is the number of elements that are not 0 within a single row. I tried to think of ways to output this, but essentially I would need this stored in a C++ array. So even if I output to a file I would still have the issue of not having it in array as I need it. At the end of it all I need that array because I want to generate a Market Matrix file. I found an implementation in C++ to take an array and convert it to the market matrix file, so this is what I am basing my findings on. My input for the rest of the code takes in this market matrix file so I need that to be the primary form of output. The language does not matter, I just want to generate the file at the end (I found a way mmwrite and mmread in python as well)
Please help, I am stuck and not really sure how to implement this.
|
[
"import random\n\nN = 10\n\nmatrix = []\n\nfor j in range(N):\n t = [int(random.random()<0.6) for i in range(N)]\n ones = t.count(1)\n row = [float(x)/ones for x in t] if ones else t\n matrix.append(row)\n\nfor r in matrix:\n print r\n\n",
"By C++ array, do you mean a C array or a STL vector<vector< > >? The latter would be cleaner, but here's an example using C arrays:\n#include <stdlib.h>\n#include <stdio.h>\n\nfloat* makeProbabilityMatrix(int N, float zeroProbability)\n{\n float* matrix = (float*)malloc(N*N*sizeof(float));\n\n for (int ii = 0; ii < N; ii++)\n {\n int m = 0;\n for (int jj = 0; jj < N; jj++)\n {\n int val = (rand() / (RAND_MAX*1.0) < zeroProbability) ? 0 : 1;\n matrix[ii*N+jj] = val;\n m += val;\n }\n for (int jj = 0; jj < N; jj++)\n {\n matrix[ii*N+jj] /= m;\n }\n }\n\n return matrix;\n}\n\nint main() \n{\n srand(234);\n int N = 10;\n\n float* matrix = makeProbabilityMatrix(N, 0.70);\n\n for (int ii = 0; ii < N; ii++)\n { \n for (int jj = 0; jj < N; jj++)\n {\n printf(\"%.2f \", matrix[ii*N+jj]);\n }\n printf(\"\\n\");\n }\n\n free(matrix);\n\n return 0;\n};\n\nOutput:\n0.00 0.20 0.20 0.00 0.00 0.00 0.00 0.20 0.20 0.20 \n0.25 0.00 0.00 0.00 0.00 0.25 0.00 0.25 0.25 0.00 \n0.00 0.33 0.33 0.33 0.00 0.00 0.00 0.00 0.00 0.00 \n0.00 0.00 0.00 0.00 0.00 0.50 0.00 0.00 0.50 0.00 \n0.25 0.25 0.00 0.00 0.00 0.00 0.25 0.00 0.25 0.00 \n0.00 0.25 0.00 0.00 0.00 0.25 0.25 0.00 0.25 0.00 \n0.00 0.00 0.33 0.00 0.33 0.00 0.00 0.00 0.33 0.00 \n0.00 0.20 0.20 0.20 0.20 0.00 0.00 0.20 0.00 0.00 \n0.20 0.00 0.20 0.00 0.00 0.00 0.00 0.20 0.20 0.20 \n0.00 0.00 0.00 0.00 0.00 0.50 0.00 0.50 0.00 0.00 \n\n"
] |
[
2,
0
] |
[] |
[] |
[
"c++",
"python"
] |
stackoverflow_0002497843_c++_python.txt
|
Q:
Best way to encrypt a directory of files?
I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.
How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?
Programming language doesn't matter. I am dictioned in all syntax.
A:
How can I accomplish this, and WHAT IS
the BEST encryption way to do it, if
applicable?
tar and gzip the directory.
Generate a random bit stream of equal size to the file
Run bitwise XOR on the streams
Only truly secure method is a truly random one time pad.
A:
I still say 7-zip is the answer. It hasn't been "cracked".
A:
The OpenSSL library has a variety of block cipher implementations including the well-known AES. It has both a function-call interface (for use with languages like C/C++) and a program-call interface (for use in shell scripts). http://www.openssl.org/
A:
4096-Bit (Open)PGP: 'Pretty Good' Privacy !
GnuPG is the GNU project's complete and free implementation of the OpenPGP standard as defined by RFC4880 . GnuPG allows to encrypt and sign your data and communication, features a versatile key managment system as well as access modules for all kind of public key directories. GnuPG, also known as GPG, is a command line tool with features for easy integration with other applications. A wealth of frontend applications and libraries are available. Version 2 of GnuPG also provides support for S/MIME.
libgcrypt:
http://www.gnupg.org/related_software/libraries.en.html
Edit:
BouncyCastle now has OpenPGP support.
http://www.bouncycastle.org/
A:
Use AES. You'll find implementations in your favourite programming language by asking google for AES encryption + myfavouritelanguage.
A:
If you're using .NET, why not use a free compression framework (http://www.icsharpcode.net/OpenSource/SharpZipLib/) that supports Encryption?
|
Best way to encrypt a directory of files?
|
I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.
How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?
Programming language doesn't matter. I am dictioned in all syntax.
|
[
"\nHow can I accomplish this, and WHAT IS\n the BEST encryption way to do it, if\n applicable?\n\n\ntar and gzip the directory. \nGenerate a random bit stream of equal size to the file\nRun bitwise XOR on the streams\n\nOnly truly secure method is a truly random one time pad.\n",
"I still say 7-zip is the answer. It hasn't been \"cracked\".\n",
"The OpenSSL library has a variety of block cipher implementations including the well-known AES. It has both a function-call interface (for use with languages like C/C++) and a program-call interface (for use in shell scripts). http://www.openssl.org/\n",
"4096-Bit (Open)PGP: 'Pretty Good' Privacy !\n\n\nGnuPG is the GNU project's complete and free implementation of the OpenPGP standard as defined by RFC4880 . GnuPG allows to encrypt and sign your data and communication, features a versatile key managment system as well as access modules for all kind of public key directories. GnuPG, also known as GPG, is a command line tool with features for easy integration with other applications. A wealth of frontend applications and libraries are available. Version 2 of GnuPG also provides support for S/MIME.\n\n\nlibgcrypt:\nhttp://www.gnupg.org/related_software/libraries.en.html\nEdit:\nBouncyCastle now has OpenPGP support.\nhttp://www.bouncycastle.org/\n",
"Use AES. You'll find implementations in your favourite programming language by asking google for AES encryption + myfavouritelanguage. \n",
"If you're using .NET, why not use a free compression framework (http://www.icsharpcode.net/OpenSource/SharpZipLib/) that supports Encryption?\n"
] |
[
4,
3,
3,
3,
2,
0
] |
[] |
[] |
[
".net",
"c++",
"encryption",
"java",
"python"
] |
stackoverflow_0002498009_.net_c++_encryption_java_python.txt
|
Q:
stopping a cherrypy server over http
I have a cherrypy app that I'm controlling over http with a wxpython ui. I want to kill the server when the ui closes, but I don't know how to do that. Right now I'm just doing a sys.exit() on the window close event but thats resulting in
Traceback (most recent call last):
File "ui.py", line 67, in exitevent
urllib.urlopen("http://"+server+"/?sigkill=1")
File "c:\python26\lib\urllib.py", line 87, in urlopen
return opener.open(url)
File "c:\python26\lib\urllib.py", line 206, in open
return getattr(self, name)(url)
File "c:\python26\lib\urllib.py", line 354, in open_http
'got a bad status line', None)
IOError: ('http protocol error', 0, 'got a bad status line', None)
is that because I'm not stopping cherrypy properly?
A:
How are you stopping CherryPy? By sending a SIGKILL to itself? You should send TERM instead at the least, but even better would be to call cherrypy.engine.exit() (version 3.1+). Both techniques will allow CherryPy to shut down more gracefully, which includes allowing any in-process requests (like your "?sigkill=1" request itself) to finish up and close cleanly.
A:
I use os._exit. I also put it on a thread, so that I can serve up a "you've quit the server" page before exiting.
class MyApp(object):
@cherrypy.expose
def exit(self):
"""
/exit
Quits the application
"""
threading.Timer(1, lambda: os._exit(0)).start()
return render("exit.html", {})
|
stopping a cherrypy server over http
|
I have a cherrypy app that I'm controlling over http with a wxpython ui. I want to kill the server when the ui closes, but I don't know how to do that. Right now I'm just doing a sys.exit() on the window close event but thats resulting in
Traceback (most recent call last):
File "ui.py", line 67, in exitevent
urllib.urlopen("http://"+server+"/?sigkill=1")
File "c:\python26\lib\urllib.py", line 87, in urlopen
return opener.open(url)
File "c:\python26\lib\urllib.py", line 206, in open
return getattr(self, name)(url)
File "c:\python26\lib\urllib.py", line 354, in open_http
'got a bad status line', None)
IOError: ('http protocol error', 0, 'got a bad status line', None)
is that because I'm not stopping cherrypy properly?
|
[
"How are you stopping CherryPy? By sending a SIGKILL to itself? You should send TERM instead at the least, but even better would be to call cherrypy.engine.exit() (version 3.1+). Both techniques will allow CherryPy to shut down more gracefully, which includes allowing any in-process requests (like your \"?sigkill=1\" request itself) to finish up and close cleanly.\n",
"I use os._exit. I also put it on a thread, so that I can serve up a \"you've quit the server\" page before exiting.\nclass MyApp(object):\n @cherrypy.expose\n def exit(self):\n \"\"\"\n /exit\n Quits the application\n \"\"\"\n\n threading.Timer(1, lambda: os._exit(0)).start()\n return render(\"exit.html\", {})\n\n"
] |
[
10,
3
] |
[] |
[] |
[
"cherrypy",
"python"
] |
stackoverflow_0002125175_cherrypy_python.txt
|
Q:
Flash in Python
I was exploring possibilities of Rich Internet applications using Python. The most awesome possibility I found was of programming in IronPython and running it as a Silverlight. Is there something similar available for Adobe AIR? I.e. programing in Python and run in Adobe AIR (Flash, that is).
A:
You can use libming to generate Macromedia Flash files, it has Python bindings too, you can see some Python examples at "Python, Ming and Flash".
Another library is "SSWF -- A complete library to generate Flash animations", which is in C, so can be easily used from Python if needed.
A:
There are plenty of resources out there for Flex/AIR integration with Python, just google the two of them together. A good one is "Python Resources for Flex Development".
|
Flash in Python
|
I was exploring possibilities of Rich Internet applications using Python. The most awesome possibility I found was of programming in IronPython and running it as a Silverlight. Is there something similar available for Adobe AIR? I.e. programing in Python and run in Adobe AIR (Flash, that is).
|
[
"You can use libming to generate Macromedia Flash files, it has Python bindings too, you can see some Python examples at \"Python, Ming and Flash\".\nAnother library is \"SSWF -- A complete library to generate Flash animations\", which is in C, so can be easily used from Python if needed.\n",
"There are plenty of resources out there for Flex/AIR integration with Python, just google the two of them together. A good one is \"Python Resources for Flex Development\".\n"
] |
[
1,
1
] |
[] |
[] |
[
"air",
"python",
"rich_internet_application"
] |
stackoverflow_0002498269_air_python_rich_internet_application.txt
|
Q:
Python: Pretty printing a xml file directly from a tar.gz package
This is the first Python script I've tried to create. I'm reading a xml file from a tar.gz package and then I want to pretty print it. However I can't seem to turn it from a file-like object to a string. I've tried to do it a few different ways including str(), tostring(), etc but nothing is working for me.
For testing I just tried to print the string at "print myfile[0:200]" and it always generates "<tarfile.ExFileObject object at 0x10053df10>"
import os
import sys
import tarfile
from xml.dom.minidom import parseString
tar = tarfile.open("data/ucd.all.flat.tar.gz", "r")
getfile = tar.extractfile("ucd.all.flat.xml")
myfile = str(getfile)
print myfile[0:200]
output = parseString(getfile).toprettyxml()
print output
tar.close()
A:
Untested but you probably just need a read() call on the file-like object returned by tarfile, e.g.:
myfile = getfile.read()
|
Python: Pretty printing a xml file directly from a tar.gz package
|
This is the first Python script I've tried to create. I'm reading a xml file from a tar.gz package and then I want to pretty print it. However I can't seem to turn it from a file-like object to a string. I've tried to do it a few different ways including str(), tostring(), etc but nothing is working for me.
For testing I just tried to print the string at "print myfile[0:200]" and it always generates "<tarfile.ExFileObject object at 0x10053df10>"
import os
import sys
import tarfile
from xml.dom.minidom import parseString
tar = tarfile.open("data/ucd.all.flat.tar.gz", "r")
getfile = tar.extractfile("ucd.all.flat.xml")
myfile = str(getfile)
print myfile[0:200]
output = parseString(getfile).toprettyxml()
print output
tar.close()
|
[
"Untested but you probably just need a read() call on the file-like object returned by tarfile, e.g.:\nmyfile = getfile.read()\n\n"
] |
[
2
] |
[] |
[] |
[
"pretty_print",
"python",
"tar"
] |
stackoverflow_0002498732_pretty_print_python_tar.txt
|
Q:
Django parallel arrays in a template
I have 2 arrays that I would like to render in a template, one is the data to be output, the other is a formset for deleting items. since it seems django does not support boolean operators in the template tag, I have tried packaging the items, but they return the first item and the first form in 2 rows only.
How does one package such items so that they are rendered in one for loop.
my view
@login_required
def forums(request ):
post = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0'))
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
newpostform = PostForm(request.POST)
deletepostform = PostDeleteForm(request.POST)
DelPostFormSet = modelformset_factory(forum, exclude=('child','postSubject','postBody','postPoster','postDate','childParentId'))
readform = ReadForumForm(request.POST)
if newpostform.is_valid():
topic = request.POST['postSubject']
poster = request.POST['postPoster']
newpostform.save()
newpostform = PostForm(initial = {'postPoster':user.id})
post = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0'))
else:
newpostform = PostForm(initial = {'postPoster':user.id})
if request.method == 'POST':
delpostformset = DelPostFormSet(request.POST)
if delpostformset.is_valid():
delpostformset.save()
else:
delpostformset = DelPostFormSet(queryset=forum.objects.filter(child='0', deleted='0'))
"""if readform.is_valid():
readform.save()
else:
readform = ReadForumForm()"""
return render_to_response('forum.html', {'post':( post,delpostformset.forms), 'newpostform': newpostform, })
my Template
<table class="results">
<tr class="inner_results_header"><td >Title</td><td>Date/Time</td><td>Poster</td> <td>Body</td><td><form method="post" id="form" action="" class="usertabs accfrm"><input type="submit" value="Delete" /></td></tr>
{{formset.management_form}}
{% for p, form in post %}
{% url forum_view p.postID as post_url%}
<tr class="inner_results {% if forloop.counter|divisibleby:2 %}evens{% else %}odds{% endif %}"><span onclick="document.location.href='{{post_url}}';"><td>{{ p.postSubject}}</td><td>{{p.postDate}}</td><td>{{ p.postPoster}}</td><td>{{ p.postBody|truncatewords:50}}</td></span><td>
{{ form.as_p }}
</td></tr>
{% endfor %}
<tr class="inner_results_header"><td >Title</td><td>Date/Time</td><td>Poster</td> <td>Body</td><td><input type="submit" value="Delete" /></form></td></tr>
A:
Use zip builtin. If both post and delpostformset.forms are iterables, zip will return a list of tuples. In view:
post_and_form = zip(post, delpostformset.forms)
and in template:
{% for post, form in post_and_form %}
{% endfor %}
|
Django parallel arrays in a template
|
I have 2 arrays that I would like to render in a template, one is the data to be output, the other is a formset for deleting items. since it seems django does not support boolean operators in the template tag, I have tried packaging the items, but they return the first item and the first form in 2 rows only.
How does one package such items so that they are rendered in one for loop.
my view
@login_required
def forums(request ):
post = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0'))
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
newpostform = PostForm(request.POST)
deletepostform = PostDeleteForm(request.POST)
DelPostFormSet = modelformset_factory(forum, exclude=('child','postSubject','postBody','postPoster','postDate','childParentId'))
readform = ReadForumForm(request.POST)
if newpostform.is_valid():
topic = request.POST['postSubject']
poster = request.POST['postPoster']
newpostform.save()
newpostform = PostForm(initial = {'postPoster':user.id})
post = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0'))
else:
newpostform = PostForm(initial = {'postPoster':user.id})
if request.method == 'POST':
delpostformset = DelPostFormSet(request.POST)
if delpostformset.is_valid():
delpostformset.save()
else:
delpostformset = DelPostFormSet(queryset=forum.objects.filter(child='0', deleted='0'))
"""if readform.is_valid():
readform.save()
else:
readform = ReadForumForm()"""
return render_to_response('forum.html', {'post':( post,delpostformset.forms), 'newpostform': newpostform, })
my Template
<table class="results">
<tr class="inner_results_header"><td >Title</td><td>Date/Time</td><td>Poster</td> <td>Body</td><td><form method="post" id="form" action="" class="usertabs accfrm"><input type="submit" value="Delete" /></td></tr>
{{formset.management_form}}
{% for p, form in post %}
{% url forum_view p.postID as post_url%}
<tr class="inner_results {% if forloop.counter|divisibleby:2 %}evens{% else %}odds{% endif %}"><span onclick="document.location.href='{{post_url}}';"><td>{{ p.postSubject}}</td><td>{{p.postDate}}</td><td>{{ p.postPoster}}</td><td>{{ p.postBody|truncatewords:50}}</td></span><td>
{{ form.as_p }}
</td></tr>
{% endfor %}
<tr class="inner_results_header"><td >Title</td><td>Date/Time</td><td>Poster</td> <td>Body</td><td><input type="submit" value="Delete" /></form></td></tr>
|
[
"Use zip builtin. If both post and delpostformset.forms are iterables, zip will return a list of tuples. In view:\npost_and_form = zip(post, delpostformset.forms)\n\nand in template:\n{% for post, form in post_and_form %}\n{% endfor %}\n\n"
] |
[
8
] |
[] |
[] |
[
"django",
"django_templates",
"django_views",
"python"
] |
stackoverflow_0002498870_django_django_templates_django_views_python.txt
|
Q:
How to extract the first non-Null match from a group of regexp matches in Python?
Suppose I have a regular expression (a)|(b)|(c)|(d). If I apply it to text 'foobar' I get a match object
>>> compiled = re.compile('(a)|(b)|(c)|(d)')
>>> compiled.search('foobar').groups()
(None, 'b', None, None)
How do I extract the 'b' from here? Or in general, how do I extract the first match from an unknown number of groups (can happen when the regexp was built dynamically)?
A:
>>> g = (None, 'b', None, None)
>>> next(x for x in g if x is not None)
'b'
>>> g = (None, None, None)
>>> next((x for x in g if x is not None), "default") # try this with filter :)
'default'
>>> g = (None, None, None) # so you know what happens, and what you could catch
>>> next(x for x in g if x is not None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
A:
reduce(lambda x, y : (x, y)[x is None], groups, None)
A:
filter(lambda x : x is not None, groups)[0]
A:
>>> g = (None,'b',None,None)
>>> filter(None,g)
('b',)
>>> h = (None,None,None)
>>> filter(None,h)
()
|
How to extract the first non-Null match from a group of regexp matches in Python?
|
Suppose I have a regular expression (a)|(b)|(c)|(d). If I apply it to text 'foobar' I get a match object
>>> compiled = re.compile('(a)|(b)|(c)|(d)')
>>> compiled.search('foobar').groups()
(None, 'b', None, None)
How do I extract the 'b' from here? Or in general, how do I extract the first match from an unknown number of groups (can happen when the regexp was built dynamically)?
|
[
">>> g = (None, 'b', None, None)\n>>> next(x for x in g if x is not None)\n'b'\n\n>>> g = (None, None, None)\n>>> next((x for x in g if x is not None), \"default\") # try this with filter :)\n'default'\n\n>>> g = (None, None, None) # so you know what happens, and what you could catch\n>>> next(x for x in g if x is not None)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nStopIteration\n\n",
"reduce(lambda x, y : (x, y)[x is None], groups, None)\n\n",
"filter(lambda x : x is not None, groups)[0]\n\n",
">>> g = (None,'b',None,None)\n>>> filter(None,g)\n('b',)\n>>> h = (None,None,None)\n>>> filter(None,h)\n()\n\n"
] |
[
4,
1,
1,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002498935_python_regex.txt
|
Q:
OSX : Defining a new URL handler that points straight at a Python script
I'm trying to define a new URL handler under OSX that will point at a python script.
I've wrapped the Python script up into an applet (right-clicked on the .py, and gone Open With -> Build Applet)
I've added the following into the applet's Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>Do My Thing</string>
<key>CFBundleURLSchemes</key>
<array>
<string>dmt</string>
</array>
</dict>
</array>
I've also used the More Internet preferences pane to specify "dmt" as a protocol, but when I try to get it to link the protocol to my applet, it says that "There was a problem setting the app as the helper"
Anyone know where I should go from here?
Thanks
A:
After a lot of messing around, I've managed to get this working under OSX...
This is how I'm doing it:
in the AppleScript Script Editor, write the following script:
on open location this_URL
do shell script "/scripts/runLocalCommand.py '" & this_URL & "'"
end open location
If you want to make sure you're running the Python from a certain shell (in my case, I'm using tcsh generally, and have a .tcshrc file that defines some environment variables that I want to have access to) then that middle line might want to be:
do shell script "tcsh -c \"/scripts/localCommand.py '" & this_URL & "'\""
I was wanting to do all of my actual processing inside a python script - but because of the way URL handers work in OSX, they have to call an application bundle rather than a script, so doing this in AppleScript seemed to be the easiest way to do it.
in the Script Editor, Save As an "Application Bundle"
Find the saved Application Bundle, and Open Contents. Find the Info.plist file, and open it. Add the following:
<key>CFBundleIdentifier</key>
<string>com.mycompany.AppleScript.LocalCommand</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>LocalCommand</string>
<key>CFBundleURLSchemes</key>
<array>
<string>local</string>
</array>
</dict>
</array>
Just before the last two lines, which should be:
</dict>
</plist>
There are three strings in there that might want to be changed:
com.mycompany.AppleScript.LocalCommand
LocalCommand
local
The third of these is the handler ID - so a URL would be local://something
So, then this passes over to the Python script.
This is what I've got for this:
#!/usr/bin/env python
import sys
import urllib
arg = sys.argv[1]
handler, fullPath = arg.split(":", 1)
path, fullArgs = fullPath.split("?", 1)
action = path.strip("/")
args = fullArgs.split("&")
params = {}
for arg in args:
key, value = map(urllib.unquote, arg.split("=", 1))
params[key] = value
|
OSX : Defining a new URL handler that points straight at a Python script
|
I'm trying to define a new URL handler under OSX that will point at a python script.
I've wrapped the Python script up into an applet (right-clicked on the .py, and gone Open With -> Build Applet)
I've added the following into the applet's Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>Do My Thing</string>
<key>CFBundleURLSchemes</key>
<array>
<string>dmt</string>
</array>
</dict>
</array>
I've also used the More Internet preferences pane to specify "dmt" as a protocol, but when I try to get it to link the protocol to my applet, it says that "There was a problem setting the app as the helper"
Anyone know where I should go from here?
Thanks
|
[
"After a lot of messing around, I've managed to get this working under OSX...\nThis is how I'm doing it:\nin the AppleScript Script Editor, write the following script:\non open location this_URL\n do shell script \"/scripts/runLocalCommand.py '\" & this_URL & \"'\"\nend open location\n\nIf you want to make sure you're running the Python from a certain shell (in my case, I'm using tcsh generally, and have a .tcshrc file that defines some environment variables that I want to have access to) then that middle line might want to be:\ndo shell script \"tcsh -c \\\"/scripts/localCommand.py '\" & this_URL & \"'\\\"\"\n\nI was wanting to do all of my actual processing inside a python script - but because of the way URL handers work in OSX, they have to call an application bundle rather than a script, so doing this in AppleScript seemed to be the easiest way to do it.\nin the Script Editor, Save As an \"Application Bundle\"\nFind the saved Application Bundle, and Open Contents. Find the Info.plist file, and open it. Add the following:\n<key>CFBundleIdentifier</key>\n<string>com.mycompany.AppleScript.LocalCommand</string>\n<key>CFBundleURLTypes</key>\n<array>\n <dict>\n <key>CFBundleURLName</key>\n <string>LocalCommand</string>\n <key>CFBundleURLSchemes</key>\n <array>\n <string>local</string>\n </array>\n </dict>\n</array>\n\nJust before the last two lines, which should be:\n</dict>\n</plist>\n\nThere are three strings in there that might want to be changed:\ncom.mycompany.AppleScript.LocalCommand\nLocalCommand\nlocal\n\nThe third of these is the handler ID - so a URL would be local://something\nSo, then this passes over to the Python script.\nThis is what I've got for this:\n#!/usr/bin/env python\nimport sys\nimport urllib\narg = sys.argv[1]\nhandler, fullPath = arg.split(\":\", 1)\npath, fullArgs = fullPath.split(\"?\", 1)\naction = path.strip(\"/\")\nargs = fullArgs.split(\"&\")\nparams = {}\nfor arg in args:\n key, value = map(urllib.unquote, arg.split(\"=\", 1))\n params[key] = value\n\n"
] |
[
16
] |
[] |
[] |
[
"handler",
"macos",
"python",
"url"
] |
stackoverflow_0002418910_handler_macos_python_url.txt
|
Q:
Django: request object to template context transparancy
I want to include an initialized data structure in my request object, making it accessible in the context object from my templates. What I'm doing right now is passing it manually and tiresome within all my views:
render_to_response(...., ( {'menu': RequestContext(request)}))
The request object contains the key, value pair which is injected using a custom context processor. While this works, I had hoped there was a more generic way of passing selected parts of the request object to the template context. I've tried passing it by generic views, but as it turns out the request object isn't instantiated when parsing the urlpatterns list.
A:
To accomplish this, you will probably have to create your own middleware. That way, you have full control of the request, both before and after the view function.
Middleware is a very powerful concept, and not as hard to implement as it could seem, but don’t overdo it – it makes it hard to follow the program flow.
A:
I don't necessarily understand your question well enough.
Either you are complaining having to include the RequestContext in all views, in which case you need to write a wrapper that passes RequestContext for you. But you will still have to pass to it the request. If you don't want to pass that too, you may have to create your own middleware as mikl suggests.
Or, you are complaining about having to pass a lot of menu items, in each and every view. Which is wrong way to do it, you need to define a template context processor that ensures these are present in the template by default.
|
Django: request object to template context transparancy
|
I want to include an initialized data structure in my request object, making it accessible in the context object from my templates. What I'm doing right now is passing it manually and tiresome within all my views:
render_to_response(...., ( {'menu': RequestContext(request)}))
The request object contains the key, value pair which is injected using a custom context processor. While this works, I had hoped there was a more generic way of passing selected parts of the request object to the template context. I've tried passing it by generic views, but as it turns out the request object isn't instantiated when parsing the urlpatterns list.
|
[
"To accomplish this, you will probably have to create your own middleware. That way, you have full control of the request, both before and after the view function.\nMiddleware is a very powerful concept, and not as hard to implement as it could seem, but don’t overdo it – it makes it hard to follow the program flow.\n",
"I don't necessarily understand your question well enough.\nEither you are complaining having to include the RequestContext in all views, in which case you need to write a wrapper that passes RequestContext for you. But you will still have to pass to it the request. If you don't want to pass that too, you may have to create your own middleware as mikl suggests.\nOr, you are complaining about having to pass a lot of menu items, in each and every view. Which is wrong way to do it, you need to define a template context processor that ensures these are present in the template by default.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"django_context",
"python",
"request",
"templates"
] |
stackoverflow_0002498582_django_django_context_python_request_templates.txt
|
Q:
Segment string into array, regex?
I have a string which looks like this:
"[segment1][segment2][segment2]"
What I'd like is to be able to split the string into an array, so I'd end up with:
Array[0] = "segment1", Array[1] = "segment2", Array[2] = "segment3"
I've tried using the string split function, but it doesn't seem to do exactly what I want. I was wondering if anyone has some regex which might help me out?
Thanks in advance
A:
You could take the slice of the string without the first and last characters, then split on ][:
s = "[segment1][segment2][segment2]"
s[1:-1].split('][')
outputs
['segment1', 'segment2', 'segment2']
A:
You could use the re.split() function:
subject = "[segment1][segment2][segment2]"
reobj = re.compile("[][]+")
result = reobj.split(subject.strip("[]"))
print result
gives you:
['segment1', 'segment2', 'segment2']
Edit: Added a .strip() to avoid an empty first and last element of the resulting list.
|
Segment string into array, regex?
|
I have a string which looks like this:
"[segment1][segment2][segment2]"
What I'd like is to be able to split the string into an array, so I'd end up with:
Array[0] = "segment1", Array[1] = "segment2", Array[2] = "segment3"
I've tried using the string split function, but it doesn't seem to do exactly what I want. I was wondering if anyone has some regex which might help me out?
Thanks in advance
|
[
"You could take the slice of the string without the first and last characters, then split on ][:\ns = \"[segment1][segment2][segment2]\"\ns[1:-1].split('][')\n\noutputs\n['segment1', 'segment2', 'segment2']\n\n",
"You could use the re.split() function:\nsubject = \"[segment1][segment2][segment2]\"\nreobj = re.compile(\"[][]+\")\nresult = reobj.split(subject.strip(\"[]\"))\nprint result\n\ngives you:\n['segment1', 'segment2', 'segment2']\n\nEdit: Added a .strip() to avoid an empty first and last element of the resulting list.\n"
] |
[
4,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002499865_python_regex.txt
|
Q:
Faster float to int conversion in Python
Here's a piece of code that takes most time in my program, according to timeit statistics. It's a dirty function to convert floats in [-1.0, 1.0] interval into unsigned integer [0, 2**32]. How can I accelerate floatToInt?
piece = []
rng = range(32)
for i in rng:
piece.append(1.0/2**i)
def floatToInt(x):
n = x + 1.0
res = 0
for i in rng:
if n >= piece[i]:
res += 2**(31-i)
n -= piece[i]
return res
A:
Did you try the obvious one?
def floatToInt(x):
return int((x+1.0) * (2**31))
|
Faster float to int conversion in Python
|
Here's a piece of code that takes most time in my program, according to timeit statistics. It's a dirty function to convert floats in [-1.0, 1.0] interval into unsigned integer [0, 2**32]. How can I accelerate floatToInt?
piece = []
rng = range(32)
for i in rng:
piece.append(1.0/2**i)
def floatToInt(x):
n = x + 1.0
res = 0
for i in rng:
if n >= piece[i]:
res += 2**(31-i)
n -= piece[i]
return res
|
[
"Did you try the obvious one?\ndef floatToInt(x):\n return int((x+1.0) * (2**31))\n\n"
] |
[
4
] |
[] |
[] |
[
"binary_data",
"floating_point",
"python"
] |
stackoverflow_0002499933_binary_data_floating_point_python.txt
|
Q:
in Python find number of same elements in 2 lists
In Python if I have 2 lists say:
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
is there a way to find out how many elements they have the same. In the case about it would be 2 (c and d)
I know I could just do a nested loop but is there not a built in function like in php with the array_intersect function
Thanks
A:
You can use a set intersection for that :)
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])
A:
>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
A:
If you only have unique elements, you can use the set data type and use intersection:
s1, s2 = set(l1), set(l2)
num = len(s1.intersection(s2))
A:
Using sets:
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
def list_count_common(list_a, list_b):
result = len(list(set(list_a) & set(list_b))) ## this is the line that does what you want
return result
print list_count_common(l1, l2) ## prints 2
|
in Python find number of same elements in 2 lists
|
In Python if I have 2 lists say:
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
is there a way to find out how many elements they have the same. In the case about it would be 2 (c and d)
I know I could just do a nested loop but is there not a built in function like in php with the array_intersect function
Thanks
|
[
"You can use a set intersection for that :)\nl1 = ['a', 'b', 'c', 'd']\nl2 = ['c', 'd', 'e']\nset(l1).intersection(l2)\nset(['c', 'd'])\n\n",
">>> l1 = ['a', 'b', 'c', 'd']\n>>> l2 = ['c', 'd', 'e']\n>>> set(l1) & set(l2)\nset(['c', 'd'])\n\n",
"If you only have unique elements, you can use the set data type and use intersection:\ns1, s2 = set(l1), set(l2)\nnum = len(s1.intersection(s2))\n\n",
"Using sets:\nl1 = ['a', 'b', 'c', 'd']\nl2 = ['c', 'd', 'e']\n\n\ndef list_count_common(list_a, list_b):\n result = len(list(set(list_a) & set(list_b))) ## this is the line that does what you want\n return result\n\nprint list_count_common(l1, l2) ## prints 2\n\n"
] |
[
10,
6,
5,
1
] |
[] |
[] |
[
"array_intersect",
"arrays",
"python"
] |
stackoverflow_0002500124_array_intersect_arrays_python.txt
|
Q:
Pylons and multiple forms per page
I've got a web page I'm generating with Pylons and the evoque templating tool. I'm trying to generate a page with multiple forms per page (one form is part of a base template that becomes part of every page). I'm having a problem as I seemingly can only get the form element values for one form; whenever I try to get the value from the base template, I get nothing back. Is there a way in Pylons to get a form element from a form by name? I'm using the request.params("variable_name") style that is standard in Pylons.
Thanks in advance for your help!
Doug
A:
You will only get the form values for the form that was posted in the request(ie: whichever submit button the user clicked), that's how html works.
A:
Yes (to iterate Tom's answer), HTML is designed to explicitly only allow a single form to be submitted at a time. Plus, forms may not be nested, so no confusion possible there.
However, a single form may contain multiple submit buttons. So, you may if you really want to organize your page as one big single form, and so submitting will submit all the values each time. You will need to take care then that there are all field names are distinct -- so, not convenient if you have a repetition of "item" forms, in which case it should be a lot cleaner to have a form per item...
|
Pylons and multiple forms per page
|
I've got a web page I'm generating with Pylons and the evoque templating tool. I'm trying to generate a page with multiple forms per page (one form is part of a base template that becomes part of every page). I'm having a problem as I seemingly can only get the form element values for one form; whenever I try to get the value from the base template, I get nothing back. Is there a way in Pylons to get a form element from a form by name? I'm using the request.params("variable_name") style that is standard in Pylons.
Thanks in advance for your help!
Doug
|
[
"You will only get the form values for the form that was posted in the request(ie: whichever submit button the user clicked), that's how html works. \n",
"Yes (to iterate Tom's answer), HTML is designed to explicitly only allow a single form to be submitted at a time. Plus, forms may not be nested, so no confusion possible there. \nHowever, a single form may contain multiple submit buttons. So, you may if you really want to organize your page as one big single form, and so submitting will submit all the values each time. You will need to take care then that there are all field names are distinct -- so, not convenient if you have a repetition of \"item\" forms, in which case it should be a lot cleaner to have a form per item...\n"
] |
[
1,
0
] |
[] |
[] |
[
"forms",
"html",
"pylons",
"python"
] |
stackoverflow_0002097556_forms_html_pylons_python.txt
|
Q:
QTableWidget signal cellChanged(): distinguish between user input and change by routines
i am using PyQt but my question is a general Qt one:
I have a QTableWidget that is set up by the function updateTable. It writes the data from DATASET to the table when it is called. Unfortunately this causes my QTableWidget to emit the signal cellChanged() for every cell.
The signal cellChanged() is connected to a function on_tableWidget_cellChanged that reads the contents of the changed cell and writes it back to DATASET. This is necessary to allow the user to change the data manually.
So everytime the table is updated, its contents are written back to DATASET.
Is there a way to distinguish if the cell was changed by the user or by updateTable?
i thought of disconnecting on_tableWidget_cellChanged by updateTable temporarily but that seems to be a little dirty.
A:
In similar situation I've just used
bool QObject::blockSignals ( bool block )
bool QObject::signalsBlocked () const
Block signals before setting up the table, then unblock:
myTable.blockSignals(True)
#blah-blah..
myTable.blockSignals(False)
A:
It seems, that this is the only signal in QTableWidget at least for 4.6. You could post a feature request, but I don't know if it is accepted and you might wait for long time ;-)
Maybe you could try to write a subclass of QTableWidget and emit own signals, when cell is changed internally.
Anyway, disconnecting for the time of updating the cell isn't that bad, since you can't connect to specific signal.
A:
I would recommend changing from a QTableWidget to a QTableView with an appropriate model. From the sounds of it, you have a database or other data object holding and arranging the data anyway, so it would hopefully be fairly easy to do. This would then allow you to distinguish between edits (setData is called on your model) and updates (data is called on your model).
|
QTableWidget signal cellChanged(): distinguish between user input and change by routines
|
i am using PyQt but my question is a general Qt one:
I have a QTableWidget that is set up by the function updateTable. It writes the data from DATASET to the table when it is called. Unfortunately this causes my QTableWidget to emit the signal cellChanged() for every cell.
The signal cellChanged() is connected to a function on_tableWidget_cellChanged that reads the contents of the changed cell and writes it back to DATASET. This is necessary to allow the user to change the data manually.
So everytime the table is updated, its contents are written back to DATASET.
Is there a way to distinguish if the cell was changed by the user or by updateTable?
i thought of disconnecting on_tableWidget_cellChanged by updateTable temporarily but that seems to be a little dirty.
|
[
"In similar situation I've just used\nbool QObject::blockSignals ( bool block )\nbool QObject::signalsBlocked () const\n\nBlock signals before setting up the table, then unblock:\nmyTable.blockSignals(True)\n#blah-blah..\nmyTable.blockSignals(False)\n\n",
"It seems, that this is the only signal in QTableWidget at least for 4.6. You could post a feature request, but I don't know if it is accepted and you might wait for long time ;-)\nMaybe you could try to write a subclass of QTableWidget and emit own signals, when cell is changed internally.\nAnyway, disconnecting for the time of updating the cell isn't that bad, since you can't connect to specific signal.\n",
"I would recommend changing from a QTableWidget to a QTableView with an appropriate model. From the sounds of it, you have a database or other data object holding and arranging the data anyway, so it would hopefully be fairly easy to do. This would then allow you to distinguish between edits (setData is called on your model) and updates (data is called on your model).\n"
] |
[
8,
1,
1
] |
[] |
[] |
[
"pyqt",
"python",
"qt",
"qtablewidget",
"signals"
] |
stackoverflow_0002431844_pyqt_python_qt_qtablewidget_signals.txt
|
Q:
In Elixir or SQLAlchemy, is there a way to also store a comment for a/each field in my entities?
Our project is basically a web interface to several systems of record. We have many tables mapped, and the names of each column aren't as well named and intuitive as we'd like... The users would like to know what data fields are available (i.e. what's been mapped from the database). But, it's pointless to just give them column names like: USER_REF1, USER_REF2, etc.
So, I was wondering, is there a way to provide a comment in the declaration of my field?
E.g.
class SegregationCode(Entity):
using_options(tablename="SEGREGATION_CODES")
segCode = Field(String(20), colname="CODE", ...
primary_key=True) #Have a comment attr too?
If not, any suggestions?
A:
Doing some research thru the SQLAlchemy documentation, my buddy and I found a line that says the Column object has a default dictionary called info that is a space to store "application specific data." So, in my case, I can just doing something like:
class SegregationCode(Entity):
using_options(tablename="SEGREGATION_CODES")
segCode = Field(String(20), colname="CODE", ...
primary_key=True, info={'description'='Segregation Code'})
|
In Elixir or SQLAlchemy, is there a way to also store a comment for a/each field in my entities?
|
Our project is basically a web interface to several systems of record. We have many tables mapped, and the names of each column aren't as well named and intuitive as we'd like... The users would like to know what data fields are available (i.e. what's been mapped from the database). But, it's pointless to just give them column names like: USER_REF1, USER_REF2, etc.
So, I was wondering, is there a way to provide a comment in the declaration of my field?
E.g.
class SegregationCode(Entity):
using_options(tablename="SEGREGATION_CODES")
segCode = Field(String(20), colname="CODE", ...
primary_key=True) #Have a comment attr too?
If not, any suggestions?
|
[
"Doing some research thru the SQLAlchemy documentation, my buddy and I found a line that says the Column object has a default dictionary called info that is a space to store \"application specific data.\" So, in my case, I can just doing something like:\nclass SegregationCode(Entity):\n using_options(tablename=\"SEGREGATION_CODES\")\n segCode = Field(String(20), colname=\"CODE\", ...\n primary_key=True, info={'description'='Segregation Code'})\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_elixir",
"sqlalchemy"
] |
stackoverflow_0002499821_python_python_elixir_sqlalchemy.txt
|
Q:
Spaceship objects
I'm trying to make a program which creates a spaceship and I'm using the status() method to display the ship's name and fuel values. However, it doesn't seem to be working. I think I may have messed something up with the status() method. I'm also trying to make it so that I can change the fuel values, but I don't want to create a new method to do so. I think I've taken a horrible wrong turn somewhere in there. Help please!
class Ship(object):
def __init__(self, name="Enterprise", fuel=0):
self.name=name
self.fuel=fuel
print "The spaceship", name, "has arrived!"
def status():
print "Name: ", self.name
print "Fuel level: ", self.fuel
status=staticmethod(status)
def main():
ship1=Ship(raw_input("What would you like to name this ship?"))
fuel_level=raw_input("How much fuel does this ship have?")
if fuel_level<0:
self.fuel=0
else:
self.fuel(fuel_level)
ship2=Ship(raw_input("What would you like to name this ship?"))
fuel_level2=raw_input("How much fuel does this ship have?")
if fuel_level2<0:
self.fuel=0
else:
self.fuel(fuel_level2)
ship3=Ship(raw_input("What would you like to name this ship?"))
fuel_level3=raw_input("How much fuel does this ship have?")
if fuel_level3<0:
self.fuel=0
else:
self.fuel(fuel_level3)
Ship.status()
main()
raw_input("Press enter to exit.")
A:
In your status method self is not defined, because you made it a static method. It makes more sense to make it non-static, since every ship has its individual name. So just say
def status(self):
print "Name: ", self.name
print "Fuel level: ", self.fuel
and later call
ship1.status()
ship2.status()
ship3.status()
A:
Each ship has its own fuel, so static isn't the way to go. If you don't want the parameter to look like a method, consider a property. It encapsulates the value-checking of the fuel as well.
class Ship(object):
def __init__(self, name="Enterprise", fuel=0):
self.name = name
self._fuel = fuel
print "The spaceship", name, "has arrived!"
def status(self):
print "Name: ", self.name
print "Fuel level: ", self.fuel
@property
def fuel(self):
return self._fuel
@fuel.setter
def fuel(self,level):
if level < 0:
self._fuel = 0
else:
self._fuel = level
In main(), consider loops to initialize the ships and display status instead of repeating code, and use ship.fuel instead of self.fuel. self is only valid in methods of the class.
def main():
ships = []
for n in range(4):
ship = Ship(raw_input("What would you like to name this ship?"))
ship.fuel = int(raw_input("How much fuel does this ship have?"))
ships.append(ship)
for ship in ships:
ship.status()
main()
raw_input("Press enter to exit.")
|
Spaceship objects
|
I'm trying to make a program which creates a spaceship and I'm using the status() method to display the ship's name and fuel values. However, it doesn't seem to be working. I think I may have messed something up with the status() method. I'm also trying to make it so that I can change the fuel values, but I don't want to create a new method to do so. I think I've taken a horrible wrong turn somewhere in there. Help please!
class Ship(object):
def __init__(self, name="Enterprise", fuel=0):
self.name=name
self.fuel=fuel
print "The spaceship", name, "has arrived!"
def status():
print "Name: ", self.name
print "Fuel level: ", self.fuel
status=staticmethod(status)
def main():
ship1=Ship(raw_input("What would you like to name this ship?"))
fuel_level=raw_input("How much fuel does this ship have?")
if fuel_level<0:
self.fuel=0
else:
self.fuel(fuel_level)
ship2=Ship(raw_input("What would you like to name this ship?"))
fuel_level2=raw_input("How much fuel does this ship have?")
if fuel_level2<0:
self.fuel=0
else:
self.fuel(fuel_level2)
ship3=Ship(raw_input("What would you like to name this ship?"))
fuel_level3=raw_input("How much fuel does this ship have?")
if fuel_level3<0:
self.fuel=0
else:
self.fuel(fuel_level3)
Ship.status()
main()
raw_input("Press enter to exit.")
|
[
"In your status method self is not defined, because you made it a static method. It makes more sense to make it non-static, since every ship has its individual name. So just say\ndef status(self):\n print \"Name: \", self.name\n print \"Fuel level: \", self.fuel\n\nand later call\nship1.status()\nship2.status()\nship3.status()\n\n",
"Each ship has its own fuel, so static isn't the way to go. If you don't want the parameter to look like a method, consider a property. It encapsulates the value-checking of the fuel as well.\nclass Ship(object):\n\n def __init__(self, name=\"Enterprise\", fuel=0):\n self.name = name\n self._fuel = fuel\n print \"The spaceship\", name, \"has arrived!\"\n\n def status(self):\n print \"Name: \", self.name\n print \"Fuel level: \", self.fuel\n\n @property\n def fuel(self):\n return self._fuel\n\n @fuel.setter\n def fuel(self,level):\n if level < 0:\n self._fuel = 0\n else:\n self._fuel = level\n\nIn main(), consider loops to initialize the ships and display status instead of repeating code, and use ship.fuel instead of self.fuel. self is only valid in methods of the class.\ndef main():\n\n ships = []\n for n in range(4):\n ship = Ship(raw_input(\"What would you like to name this ship?\"))\n ship.fuel = int(raw_input(\"How much fuel does this ship have?\"))\n ships.append(ship)\n\n for ship in ships:\n ship.status()\n\nmain()\nraw_input(\"Press enter to exit.\")\n\n"
] |
[
4,
4
] |
[] |
[] |
[
"object",
"python",
"static_methods"
] |
stackoverflow_0002500584_object_python_static_methods.txt
|
Q:
Nose Tests - File Uploads
How would one go about testing a Pylons controller (using Nose Tests) that takes a file upload as a POST parameter?
A:
Like this:
class TestUploadController(TestController):
// ....
def test_upload_files(self):
""" Check that upload of text file works. """
files = [("Filedata", "filename.txt", "contents of the file")]
res = self.app.post("/my/upload/path", upload_files = files)
Uploading file usually requires authenticated user so you may also need to pass "extra_environ" argument to self.app.post() to circumvent that.
See paste.fixture documentation for details on the arguments accepted by self.app.post()
|
Nose Tests - File Uploads
|
How would one go about testing a Pylons controller (using Nose Tests) that takes a file upload as a POST parameter?
|
[
"Like this:\nclass TestUploadController(TestController):\n // ....\n def test_upload_files(self):\n \"\"\" Check that upload of text file works. \"\"\"\n\n files = [(\"Filedata\", \"filename.txt\", \"contents of the file\")]\n res = self.app.post(\"/my/upload/path\", upload_files = files)\n\nUploading file usually requires authenticated user so you may also need to pass \"extra_environ\" argument to self.app.post() to circumvent that.\nSee paste.fixture documentation for details on the arguments accepted by self.app.post()\n"
] |
[
4
] |
[] |
[] |
[
"nosetests",
"pylons",
"python",
"unit_testing"
] |
stackoverflow_0002488978_nosetests_pylons_python_unit_testing.txt
|
Q:
Programmatically specifying Django model attributes
I would like to add attributes to a Django models programmatically. At class creation time (the time of the definition of the model class). The model is not going to change after that in run time. For instance, lets say I want to define a Car model class and want to add one price attribute (database column) per currency, given a list of currencies. (This list of currencies should be considered a constant that won't change runtime. I don't want a related model for these prices.)
What would be the best way to do this?
I had an approach that I thought would work, but it didn't exactly. This is how I tried doing it, using the car example above:
from django.db import models
class Car(models.Model):
name = models.CharField(max_length=50)
currencies = ['EUR', 'USD']
for currency in currencies:
Car.add_to_class('price_%s' % currency.lower(), models.IntegerField())
This does seem to work pretty well at first sight:
$ ./manage.py syncdb
Creating table shop_car
$ ./manage.py dbshell
shop=# \d shop_car
Table "public.shop_car"
Column | Type | Modifiers
-----------+-----------------------+-------------------------------------------------------
id | integer | not null default nextval('shop_car_id_seq'::regclass)
name | character varying(50) | not null
price_eur | integer | not null
price_usd | integer | not null
Indexes:
"shop_car_pkey" PRIMARY KEY, btree (id)
But when I try to create a new Car, it doesn't really work anymore:
>>> from shop.models import Car
>>> mycar = Car(name='VW Jetta', price_eur=100, price_usd=130)
>>> mycar
<Car: Car object>
>>> mycar.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/base.py", line 410, in save
self.save_base(force_insert=force_insert, force_update=force_update)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/base.py", line 495, in save_base
result = manager._insert(values, return_id=update_pk)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/manager.py", line 177, in _insert
return insert_query(self.model, values, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/query.py", line 1087, in insert_query
return query.execute_sql(return_id)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/sql/subqueries.py", line 320, in execute_sql
cursor = super(InsertQuery, self).execute_sql(None)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/sql/query.py", line 2369, in execute_sql
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/util.py", line 19, in execute
return self.cursor.execute(sql, params)
ProgrammingError: column "price_eur" specified more than once
LINE 1: ...NTO "shop_car" ("name", "price_eur", "price_usd", "price_eur...
^
Apparently, though, my code seem to run several times, causing the "price_eur" attribute to be added several times.
Comment: Initially I used the wording "at run time" ("I would like to add attributes to a Django models programmatically, at run time."). This wording wasn't the best. What I really want to was to add those fields at "model definition time" or "class creation time".
A:
My solution is something which is bad from various reasons, but it works:
from django.db import models
currencies = ["EUR", "USD"]
class Car(models.Model):
name = models.CharField(max_length=50)
for currency in currencies:
locals()['price_%s' % currency.lower()] = models.IntegerField()
In the place where I had to do this I had choice between something like that and maintaining table with more than 200 columns (I know, how bad it was, but I had no influence on it).
A:
The still not nice, but nicer than using locals solution is to use Field.contribute_to_class:
for currency in currencies:
models.IntegerField().contribute_to_class(Car, 'price_%s' % currency.lower())
I used it for MPTT (for which I've been a very bad maintainer *hides*)
Edit: On second thoughts, your code was working fine (Car.add_to_class calls the field's contribute_to_class for you) but the problem seems to be that the code to add the additional fields is being executed multiple times, so your model thinks it needs to save multiple fields with the same name. You need to put something in there to make sure you only dynamically add the fields once.
django.db.models.fields.Field.contribute_to_class calls django.db.models.options.Options.add_field (the object's _meta attribute is an instance of an Options), which doesn't check to see if a field with that name already exists and happily adds the field details to the list of fields it knows about.
A:
"I would like to add attributes to a Django models programmatically. At class creation time"
Don't. "Programmatically" adding columns is silly and confusing. It seems fine to you -- the developer -- who deeply gets the nuances of Django.
For us, the maintainers, that code will (a) make no sense and (b) have to be replaced with simple, obvious code that does the same job the simplest most obvious way.
Remember, the maintainers are violent sociopaths who know where you live. Pander to them with simple and obvious code.
There's no reason to replace a cluster of simple attribute definitions with a tricky-looking loop. There's no improvement and no savings.
The run-time performance of the view functions is the same.
The one-time class-definition has saved a few lines of code that are executed once during application start-up.
The development cost (i.e., solving this question) is higher.
The maintenance cost (i.e., turning this code over to someone else to keep it running) is astronomically high. The code will simply be replaced with something simpler and more obvious.
Even if you have 100's of currencies, this is still a perfectly bad idea.
"I don't want a related model for these prices"
Why not? A related model is (1) simple, (2) obvious, (3) standard, (4) extensible. It has almost no measurable cost at run time or development time and certainly no complexity.
"For instance, lets say I have a Car model class and want to add one price attribute
(database column) per currency, given a list of currencies."
That is not a new attribute at all.
That is a new value (in a row) of a table that has Car Model and Currency as the keys.
You class looks something like this:
class Price( models.Model ):
car = models.ForeignKey( Car )
currency = models.ForeignKey( Currency )
amount = models.DecimalField()
Previous Version of the question
"I would like to add attributes to a Django models programmatically, at run time."
Don't. There are absolutely no circumstances under which you ever want to add attributes to a database "at run time".
A:
You cannot do this at run time. It would change the database model and the database is changed via the command syncdb and somehow this feels really ugly.
Why not create a second model Price that holds the price for different currencies. Or if possible convert the price on the fly to a specific currency.
|
Programmatically specifying Django model attributes
|
I would like to add attributes to a Django models programmatically. At class creation time (the time of the definition of the model class). The model is not going to change after that in run time. For instance, lets say I want to define a Car model class and want to add one price attribute (database column) per currency, given a list of currencies. (This list of currencies should be considered a constant that won't change runtime. I don't want a related model for these prices.)
What would be the best way to do this?
I had an approach that I thought would work, but it didn't exactly. This is how I tried doing it, using the car example above:
from django.db import models
class Car(models.Model):
name = models.CharField(max_length=50)
currencies = ['EUR', 'USD']
for currency in currencies:
Car.add_to_class('price_%s' % currency.lower(), models.IntegerField())
This does seem to work pretty well at first sight:
$ ./manage.py syncdb
Creating table shop_car
$ ./manage.py dbshell
shop=# \d shop_car
Table "public.shop_car"
Column | Type | Modifiers
-----------+-----------------------+-------------------------------------------------------
id | integer | not null default nextval('shop_car_id_seq'::regclass)
name | character varying(50) | not null
price_eur | integer | not null
price_usd | integer | not null
Indexes:
"shop_car_pkey" PRIMARY KEY, btree (id)
But when I try to create a new Car, it doesn't really work anymore:
>>> from shop.models import Car
>>> mycar = Car(name='VW Jetta', price_eur=100, price_usd=130)
>>> mycar
<Car: Car object>
>>> mycar.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/base.py", line 410, in save
self.save_base(force_insert=force_insert, force_update=force_update)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/base.py", line 495, in save_base
result = manager._insert(values, return_id=update_pk)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/manager.py", line 177, in _insert
return insert_query(self.model, values, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/query.py", line 1087, in insert_query
return query.execute_sql(return_id)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/sql/subqueries.py", line 320, in execute_sql
cursor = super(InsertQuery, self).execute_sql(None)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/sql/query.py", line 2369, in execute_sql
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/util.py", line 19, in execute
return self.cursor.execute(sql, params)
ProgrammingError: column "price_eur" specified more than once
LINE 1: ...NTO "shop_car" ("name", "price_eur", "price_usd", "price_eur...
^
Apparently, though, my code seem to run several times, causing the "price_eur" attribute to be added several times.
Comment: Initially I used the wording "at run time" ("I would like to add attributes to a Django models programmatically, at run time."). This wording wasn't the best. What I really want to was to add those fields at "model definition time" or "class creation time".
|
[
"My solution is something which is bad from various reasons, but it works:\nfrom django.db import models\n\ncurrencies = [\"EUR\", \"USD\"]\n\nclass Car(models.Model):\n\n name = models.CharField(max_length=50)\n\n for currency in currencies:\n locals()['price_%s' % currency.lower()] = models.IntegerField()\n\nIn the place where I had to do this I had choice between something like that and maintaining table with more than 200 columns (I know, how bad it was, but I had no influence on it).\n",
"The still not nice, but nicer than using locals solution is to use Field.contribute_to_class:\nfor currency in currencies:\n models.IntegerField().contribute_to_class(Car, 'price_%s' % currency.lower())\n\nI used it for MPTT (for which I've been a very bad maintainer *hides*)\nEdit: On second thoughts, your code was working fine (Car.add_to_class calls the field's contribute_to_class for you) but the problem seems to be that the code to add the additional fields is being executed multiple times, so your model thinks it needs to save multiple fields with the same name. You need to put something in there to make sure you only dynamically add the fields once.\ndjango.db.models.fields.Field.contribute_to_class calls django.db.models.options.Options.add_field (the object's _meta attribute is an instance of an Options), which doesn't check to see if a field with that name already exists and happily adds the field details to the list of fields it knows about.\n",
"\n\"I would like to add attributes to a Django models programmatically. At class creation time\"\n\nDon't. \"Programmatically\" adding columns is silly and confusing. It seems fine to you -- the developer -- who deeply gets the nuances of Django.\nFor us, the maintainers, that code will (a) make no sense and (b) have to be replaced with simple, obvious code that does the same job the simplest most obvious way.\nRemember, the maintainers are violent sociopaths who know where you live. Pander to them with simple and obvious code.\nThere's no reason to replace a cluster of simple attribute definitions with a tricky-looking loop. There's no improvement and no savings.\n\nThe run-time performance of the view functions is the same.\nThe one-time class-definition has saved a few lines of code that are executed once during application start-up. \nThe development cost (i.e., solving this question) is higher.\nThe maintenance cost (i.e., turning this code over to someone else to keep it running) is astronomically high. The code will simply be replaced with something simpler and more obvious.\n\nEven if you have 100's of currencies, this is still a perfectly bad idea.\n\n\"I don't want a related model for these prices\"\n\nWhy not? A related model is (1) simple, (2) obvious, (3) standard, (4) extensible. It has almost no measurable cost at run time or development time and certainly no complexity.\n\n\"For instance, lets say I have a Car model class and want to add one price attribute \n (database column) per currency, given a list of currencies.\"\n\nThat is not a new attribute at all.\nThat is a new value (in a row) of a table that has Car Model and Currency as the keys.\nYou class looks something like this:\nclass Price( models.Model ):\n car = models.ForeignKey( Car )\n currency = models.ForeignKey( Currency )\n amount = models.DecimalField()\n\nPrevious Version of the question\n\n\"I would like to add attributes to a Django models programmatically, at run time.\"\n\nDon't. There are absolutely no circumstances under which you ever want to add attributes to a database \"at run time\".\n",
"You cannot do this at run time. It would change the database model and the database is changed via the command syncdb and somehow this feels really ugly.\nWhy not create a second model Price that holds the price for different currencies. Or if possible convert the price on the fly to a specific currency.\n"
] |
[
5,
4,
2,
0
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002501173_django_django_models_python.txt
|
Q:
String comparison in Numpy
In the following example
In [8]: import numpy as np
In [9]: strings = np.array(['hello ', 'world '], dtype='|S10')
In [10]: strings == 'hello'
Out[10]: array([False, False], dtype=bool)
The comparison fails because of the whitespace. Is there a Numpy built-in function that does the equivalent of
In [12]: np.array([x.strip()=='hello' for x in strings])
Out[12]: array([ True, False], dtype=bool)
which does give the correct result?
A:
Numpy provides vectorised string operations for arrays similar to Python's string methods. They are in the numpy.char module.
http://docs.scipy.org/doc/numpy/reference/routines.char.html
import numpy as np
strings = np.array(['hello ', 'world '], dtype='|S10')
print np.char.strip(strings) == 'hello'
# prints [ True False]
Hope this is helpful.
|
String comparison in Numpy
|
In the following example
In [8]: import numpy as np
In [9]: strings = np.array(['hello ', 'world '], dtype='|S10')
In [10]: strings == 'hello'
Out[10]: array([False, False], dtype=bool)
The comparison fails because of the whitespace. Is there a Numpy built-in function that does the equivalent of
In [12]: np.array([x.strip()=='hello' for x in strings])
Out[12]: array([ True, False], dtype=bool)
which does give the correct result?
|
[
"Numpy provides vectorised string operations for arrays similar to Python's string methods. They are in the numpy.char module.\nhttp://docs.scipy.org/doc/numpy/reference/routines.char.html\nimport numpy as np\n\nstrings = np.array(['hello ', 'world '], dtype='|S10')\n\nprint np.char.strip(strings) == 'hello'\n# prints [ True False]\n\nHope this is helpful.\n"
] |
[
11
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0002501362_numpy_python.txt
|
Q:
What can be done in Cpython that can not be done in IronPython?
What can be done in Cpython that can not be done in IronPython?
A:
If you are writing "100% pure Python", you can do everything that CPython can do in IronPython. The problem comes in when you want to use a third-party package. Many of them will have written their performance-intensive portions in C, and rely on the Python/C API (e.g. NumPy).
As a glue language for hooking together .NET components, IronPython is great.
|
What can be done in Cpython that can not be done in IronPython?
|
What can be done in Cpython that can not be done in IronPython?
|
[
"If you are writing \"100% pure Python\", you can do everything that CPython can do in IronPython. The problem comes in when you want to use a third-party package. Many of them will have written their performance-intensive portions in C, and rely on the Python/C API (e.g. NumPy).\nAs a glue language for hooking together .NET components, IronPython is great.\n"
] |
[
4
] |
[] |
[] |
[
"ironpython",
"python"
] |
stackoverflow_0002501492_ironpython_python.txt
|
Q:
add a decorate function to a class
I have a decorated function (simplified version):
class Memoize:
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args, **kwds):
hash = args
try:
return self.memoized[hash]
except KeyError:
self.memoized[hash] = self.function(*args)
return self.memoized[hash]
@Memoize
def _DrawPlot(self, options):
do something...
now I want to add this method to a pre-esisting class.
ROOT.TChain.DrawPlot = _DrawPlot
when I call this method:
chain = TChain()
chain.DrawPlot(opts)
I got:
self.memoized[hash] = self.function(*args)
TypeError: _DrawPlot() takes exactly 2 arguments (1 given)
why doesn't it propagate self?
A:
The problem is that you have defined your own callable class then tried to use it as a method. When you use a function as an attribute, accessing the function as an attribute calls it its __get__ method to return something other than the function itself—the bound method. When you have your own class without defining __get__, it just returns your instance without implicitly passing self.
Descriptors are explained some on http://docs.python.org/reference/datamodel.html#descriptors if you are not familiar with them. The __get__, __set__, and __delete__ methods change how interacting with your object as an attribute works.
You could implement memoize as a function and use the built-in __get__ magic that functions already have
import functools
def memoize(f):
@functools.wraps(f)
def memoized(*args, _cache={}):
# This abuses the normally-unwanted behaviour of mutable default arguments.
if args not in _cache:
_cache[args] = f(*args)
return _cache[args]
return memoized
or by modifying your class along the lines of
import functools
class Memoize(object): #inherit object
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args): #don't accept kwargs you don't want.
# I removed "hash = args" because it shadowed a builtin function and
# because it was untrue--it wasn't a hash, it was something you intended for
# Python to hash for you.
try:
return self.memoized[args]
except KeyError:
self.memoized[args] = self.function(*args)
return self.memoized[args]
def __get__(self, obj, type):
if obj is None: #We looked up on the class
return self
return functools.partial(self, obj)
Note that both of these choke if any of the arguments you pass in are mutable (well, unhashable technically). This might be suitable for your case, but you may also want to deal with the case where args is unhashable.
|
add a decorate function to a class
|
I have a decorated function (simplified version):
class Memoize:
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args, **kwds):
hash = args
try:
return self.memoized[hash]
except KeyError:
self.memoized[hash] = self.function(*args)
return self.memoized[hash]
@Memoize
def _DrawPlot(self, options):
do something...
now I want to add this method to a pre-esisting class.
ROOT.TChain.DrawPlot = _DrawPlot
when I call this method:
chain = TChain()
chain.DrawPlot(opts)
I got:
self.memoized[hash] = self.function(*args)
TypeError: _DrawPlot() takes exactly 2 arguments (1 given)
why doesn't it propagate self?
|
[
"The problem is that you have defined your own callable class then tried to use it as a method. When you use a function as an attribute, accessing the function as an attribute calls it its __get__ method to return something other than the function itself—the bound method. When you have your own class without defining __get__, it just returns your instance without implicitly passing self.\nDescriptors are explained some on http://docs.python.org/reference/datamodel.html#descriptors if you are not familiar with them. The __get__, __set__, and __delete__ methods change how interacting with your object as an attribute works.\n\nYou could implement memoize as a function and use the built-in __get__ magic that functions already have\nimport functools\n\ndef memoize(f):\n @functools.wraps(f)\n def memoized(*args, _cache={}): \n # This abuses the normally-unwanted behaviour of mutable default arguments.\n if args not in _cache:\n _cache[args] = f(*args)\n return _cache[args]\n return memoized\n\nor by modifying your class along the lines of\nimport functools\n\nclass Memoize(object): #inherit object\n def __init__(self, function):\n self.function = function\n self.memoized = {}\n def __call__(self, *args): #don't accept kwargs you don't want.\n # I removed \"hash = args\" because it shadowed a builtin function and \n # because it was untrue--it wasn't a hash, it was something you intended for\n # Python to hash for you.\n try:\n return self.memoized[args]\n except KeyError:\n self.memoized[args] = self.function(*args)\n return self.memoized[args]\n def __get__(self, obj, type):\n if obj is None: #We looked up on the class\n return self\n\n return functools.partial(self, obj)\n\nNote that both of these choke if any of the arguments you pass in are mutable (well, unhashable technically). This might be suitable for your case, but you may also want to deal with the case where args is unhashable.\n"
] |
[
3
] |
[] |
[] |
[
"class",
"decorator",
"descriptor",
"python"
] |
stackoverflow_0002501529_class_decorator_descriptor_python.txt
|
Q:
How to step through debug twisted?
I'd like to be able to debug Punjab, a twisted python application, in Netbeans so that I can step through the code. How can I do that? Alternatively, how could I do it in a different debugger?
A:
Since you're trying to debug a twisted application, you have a few options:
If you're running via twistd you can use the -b command-line options:
-b, --debug run the application in the Python Debugger (implies
nodaemon), sending SIGUSR2 will drop into debugger
You can run manhole in your twisted process - this allows you to telnet into the server and examine Python objects - http://twistedmatrix.com/documents/current/core/howto/telnet.html
You can optionally run pdb manually - see: http://docs.python.org/library/pdb.html
|
How to step through debug twisted?
|
I'd like to be able to debug Punjab, a twisted python application, in Netbeans so that I can step through the code. How can I do that? Alternatively, how could I do it in a different debugger?
|
[
"Since you're trying to debug a twisted application, you have a few options:\n\nIf you're running via twistd you can use the -b command-line options:\n -b, --debug run the application in the Python Debugger (implies\n nodaemon), sending SIGUSR2 will drop into debugger\n\nYou can run manhole in your twisted process - this allows you to telnet into the server and examine Python objects - http://twistedmatrix.com/documents/current/core/howto/telnet.html\nYou can optionally run pdb manually - see: http://docs.python.org/library/pdb.html\n\n"
] |
[
10
] |
[] |
[] |
[
"debugging",
"netbeans",
"python",
"twisted"
] |
stackoverflow_0002501136_debugging_netbeans_python_twisted.txt
|
Q:
format printing
How to format printing stmt in python?
print"---------------------------------"
print"client:mount-point:logfile:status"
print"---------------------------------"
print clientname,mntpt,logfile,status
Currently it prints something like this :
---------------------------------
client:mount-point:logfile:status
---------------------------------
client01 : /some/path/mnt/1007/1 : /export/something/laks/specs_dir/log/client1/gc.log:running
How to make this output better?. Any suggestions
A:
Take a look at string formatting : http://docs.python.org/release/2.5.2/lib/typesseq-strings.html
A:
If you're trying to format a table, consider using other software for table formatting.
As an example, you can produce HTML with the print statements and view the table with a browser. Another option is to generate csv data to be viewed using a spreadsheet program.
A:
Stick some tab spacing in for a start?
'\t'
|
format printing
|
How to format printing stmt in python?
print"---------------------------------"
print"client:mount-point:logfile:status"
print"---------------------------------"
print clientname,mntpt,logfile,status
Currently it prints something like this :
---------------------------------
client:mount-point:logfile:status
---------------------------------
client01 : /some/path/mnt/1007/1 : /export/something/laks/specs_dir/log/client1/gc.log:running
How to make this output better?. Any suggestions
|
[
"Take a look at string formatting : http://docs.python.org/release/2.5.2/lib/typesseq-strings.html\n",
"If you're trying to format a table, consider using other software for table formatting.\nAs an example, you can produce HTML with the print statements and view the table with a browser. Another option is to generate csv data to be viewed using a spreadsheet program.\n",
"Stick some tab spacing in for a start?\n'\\t'\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"printing",
"python"
] |
stackoverflow_0002499917_printing_python.txt
|
Q:
Printing elements out of list
I have a certain check to be done and if the check satisfies, I want the result to be printed. Below is the code:
import string
import codecs
import sys
y=sys.argv[1]
list_1=[]
f=1.0
x=0.05
write_in = open ("new_file.txt", "w")
write_in_1 = open ("new_file_1.txt", "w")
ligand_file=open( y, "r" ) #Open the receptor.txt file
ligand_lines=ligand_file.readlines() # Read all the lines into the array
ligand_lines=map( string.strip, ligand_lines ) #Remove the newline character from all the pdb file names
ligand_file.close()
ligand_file=open( "unique_count_c_from_ac.txt", "r" ) #Open the receptor.txt file
ligand_lines_1=ligand_file.readlines() # Read all the lines into the array
ligand_lines_1=map( string.strip, ligand_lines_1 ) #Remove the newline character from all the pdb file names
ligand_file.close()
s=[]
for i in ligand_lines:
for j in ligand_lines_1:
j = j.split()
if i == j[1]:
print j
The above code works great but when I print j, it prints like ['351', '342'] but I am expecting to get 351 342 (with one space in between). Since it is more of a python question, I have not included the input files (basically they are just numbers).
Can anyone help me?
Cheers,
Chavanak
A:
To convert a list of strings to a single string with spaces in between the lists's items, use ' '.join(seq).
>>> ' '.join(['1','2','3'])
'1 2 3'
You can replace ' ' with whatever string you want in between the items.
A:
Mark Rushakoff seems to have solved your immediate problem, but there are some other improvements that could be made to your code.
Always use context managers (with open(filename, mode) as f:) for opening files rather than relying on close getting called manually.
Don't bother reading a whole file into memory very often. Looping over some_file.readilines() can be replaced with looping over some_file directly.
For example, you could have used map(string.strip, ligland_file) or better yet [line.strip() for line in ligland_file]
Don't choose names to include the type of the object they refer to. This information can be found other ways.
For exmaple, the code you posted can be simplified to something along the lines of
import sys
from contextlib import nested
some_real_name = sys.argv[1]
other_file = "unique_count_c_from_ac.txt"
with nested(open(some_real_name, "r"), open(other_file, "r")) as ligand_1, ligand_2:
for line_1 in ligand_1:
# Take care of the trailing newline
line_1 = line_1.strip()
for line_2 in ligand_2:
line_2 = line2.strip()
numbers = line2.split()
if line_1 == numbers[1]:
# If the second number from this line matches the number that is
# in the user's file, print all the numbers from this line
print ' '.join(numbers)
which is more reliable and I believe more easily read.
Note that the algorithmic performance of this is far from ideal because of these nested loops. Depending on your need, this could potentially be improved, but since I don't know exactly what data you need to extract to tell you whether you can.
The time this takes currently in my code and yours is O(nmq), where n is the number of lines in one file, m is the number of lines in the other, and q is the length of lines in unique_count_c_from_ac.txt. If two of these are fixed/small, then you have linear performance. If two can grow arbitrarily (I sort of imagine n and m can?), then you could look into improving your algorithm, probably using sets or dicts.
|
Printing elements out of list
|
I have a certain check to be done and if the check satisfies, I want the result to be printed. Below is the code:
import string
import codecs
import sys
y=sys.argv[1]
list_1=[]
f=1.0
x=0.05
write_in = open ("new_file.txt", "w")
write_in_1 = open ("new_file_1.txt", "w")
ligand_file=open( y, "r" ) #Open the receptor.txt file
ligand_lines=ligand_file.readlines() # Read all the lines into the array
ligand_lines=map( string.strip, ligand_lines ) #Remove the newline character from all the pdb file names
ligand_file.close()
ligand_file=open( "unique_count_c_from_ac.txt", "r" ) #Open the receptor.txt file
ligand_lines_1=ligand_file.readlines() # Read all the lines into the array
ligand_lines_1=map( string.strip, ligand_lines_1 ) #Remove the newline character from all the pdb file names
ligand_file.close()
s=[]
for i in ligand_lines:
for j in ligand_lines_1:
j = j.split()
if i == j[1]:
print j
The above code works great but when I print j, it prints like ['351', '342'] but I am expecting to get 351 342 (with one space in between). Since it is more of a python question, I have not included the input files (basically they are just numbers).
Can anyone help me?
Cheers,
Chavanak
|
[
"To convert a list of strings to a single string with spaces in between the lists's items, use ' '.join(seq).\n>>> ' '.join(['1','2','3'])\n'1 2 3'\n\nYou can replace ' ' with whatever string you want in between the items.\n",
"Mark Rushakoff seems to have solved your immediate problem, but there are some other improvements that could be made to your code.\n\nAlways use context managers (with open(filename, mode) as f:) for opening files rather than relying on close getting called manually.\nDon't bother reading a whole file into memory very often. Looping over some_file.readilines() can be replaced with looping over some_file directly.\n\nFor example, you could have used map(string.strip, ligland_file) or better yet [line.strip() for line in ligland_file]\n\nDon't choose names to include the type of the object they refer to. This information can be found other ways.\n\nFor exmaple, the code you posted can be simplified to something along the lines of\nimport sys\nfrom contextlib import nested\n\nsome_real_name = sys.argv[1]\nother_file = \"unique_count_c_from_ac.txt\"\n\nwith nested(open(some_real_name, \"r\"), open(other_file, \"r\")) as ligand_1, ligand_2:\n for line_1 in ligand_1:\n # Take care of the trailing newline\n line_1 = line_1.strip()\n\n for line_2 in ligand_2:\n line_2 = line2.strip()\n\n numbers = line2.split()\n\n if line_1 == numbers[1]:\n # If the second number from this line matches the number that is \n # in the user's file, print all the numbers from this line\n print ' '.join(numbers)\n\nwhich is more reliable and I believe more easily read.\nNote that the algorithmic performance of this is far from ideal because of these nested loops. Depending on your need, this could potentially be improved, but since I don't know exactly what data you need to extract to tell you whether you can.\nThe time this takes currently in my code and yours is O(nmq), where n is the number of lines in one file, m is the number of lines in the other, and q is the length of lines in unique_count_c_from_ac.txt. If two of these are fixed/small, then you have linear performance. If two can grow arbitrarily (I sort of imagine n and m can?), then you could look into improving your algorithm, probably using sets or dicts. \n"
] |
[
9,
2
] |
[] |
[] |
[
"list",
"printing",
"python"
] |
stackoverflow_0002501675_list_printing_python.txt
|
Q:
Reading UDP Packets
I am having some trouble dissecting a UDP packet. I am receiving the packets and storing the data and sender-address in variables 'data' and 'addr' with:
data,addr = UDPSock.recvfrom(buf)
This parses the data as a string, that I am now unable to turn into bytes. I know the structure of the datagram packet which is a total of 28 bytes, and that the data I am trying to get out is in bytes 17:28.
I have tried doing this:
mybytes = data[16:19]
print struct.unpack('>I', mybytes)
--> struct.error: unpack str size does not match format
And this:
response = (0, 0, data[16], data[17], 6)
bytes = array('B', response[:-1])
print struct.unpack('>I', bytes)
--> TypeError: Type not compatible with array type
And this:
print "\nData byte 17:", str.encode(data[17])
--> UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0: ordinal not in range(128)
More specifically I want to parse what I think is an unsigned int. And now I am not sure what to try next. I am completely new to sockets and byte-conversions in Python, so any advice would be helpful :)
Thanks,
Thomas
A:
An unsigned int32 is 4 bytes long, so you have to feed 4 bytes into struct.unpack.
Replace
mybytes = data[16:19]
with
mybytes = data[16:20]
(right number is the first byte not included, i.e. range(16,19) = [16,17,18]) and you should be good to go.
|
Reading UDP Packets
|
I am having some trouble dissecting a UDP packet. I am receiving the packets and storing the data and sender-address in variables 'data' and 'addr' with:
data,addr = UDPSock.recvfrom(buf)
This parses the data as a string, that I am now unable to turn into bytes. I know the structure of the datagram packet which is a total of 28 bytes, and that the data I am trying to get out is in bytes 17:28.
I have tried doing this:
mybytes = data[16:19]
print struct.unpack('>I', mybytes)
--> struct.error: unpack str size does not match format
And this:
response = (0, 0, data[16], data[17], 6)
bytes = array('B', response[:-1])
print struct.unpack('>I', bytes)
--> TypeError: Type not compatible with array type
And this:
print "\nData byte 17:", str.encode(data[17])
--> UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0: ordinal not in range(128)
More specifically I want to parse what I think is an unsigned int. And now I am not sure what to try next. I am completely new to sockets and byte-conversions in Python, so any advice would be helpful :)
Thanks,
Thomas
|
[
"An unsigned int32 is 4 bytes long, so you have to feed 4 bytes into struct.unpack.\nReplace\nmybytes = data[16:19]\n\nwith\nmybytes = data[16:20]\n\n(right number is the first byte not included, i.e. range(16,19) = [16,17,18]) and you should be good to go.\n"
] |
[
3
] |
[] |
[] |
[
"networking",
"python",
"udp"
] |
stackoverflow_0002501882_networking_python_udp.txt
|
Q:
Python 2.5 fails on a datetime.strptime format
I have seen several questions with people asking about the same problem but none of the answers are helping me.
I'm receiving this error:
pydev debugger: starting
Traceback (most recent call last):
>>>
File "/usr/local/zend/apache2/htdocs/pyth/src/conn.py", line 23, in <module>
userConnDate = datetime.strptime(data[1] + ' ' + data[2], "%y-%m-%d %H:%M:%S")
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/_strptime.py", line 330, in strptime
(data_string, format))
ValueError: time data did not match format: data=2010-03-11 08:35:25 fmt=%y-%m-%d %H:%M:%S
It looks fine to me, what is python seeing that I don't?
Thanks for you time.
A:
you are using %y (which matches a 2 digit year).
try with %Y, which matches a 4 digit year (like your 2010)
A:
Try using the a capital Y - '%Y' to match a 4-digit year.
|
Python 2.5 fails on a datetime.strptime format
|
I have seen several questions with people asking about the same problem but none of the answers are helping me.
I'm receiving this error:
pydev debugger: starting
Traceback (most recent call last):
>>>
File "/usr/local/zend/apache2/htdocs/pyth/src/conn.py", line 23, in <module>
userConnDate = datetime.strptime(data[1] + ' ' + data[2], "%y-%m-%d %H:%M:%S")
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/_strptime.py", line 330, in strptime
(data_string, format))
ValueError: time data did not match format: data=2010-03-11 08:35:25 fmt=%y-%m-%d %H:%M:%S
It looks fine to me, what is python seeing that I don't?
Thanks for you time.
|
[
"you are using %y (which matches a 2 digit year).\ntry with %Y, which matches a 4 digit year (like your 2010)\n",
"Try using the a capital Y - '%Y' to match a 4-digit year.\n"
] |
[
3,
1
] |
[] |
[] |
[
"python",
"strptime"
] |
stackoverflow_0002502123_python_strptime.txt
|
Q:
Profiling shared library/plugins written in C++ for Python?
I've got a C++ library that lets me write plugins in C++ and then automatically exposes them
to python. I'm working on some networking stuff in a plugin and I'd like to profile it with something like gprof, but simply compiling with -pg and running the plugin via python doesn't generated the necessary profiling data. Unfortunately the plugins are tightly coupled so it's not possible to run them as standalone programs. Does anyone know of ways to profile shared libraries and/or plugins independently of the program running them?
A:
I've found valgrind's cachegrind with KCachegrind to be helpful in analysis of un-prepared (e.g. no gprof code embedded) binaries.
|
Profiling shared library/plugins written in C++ for Python?
|
I've got a C++ library that lets me write plugins in C++ and then automatically exposes them
to python. I'm working on some networking stuff in a plugin and I'd like to profile it with something like gprof, but simply compiling with -pg and running the plugin via python doesn't generated the necessary profiling data. Unfortunately the plugins are tightly coupled so it's not possible to run them as standalone programs. Does anyone know of ways to profile shared libraries and/or plugins independently of the program running them?
|
[
"I've found valgrind's cachegrind with KCachegrind to be helpful in analysis of un-prepared (e.g. no gprof code embedded) binaries.\n"
] |
[
1
] |
[] |
[] |
[
"c++",
"profile",
"python"
] |
stackoverflow_0002502262_c++_profile_python.txt
|
Q:
Implementing pyglet breaks my once working framebuffer OpenGL code
This question repeats my earlier one but my earlier one was a failure because I didn't copy some vital information correctly, so I have to redo it.
I'm getting an error with a call to an OpenGL function. Maybe pyglet isn't initialising OpenGL correctly? The error happens with a simple function that worked before:
def setup_framebuffer(surface):
#Create texture if not done already
if surface.texture is None:
create_texture(surface)
#Render child to parent
if surface.frame_buffer is None:
surface.frame_buffer = glGenFramebuffersEXT(1)
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0)
glPushAttrib(GL_VIEWPORT_BIT)
glViewport(0,0,surface._scale[0],surface._scale[1])
glMatrixMode(GL_PROJECTION)
glLoadIdentity() #Load the projection matrix
gluOrtho2D(0,surface._scale[0],0,surface._scale[1])
The error is:
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)
ctypes.ArgumentError: argument 2: : wrong type
Wrong type? Then is glGenFramebuffersEXT(1) giving the wrong type now? Why would that be?
Before that function is called I initialise a class instance which manages my game. Here's the init method:
pyglet.options['audio'] = ('alsa','openal','directsound','silent')
self.keys = [False] * 323
self.events = []
self.title = title
self.game_size = game_size
self.first_screen = (1280,720) #Take 120 pixels from the height because the menu bar, window bar and dock takes space
config = pyglet.gl.Config(alpha_size=8,double_buffer=True,sample_buffers=1,samples=4)
self.window = pyglet.window.Window(game_size[0],game_size[1],title,True,config=config)
self.window.set_handler('on_draw',self.game_loop)
self.window.set_handler('on_resize',self.reshaped)
self.window.set_handler('on_key_press',self.keydown)
self.window.set_handler('on_key_release',self.keyup)
self.window.set_handler('on_mouse_press',self.mouse_func)
glViewport(0,0,self.first_screen[0],self.first_screen[1]) #Creates the viewport which is mapped to the window
glEnable(GL_BLEND) #Enable alpha blending
glEnable(GL_TEXTURE_2D) #Enable 2D Textures
glEnable(GL_MULTISAMPLE) #Enable Multisampling anti-aliasing
glEnable(GL_POLYGON_SMOOTH) #Enable antialiased polygons
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glMatrixMode(GL_PROJECTION)
glLoadIdentity() #Load the projection matrix
gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view
self.game_gap = (0,0)
self.on_exit = on_exit
self.mod_key = 1024 if sys.platform == "darwin" else 64
Surface.__init__(self,game_size)
self.screen_change = True
self.frames = [time.time()]
self.fps = 60
self.last_time = 0
self.fade_surface = Surface([1280,720])
pyglet.font.add_file(os.path.dirname(sys.argv[0]) + "/NEUROPOL.ttf")
pyglet.font.load('NEUROPOL')
Surface is a class that I made which acts a bit like the pygame.Surface class but uses OpenGL textures.
That method sets up the Window and OpenGL (Probably not properly which is the problem?) and after calling it I set-up some things for my game which uses the setup_framebuffer function for rendering to textures. Then pyglet.app.run() is called which should hopefully run my game_loop method since I did self.window.set_handler('on_draw,self.game_loop) but my game crashes before it gets there.
This is the first time I've use pyglet. The documentation doesn't explain to me what I'm doing wrong. Can anyone help?
Thank you.
A:
glBindFramebufferEXT expects pointer to a buffer. AFAIK, you have to use ctypes in this case.
from pyglet.gl import *
from ctypes import c_uint, byref
fb = c_uint()
glGenFramebuffersEXT(1, byref(fb))
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb)
Search pyglet mailing list for better examples. And BTW:
>> glGenFramebuffersEXT(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: this function takes at least 2 arguments (1 given)
Edit:
I should have guessed that you are using pyOpenGL:
fb = int(glGenFramebuffersEXT(1))
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb)
|
Implementing pyglet breaks my once working framebuffer OpenGL code
|
This question repeats my earlier one but my earlier one was a failure because I didn't copy some vital information correctly, so I have to redo it.
I'm getting an error with a call to an OpenGL function. Maybe pyglet isn't initialising OpenGL correctly? The error happens with a simple function that worked before:
def setup_framebuffer(surface):
#Create texture if not done already
if surface.texture is None:
create_texture(surface)
#Render child to parent
if surface.frame_buffer is None:
surface.frame_buffer = glGenFramebuffersEXT(1)
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0)
glPushAttrib(GL_VIEWPORT_BIT)
glViewport(0,0,surface._scale[0],surface._scale[1])
glMatrixMode(GL_PROJECTION)
glLoadIdentity() #Load the projection matrix
gluOrtho2D(0,surface._scale[0],0,surface._scale[1])
The error is:
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)
ctypes.ArgumentError: argument 2: : wrong type
Wrong type? Then is glGenFramebuffersEXT(1) giving the wrong type now? Why would that be?
Before that function is called I initialise a class instance which manages my game. Here's the init method:
pyglet.options['audio'] = ('alsa','openal','directsound','silent')
self.keys = [False] * 323
self.events = []
self.title = title
self.game_size = game_size
self.first_screen = (1280,720) #Take 120 pixels from the height because the menu bar, window bar and dock takes space
config = pyglet.gl.Config(alpha_size=8,double_buffer=True,sample_buffers=1,samples=4)
self.window = pyglet.window.Window(game_size[0],game_size[1],title,True,config=config)
self.window.set_handler('on_draw',self.game_loop)
self.window.set_handler('on_resize',self.reshaped)
self.window.set_handler('on_key_press',self.keydown)
self.window.set_handler('on_key_release',self.keyup)
self.window.set_handler('on_mouse_press',self.mouse_func)
glViewport(0,0,self.first_screen[0],self.first_screen[1]) #Creates the viewport which is mapped to the window
glEnable(GL_BLEND) #Enable alpha blending
glEnable(GL_TEXTURE_2D) #Enable 2D Textures
glEnable(GL_MULTISAMPLE) #Enable Multisampling anti-aliasing
glEnable(GL_POLYGON_SMOOTH) #Enable antialiased polygons
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glMatrixMode(GL_PROJECTION)
glLoadIdentity() #Load the projection matrix
gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view
self.game_gap = (0,0)
self.on_exit = on_exit
self.mod_key = 1024 if sys.platform == "darwin" else 64
Surface.__init__(self,game_size)
self.screen_change = True
self.frames = [time.time()]
self.fps = 60
self.last_time = 0
self.fade_surface = Surface([1280,720])
pyglet.font.add_file(os.path.dirname(sys.argv[0]) + "/NEUROPOL.ttf")
pyglet.font.load('NEUROPOL')
Surface is a class that I made which acts a bit like the pygame.Surface class but uses OpenGL textures.
That method sets up the Window and OpenGL (Probably not properly which is the problem?) and after calling it I set-up some things for my game which uses the setup_framebuffer function for rendering to textures. Then pyglet.app.run() is called which should hopefully run my game_loop method since I did self.window.set_handler('on_draw,self.game_loop) but my game crashes before it gets there.
This is the first time I've use pyglet. The documentation doesn't explain to me what I'm doing wrong. Can anyone help?
Thank you.
|
[
"glBindFramebufferEXT expects pointer to a buffer. AFAIK, you have to use ctypes in this case.\nfrom pyglet.gl import *\nfrom ctypes import c_uint, byref\n\nfb = c_uint()\nglGenFramebuffersEXT(1, byref(fb))\nglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb) \n\nSearch pyglet mailing list for better examples. And BTW:\n>> glGenFramebuffersEXT(1)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: this function takes at least 2 arguments (1 given)\n\nEdit:\nI should have guessed that you are using pyOpenGL:\nfb = int(glGenFramebuffersEXT(1))\nglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb)\n\n"
] |
[
1
] |
[] |
[] |
[
"framebuffer",
"opengl",
"pyglet",
"pyopengl",
"python"
] |
stackoverflow_0002502362_framebuffer_opengl_pyglet_pyopengl_python.txt
|
Q:
What are some strategies to add spell checking to a Google App Engine program?
I'm working on a Google App Engine program that will require some basic spell checking features. Normally iSpell or it's cousins would be options, but I'm not sure that will work in GEA. Are there other strategies/tools that would work in that environment?
A:
A very minimal, pure-Python spell checker can be found here: http://norvig.com/spell-correct.html
The big.txt file Norvig uses to train his spell checker is too large to upload to App Engine at 6.2 megabytes, but the NWORDS dict that results from training is only ~650K when pickled. So one solution might be to pre-train the spell checker, pickle the results and include the pickled training data in your application.
This spell checker might not be good enough for your needs, and the way I've proposed you integrate it into your app might be an absolutely terrible idea. I'm really not sure. Might be interesting to try, though.
A:
I personally would try to go down the route of using Google's API for spellcheck. I'm trying to find it now, but I believe their exposed web service includes a spell checker.
It's always tough finding good python libraries that are actually being maintained. On the other hand, I imagine Google's service should be around and dependable for a while.
Not sure in what format the results come back, but on your side, you could implement your own Levenstein distance formula to see how close the results are to your word in question.
Mark
|
What are some strategies to add spell checking to a Google App Engine program?
|
I'm working on a Google App Engine program that will require some basic spell checking features. Normally iSpell or it's cousins would be options, but I'm not sure that will work in GEA. Are there other strategies/tools that would work in that environment?
|
[
"A very minimal, pure-Python spell checker can be found here: http://norvig.com/spell-correct.html\nThe big.txt file Norvig uses to train his spell checker is too large to upload to App Engine at 6.2 megabytes, but the NWORDS dict that results from training is only ~650K when pickled. So one solution might be to pre-train the spell checker, pickle the results and include the pickled training data in your application.\nThis spell checker might not be good enough for your needs, and the way I've proposed you integrate it into your app might be an absolutely terrible idea. I'm really not sure. Might be interesting to try, though.\n",
"I personally would try to go down the route of using Google's API for spellcheck. I'm trying to find it now, but I believe their exposed web service includes a spell checker.\nIt's always tough finding good python libraries that are actually being maintained. On the other hand, I imagine Google's service should be around and dependable for a while.\nNot sure in what format the results come back, but on your side, you could implement your own Levenstein distance formula to see how close the results are to your word in question.\nMark\n"
] |
[
1,
0
] |
[] |
[] |
[
"google_app_engine",
"python",
"spell_checking"
] |
stackoverflow_0002500093_google_app_engine_python_spell_checking.txt
|
Q:
GAE Datastore Put()
def post(self):
update = self.request.get('update')
if users.get_current_user():
if update:
personal = db.GqlQuery("SELECT * FROM Personal WHERE __key__ = :1", db.Key(update))
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
personal= Personal()
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')
Should this will update the existing record if the 'update' is querystring containing key datastore key. I try this but keep adding new record/entity. Please give me some sugesstion to correctly updating the record/entity.
Correction? :
def post(self):
update = self.request.get('update')
if users.get_current_user():
if update:
personal = Personal.get(db.Key(update))
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
personal= Personal()
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')
A:
There's no need to do a query when you know the key: Simply call db.get() on the key to retrieve it directly, which is much faster than doing a query.
As to why you're creating a new record each time, it looks like you're not passing in 'update' to your page correctly. Try logging the query string parameters to see what's going wrong.
A:
I finally answer this myself, Thanks for Nick Johnson guide on this.
I cannot get the query string url as 'string key' that always raise BadKeyError: Invalid string key exception.
I try to put this 'update' string as hidden field on html edit form and this works since 'update' is a valid 'string key' now.
def post(self):
update = self.request.get('update')
if users.get_current_user():
if update != '':
personal = Personal.get(db.Key(update))
|
GAE Datastore Put()
|
def post(self):
update = self.request.get('update')
if users.get_current_user():
if update:
personal = db.GqlQuery("SELECT * FROM Personal WHERE __key__ = :1", db.Key(update))
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
personal= Personal()
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')
Should this will update the existing record if the 'update' is querystring containing key datastore key. I try this but keep adding new record/entity. Please give me some sugesstion to correctly updating the record/entity.
Correction? :
def post(self):
update = self.request.get('update')
if users.get_current_user():
if update:
personal = Personal.get(db.Key(update))
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
personal= Personal()
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')
|
[
"There's no need to do a query when you know the key: Simply call db.get() on the key to retrieve it directly, which is much faster than doing a query.\nAs to why you're creating a new record each time, it looks like you're not passing in 'update' to your page correctly. Try logging the query string parameters to see what's going wrong.\n",
"I finally answer this myself, Thanks for Nick Johnson guide on this.\nI cannot get the query string url as 'string key' that always raise BadKeyError: Invalid string key exception.\nI try to put this 'update' string as hidden field on html edit form and this works since 'update' is a valid 'string key' now.\ndef post(self):\n update = self.request.get('update')\n\n if users.get_current_user():\n if update != '':\n personal = Personal.get(db.Key(update))\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002498264_google_app_engine_google_cloud_datastore_python.txt
|
Q:
Reducing size of a character array in Numpy
Given a character array:
In [21]: x = np.array(['a ','bb ','cccc '])
One can remove the whitespace using:
In [22]: np.char.strip(x)
Out[22]:
array(['a', 'bb', 'cccc'],
dtype='|S8')
but is there a way to also shrink the width of the column to the minimum required size, in the above case |S4?
A:
Do you just want to change the data type?
import numpy as NP
a = NP.array(["a", "bb", "ccc"])
a
# returns array(['a', 'bb', 'ccc'], dtype='|S3')
a = NP.array(a, dtype="|S8") # change dtype
# returns array(['a', 'bb', 'ccc'], dtype='|S8')
a = NP.array(a, dtype="|S3") # change it back
# returns array(['a', 'bb', 'ccc'], dtype='|S3')
A:
>>> x = np.array(['a ','bb ','cccc '])
>>> x = np.array([s.strip() for s in x])
>>> x
array(['a', 'bb', 'cccc'],
dtype='|S4')
|
Reducing size of a character array in Numpy
|
Given a character array:
In [21]: x = np.array(['a ','bb ','cccc '])
One can remove the whitespace using:
In [22]: np.char.strip(x)
Out[22]:
array(['a', 'bb', 'cccc'],
dtype='|S8')
but is there a way to also shrink the width of the column to the minimum required size, in the above case |S4?
|
[
"Do you just want to change the data type?\nimport numpy as NP\na = NP.array([\"a\", \"bb\", \"ccc\"])\na \n# returns array(['a', 'bb', 'ccc'], dtype='|S3')\na = NP.array(a, dtype=\"|S8\") # change dtype\n# returns array(['a', 'bb', 'ccc'], dtype='|S8')\n\na = NP.array(a, dtype=\"|S3\") # change it back\n# returns array(['a', 'bb', 'ccc'], dtype='|S3') \n\n",
">>> x = np.array(['a ','bb ','cccc '])\n>>> x = np.array([s.strip() for s in x])\n>>> x\narray(['a', 'bb', 'cccc'], \n dtype='|S4')\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0002502235_numpy_python.txt
|
Q:
Simple forloop - Python
this is probably too simple of a question, but here I go.
I have paginated items, each page contains 100 items. The program fetches items till it reaches the item index specified within item_num
This is what I have:
item_num = 56
range(0, item_num/100 + (item_num%100 > 0)):
get_next_100()
I'm not really sure about the (item_num%100 > 0) boolean I used.
Is there anything wrong with what I did?
A:
You seem to be trying to call the function zero times if item_num is 0, once if item_num is 1 to 100, twice if item_num is between 101 and 200, etc...
A simpler way to write this is:
n = 0
while n < item_num:
get_next_100()
n += 100
Or you could do it as a for loop:
for _ in range(0, item_num, 100):
get_next_100()
A:
range takes a 3rd optional parameter of step.
So
range(0,234,100)
Gives
[0, 100, 200]
So you can do something like
for items in range(0,234,100):
get_next_100()
|
Simple forloop - Python
|
this is probably too simple of a question, but here I go.
I have paginated items, each page contains 100 items. The program fetches items till it reaches the item index specified within item_num
This is what I have:
item_num = 56
range(0, item_num/100 + (item_num%100 > 0)):
get_next_100()
I'm not really sure about the (item_num%100 > 0) boolean I used.
Is there anything wrong with what I did?
|
[
"You seem to be trying to call the function zero times if item_num is 0, once if item_num is 1 to 100, twice if item_num is between 101 and 200, etc...\nA simpler way to write this is:\nn = 0\nwhile n < item_num:\n get_next_100()\n n += 100\n\nOr you could do it as a for loop:\nfor _ in range(0, item_num, 100):\n get_next_100()\n\n",
"range takes a 3rd optional parameter of step.\nSo\nrange(0,234,100)\n\nGives\n[0, 100, 200]\n\nSo you can do something like\nfor items in range(0,234,100):\n get_next_100()\n\n"
] |
[
6,
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002503543_python.txt
|
Q:
python design patterns
I am looking for any resources that gives examples of Best Practices, Design patterns and the SOLID principles using Python.
A:
Some overlap in these
Intermediate and Advanced Software Carpentry in Python
Code Like a Pythonista: Idiomatic Python
Python Idioms and Efficiency
Google Developers Day US - Python Design Patterns
Another resource is by example at the Python Recipes. A good number do not follow best practices but you can find some patterns in there that are useful
A:
Type
>>> import this
in a Python console.
Although this is usually treated as a (fine!) joke, it contains a couple of valid python-specific axioms.
A:
Bruce Eckel's Thinking in Python leans heavily on Design Patterns
A:
You can get started here and here.
For a more in depth look at design pattners you should look at Design Patterns: Elements of Reusable Object-Oriented Software. The source code is not in Python, but it doesn't need to be for you to understand the patterns.
A:
Something you can use to simplify your code when calling attributes on objects that might or might not exist is to use the Null Object Design Pattern (to which I was introduced in Python Cookbook).
Roughly, the goal with Null objects is to provide an 'intelligent'
replacement for the often used primitive data type None in Python or
Null (or Null pointers) in other languages. These are used for many
purposes including the important case where one member of some group
of otherwise similar elements is special for whatever reason. Most
often this results in conditional statements to distinguish between
ordinary elements and the primitive Null value.
This object just eats the lack of attribute error, and you can avoid checking for their existence.
It's nothing more than
class Null(object):
def __init__(self, *args, **kwargs):
"Ignore parameters."
return None
def __call__(self, *args, **kwargs):
"Ignore method calls."
return self
def __getattr__(self, mname):
"Ignore attribute requests."
return self
def __setattr__(self, name, value):
"Ignore attribute setting."
return self
def __delattr__(self, name):
"Ignore deleting attributes."
return self
def __repr__(self):
"Return a string representation."
return "<Null>"
def __str__(self):
"Convert to a string and return it."
return "Null"
With this, if you do Null("any", "params", "you", "want").attribute_that_doesnt_exists() it won't explode, but just silently become the equivalent of pass.
Normally you'd do something like
if obj.attr:
obj.attr()
With this, you just do:
obj.attr()
and forget about it. Beware that extensive use of the Null object can potentially hide bugs in your code.
A:
You may also wish to read this article (select the .pdf file), which discusses Design Patterns in dynamic object oriented languages (i.e. Python). To quote the page:
This paper explores how the patterns from the "Gang of Four", or "GOF" book, as it is often called, appear when similar problems are addressed using a dynamic, higher-order, object-oriented programming language. Some of the patterns disappear -- that is, they are supported directly by language features, some patterns are simpler or have a different focus, and some are essentially unchanged.
|
python design patterns
|
I am looking for any resources that gives examples of Best Practices, Design patterns and the SOLID principles using Python.
|
[
"Some overlap in these\nIntermediate and Advanced Software Carpentry in Python\nCode Like a Pythonista: Idiomatic Python\nPython Idioms and Efficiency\nGoogle Developers Day US - Python Design Patterns\nAnother resource is by example at the Python Recipes. A good number do not follow best practices but you can find some patterns in there that are useful\n",
"Type\n>>> import this\n\nin a Python console.\nAlthough this is usually treated as a (fine!) joke, it contains a couple of valid python-specific axioms.\n",
"Bruce Eckel's Thinking in Python leans heavily on Design Patterns\n",
"You can get started here and here. \nFor a more in depth look at design pattners you should look at Design Patterns: Elements of Reusable Object-Oriented Software. The source code is not in Python, but it doesn't need to be for you to understand the patterns. \n",
"Something you can use to simplify your code when calling attributes on objects that might or might not exist is to use the Null Object Design Pattern (to which I was introduced in Python Cookbook).\n\nRoughly, the goal with Null objects is to provide an 'intelligent'\n replacement for the often used primitive data type None in Python or\n Null (or Null pointers) in other languages. These are used for many\n purposes including the important case where one member of some group \n of otherwise similar elements is special for whatever reason. Most \n often this results in conditional statements to distinguish between\n ordinary elements and the primitive Null value.\n\nThis object just eats the lack of attribute error, and you can avoid checking for their existence.\nIt's nothing more than\nclass Null(object):\n\n def __init__(self, *args, **kwargs):\n \"Ignore parameters.\"\n return None\n\n def __call__(self, *args, **kwargs):\n \"Ignore method calls.\"\n return self\n\n def __getattr__(self, mname):\n \"Ignore attribute requests.\"\n return self\n\n def __setattr__(self, name, value):\n \"Ignore attribute setting.\"\n return self\n\n def __delattr__(self, name):\n \"Ignore deleting attributes.\"\n return self\n\n def __repr__(self):\n \"Return a string representation.\"\n return \"<Null>\"\n\n def __str__(self):\n \"Convert to a string and return it.\"\n return \"Null\"\n\nWith this, if you do Null(\"any\", \"params\", \"you\", \"want\").attribute_that_doesnt_exists() it won't explode, but just silently become the equivalent of pass.\nNormally you'd do something like\nif obj.attr:\n obj.attr()\n\nWith this, you just do:\nobj.attr()\n\nand forget about it. Beware that extensive use of the Null object can potentially hide bugs in your code.\n",
"You may also wish to read this article (select the .pdf file), which discusses Design Patterns in dynamic object oriented languages (i.e. Python). To quote the page:\n\nThis paper explores how the patterns from the \"Gang of Four\", or \"GOF\" book, as it is often called, appear when similar problems are addressed using a dynamic, higher-order, object-oriented programming language. Some of the patterns disappear -- that is, they are supported directly by language features, some patterns are simpler or have a different focus, and some are essentially unchanged. \n\n"
] |
[
152,
25,
13,
6,
6,
3
] |
[] |
[] |
[
"design_patterns",
"python"
] |
stackoverflow_0000606448_design_patterns_python.txt
|
Q:
Superfluous python parameters
I've noticed a discrepancy in the way that python parameters are called. In every other language I've dealt with, you either have
foo()
meaning either no parameters, or as many parameters as you like, or
foo(arg1, arg2,...,argn)
where you pass in the same number of parameters to define the function and call it. In python however, I've noticed that the function definitions, and when the function is called, can have two different parameters sets, this usually consists of:
class foo(object):
def bar(self, arg1, arg2):
pass
However, when I want to call the function, all I have to do is:
zoo = foo()
zoo.bar(arg1, arg2)
Where did the self parameter go?
Thank you.
A:
Where did the self parameter go?
It's in front of the dot when you call the function, i.e. in your case it's zoo.
Note that you can also call the function as foo.bar(zoo, arg1, arg2). Basically in python object.method(arguments) is a shortcut for objects_class.method(object, arguments).
A:
zoo is the self parameter.
In C++, for example, you get the object passed implicitly as the this pointer. In Python, this parameter is explicit.
A:
zoo is implicitly passed as the first parameter in your example.
A:
As I remember, "zoo.bar" gives you just an attribute "bar" of object "zoo" that can be called. All magic is done at construction where all methods of class is binded to that object while dictionary of attributes is populated.
Consider next example:
zoo = foo()
xbar = zoo.bar
xbar(arg1, arg2)
|
Superfluous python parameters
|
I've noticed a discrepancy in the way that python parameters are called. In every other language I've dealt with, you either have
foo()
meaning either no parameters, or as many parameters as you like, or
foo(arg1, arg2,...,argn)
where you pass in the same number of parameters to define the function and call it. In python however, I've noticed that the function definitions, and when the function is called, can have two different parameters sets, this usually consists of:
class foo(object):
def bar(self, arg1, arg2):
pass
However, when I want to call the function, all I have to do is:
zoo = foo()
zoo.bar(arg1, arg2)
Where did the self parameter go?
Thank you.
|
[
"\nWhere did the self parameter go?\n\nIt's in front of the dot when you call the function, i.e. in your case it's zoo.\nNote that you can also call the function as foo.bar(zoo, arg1, arg2). Basically in python object.method(arguments) is a shortcut for objects_class.method(object, arguments).\n",
"zoo is the self parameter.\nIn C++, for example, you get the object passed implicitly as the this pointer. In Python, this parameter is explicit.\n",
"zoo is implicitly passed as the first parameter in your example.\n",
"As I remember, \"zoo.bar\" gives you just an attribute \"bar\" of object \"zoo\" that can be called. All magic is done at construction where all methods of class is binded to that object while dictionary of attributes is populated.\nConsider next example:\nzoo = foo()\nxbar = zoo.bar\nxbar(arg1, arg2)\n\n"
] |
[
7,
3,
1,
0
] |
[] |
[] |
[
"class",
"function",
"parameters",
"python"
] |
stackoverflow_0002503281_class_function_parameters_python.txt
|
Q:
How to make Python Extensions for Windows for absolute beginners
I've been looking around the internet trying to find a good step by step guide to extend Python in Windows, and I haven't been able to find something for my skill level.
let's say you have some c code that looks like this:
#include <stdio.h>
#include <math.h>
double valuex(float value, double rate, double timex)
{
float value;
double rate, timex;
return value / (double) pow ((1 + rate), (timex));
}
and you want to turn that into a Python 3 module for use on a windows (64bit if that makes a difference) system. How would you go about doing that? I've looked up SWIG and Pyrex and in both circumstances they seem geared towards the unix user. With Pyrex I am not sure if it works with Python 3.
I'm just trying to learn the basics of programing, using some practical examples.
Lastly, if there is a good book that someone can recommend for learning to extend, I would greatly appreciate it.
Thank you.
A:
Cython (Pyrex with a few kinks worked out and decisions made for practicality) can use one code base to make Python 2 and Python 3 modules. It's a really great choice for making libraries for 2 and 3. The user guide explains how to use it, but it doesn't demystify Windows programming or C or Python or programming in general, thought it can simplify some things for you.
SWIG can be hard to work with when you run into a problem and will not be especially conducive to creating a very native-feeling, idiomatic binding of the C you are relying on. For that, you would need to re-wrap the wrapper in Python, at which point it might have been nicer just to use Cython. It can be nice for bindings that you cannot dedicate enough work to make truly nice, and is convenient in that you can expose your API to many languages at once in it.
A:
Depending on what you're trying to do, building your "extension" as a simple DLL and accessing it with ctypes could be, by far, the simplest approach.
I used your code, slightly adjusted and saved as mydll.c:
#include <stdio.h>
#include <math.h>
#define DLL_EXPORT __declspec(dllexport)
DLL_EXPORT double valuex(float value, double rate, double timex)
{
float value;
double rate, timex;
return value / (double) pow ((1 + rate), (timex));
}
I downloaded the Tiny C Compiler and invoked with this command.
tcc -shared mydll.c
(I believe adding -rdynamic would avoid the need to sprinkle DLL_EXPORT all over your function defs.)
This generated mydll.dll. I then ran Python:
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) ... on win32
>>> from ctypes import *
>>> mydll = cdll.mydll
>>> valuex = mydll.valuex
>>> valuex.argtypes = [c_float, c_double, c_double]
>>> valuex.restype = c_double
>>> valuex(1.2, 2.3, 3.4)
2.0470634033800796e-21
A:
A start would be the documentation Building C and C++ Extensions on Windows.
A:
Well, the easiest way to create Python plugins is to use C++ and Boost.Python. In your example, the extension module would look as simple as this:
#include <boost/python.hpp>
using namespace boost::python;
// ... your valuex function goes here ...
BOOST_PYTHON_MODULE(yourModuleName)
{
def("valuex", valuex, "an optional documentation string");
}
Boost.Python is available on the popular operating systems and should work with Python 3, too (not tested it, though, support was added in 2009).
Regarding SWIG: It is not for Unix only. You can download precompiled Windows binaries or compile it yourself with MinGW/MSYS.
You could as well try out Cython which is said to be Python 3 compatible.
A:
At PyCon 2009, I gave a talk on how to write Python C extensions: A Whirlwind Excursion through Python C Extensions. There's nothing specific to Windows in it, but it covers the basic structure of an extension.
|
How to make Python Extensions for Windows for absolute beginners
|
I've been looking around the internet trying to find a good step by step guide to extend Python in Windows, and I haven't been able to find something for my skill level.
let's say you have some c code that looks like this:
#include <stdio.h>
#include <math.h>
double valuex(float value, double rate, double timex)
{
float value;
double rate, timex;
return value / (double) pow ((1 + rate), (timex));
}
and you want to turn that into a Python 3 module for use on a windows (64bit if that makes a difference) system. How would you go about doing that? I've looked up SWIG and Pyrex and in both circumstances they seem geared towards the unix user. With Pyrex I am not sure if it works with Python 3.
I'm just trying to learn the basics of programing, using some practical examples.
Lastly, if there is a good book that someone can recommend for learning to extend, I would greatly appreciate it.
Thank you.
|
[
"Cython (Pyrex with a few kinks worked out and decisions made for practicality) can use one code base to make Python 2 and Python 3 modules. It's a really great choice for making libraries for 2 and 3. The user guide explains how to use it, but it doesn't demystify Windows programming or C or Python or programming in general, thought it can simplify some things for you.\nSWIG can be hard to work with when you run into a problem and will not be especially conducive to creating a very native-feeling, idiomatic binding of the C you are relying on. For that, you would need to re-wrap the wrapper in Python, at which point it might have been nicer just to use Cython. It can be nice for bindings that you cannot dedicate enough work to make truly nice, and is convenient in that you can expose your API to many languages at once in it.\n",
"Depending on what you're trying to do, building your \"extension\" as a simple DLL and accessing it with ctypes could be, by far, the simplest approach.\nI used your code, slightly adjusted and saved as mydll.c:\n#include <stdio.h>\n#include <math.h>\n\n#define DLL_EXPORT __declspec(dllexport)\nDLL_EXPORT double valuex(float value, double rate, double timex)\n {\n float value;\n double rate, timex;\n return value / (double) pow ((1 + rate), (timex));\n }\n\nI downloaded the Tiny C Compiler and invoked with this command. \ntcc -shared mydll.c\n\n(I believe adding -rdynamic would avoid the need to sprinkle DLL_EXPORT all over your function defs.) \nThis generated mydll.dll. I then ran Python:\nPython 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) ... on win32\n>>> from ctypes import *\n>>> mydll = cdll.mydll\n>>> valuex = mydll.valuex\n>>> valuex.argtypes = [c_float, c_double, c_double]\n>>> valuex.restype = c_double\n>>> valuex(1.2, 2.3, 3.4)\n2.0470634033800796e-21\n\n",
"A start would be the documentation Building C and C++ Extensions on Windows.\n",
"Well, the easiest way to create Python plugins is to use C++ and Boost.Python. In your example, the extension module would look as simple as this:\n#include <boost/python.hpp>\nusing namespace boost::python;\n\n// ... your valuex function goes here ...\n\nBOOST_PYTHON_MODULE(yourModuleName)\n{\n def(\"valuex\", valuex, \"an optional documentation string\");\n}\n\nBoost.Python is available on the popular operating systems and should work with Python 3, too (not tested it, though, support was added in 2009).\nRegarding SWIG: It is not for Unix only. You can download precompiled Windows binaries or compile it yourself with MinGW/MSYS.\nYou could as well try out Cython which is said to be Python 3 compatible.\n",
"At PyCon 2009, I gave a talk on how to write Python C extensions: A Whirlwind Excursion through Python C Extensions. There's nothing specific to Windows in it, but it covers the basic structure of an extension.\n"
] |
[
2,
2,
1,
0,
0
] |
[] |
[] |
[
"python",
"python_3.x",
"windows"
] |
stackoverflow_0002503310_python_python_3.x_windows.txt
|
Q:
Dynamically creating page definitions in Cherrypy
I've been looking around the CherryPy documentation, but can't quite get my head around what I want to do. I suspect it might be more of a Python thing than a CherryPy thing...
My current class looks something like this:
import managerUtils
class WebManager:
def A(self, **kwds):
return managerUtils.runAction("A", kwds)
A.enabled = True
def B(self, **kwds):
return managerUtils.runAction("B", kwds)
B.enabled = True
def C(self, **kwds):
return managerUtils.runAction("C", kwds)
C.enabled = True
Obviously there's a lot of repetition in here.
in managerUtils.py, I have a dict that's something like:
actions = {'A': functionToRunForA,
'B': functionToRunForB,
'C': functionToRunForC}
Okay, so that's a slightly simplistic view of it, but I'm sure you get the idea.
I want to be able to do something like:
import managerUtils
class WebManager:
def __init__(self):
for action in managerUtils.actions:
f = registerFunction(action)
f.enabled = True
Any ideas of how to do this?
One answer suggested doing:
class WebManager:
def index(self, action, **kwds):
return managerUtils.runAction(action, kwds)
index.enabled = True
That picks up, I believe:
http://webserver/?action&kwds
Rather than what I want, which is:
http://webserver/action?kwds
When I do what you suggest, I get the following 404 error:
Traceback (most recent call last):
File "/Library/Python/2.5/site-packages/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/Library/Python/2.5/site-packages/cherrypy/_cperror.py", line 227, in __call__
raise self
NotFound: (404, "The path '/myAction' was not found.")
A:
class WebManager:
def default(self, action, **kwds):
return managerUtils.runAction(action, kwds)
default.exposed = True
Two notes about why this is different than other answers:
.exposed is the correct attribute for publishing methods, not .enabled
the index method is the only one which does not allow positional arguments like "action". Use a default method instead.
Hope that helps!
|
Dynamically creating page definitions in Cherrypy
|
I've been looking around the CherryPy documentation, but can't quite get my head around what I want to do. I suspect it might be more of a Python thing than a CherryPy thing...
My current class looks something like this:
import managerUtils
class WebManager:
def A(self, **kwds):
return managerUtils.runAction("A", kwds)
A.enabled = True
def B(self, **kwds):
return managerUtils.runAction("B", kwds)
B.enabled = True
def C(self, **kwds):
return managerUtils.runAction("C", kwds)
C.enabled = True
Obviously there's a lot of repetition in here.
in managerUtils.py, I have a dict that's something like:
actions = {'A': functionToRunForA,
'B': functionToRunForB,
'C': functionToRunForC}
Okay, so that's a slightly simplistic view of it, but I'm sure you get the idea.
I want to be able to do something like:
import managerUtils
class WebManager:
def __init__(self):
for action in managerUtils.actions:
f = registerFunction(action)
f.enabled = True
Any ideas of how to do this?
One answer suggested doing:
class WebManager:
def index(self, action, **kwds):
return managerUtils.runAction(action, kwds)
index.enabled = True
That picks up, I believe:
http://webserver/?action&kwds
Rather than what I want, which is:
http://webserver/action?kwds
When I do what you suggest, I get the following 404 error:
Traceback (most recent call last):
File "/Library/Python/2.5/site-packages/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/Library/Python/2.5/site-packages/cherrypy/_cperror.py", line 227, in __call__
raise self
NotFound: (404, "The path '/myAction' was not found.")
|
[
"class WebManager:\n def default(self, action, **kwds):\n return managerUtils.runAction(action, kwds)\n default.exposed = True\n\nTwo notes about why this is different than other answers:\n\n.exposed is the correct attribute for publishing methods, not .enabled\nthe index method is the only one which does not allow positional arguments like \"action\". Use a default method instead.\n\nHope that helps!\n"
] |
[
3
] |
[] |
[] |
[
"cherrypy",
"python"
] |
stackoverflow_0002499219_cherrypy_python.txt
|
Q:
Is it good to use Django 1.1 on App Engine?
We are planning a web application to build on Google's App Engine platform.
Is it good to use the Django 1.1 framework to develop Google App Engine applications?
If not, could you please suggest me the best option available, which has good tutorials and learning resource?
A:
Yes, Django 1.1 is well-supported on Google App Engine. You'll need to do your own installation thereof locally, to enable it in the GAE SDK -- but it's already there for you on the App Engine production servers, see the docs -- just do
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.1')
Edit: Django is by far the leading web app framework for Python, and its popularity is surely well-deserved. However, personally, I use it only when I "have to" (mostly to get collaborators and make them comfy on a project's technology stack) -- maybe because what I tend to develop server-side are more "web services/apps" than "sites" (the UI part I'd rather leave to the browser, with Dojo, jQuery, or Google Closure!-), I find Django too "heavy" for my tastes. I'd rather have Werkzeug, or tipfy -- the latest and greatest super-light Wekzeug-based App Engine - specialized framework!-) -- I love e.g. tipfy's ability to use Jinja2 and/or Mako in lieu of Django's templates, the simple and flexible authentication and session schemes, and the debugger -- in addition to all the luscious, light-weight flexibility of Werkzeug and Webapp. But, hey, that's a very subjective opinion of mine!-)
A:
Google has developed a 'helper' project to aid with Django integration:
http://code.google.com/p/google-app-engine-django/
Also, you might check out this video where Guido walks through it:
http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine
A:
You should check out appenginepatch (http://code.google.com/p/app-engine-patch/) and django-nonrel (http://www.allbuttonspressed.com/projects/django-nonrel)
I'm using appenginepatch for my website (beta.fiddme.com) and its awesome (there's a full post on the technology stack we're using at http://www.developerzen.com/2009/10/29/building-an-iphone-application/)
A:
You might also want to take a look at Kay Framework. It's based on Django with middleware and such. It is exclusively geared towards App Engine and uses Werkzeug and Jinja2. I have fiddled with it and it all works. I've settled on the already mentioned Tipfy framework. Also comes with Jinja2 (and Mako, it's your choice), it's lightweight and easy to comprehend.
|
Is it good to use Django 1.1 on App Engine?
|
We are planning a web application to build on Google's App Engine platform.
Is it good to use the Django 1.1 framework to develop Google App Engine applications?
If not, could you please suggest me the best option available, which has good tutorials and learning resource?
|
[
"Yes, Django 1.1 is well-supported on Google App Engine. You'll need to do your own installation thereof locally, to enable it in the GAE SDK -- but it's already there for you on the App Engine production servers, see the docs -- just do\nimport os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\n\nfrom google.appengine.dist import use_library\nuse_library('django', '1.1')\n\nEdit: Django is by far the leading web app framework for Python, and its popularity is surely well-deserved. However, personally, I use it only when I \"have to\" (mostly to get collaborators and make them comfy on a project's technology stack) -- maybe because what I tend to develop server-side are more \"web services/apps\" than \"sites\" (the UI part I'd rather leave to the browser, with Dojo, jQuery, or Google Closure!-), I find Django too \"heavy\" for my tastes. I'd rather have Werkzeug, or tipfy -- the latest and greatest super-light Wekzeug-based App Engine - specialized framework!-) -- I love e.g. tipfy's ability to use Jinja2 and/or Mako in lieu of Django's templates, the simple and flexible authentication and session schemes, and the debugger -- in addition to all the luscious, light-weight flexibility of Werkzeug and Webapp. But, hey, that's a very subjective opinion of mine!-)\n",
"Google has developed a 'helper' project to aid with Django integration:\nhttp://code.google.com/p/google-app-engine-django/\nAlso, you might check out this video where Guido walks through it:\nhttp://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine\n",
"You should check out appenginepatch (http://code.google.com/p/app-engine-patch/) and django-nonrel (http://www.allbuttonspressed.com/projects/django-nonrel)\nI'm using appenginepatch for my website (beta.fiddme.com) and its awesome (there's a full post on the technology stack we're using at http://www.developerzen.com/2009/10/29/building-an-iphone-application/)\n",
"You might also want to take a look at Kay Framework. It's based on Django with middleware and such. It is exclusively geared towards App Engine and uses Werkzeug and Jinja2. I have fiddled with it and it all works. I've settled on the already mentioned Tipfy framework. Also comes with Jinja2 (and Mako, it's your choice), it's lightweight and easy to comprehend. \n"
] |
[
4,
1,
0,
0
] |
[] |
[] |
[
"django",
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002490335_django_google_app_engine_google_cloud_datastore_python.txt
|
Q:
Update element values using xml.dom.minidom
I have an XML structure which looks similar to:
<Store>
<foo>
<book>
<isbn>123456</isbn>
</book>
<title>XYZ</title>
<checkout>no</checkout>
</foo>
<bar>
<book>
<isbn>7890</isbn>
</book>
<title>XYZ2</title>
<checkout>yes</checkout>
</bar>
</Store>
Using xml.dom.minidom only (restrictions) i would like to
1)traverse through the XML file
2)Search/Get for particular element, depending on its parent
Example: checkout element for author1, isbn for author2
3)Change/Set that element's value
4)Write the new XML structure to a file
Can anyone help here?
Thank you!
UPDATE:
This is what i have done till now
import xml.dom.minidom
checkout = "yes"
def getLoneChild(node, tagname):
assert ((node is not None) and (tagname is not None))
elem = node.getElementsByTagName(tagname)
if ((elem is None) or (len(elem) != 1)):
return None
return elem
def getLoneLeaf(node, tagname):
assert ((node is not None) and (tagname is not None))
elem = node.getElementsByTagName(tagname)
if ((elem is None) or (len(elem) != 1)):
return None
leaf = elem[0].firstChild
if (leaf is None):
return None
return leaf.data
def setcheckout(node, tagname):
assert ((node is not None) and (tagname is not None))
child = getLoneChild(node, 'foo')
Check = getLoneLeaf(child[0],'checkout')
Check = tagname
return Check
doc = xml.dom.minidom.parse('test.xml')
root = doc.getElementsByTagName('Store')[0]
output = setcheckout(root, checkout)
tmp_config = '/tmp/tmp_config.xml'
fw = open(tmp_config, 'w')
fw.write(doc.toxml())
fw.close()
A:
I'm not entirely sure what you mean by "checkout". This script will find the element and alter the value of that element. Perhaps you can adapt it to your specific needs.
import xml.dom.minidom as DOM
# find the author as a child of the "Store"
def getAuthor(parent, author):
# by looking at the children
for child in [child for child in parent.childNodes
if child.nodeType != DOM.Element.TEXT_NODE]:
if child.tagName == author:
return child
return None
def alterElement(parent, attribute, newValue):
found = False;
# look through the child elements, skipping Text_Nodes
#(in your example these hold the "values"
for child in [child for child in parent.childNodes
if child.nodeType != DOM.Element.TEXT_NODE]:
# if the child element tagName matches target element name
if child.tagName == attribute:
# alter the data, i.e. the Text_Node value,
# which is the firstChild of the "isbn" element
child.firstChild.data = newValue
return True
else:
# otherwise look at all the children of this node.
found = alterElement(child, attribute, newValue)
if found:
break
# return found status
return found
doc = DOM.parse("test.xml")
# This assumes that there is only one "Store" in the file
root = doc.getElementsByTagName("Store")[0]
# find the author
# this assumes that there are no duplicate author names in the file
author = getAuthor(root, "foo")
if not author:
print "Author not found!"
else:
# alter an element
if not alterElement(author, "isbn", "987654321"):
print "isbn not found"
else:
# output the xml
tmp_config = '/tmp/tmp_config.xml'
f = open(tmp_config, 'w')
doc.writexml( f )
f.close()
The general idea is that you match the name of the author against the tagNames of the children of the "Store" element, then recurse through the children of the author, looking for a match against a target element tagName. There are a lot of assumptions made in this solution, but it may get you started. It's painful to try and deal with hierarchical structures like XML without using recursion.
In retrospect there was an error in the "alterElement" function. I've fixed this (note the "found" variable")
|
Update element values using xml.dom.minidom
|
I have an XML structure which looks similar to:
<Store>
<foo>
<book>
<isbn>123456</isbn>
</book>
<title>XYZ</title>
<checkout>no</checkout>
</foo>
<bar>
<book>
<isbn>7890</isbn>
</book>
<title>XYZ2</title>
<checkout>yes</checkout>
</bar>
</Store>
Using xml.dom.minidom only (restrictions) i would like to
1)traverse through the XML file
2)Search/Get for particular element, depending on its parent
Example: checkout element for author1, isbn for author2
3)Change/Set that element's value
4)Write the new XML structure to a file
Can anyone help here?
Thank you!
UPDATE:
This is what i have done till now
import xml.dom.minidom
checkout = "yes"
def getLoneChild(node, tagname):
assert ((node is not None) and (tagname is not None))
elem = node.getElementsByTagName(tagname)
if ((elem is None) or (len(elem) != 1)):
return None
return elem
def getLoneLeaf(node, tagname):
assert ((node is not None) and (tagname is not None))
elem = node.getElementsByTagName(tagname)
if ((elem is None) or (len(elem) != 1)):
return None
leaf = elem[0].firstChild
if (leaf is None):
return None
return leaf.data
def setcheckout(node, tagname):
assert ((node is not None) and (tagname is not None))
child = getLoneChild(node, 'foo')
Check = getLoneLeaf(child[0],'checkout')
Check = tagname
return Check
doc = xml.dom.minidom.parse('test.xml')
root = doc.getElementsByTagName('Store')[0]
output = setcheckout(root, checkout)
tmp_config = '/tmp/tmp_config.xml'
fw = open(tmp_config, 'w')
fw.write(doc.toxml())
fw.close()
|
[
"I'm not entirely sure what you mean by \"checkout\". This script will find the element and alter the value of that element. Perhaps you can adapt it to your specific needs.\nimport xml.dom.minidom as DOM\n\n# find the author as a child of the \"Store\"\ndef getAuthor(parent, author):\n # by looking at the children\n for child in [child for child in parent.childNodes \n if child.nodeType != DOM.Element.TEXT_NODE]:\n if child.tagName == author:\n return child\n return None\n\ndef alterElement(parent, attribute, newValue):\n found = False;\n # look through the child elements, skipping Text_Nodes \n #(in your example these hold the \"values\"\n for child in [child for child in parent.childNodes \n if child.nodeType != DOM.Element.TEXT_NODE]:\n\n # if the child element tagName matches target element name\n if child.tagName == attribute:\n # alter the data, i.e. the Text_Node value, \n # which is the firstChild of the \"isbn\" element\n child.firstChild.data = newValue\n return True\n\n else:\n # otherwise look at all the children of this node.\n found = alterElement(child, attribute, newValue)\n\n if found:\n break \n\n # return found status\n return found\n\ndoc = DOM.parse(\"test.xml\")\n# This assumes that there is only one \"Store\" in the file\nroot = doc.getElementsByTagName(\"Store\")[0]\n\n# find the author\n# this assumes that there are no duplicate author names in the file\nauthor = getAuthor(root, \"foo\")\nif not author:\n print \"Author not found!\"\nelse:\n # alter an element\n if not alterElement(author, \"isbn\", \"987654321\"):\n print \"isbn not found\"\n else:\n # output the xml\n tmp_config = '/tmp/tmp_config.xml'\n f = open(tmp_config, 'w')\n doc.writexml( f )\n f.close()\n\nThe general idea is that you match the name of the author against the tagNames of the children of the \"Store\" element, then recurse through the children of the author, looking for a match against a target element tagName. There are a lot of assumptions made in this solution, but it may get you started. It's painful to try and deal with hierarchical structures like XML without using recursion.\n\nIn retrospect there was an error in the \"alterElement\" function. I've fixed this (note the \"found\" variable\")\n"
] |
[
5
] |
[] |
[] |
[
"minidom",
"python",
"xml"
] |
stackoverflow_0002502758_minidom_python_xml.txt
|
Q:
Put an AuiManager inside a AuiNotebook page
Is it possible ho put an AuiManager inside an AuiNotebook page?
Have tested with a small sample code, but I only get a 'Segmentation fault'.
Is this possible to begin with? The reason why I want this is to split a notebook page in two parts and get the caption field and the maximize field in the top of each part of the two parts. A simple splitterwindow would work but does not look as good and cannot be maximized as easily. And nor does it have the caption field.
Sample code below.
import wx
import wx.aui
import wx.lib.inspection
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.mgr = wx.aui.AuiManager(self)
self.left = wx.Panel(self, -1, size = (200, 150))
self.right = wx.aui.AuiNotebook(self, -1, size = (200, 150))
self.bottom = wx.Panel(self, -1, size = (200, 150))
self.mgr.AddPane(self.bottom, wx.aui.AuiPaneInfo().Bottom())
self.mgr.AddPane(self.left, wx.aui.AuiPaneInfo().Left().Layer(1))
self.mgr.AddPane(self.right, wx.aui.AuiPaneInfo().CenterPane())
self.new_panel('Panel 1')
self.mgr.Update()
self.Update()
def new_panel(self, nm):
pnl = wx.Window(self)
pnl.identifierTag = nm
self.right.AddPage(pnl, nm, select = True)
self.sizer = wx.BoxSizer()
self.sizer.Add(self.right, 1, wx.EXPAND)
self.SetSizer(self.sizer)
pnl.SetFocus()
mgr = wx.aui.AuiManager(pnl)
left = wx.Panel(self)
right = wx.Panel(self)
mgr.AddPane(left, wx.aui.AuiPaneInfo().Left())
mgr.AddPane(right, wx.aui.AuiPaneInfo().Right())
mgr.Update()
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, '07_wxaui.py')
frame.Show()
self.SetTopWindow(frame)
return 1
if __name__ == "__main__":
app = MyApp(0)
wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
A:
wxAUIManager only works as a child of a wxFrame.
http://docs.wxwidgets.org/trunk/classwx_aui_manager.html
|
Put an AuiManager inside a AuiNotebook page
|
Is it possible ho put an AuiManager inside an AuiNotebook page?
Have tested with a small sample code, but I only get a 'Segmentation fault'.
Is this possible to begin with? The reason why I want this is to split a notebook page in two parts and get the caption field and the maximize field in the top of each part of the two parts. A simple splitterwindow would work but does not look as good and cannot be maximized as easily. And nor does it have the caption field.
Sample code below.
import wx
import wx.aui
import wx.lib.inspection
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.mgr = wx.aui.AuiManager(self)
self.left = wx.Panel(self, -1, size = (200, 150))
self.right = wx.aui.AuiNotebook(self, -1, size = (200, 150))
self.bottom = wx.Panel(self, -1, size = (200, 150))
self.mgr.AddPane(self.bottom, wx.aui.AuiPaneInfo().Bottom())
self.mgr.AddPane(self.left, wx.aui.AuiPaneInfo().Left().Layer(1))
self.mgr.AddPane(self.right, wx.aui.AuiPaneInfo().CenterPane())
self.new_panel('Panel 1')
self.mgr.Update()
self.Update()
def new_panel(self, nm):
pnl = wx.Window(self)
pnl.identifierTag = nm
self.right.AddPage(pnl, nm, select = True)
self.sizer = wx.BoxSizer()
self.sizer.Add(self.right, 1, wx.EXPAND)
self.SetSizer(self.sizer)
pnl.SetFocus()
mgr = wx.aui.AuiManager(pnl)
left = wx.Panel(self)
right = wx.Panel(self)
mgr.AddPane(left, wx.aui.AuiPaneInfo().Left())
mgr.AddPane(right, wx.aui.AuiPaneInfo().Right())
mgr.Update()
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, '07_wxaui.py')
frame.Show()
self.SetTopWindow(frame)
return 1
if __name__ == "__main__":
app = MyApp(0)
wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
|
[
"wxAUIManager only works as a child of a wxFrame.\nhttp://docs.wxwidgets.org/trunk/classwx_aui_manager.html\n"
] |
[
2
] |
[] |
[] |
[
"python",
"wxpython",
"wxwidgets"
] |
stackoverflow_0002502270_python_wxpython_wxwidgets.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.