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:
Ideas on how to uniquely identify a computer?
I have been thinking of ways I could uniquely identify a computer in python. First, I thought about checking the user's mac address and hard disk space, then I tried to compute some sort of rating from many of these variables. However, this solution doesn't feel right. It takes a long time to run and I had to change it many times already due to unforeseen errors.
Ideas?? Additionally, it would be very nice if it could detect running on a virtual machine.
A:
First you need to define "computer." Is a computer the same computer if you change the case? The hard drive? The network card? Increase the RAM? Upgrade the kernel?
(It brings to mind the saying about "my grandfather's hammer" — sure, I've replaced the head five times and the handle twice, but it's still the same hammer...)
It helps to step back and identify why you need to do this. The solution might be to put a configuration file somewhere with a random key in it, and then if the user needs to absolutely nuke this identifying cookie for whatever reason, they can. (Or maybe you don't want that...)
You might find the Python UUID module useful too.
| Ideas on how to uniquely identify a computer? | I have been thinking of ways I could uniquely identify a computer in python. First, I thought about checking the user's mac address and hard disk space, then I tried to compute some sort of rating from many of these variables. However, this solution doesn't feel right. It takes a long time to run and I had to change it many times already due to unforeseen errors.
Ideas?? Additionally, it would be very nice if it could detect running on a virtual machine.
| [
"First you need to define \"computer.\" Is a computer the same computer if you change the case? The hard drive? The network card? Increase the RAM? Upgrade the kernel?\n(It brings to mind the saying about \"my grandfather's hammer\" — sure, I've replaced the head five times and the handle twice, but it's still the ... | [
9
] | [] | [] | [
"hash",
"python",
"uniqueidentifier"
] | stackoverflow_0003873105_hash_python_uniqueidentifier.txt |
Q:
Keeping imported modules out of python package namespaces
I've noticed sometimes if you call dir() on a package/module, you'll see other modules in the namespace that were imported as part of the implementation and aren't meant for you to use. For instance, if I install the fish package from PyPI and import it, I see fish.sys, which just refers to the built-in sys module.
My question is whether that's sane and what to do about it if it's not.
I don't think the __all__ variable is too relevant, since that only affects the behavior of from X import *. The options I see are:
structure your packages better, and at least push the namespace clutter down into submodules
use import X as _X in your package to distinguish implementation details from your package API
import things from inside your functions (blegh)
A:
My question is whether that's sane
It's sane. Doing import fish adds just one name to your namespace, that is not "namespace clutter". It's pretty much the big idea behind modules, grouping many things under one name!
When you want to know what a module does, look at the documentation or call help, don't do dir.
All names in Python are stored in dictonaries. This means that no matter how many names you see, looking up one of them takes constant time. So there is no speed drawback of any kind either.
| Keeping imported modules out of python package namespaces | I've noticed sometimes if you call dir() on a package/module, you'll see other modules in the namespace that were imported as part of the implementation and aren't meant for you to use. For instance, if I install the fish package from PyPI and import it, I see fish.sys, which just refers to the built-in sys module.
My question is whether that's sane and what to do about it if it's not.
I don't think the __all__ variable is too relevant, since that only affects the behavior of from X import *. The options I see are:
structure your packages better, and at least push the namespace clutter down into submodules
use import X as _X in your package to distinguish implementation details from your package API
import things from inside your functions (blegh)
| [
"\nMy question is whether that's sane\n\nIt's sane. Doing import fish adds just one name to your namespace, that is not \"namespace clutter\". It's pretty much the big idea behind modules, grouping many things under one name!\nWhen you want to know what a module does, look at the documentation or call help, don't d... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003873115_python.txt |
Q:
Send an E-mail to an internationalized E-mail address with Python / SMTPlib
In my Python application, I would like to be able to send mail to addresses like っていった@example.jp, démo@example.fr, or even عرض@وزارة-الأتصالات.مصر, which are perfectly valid.
When passing the address as UTF-8, I get an UnicodeDecodeException. If I encode the address with address.encode('utf-8'), no Python error but I get bounce mail explaining Diagnostic-Code: smtp; 501 Malformed RCPT TO: - psmtp.
What's the way to make everything work ?
Thanks.
A:
Make sure the server you're talking to includes UTF8SMTP in its EHLO response. Otherwise it doesn't support rfc5336. You can tell by using telnet or netcat to connect to the server and pretending to be an SMTP client.
| Send an E-mail to an internationalized E-mail address with Python / SMTPlib | In my Python application, I would like to be able to send mail to addresses like っていった@example.jp, démo@example.fr, or even عرض@وزارة-الأتصالات.مصر, which are perfectly valid.
When passing the address as UTF-8, I get an UnicodeDecodeException. If I encode the address with address.encode('utf-8'), no Python error but I get bounce mail explaining Diagnostic-Code: smtp; 501 Malformed RCPT TO: - psmtp.
What's the way to make everything work ?
Thanks.
| [
"Make sure the server you're talking to includes UTF8SMTP in its EHLO response. Otherwise it doesn't support rfc5336. You can tell by using telnet or netcat to connect to the server and pretending to be an SMTP client.\n"
] | [
2
] | [] | [] | [
"python",
"smtp"
] | stackoverflow_0003873582_python_smtp.txt |
Q:
Pixel by pixel operation on image in Google App Engine using Python
I would like to go over an image and do some pixel by pixel operation. The image API provided by Google App Engine seems to be incapable to do this. And it doesn't include Python Imaging Library. So, how should I proceed with it.
Thanks..
A:
You could maybe use the image API to convert to PNG, then use the png module (which is pure python, so should hopefully run on app engine) to load the PNG and modify the pixels. Then convert back to PNG using the png module, and back to whatever format you need using the image API.
| Pixel by pixel operation on image in Google App Engine using Python | I would like to go over an image and do some pixel by pixel operation. The image API provided by Google App Engine seems to be incapable to do this. And it doesn't include Python Imaging Library. So, how should I proceed with it.
Thanks..
| [
"You could maybe use the image API to convert to PNG, then use the png module (which is pure python, so should hopefully run on app engine) to load the PNG and modify the pixels. Then convert back to PNG using the png module, and back to whatever format you need using the image API.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python",
"python_imaging_library"
] | stackoverflow_0003872694_google_app_engine_python_python_imaging_library.txt |
Q:
Numpy - why value error for NaN when trying to delete rows
I have a numpy array:
A = array([['id1', '1', '2', 'NaN'],
['id2', '2', '0', 'NaN']])
I also have a list:
li = ['id1', 'id3', 'id6']
I wish to iterate over the array and the list and where the first element in each row of the array is not in the list, then delete that entire row from the array.
My code to date:
from numpy import *
for row in A:
if row[0] not in li:
delete(A, row, axis = 0)
This returns the following error:
ValueError: invalid literal for int() with base 10: 'NaN'
The type of all elements in each row is str(), therefore I do not understand this mention of int() in the error.
Any suggestions?
Thanks,
S ;-)
A:
Just generating a new array is no option?
numpy.array([x for x in A if x[0] in li])
A:
It appears you want to delete a row of your array in-place, however, this is not possible using the np.delete function, as such an operation goes against the way that Python and Numpy manage memory.
I found an interesting post on the Numpy mailing list (Travis Oliphant, [Numpy-discussion] Deleting a row from a matrix) where the np.delete function is first discussed:
So, "in-place" deletion of array
objects would not be particularly
useful, because it would only work for
arrays with no additional reference
counts (i.e. simple b=a assignment
would increase the reference count and
make it impossible to say del a[obj]).
....
But, the problem with both of those
approaches is that once you start
removing arbitrary rows (or n-1
dimensional sub-spaces) from an array
you very likely will no longer have a
chunk of memory that can be described
using the n-dimensional array memory
model.
If you take a look at the documentation for np.delete (http://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html), we can see that the function returns a new array with the desired parts (not necessarily rows) deleted.
Definition: np.delete(arr, obj, axis=None)
Docstring:
Return a new array with sub-arrays along an axis deleted.
Parameters
----------
arr : array_like
Input array.
obj : slice, int or array of ints
Indicate which sub-arrays to remove.
axis : int, optional
The axis along which to delete the subarray defined by `obj`.
If `axis` is None, `obj` is applied to the flattened array.
Returns
-------
out : ndarray
A copy of `arr` with the elements specified by `obj` removed. Note
that `delete` does not occur in-place. If `axis` is None, `out` is
a flattened array.
So, in your case I think you'll want to do something like:
A = array([['id1', '1', '2', 'NaN'],
['id2', '2', '0', 'NaN']])
li = ['id1', 'id3', 'id6']
for i, row in enumerate(A):
if row[0] not in li:
A = np.delete(A, i, axis=0)
A is now cut down as you wanted, but remember it is a new piece of memory. Each time np.delete is called new memory is allocated which the name A will point to.
I'm sure there is a better vectorized way (maybe using masked arrays?) to find out which rows to delete, but I couldn't get it together. If anyone has it though please comment!
| Numpy - why value error for NaN when trying to delete rows | I have a numpy array:
A = array([['id1', '1', '2', 'NaN'],
['id2', '2', '0', 'NaN']])
I also have a list:
li = ['id1', 'id3', 'id6']
I wish to iterate over the array and the list and where the first element in each row of the array is not in the list, then delete that entire row from the array.
My code to date:
from numpy import *
for row in A:
if row[0] not in li:
delete(A, row, axis = 0)
This returns the following error:
ValueError: invalid literal for int() with base 10: 'NaN'
The type of all elements in each row is str(), therefore I do not understand this mention of int() in the error.
Any suggestions?
Thanks,
S ;-)
| [
"Just generating a new array is no option?\nnumpy.array([x for x in A if x[0] in li])\n\n",
"It appears you want to delete a row of your array in-place, however, this is not possible using the np.delete function, as such an operation goes against the way that Python and Numpy manage memory.\nI found an interestin... | [
5,
2
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0003873314_arrays_numpy_python.txt |
Q:
Why do C programs require decompilers but python programs dont?
If I write a python script, anyone can simply point an editor to it and read it. But for programming written in C, one would have to use decompilers and hex tables and such. Why is that? I mean I simply can't open up the Safari web browser and look at its code.
A:
Note: The author disavows a deep expertise in this subject. Some assertions may be incorrect.
Python actually is compiled into bytecode, which is what gets run by the python interpreter. Whenever you use a Python module, Python will generate a .pyc file with a name corresponding to the module. This is the equivalent of the .o file that's generated when you compile a C file.
So if you want something to disassemble, the .pyc file would be it :)
The process that Python goes through when compiling a module is pretty similar to what gcc or another C compiler does with C source code. The major difference is that it happens transparently as part of execution of the file. It's also optional: when running a non-module, i.e. an end-user script, Python will just interpret the code rather than compiling it first.
So really your question is "Why are python programs distributed as source rather than as compiled modules?" Or, put another way, "Why are C applications distributed as compiled binaries rather than as source code?"
It used to be very common for C applications to be distributed as source code. This was back before operating systems and their various subentities (i.e. linux distributions) became more established. Some distros, for example gentoo, still distribute apps as source code. Apps which are a bit more cutting edge or obscure are still distributed as source code for all platforms they target.
The reason for this is compatibility, and dependencies. The reason you can run the precompiled binary Safari on a Mac, or Firefox on Ubuntu Linux, is because it's been specifically built for that operating system, architecture (e.g. x86_64), and set of libraries.
Unfortunately, compilation of a large app is pretty slow, and needs to be redone at least partially every time the app is updated. Thus the motivation for binary distributions.
So why not create a binary distribution of Python? For one thing, as Aaron mentions, modules would need to be recompiled for each new version of the Python bytecode. But this would be similar to rebuilding a C app to link with a newer version of a dynamic library — Python modules are analogous in this sense to C libraries.
The real reason is that Python compilation is very much quicker than C compilation. This is in part, I think, because of the dynamic nature of the language, and also because it's not as thorough of a compilation. This has its tradeoffs: in particular, Python apps run much more slowly than do their C counterparts, because Python has to interpret the compiled bytecode into instructions for the processor, whereas the C app already contains such instructions.
That all being said, there is a program called py2exe that will take a Python module and distribution and build a precompiled windows executable, including in it the logic of the module and its dependencies, including Python itself. I guess the point of this is to avoid having to coerce people into installing Python on their Windows system just to run your app. Under linux, or I think even OS/X, Python is usually already installed, so precompilation is not really necessary. Linux systems also have super-dandy package managers that will transparently install dependencies such as Python if they are not already installed.
A:
Python is a script language, runs in a virtual machine through an interpeter.
C is a compiled language, the code compiled to binary code which the computer can run without all that extra stuff Python needs.
A:
This is sorta a big topic. You should look into your local friendly Computer Science curriculum, you'll find a lot of great stuff on this subject there.
The short answer is the Python is an "interpreted" language, which means that it requires a machine language program (the python interpreter) to run the python program, adding a layer of indirection. C or C++ are different. They are compiled directly to machine code, which runs directly on your processor.
There is a lot of additional voodoo to be learned here, however. Technically Python is compiled to a bytecode, and modern interpreters do more and more "Just in Time" compilation, so the boundaries between compiled and interpreted code are getting fuzzier all the time.
A:
In several comments you asked: "Is it then possible to compile python to an executable binary file and then simply distribute that?"
From a theoretical viewpoint, there's no question the answer is yes -- a Python program could be compiled to, and distributed as, fully compiled machine code.
From a practical viewpoint, it's open to a lot more question. There are a few things like Unladen Swallow, Psyco, Shed Skin, and PyPy that you might want to know about though.
Unladen Swallow is primarily an attempt at making Python run faster, but part of the plan to do so involves using LLVM for its back-end. LLVM can (among other things) produce native machine code output. The last couple of releases of Unladen Swallow have used LLVM for native code generation, but 1) the most recent update on the web site is from late 2009, and 2) the release notes for that version say: "The Unladen Swallow team does not recommend wide adoption of the 2009Q3 release."
Psyco works as a plug-in for Python that basically does JIT compilation, so even though it can speed up execution (quite a lot in some cases), it doesn't produce a machine-code executable you can distribute. In short, while it's sort of similar to what you want, it's not intended to do exactly what you've asked for.
Shed Skin Python-to-C++ produces C++ as its output, and you then compile the C++ and (potentially) distribute the result of that. Shedskin is currently at version 0.5 -- i.e., nobody's claiming that it's a finished, released product. On the other hand, development is ongoing, and each release does seem to include pretty substantial improvements.
PyPy is a Python implementation written in Python. Their intent is to allow code production to be "plugged in" without affecting the rest of the implementation -- but while they currently support 4 different code generation models, I don't believe any of them results in producing native machine code that runs directly on the hardware.
Bottom line: work has been done and is being done with the intent of doing what you asked about, but at least to my knowledge there's not really anything I could reasonably recommend as a finished product that you can really depend on to do the job right now. The primary emphasis is really on execution speed, not producing standalone executables.
A:
you can't open up and read the code that actually runs for python either. Try
import dis
def foo():
for i in range(100):
print i
print dis.dis(foo)
That will show you the (human readable) bytcode of the foo program. equivalently, you can save the file and import it from the interactive python interpreter. This will create a .pyc file with the same basename as the script. open that with a hex editor and you are looking at the actually python bytecode.
The reason for the difference is that python changes up it's byte code between releases so that you would either need to distribute a different version of a binary only release for each version of python. This would be a pain.
With C, it's compiled to native code and so the byte code is much more stable making binary only releases possible.
A:
Yes, you can - it's called disassembling, and allows you to look at the code of Safari perfectly well. The thing is, C, among other languages, compiles to native code, i.e. code that your CPU can "understand" and execute.
More or less obviously, the level of abstraction present in the instruction set of your CPU is much smaller than that of a high level language like Python. The CPU instructions are not concerned with "downloading that URI", but more "check if that bit is set in a hardware register".
So, in conclusion, the level of complexity present in a native application is much higher when looking at the machine code, so many people simply can't make any sense of what is going on there, it's hard to get the big picture. With experience and time at your hands, it is possible though - people do it all the time, reversing applications and all.
A:
because C code is complied to object (machine) code and python code is compiled into an intermediate byte code. I am not sure if you are even referring to the byte code of python - you must be referring to the source file itself which is directly executable (hiding the byte code from you!). C needs to be compiled and linked.
A:
Python scripts are parsed and converted to binary only when they're run - i.e., they're text files and you can read them with an editor.
C code is compiled and linked to an executable binary file before they can be run. Normally, only this executable binary file is distributed - hence you need a decompiler. You can always view the source code, if you've access to it.
A:
Python scripts are analogous to a man looking at a to-do list written in English (or language he understands). The man has to do all the work, every time that list of things has to be done.
If the man, instead of doing the steps on his own each time, creates and programs a robot which can carry out those steps again and again (and probably faster than him), that robot is analogous to the C program.
The man in the python case is called the "interpreter" and in the C case is called the "compiler", and the C robot is called the compiled program/executable.
When you look at the python program source, you see the to-do list. In case of the robot, you see the gears, motors and batteries, etc, which look very different from the to-do list. If you could get hold of the C "to-do" list, it looks somewhat like the python code, just in a different language.
A:
Not all C programs require decompilers. There's lots of C code distributed in source form. And some Python programs do require decompilers, if distributed as bytecode (.pyc files).
But, to the extent that your assumptions are valid, it's because C is a compiled language while Python is an interpreted language.
A:
G-WAN executes ANSI C scripts on the fly -making it just like Python scripts.
This can be server-side scripts (using G-WAN as a Web server) or any general-purpose C program and you can link any existing library.
Oh, and G-WAN C scripts are much faster than Python, PHP or Java...
| Why do C programs require decompilers but python programs dont? | If I write a python script, anyone can simply point an editor to it and read it. But for programming written in C, one would have to use decompilers and hex tables and such. Why is that? I mean I simply can't open up the Safari web browser and look at its code.
| [
"Note: The author disavows a deep expertise in this subject. Some assertions may be incorrect.\nPython actually is compiled into bytecode, which is what gets run by the python interpreter. Whenever you use a Python module, Python will generate a .pyc file with a name corresponding to the module. This is the equiv... | [
12,
10,
5,
3,
2,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"c",
"decompiling",
"python"
] | stackoverflow_0003869435_c_decompiling_python.txt |
Q:
Can I change an an existing virtualenv to ignore global site packages? (like --no-site-package on a new one)
I can create a new virtualenv that ignores global site-packages with "--no-site-package". Is it possible to change an existing virtualenv (which was created without "--no-site-package") to also ignore the global site-packages? (So that it workes like it was created with "--no-site-package" in the first place.)
thanks in advance,
Sebastian
A:
I think all you have to do is create an empty file called no-global-site-packages.txt and put it into the virtualenv's python2.x folder (eg, lib/python2.6/, the one with all the modules). Then the normal site.py generated by virtualenv detects the difference and handles everything from there.
A:
Can you just create a new one and then re-create it with the --no-site-package? If you use pip then you can use pip freeze > requirements.pip to generate a requirements file to re-install into your new virtualenv.
| Can I change an an existing virtualenv to ignore global site packages? (like --no-site-package on a new one) | I can create a new virtualenv that ignores global site-packages with "--no-site-package". Is it possible to change an existing virtualenv (which was created without "--no-site-package") to also ignore the global site-packages? (So that it workes like it was created with "--no-site-package" in the first place.)
thanks in advance,
Sebastian
| [
"I think all you have to do is create an empty file called no-global-site-packages.txt and put it into the virtualenv's python2.x folder (eg, lib/python2.6/, the one with all the modules). Then the normal site.py generated by virtualenv detects the difference and handles everything from there.\n",
"Can you just c... | [
20,
9
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0003873294_python_virtualenv.txt |
Q:
Javascript Execution Through Python
I am attempting to create an html document parser with Python. I am very familiar with jQuery and I would like to use its traversing functionality to parse these html files and return the data gathered with jQuery back to my Python program.
Is there any way to use javascript scripts through Python? Or is this just a pipe dream?
A:
You might not need to do this. There is a Python module called PyQuery that directly emulates the API for jQuery. It works exactly as you would expect it to in almost every way. Give it a shot!
A:
jQuery itself does not contain an HTML/XML parser at all. It uses the browser to do all its parsing. Thus, even if you figure out how to run Javascript from Python, it won't do you any good.
A:
jQuery doesn't parse HTML - it traverses the DOM. You'd need an entire rendering engine (e.g. WebKit) if you wanted to use jQuery to work on the HTML.
A:
Well from your question it seems you will require python-javascript bridge like
Pyjamas http://pyjs.org/ , PyPy http://codespeak.net/pypy/dist/pypy/doc/ , skulpt http://www.skulpt.org/ . Or my personal favorite PyXPCOM http://pyxpcomext.mozdev.org/ it installs a python backend directly into the firefox browser and using xpi stubs one can make bidirectioal calls ( mind you very complicated )
| Javascript Execution Through Python | I am attempting to create an html document parser with Python. I am very familiar with jQuery and I would like to use its traversing functionality to parse these html files and return the data gathered with jQuery back to my Python program.
Is there any way to use javascript scripts through Python? Or is this just a pipe dream?
| [
"You might not need to do this. There is a Python module called PyQuery that directly emulates the API for jQuery. It works exactly as you would expect it to in almost every way. Give it a shot!\n",
"jQuery itself does not contain an HTML/XML parser at all. It uses the browser to do all its parsing. Thus, even i... | [
6,
1,
1,
0
] | [] | [] | [
"html",
"javascript",
"jquery",
"parsing",
"python"
] | stackoverflow_0003874280_html_javascript_jquery_parsing_python.txt |
Q:
Getting html stripped of script and style tags with BeautifulSoup?
I have a simple script where I am fetching an HTML page, passing it to BeautifulSoup to remove all script and style tags, then I want to pass the HTML result to another method. Is there an easy way to do this? Skimming the BeautifulSoup.py, I haven't seen it yet.
soup = BeautifulSoup(html)
for script in soup("script"):
soup.script.extract()
for style in soup("style"):
soup.style.extract()
contents = soup.html.contents
text = loader.extract_text(contents)
contents = soup.html.contents just gets a list and everything is defined in classes there. Is there a method that just returns the raw html after soup manipulates it? Or do I just need to go through the contents list and piece the html back together excluding the script & style tags?
Or is there an even better solution to accomplish what I want?
A:
unicode( soup ) gives you the html.
Also what you want is this:
for elem in soup.findAll(['script', 'style']):
elem.extract()
| Getting html stripped of script and style tags with BeautifulSoup? | I have a simple script where I am fetching an HTML page, passing it to BeautifulSoup to remove all script and style tags, then I want to pass the HTML result to another method. Is there an easy way to do this? Skimming the BeautifulSoup.py, I haven't seen it yet.
soup = BeautifulSoup(html)
for script in soup("script"):
soup.script.extract()
for style in soup("style"):
soup.style.extract()
contents = soup.html.contents
text = loader.extract_text(contents)
contents = soup.html.contents just gets a list and everything is defined in classes there. Is there a method that just returns the raw html after soup manipulates it? Or do I just need to go through the contents list and piece the html back together excluding the script & style tags?
Or is there an even better solution to accomplish what I want?
| [
"unicode( soup ) gives you the html.\nAlso what you want is this:\nfor elem in soup.findAll(['script', 'style']):\n elem.extract()\n\n"
] | [
9
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python",
"python_2.6"
] | stackoverflow_0003874442_beautifulsoup_html_parsing_python_python_2.6.txt |
Q:
How to use python for a webservice
I am really new to python, just played around with the scrapy framework that is used to crawl websites and extract data.
My question is, how to I pass parameters to a python script that is hosted somewhere online.
E.g. I make following request mysite.net/rest/index.py
Now I want to pass some parameters similar to php like *.php?id=...
A:
Yes that would work. Although you would need to write handlers for extracting the url parameters in index.py. Try import cgi module for this in python.
Please note that there are several robust python based web frameworks available (aka Django, Pylons etc.) which automatically parses your url & forms a dictionary of all it's parameters, plus they do much more like session management, user authentication etc. I would highly recommend you use them for faster code turn-around and less maintenance hassles.
| How to use python for a webservice | I am really new to python, just played around with the scrapy framework that is used to crawl websites and extract data.
My question is, how to I pass parameters to a python script that is hosted somewhere online.
E.g. I make following request mysite.net/rest/index.py
Now I want to pass some parameters similar to php like *.php?id=...
| [
"Yes that would work. Although you would need to write handlers for extracting the url parameters in index.py. Try import cgi module for this in python.\nPlease note that there are several robust python based web frameworks available (aka Django, Pylons etc.) which automatically parses your url & forms a dictionary... | [
2
] | [] | [] | [
"parameters",
"python",
"scrapy",
"web_services"
] | stackoverflow_0003874477_parameters_python_scrapy_web_services.txt |
Q:
Is there a way to make every variable inside a definition or class to become global automatically?
I am using a large list of variables inside some definitions and classes (mainly because I want to be able to use the code-folding feature of pydev). Is there any constructor I can use on a definition or class to make its variables automatically considered globals?
This is an example of what I did after following some of the recommendations provided on the comments:
From:
img_globe = os.path.join(set_img_dir, 'img_globe.png')
img_help = os.path.join(set_img_dir, 'img_help.png')
img_exit = os.path.join(set_img_dir, 'img_exit.png')
img_open = os.path.join(set_img_dir, 'img_open.png')
img_tutorial = os.path.join(set_img_dir, 'img_tutorial.png')
img_save = os.path.join(set_img_dir, 'img_save.png')
img_site = os.path.join(set_img_dir, 'img_site.png')
... (long, long list)
To:
varies = {}
dirList=os.listdir(set_img_dir)
for fname in dirList:
varies[fname.split(".")[0]] = os.path.join(set_img_dir, fname)
A:
Although you should not do this and the solution you are looking for is not as simple as you might think, here is a very simple example of how you might take the local variables from within a function and make them global:
def make_locals_globals():
"""This is just bad"""
foo = 1
bar = 2
locals_dict = locals()
globals_dict = globals()
print 'Locals:', locals_dict
for varname, varval in locals_dict.items():
print 'Setting global: %s=%s' % (varname, varval)
globals_dict[varname] = varval
if __name__ == '__main__':
make_locals_globals()
print '\nGlobals:'
print 'foo=', foo
print 'bar=', bar
| Is there a way to make every variable inside a definition or class to become global automatically? | I am using a large list of variables inside some definitions and classes (mainly because I want to be able to use the code-folding feature of pydev). Is there any constructor I can use on a definition or class to make its variables automatically considered globals?
This is an example of what I did after following some of the recommendations provided on the comments:
From:
img_globe = os.path.join(set_img_dir, 'img_globe.png')
img_help = os.path.join(set_img_dir, 'img_help.png')
img_exit = os.path.join(set_img_dir, 'img_exit.png')
img_open = os.path.join(set_img_dir, 'img_open.png')
img_tutorial = os.path.join(set_img_dir, 'img_tutorial.png')
img_save = os.path.join(set_img_dir, 'img_save.png')
img_site = os.path.join(set_img_dir, 'img_site.png')
... (long, long list)
To:
varies = {}
dirList=os.listdir(set_img_dir)
for fname in dirList:
varies[fname.split(".")[0]] = os.path.join(set_img_dir, fname)
| [
"Although you should not do this and the solution you are looking for is not as simple as you might think, here is a very simple example of how you might take the local variables from within a function and make them global:\ndef make_locals_globals():\n \"\"\"This is just bad\"\"\"\n foo = 1\n bar = 2\n\n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003874613_python.txt |
Q:
Python - correct order of the application of decorators
I'm decorating a function as such:
def some_abstract_decorator(func):
@another_lower_level_decorator
def wrapper(*args, **kwargs):
# ... details omitted
return func(*args, **kwargs)
return wrapper
This does what you'd expect (applies a low level decorator and then does some more stuff. My problem is that I now want to use functools.wraps and I don't know where to put it. This is my guess, but I don't know if it'll have unintended consequences.
def some_abstract_decorator(func):
@wraps(func)
@another_lower_level_decorator
def wrapper(*args, **kwargs):
# ... details omitted
return func(*args, **kwargs)
return wrapper
(I of course apply wraps inside of another_lower_level_decorator as well)
A:
That's right. The way this works is
wrapper is defined. It calls func with its arguments.
another_lower_level_decorator is called, with wrapper as its argument. The function it returns becomes the new value of wrapper.
wraps(func) is called to create a wrapper that will apply the name/docstring/etc. of func to whatever function it's called on.
The return value of wraps(func), i.e. the produced wrapper function, is passed the current value of wrapper. This, remember, was the return value from another_lower_level_decorator.
wraps(func)(wrapper) becomes the new value of wrapper.
That value is returned by some_abstract_decorator, making that function suitable for use as a decorator.
Or that's effectively it, anyway. I think in practice wrapper is only reassigned to once.
A:
Try it out:
from functools import wraps
def another_lower_level_decorator(func):
@wraps( func )
def wrapped(*args, **kwargs):
return func(*args, **kwargs)
return wrapped
def some_abstract_decorator(func):
@wraps(func)
@another_lower_level_decorator
def wrapper(*args, **kwargs):
# ... details omitted
return func(*args, **kwargs)
return wrapper
@some_abstract_decorator
def test():
""" This is a docstring that should be on the decorated function """
pass
help(test)
Prints:
Help on function test in module __main__:
test(*args, **kwargs)
This is a docstring that should be on the decorated function
As you can see it works! The docstring is there and the name assigned.
But this works just the same:
def some_abstract_decorator(func):
@another_lower_level_decorator
@wraps(func)
def wrapper(*args, **kwargs):
# ... details omitted
return func(*args, **kwargs)
return wrapper
wraps just fixes the docstrings/names. As long as all the decorators use wraps, the order in which you apply it doesn't matter
Btw, there is a much cooler decorator library:
from decorator import decorator
@decorator
def another_decorator(func, *args, **kwargs):
return func(*args, **kwargs)
@decorator
@another_decorator
def some_abstract_decorator(func, *args, **kwargs):
# ... details omitted
return func(*args, **kwargs)
@some_abstract_decorator
def test(x):
""" this is a docstring that should be on the decorated function """
pass
A:
Yes, that looks right to me. @another_lower_level_decorator will return a function, which @wraps will wrap so that it has the same name as func.
| Python - correct order of the application of decorators | I'm decorating a function as such:
def some_abstract_decorator(func):
@another_lower_level_decorator
def wrapper(*args, **kwargs):
# ... details omitted
return func(*args, **kwargs)
return wrapper
This does what you'd expect (applies a low level decorator and then does some more stuff. My problem is that I now want to use functools.wraps and I don't know where to put it. This is my guess, but I don't know if it'll have unintended consequences.
def some_abstract_decorator(func):
@wraps(func)
@another_lower_level_decorator
def wrapper(*args, **kwargs):
# ... details omitted
return func(*args, **kwargs)
return wrapper
(I of course apply wraps inside of another_lower_level_decorator as well)
| [
"That's right. The way this works is\n\nwrapper is defined. It calls func with its arguments.\nanother_lower_level_decorator is called, with wrapper as its argument. The function it returns becomes the new value of wrapper.\nwraps(func) is called to create a wrapper that will apply the name/docstring/etc. of fun... | [
2,
2,
1
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0003874962_decorator_python.txt |
Q:
django gui for statistical analysis of data
Im trying to setup situation where users of application can do statistical analysis of data.
There are 3 tables, users, exams, polls
I should have gui to build custom queries, like these:
users born between 1930 and 1940, that have 3 exams taken; show
name, surname, group by age of person
count of users born 1945 that have not taken poll grouped by reason;show count,reason
Language of choice is python, django.
If anyone has experience or can recommend some python package that would make my job easier I'd be greatful.
A:
I have developed django-cube for this very purpose.
It allows you to organize your django data as multi-dimensional data, declare an aggregation function (to calculate your statistics), and then you have several helpers to display a table, and ready-to-use Django templates for tables.
A:
I've had some pretty good success recently using Alex Gaynor's django-filter app, located here.
It brings a lot of the Django admin's drill-down filtering controls to your site's front-end objects, and after a bit of configuration you should be able to use it to provide a nice set of filters for your User, Exam, and Poll models that anyone can use.
| django gui for statistical analysis of data | Im trying to setup situation where users of application can do statistical analysis of data.
There are 3 tables, users, exams, polls
I should have gui to build custom queries, like these:
users born between 1930 and 1940, that have 3 exams taken; show
name, surname, group by age of person
count of users born 1945 that have not taken poll grouped by reason;show count,reason
Language of choice is python, django.
If anyone has experience or can recommend some python package that would make my job easier I'd be greatful.
| [
"I have developed django-cube for this very purpose.\nIt allows you to organize your django data as multi-dimensional data, declare an aggregation function (to calculate your statistics), and then you have several helpers to display a table, and ready-to-use Django templates for tables.\n",
"I've had some pretty ... | [
2,
1
] | [] | [] | [
"django",
"django_statistics",
"python",
"search"
] | stackoverflow_0003873671_django_django_statistics_python_search.txt |
Q:
Wake up from standby/hibernate programmatically in Windows in python?
I'm thinking of making an alarm clock that can wake up some systems (depending on motherboard model) from hibernation/standby modes at a certain pre-determined time. I've seen similar software do this, I think in VB. I can't seem to find any documentation anywhere on how to do this in Python. Does anyone have any hints? If it's not possible in Python, is there perhaps a way to do it in e.g. c++ and call that binary from python?
Thanks!
A:
SetWaitableTimer can wake up a suspended machine.
| Wake up from standby/hibernate programmatically in Windows in python? | I'm thinking of making an alarm clock that can wake up some systems (depending on motherboard model) from hibernation/standby modes at a certain pre-determined time. I've seen similar software do this, I think in VB. I can't seem to find any documentation anywhere on how to do this in Python. Does anyone have any hints? If it's not possible in Python, is there perhaps a way to do it in e.g. c++ and call that binary from python?
Thanks!
| [
"SetWaitableTimer can wake up a suspended machine.\n"
] | [
2
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003875209_python_windows.txt |
Q:
Data type problem using scipy.spatial
I want to use scipy.spatial's KDTree to find nearest neighbor pairs in a two dimensional array (essentially a list of lists where the dimension of the nested list is 2). I generate my list of lists, pipe it into numpy's array and then create the KDTree instance. However, whenever I try to run "query" on it, I inevitably get weird answers. For example, when I type:
tree = KDTree(array)
nearest = tree.query(np.array[1,1])
nearest prints out (0.0, 0). Currently, I'm using an an array that is basically y = x for the range (1,50) so I expect that I should get the nearest neighbor of (2,2) for (1,1)
What am I doing wrong, scipy gurus?
EDIT: Alternatively, if someone can point me to a KDTree package for python that they've used for nearest neighbor searches of a given point I would love to hear about it.
A:
I have used scipy.spatial before, and it appears to be a nice improvement (especially wrt the interface) as compared to scikits.ann.
In this case I think you have confused the return from your tree.query(...) call. From the scipy.spatial.KDTree.query docs:
Returns
-------
d : array of floats
The distances to the nearest neighbors.
If x has shape tuple+(self.m,), then d has shape tuple if
k is one, or tuple+(k,) if k is larger than one. Missing
neighbors are indicated with infinite distances. If k is None,
then d is an object array of shape tuple, containing lists
of distances. In either case the hits are sorted by distance
(nearest first).
i : array of integers
The locations of the neighbors in self.data. i is the same
shape as d.
So in this case when you query for the nearest to [1,1] you are getting:
distance to nearest: 0.0
index of nearest in original array: 0
This means that [1,1] is the first row of your original data in array, which is expected given your data is y = x on the range [1,50].
The scipy.spatial.KDTree.query function has lots of other options, so if for example you wanted to make sure to get the nearest neighbour that isn't itself try:
tree.query([1,1], k=2)
This will return the two nearest neighbours, which you could apply further logic to such that cases where the distance returned is zero (i.e. the point queried is one of data items used to build the tree) the second nearest neighbour is taken rather than the first.
| Data type problem using scipy.spatial | I want to use scipy.spatial's KDTree to find nearest neighbor pairs in a two dimensional array (essentially a list of lists where the dimension of the nested list is 2). I generate my list of lists, pipe it into numpy's array and then create the KDTree instance. However, whenever I try to run "query" on it, I inevitably get weird answers. For example, when I type:
tree = KDTree(array)
nearest = tree.query(np.array[1,1])
nearest prints out (0.0, 0). Currently, I'm using an an array that is basically y = x for the range (1,50) so I expect that I should get the nearest neighbor of (2,2) for (1,1)
What am I doing wrong, scipy gurus?
EDIT: Alternatively, if someone can point me to a KDTree package for python that they've used for nearest neighbor searches of a given point I would love to hear about it.
| [
"I have used scipy.spatial before, and it appears to be a nice improvement (especially wrt the interface) as compared to scikits.ann.\nIn this case I think you have confused the return from your tree.query(...) call. From the scipy.spatial.KDTree.query docs:\nReturns\n-------\n\nd : array of floats\n The distan... | [
9
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0003875062_numpy_python_scipy.txt |
Q:
sqlite3 module for Jython
I'm using Java Scripting API to execute some external Python scripts from my Java application. The python scripts use sqlite3 module. Execution of the application is resulting in error
ImportError: No module named sqlite3
As I look into the Lib directory(which is in the classpath) of Jython, there's no sqlite3 module. Hence, my search begins and I found one _sqlite3.py file which is an implementation of javasqlite (http://bugs.jython.org/issue1682864). It's use produced more similar kind of errors.
Then I searched the original python's sqlite3 package(original directory) from the python's standard library location and placed it in the Jython's Lib folder. It then could not find imported _sqlite module which is the _sqlite.so library (actual C implementation).
So, now I need help.
A:
I don't believe there is any way to use a CPython extension in Jython, so you're out of luck there.
There's a Java wrapper for SQLite here: http://www.zentus.com/sqlitejdbc/
This is not going to work quite like a Python database driver, so using it would require some adaptation.
Not fun, but perhaps you (or someone else) could write some Jython around it to produce a drop-in replacement for the sqlite3 module.
| sqlite3 module for Jython | I'm using Java Scripting API to execute some external Python scripts from my Java application. The python scripts use sqlite3 module. Execution of the application is resulting in error
ImportError: No module named sqlite3
As I look into the Lib directory(which is in the classpath) of Jython, there's no sqlite3 module. Hence, my search begins and I found one _sqlite3.py file which is an implementation of javasqlite (http://bugs.jython.org/issue1682864). It's use produced more similar kind of errors.
Then I searched the original python's sqlite3 package(original directory) from the python's standard library location and placed it in the Jython's Lib folder. It then could not find imported _sqlite module which is the _sqlite.so library (actual C implementation).
So, now I need help.
| [
"I don't believe there is any way to use a CPython extension in Jython, so you're out of luck there.\nThere's a Java wrapper for SQLite here: http://www.zentus.com/sqlitejdbc/\nThis is not going to work quite like a Python database driver, so using it would require some adaptation. \nNot fun, but perhaps you (or so... | [
4
] | [] | [] | [
"java",
"javax.script",
"jython",
"python",
"sqlite"
] | stackoverflow_0003875212_java_javax.script_jython_python_sqlite.txt |
Q:
Is there a library or reference around showing how to build a Ribbon menu using PyGTK?
Hey there, everyone. A really random question, but I'm looking to get into some GUI programming with Python, specifically with the PyGTK library. I've only ever done GUI programming with Java/Swing, and I'd like to do some independent, personal projects in Python as a way of learning my way around the language, since it's been something that I've wanted to do for a really long time now, and haven't been able to find time for! But I digress...
I'm a fan of the Ribbon Interface introduced by Microsoft. I know that Microsoft introduced recently a library for .NET allowing users to build programs utilizing Ribbon. While I don't really want to learn IronPython yet, it's still an option for the future. These projects would be build on Linux, specifically Ubuntu, if that makes a difference.
So, finally, my question is this: Is there a library or reference point anywhere that can show me how to build a Ribbon GUI interface? Thank you for all of the advice!
A:
There is ribbon like widgets developed as a part of GSC.
http://arstechnica.com/open-source/news/2007/08/mono-developer-brings-the-ribbon-interface-to-linux.ars
http://mono-soc-2007.googlecode.com/svn/trunk/laurent/src/Ribbons/
http://debackerl.wordpress.com/2007/08/25/soc-ribbons-summary/
| Is there a library or reference around showing how to build a Ribbon menu using PyGTK? | Hey there, everyone. A really random question, but I'm looking to get into some GUI programming with Python, specifically with the PyGTK library. I've only ever done GUI programming with Java/Swing, and I'd like to do some independent, personal projects in Python as a way of learning my way around the language, since it's been something that I've wanted to do for a really long time now, and haven't been able to find time for! But I digress...
I'm a fan of the Ribbon Interface introduced by Microsoft. I know that Microsoft introduced recently a library for .NET allowing users to build programs utilizing Ribbon. While I don't really want to learn IronPython yet, it's still an option for the future. These projects would be build on Linux, specifically Ubuntu, if that makes a difference.
So, finally, my question is this: Is there a library or reference point anywhere that can show me how to build a Ribbon GUI interface? Thank you for all of the advice!
| [
"There is ribbon like widgets developed as a part of GSC.\n\nhttp://arstechnica.com/open-source/news/2007/08/mono-developer-brings-the-ribbon-interface-to-linux.ars\nhttp://mono-soc-2007.googlecode.com/svn/trunk/laurent/src/Ribbons/\nhttp://debackerl.wordpress.com/2007/08/25/soc-ribbons-summary/\n\n"
] | [
1
] | [] | [] | [
"pygtk",
"python",
"ribbon",
"user_interface"
] | stackoverflow_0003875723_pygtk_python_ribbon_user_interface.txt |
Q:
Proper way to do session handling in Python + Pylons for a php programmer
I'm a php programmer who's just getting started with Python. I'm trying to get Python to handle login/logout via database-stored sessions. Things work, but seem inconsistent. For example, sometimes a user isn't logged out. Sometimes users "switch" logins. I'm guessing this has something to do with thread-safety, but I'm just not sure where to begin on how to fix this. Any help would be appreciated. Here's what I have now:
#lib/base.py
def authenticate():
#Confirm login
try:
if user['authenticated'] != True:
redirect_to(controller='login', action='index')
except KeyError:
redirect_to(controller='login', action='index')
#Global variables
user = {}
connection = {}
class BaseController(WSGIController):
#Read if there is a cookie set
try:
session = request.cookies['session']
#Create a session object from the session id
session_logged_in = Session(session)
#If the session is valid, retrieve the user info
if session_logged_in.isValid(remote_addr):
#Set global variables about the logged in user
user_logged_in = User(session_logged_in.user_id)
user['name'] = c.name = user_logged_in.name
user['name_url'] = c.name_url = user_logged_in.name_url
user['first_name'] = c.first_name = user_logged_in.first_name
user['last_name'] = c.last_name = user_logged_in.last_name
user['email'] = c.email = user_logged_in.email
user['about'] = c.about = user_logged_in.about
user['authenticated'] = c.authenticated = True
user['profile_url'] = c.profile_url = user_logged_in.profile_url
user['user_thumb'] = c.user_thumb = user_logged_in.user_thumb
user['image_id'] = c.image_id = user_logged_in.image_id
user['id'] = c.user_id = user_logged_in.id
#Update the session
session_logged_in.current_uri = requested_url
session_logged_in.update()
#If no session has been set, do nothing
except KeyError:
user['authenticated'] = False
I can then access the user{} global from my controllers:
#controllers/profile.py
from project.lib.base import BaseController, user
class ProfileController(BaseController):
def index(self, id=None, name_url=None):
#If this is you
if user['id'] == 1
print 'this is you'
Is there a better way to do this? Thanks for your help.
A:
Pylons has a 'sessions' object that exists to handle this kind of situation. The example on the Pylons website seems to match what you want.
I think you are seeing problems because of the globals 'user' and 'connection'. Pylons has a globals object that is designed to share information between all controllers and is not reset on each request.
| Proper way to do session handling in Python + Pylons for a php programmer | I'm a php programmer who's just getting started with Python. I'm trying to get Python to handle login/logout via database-stored sessions. Things work, but seem inconsistent. For example, sometimes a user isn't logged out. Sometimes users "switch" logins. I'm guessing this has something to do with thread-safety, but I'm just not sure where to begin on how to fix this. Any help would be appreciated. Here's what I have now:
#lib/base.py
def authenticate():
#Confirm login
try:
if user['authenticated'] != True:
redirect_to(controller='login', action='index')
except KeyError:
redirect_to(controller='login', action='index')
#Global variables
user = {}
connection = {}
class BaseController(WSGIController):
#Read if there is a cookie set
try:
session = request.cookies['session']
#Create a session object from the session id
session_logged_in = Session(session)
#If the session is valid, retrieve the user info
if session_logged_in.isValid(remote_addr):
#Set global variables about the logged in user
user_logged_in = User(session_logged_in.user_id)
user['name'] = c.name = user_logged_in.name
user['name_url'] = c.name_url = user_logged_in.name_url
user['first_name'] = c.first_name = user_logged_in.first_name
user['last_name'] = c.last_name = user_logged_in.last_name
user['email'] = c.email = user_logged_in.email
user['about'] = c.about = user_logged_in.about
user['authenticated'] = c.authenticated = True
user['profile_url'] = c.profile_url = user_logged_in.profile_url
user['user_thumb'] = c.user_thumb = user_logged_in.user_thumb
user['image_id'] = c.image_id = user_logged_in.image_id
user['id'] = c.user_id = user_logged_in.id
#Update the session
session_logged_in.current_uri = requested_url
session_logged_in.update()
#If no session has been set, do nothing
except KeyError:
user['authenticated'] = False
I can then access the user{} global from my controllers:
#controllers/profile.py
from project.lib.base import BaseController, user
class ProfileController(BaseController):
def index(self, id=None, name_url=None):
#If this is you
if user['id'] == 1
print 'this is you'
Is there a better way to do this? Thanks for your help.
| [
"Pylons has a 'sessions' object that exists to handle this kind of situation. The example on the Pylons website seems to match what you want.\nI think you are seeing problems because of the globals 'user' and 'connection'. Pylons has a globals object that is designed to share information between all controllers and... | [
3
] | [] | [] | [
"pylons",
"python",
"session"
] | stackoverflow_0003873958_pylons_python_session.txt |
Q:
How does one convert a .NET tick to a python datetime?
I have a file with dates and times listed as huge numbers like 634213557000000000. I believe this is a .NET tick. That's the number of 100 nanosecond increments since midnight on January 1, 1 A.D. What's a good way to read that into a python datetime object?
A:
datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds = ticks//10)
For your example, this returns
datetime.datetime(2010, 9, 29, 11, 15)
| How does one convert a .NET tick to a python datetime? | I have a file with dates and times listed as huge numbers like 634213557000000000. I believe this is a .NET tick. That's the number of 100 nanosecond increments since midnight on January 1, 1 A.D. What's a good way to read that into a python datetime object?
| [
"datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds = ticks//10)\n\nFor your example, this returns\ndatetime.datetime(2010, 9, 29, 11, 15)\n\n"
] | [
16
] | [] | [] | [
".net",
"datetime",
"python",
"timestamp"
] | stackoverflow_0003875806_.net_datetime_python_timestamp.txt |
Q:
How to script Firefox or any Mozilla based browser
I need to automate something like this:
Open an URL
Wait until the page is fully loaded
Save COMPLETE page as... (I can provide a name).
I saw https://developer.mozilla.org/en/Command_Line_Options but I can't find an option to invoke the command "save page as... (in mode Web page complete)". So I can have all css, js, xml and related files needed to display the page.
I know some Python that I could use it if I find a way to "talk" to Firefox. The webbrowser module is not help here since it doesn't allow to save a page: http://docs.python.org/library/webbrowser.html
I am opened to any kind of solution.
Platform: Linux, but I could use another if there is no other way.
Important: I can't just retrieve the HTML given by the web server, since I need all css, js, images and files that are used to see to page as rendered by the browser. For example an image may be not linked in the HTML but referenced by a js that is executed when the page is rendered. The only way I think that I could retrieve this image is by executing the page as if I were the browser and then get all files from the resulting page (and not the original page).
A:
Maybe something from the Selenium collection of tools works for you.
Selenium IDE is an integrated development environment for Selenium scripts. It is implemented as a Firefox extension, and allows you to record, edit, and debug tests. Selenium IDE includes the entire Selenium Core, allowing you to easily and quickly record and play back tests in the actual environment that they will run.
| How to script Firefox or any Mozilla based browser | I need to automate something like this:
Open an URL
Wait until the page is fully loaded
Save COMPLETE page as... (I can provide a name).
I saw https://developer.mozilla.org/en/Command_Line_Options but I can't find an option to invoke the command "save page as... (in mode Web page complete)". So I can have all css, js, xml and related files needed to display the page.
I know some Python that I could use it if I find a way to "talk" to Firefox. The webbrowser module is not help here since it doesn't allow to save a page: http://docs.python.org/library/webbrowser.html
I am opened to any kind of solution.
Platform: Linux, but I could use another if there is no other way.
Important: I can't just retrieve the HTML given by the web server, since I need all css, js, images and files that are used to see to page as rendered by the browser. For example an image may be not linked in the HTML but referenced by a js that is executed when the page is rendered. The only way I think that I could retrieve this image is by executing the page as if I were the browser and then get all files from the resulting page (and not the original page).
| [
"Maybe something from the Selenium collection of tools works for you.\n\nSelenium IDE is an integrated development environment for Selenium scripts. It is implemented as a Firefox extension, and allows you to record, edit, and debug tests. Selenium IDE includes the entire Selenium Core, allowing you to easily and q... | [
4
] | [] | [] | [
"firefox",
"python",
"scripting"
] | stackoverflow_0003876070_firefox_python_scripting.txt |
Q:
What's the simplest way to resize an image to a given bounded area?
I'd like to create a function, like:
def generateThumbnail(self, width, height):
"""
Generates thumbnails for an image
"""
im = Image.open(self._file)
im.thumbnail((width, height), Image.ANTIALIAS)
im.save(self._path + str(width) + 'x' +
str(height) + '-' + self._filename, "JPEG")
Where a file can be given and resized.
The current function works great except it does not crop when necessary.
In the case that a rectangular image is given, and a square resize is required (width = height), some centered-weighted cropping will have to be done.
A:
You need to crop the image properly before resizing it. The basic idea is to determine the largest rectangular area of the source image having the same aspect (width to height) ratio as the thumbnail image and then trim off (crop) any excess around it before resizing to the thumbnail's dimensions). Here's a function which will compute the size and location of such a cropping area:
def cropbbox(imagewidth,imageheight, thumbwidth,thumbheight):
""" cropbbox(imagewidth,imageheight, thumbwidth,thumbheight)
Compute a centered image crop area for making thumbnail images.
imagewidth,imageheight are source image dimensions
thumbwidth,thumbheight are thumbnail image dimensions
Returns bounding box pixel coordinates of the cropping area
in this order (left,upper, right,lower).
"""
# determine scale factor
fx = float(imagewidth)/thumbwidth
fy = float(imageheight)/thumbheight
f = fx if fx < fy else fy
# calculate size of crop area
cropheight,cropwidth = int(thumbheight*f),int(thumbwidth*f)
# for centering use half the size difference of the image and the crop area
dx = (imagewidth-cropwidth)/2
dy = (imageheight-cropheight)/2
# return bounding box of centered crop area on source image
return dx,dy, cropwidth+dx,cropheight+dy
if __name__=='__main__':
print("===")
bbox = cropbbox(1024,768, 128,128)
print("cropbbox(1024,768, 128,128): {}".format(bbox))
print("===")
bbox = cropbbox(768,1024, 128,128)
print("cropbbox(768,1024, 128,128): {}".format(bbox))
print("===")
bbox = cropbbox(1024,1024, 96,128)
print("cropbbox(1024,1024, 96,128): {}".format(bbox))
print("===")
bbox = cropbbox(1024,1024, 128,96)
print("cropbbox(1024,1024, 128,96): {}".format(bbox))
After determining the crop area, call im.crop(bbox) and then call im.thumbnail(...) on the image returned.
| What's the simplest way to resize an image to a given bounded area? | I'd like to create a function, like:
def generateThumbnail(self, width, height):
"""
Generates thumbnails for an image
"""
im = Image.open(self._file)
im.thumbnail((width, height), Image.ANTIALIAS)
im.save(self._path + str(width) + 'x' +
str(height) + '-' + self._filename, "JPEG")
Where a file can be given and resized.
The current function works great except it does not crop when necessary.
In the case that a rectangular image is given, and a square resize is required (width = height), some centered-weighted cropping will have to be done.
| [
"You need to crop the image properly before resizing it. The basic idea is to determine the largest rectangular area of the source image having the same aspect (width to height) ratio as the thumbnail image and then trim off (crop) any excess around it before resizing to the thumbnail's dimensions). Here's a functi... | [
6
] | [] | [] | [
"image_resizing",
"imaging",
"python",
"python_imaging_library"
] | stackoverflow_0003873859_image_resizing_imaging_python_python_imaging_library.txt |
Q:
Python: how to tell if a string represent a statement or an expression?
I need to either call exec() or eval() based on an input string "s"
If "s" was an expression, after calling eval() I want to print the result if the result was not None
If "s" was a statement then simply exec(). If the statement happens to print something then so be it.
s = "1 == 2" # user input
# ---
try:
v = eval(s)
print "v->", v
except:
print "eval failed!"
# ---
try:
exec(s)
except:
print "exec failed!"
For example, "s" can be:
s = "print 123"
And in that case, exec() should be used.
Ofcourse, I don't want to try first eval() and if it fails call exec()
A:
Try to compile it as an expression. If it fails then it must be a statement (or just invalid).
isstatement= False
try:
code= compile(s, '<stdin>', 'eval')
except SyntaxError:
isstatement= True
code= compile(s, '<stdin>', 'exec')
result= None
if isstatement:
exec s
else:
result= eval(s)
if result is not None:
print result
A:
It sort of sounds like you'd like the user to be able to interact with a Python interpreter from within your script. Python makes it possible through a call to code.interact:
import code
x=3
code.interact(local=locals())
print(x)
Running the script:
>>> 1==2
False
>>> print 123
123
The intepreter is aware of local variables set in the script:
>>> x
3
The user can also change the value of local variables:
>>> x=4
Pressing Ctrl-d returns flow of control to the script.
>>>
4 <-- The value of x has been changed.
| Python: how to tell if a string represent a statement or an expression? | I need to either call exec() or eval() based on an input string "s"
If "s" was an expression, after calling eval() I want to print the result if the result was not None
If "s" was a statement then simply exec(). If the statement happens to print something then so be it.
s = "1 == 2" # user input
# ---
try:
v = eval(s)
print "v->", v
except:
print "eval failed!"
# ---
try:
exec(s)
except:
print "exec failed!"
For example, "s" can be:
s = "print 123"
And in that case, exec() should be used.
Ofcourse, I don't want to try first eval() and if it fails call exec()
| [
"Try to compile it as an expression. If it fails then it must be a statement (or just invalid).\nisstatement= False\ntry:\n code= compile(s, '<stdin>', 'eval')\nexcept SyntaxError:\n isstatement= True\n code= compile(s, '<stdin>', 'exec')\n\nresult= None\nif isstatement:\n exec s\nelse:\n result= eva... | [
10,
6
] | [] | [] | [
"detect",
"expression",
"python"
] | stackoverflow_0003876231_detect_expression_python.txt |
Q:
Lamson (Python SMTP Server) Error
I've installed Lamson via easy_install on my webfaction shared hosting. Went to do the '30 Second Introduction' (See http://lamsonproject.org/docs/getting_started.html) but after:
[almacmillan@web129 python2.6]$ lamson gen -project mymailserver
I get:
Traceback (most recent call last):
File "/home/almacmillan/bin/lamson", line 5, in <module>
pkg_resources.run_script('lamson==1.0', 'lamson')
File "/usr/local/lib/python2.6/site-packages/pkg_resources.py", line 448, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/usr/local/lib/python2.6/site-packages/pkg_resources.py", line 1166, in run_script
execfile(script_filename, namespace, namespace)
File "/home/almacmillan/lib/python2.6/lamson-1.0-py2.6.egg/EGG-INFO/scripts/lamson", line 3, in <module>
from lamson import args, commands
File "/home/almacmillan/lib/python2.6/lamson-1.0-py2.6.egg/lamson/commands.py", line 28, in <module>
from lamson import server, args, utils, mail, routing, queue, encoding
File "/home/almacmillan/lib/python2.6/lamson-1.0-py2.6.egg/lamson/utils.py", line 12, in <module>
from daemon import pidlockfile
File "/home/almacmillan/lib/python2.6/python_daemon-1.5.5-py2.6.egg/daemon/pidlockfile.py", line 33, in <module>
class PIDLockFile(LinkFileLock, object):
TypeError: Error when calling the metaclass bases
function() argument 1 must be code, not str
I'm a very new programmer. I'd really appreciate some debugging help.
A:
There's already a ticket for the problem here: http://support.lamsonproject.org/tktview?name=06d488141d
Use http://pypi.python.org/pypi/lockfile/0.8 as 0.9.1's
API changes break python_daemon-1.5.5-py2.5.egg/daemon/pidlockfile.py.
0.9.1 comes with easy_install. So, it's not an issue with lamson.
To solve: remove lockfile 0.9.1 from your Python site-packages
and get 0.8 from the cheese shop instead.
| Lamson (Python SMTP Server) Error | I've installed Lamson via easy_install on my webfaction shared hosting. Went to do the '30 Second Introduction' (See http://lamsonproject.org/docs/getting_started.html) but after:
[almacmillan@web129 python2.6]$ lamson gen -project mymailserver
I get:
Traceback (most recent call last):
File "/home/almacmillan/bin/lamson", line 5, in <module>
pkg_resources.run_script('lamson==1.0', 'lamson')
File "/usr/local/lib/python2.6/site-packages/pkg_resources.py", line 448, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/usr/local/lib/python2.6/site-packages/pkg_resources.py", line 1166, in run_script
execfile(script_filename, namespace, namespace)
File "/home/almacmillan/lib/python2.6/lamson-1.0-py2.6.egg/EGG-INFO/scripts/lamson", line 3, in <module>
from lamson import args, commands
File "/home/almacmillan/lib/python2.6/lamson-1.0-py2.6.egg/lamson/commands.py", line 28, in <module>
from lamson import server, args, utils, mail, routing, queue, encoding
File "/home/almacmillan/lib/python2.6/lamson-1.0-py2.6.egg/lamson/utils.py", line 12, in <module>
from daemon import pidlockfile
File "/home/almacmillan/lib/python2.6/python_daemon-1.5.5-py2.6.egg/daemon/pidlockfile.py", line 33, in <module>
class PIDLockFile(LinkFileLock, object):
TypeError: Error when calling the metaclass bases
function() argument 1 must be code, not str
I'm a very new programmer. I'd really appreciate some debugging help.
| [
"There's already a ticket for the problem here: http://support.lamsonproject.org/tktview?name=06d488141d\nUse http://pypi.python.org/pypi/lockfile/0.8 as 0.9.1's\nAPI changes break python_daemon-1.5.5-py2.5.egg/daemon/pidlockfile.py.\n0.9.1 comes with easy_install. So, it's not an issue with lamson.\nTo solve: remo... | [
3
] | [] | [] | [
"email",
"lamson",
"python",
"smtp"
] | stackoverflow_0003874771_email_lamson_python_smtp.txt |
Q:
Validating XML with DTD fails to import entity using lxml
I have a tool producing NewsML type XML files and I want to validate them after producing the files.
I'm receiving an error:
Attempt to load network entity http://www.w3.org/TR/ruby/xhtml-ruby-1.mod
The python call is:
parser = etree.XMLParser(load_dtd=True, dtd_validation=True)
treeObject = etree.parse(f, parser)
First I'm not sure if I need both "load_dtd=True, dtd_validation=True" but I'm using it anyway.
Second error seems to be coming from an imported nitf-3-4.dtd that's defined as:
<!ENTITY % xhtml-ruby.mod PUBLIC
"-//W3C//ELEMENTS XHTML Ruby 1.0//EN" "http://www.w3.org/TR/ruby/xhtml-ruby-1.mod">
%xhtml-ruby.mod;
Will lxml go out and retrieve this xhtml-ruby-1.mod or do I have to have all the DTD files locally.
A:
Try constructing the parser with no_network=False. As stated in the documentation:
no_network - prevent network access when looking up external documents (on by default)
Imported dtd modules should get retrieved by lxml, but it will not be able to do so if network access is not allowed (this does not count for the document itself, only for loading external referenced documents. In fact, I would expect you to get errors loading the dtd itself, so I assume the document refers to a locally available copy of that dtd, and that it is only the dtd itself that references a remote resource?)
You could also use a catalog to use locally available copies (not only circumventing this problem, but also more performant, and friendlier towards the w3c servers ;-)). Libxml2 (used by lxml) will check for the existance of a catalog in /etc/xml/catalog, and the XML_CATALOG_FILES environment variable (see Libxml2 docs)
(it is also possible to write your own resolvers for lxml to intercept and handle requests, but that would probably be overkill in this case)
Note that there is also another option besides parse time validation: use the DTD class to load the dtd separately, and use that as a validator.
This will validate the parsed document with the provided dtd regardless of which dtd (if any) is referenced by doctype declaration (which can be handy: not every valid xml file is necessarily valid according to the dtd you want).
Because the dtd will only have to be retrieved and parsed once, this should be faster if you're validating a lot of documents), and (if I'm not mistaken), you won't run into the no_network problem.
Another bonus of this approached: you can even validate your elements/elementtrees before you've serialized them (if your producing tool uses lxml that is).
A final note: some documents can only be parsed if you have access to the dtd at parse time (unresolvable entities...). Avoid this if you can. (and, although not everyone would agree: avoid doctype declarations altogether if possible).
| Validating XML with DTD fails to import entity using lxml | I have a tool producing NewsML type XML files and I want to validate them after producing the files.
I'm receiving an error:
Attempt to load network entity http://www.w3.org/TR/ruby/xhtml-ruby-1.mod
The python call is:
parser = etree.XMLParser(load_dtd=True, dtd_validation=True)
treeObject = etree.parse(f, parser)
First I'm not sure if I need both "load_dtd=True, dtd_validation=True" but I'm using it anyway.
Second error seems to be coming from an imported nitf-3-4.dtd that's defined as:
<!ENTITY % xhtml-ruby.mod PUBLIC
"-//W3C//ELEMENTS XHTML Ruby 1.0//EN" "http://www.w3.org/TR/ruby/xhtml-ruby-1.mod">
%xhtml-ruby.mod;
Will lxml go out and retrieve this xhtml-ruby-1.mod or do I have to have all the DTD files locally.
| [
"Try constructing the parser with no_network=False. As stated in the documentation:\n\nno_network - prevent network access when looking up external documents (on by default)\n\nImported dtd modules should get retrieved by lxml, but it will not be able to do so if network access is not allowed (this does not count f... | [
4
] | [] | [] | [
"dtd",
"lxml",
"python",
"xml"
] | stackoverflow_0003874742_dtd_lxml_python_xml.txt |
Q:
Using pyinotify to watch for file creation, but waiting for it to be completely written to disk
I'm using pyinotify to watch a folder for when files are created in it. And when certain files are created I want to move them. The problem is that as soon as the file is created (obviously), my program tries to move it, even before it's completely written to disk.
Is there a way to make pyinotify wait until a file is completely written to disk before notifying me that it's been created? Or is there any easy way to, after I'm notified, make python wait to move it until it's done being written?
A:
Have pyinotify react to IN_CLOSE_WRITE events:
wm.add_watch(watched_dir, pyinotify.IN_CLOSE_WRITE, proc_fun=MyProcessEvent())
This is from man 5 incrontab, but it applies equally well to pyinotify:
IN_ACCESS File was accessed (read) (*)
IN_ATTRIB Metadata changed (permissions, timestamps, extended attributes, etc.) (*)
IN_CLOSE_WRITE File opened for writing was closed (*)
IN_CLOSE_NOWRITE File not opened for writing was closed (*)
IN_CREATE File/directory created in watched directory (*)
IN_DELETE File/directory deleted from watched directory (*)
IN_DELETE_SELF Watched file/directory was itself deleted
IN_MODIFY File was modified (*)
IN_MOVE_SELF Watched file/directory was itself moved
IN_MOVED_FROM File moved out of watched directory (*)
IN_MOVED_TO File moved into watched directory (*)
IN_OPEN File was opened (*)
A:
It is quite difficult to tell at this level if a file is being written to. What you can do is test to see if a file is opened by some other process.
1) From the various flags that are used while opening a file, O_EXLOCK flag might be of help.
If the O_EXLOCK flag is set, the file descriptor has an exclusive lock on the file.
So my understanding is if you can do os.open() with O_EXLOCK flag, it's not open by other process.
This should work on all posix compatible OS but I have not tested it. If the file, is open then you could close, wait and retry again.
2) You can also try os.stat and see changing time stamp and try to safely interpret the information. Though this is not fool proof.
3)
On unix systems, you can try "lsof"
4) The following page describes use of symlinks from /proc/PID/fd to test for open files
http://www.gossamer-threads.com/lists/python/python/639874
[Edit : Links updated]
https://launchpad.net/ubuntu/%2Bsource/lsof
A:
If you have control of the writing process, you could call the file "foo.part" while it is being written to and rename it to "foo" when it has been closed.
| Using pyinotify to watch for file creation, but waiting for it to be completely written to disk | I'm using pyinotify to watch a folder for when files are created in it. And when certain files are created I want to move them. The problem is that as soon as the file is created (obviously), my program tries to move it, even before it's completely written to disk.
Is there a way to make pyinotify wait until a file is completely written to disk before notifying me that it's been created? Or is there any easy way to, after I'm notified, make python wait to move it until it's done being written?
| [
"Have pyinotify react to IN_CLOSE_WRITE events:\nwm.add_watch(watched_dir, pyinotify.IN_CLOSE_WRITE, proc_fun=MyProcessEvent())\n\nThis is from man 5 incrontab, but it applies equally well to pyinotify:\n IN_ACCESS File was accessed (read) (*)\n IN_ATTRIB Metadata changed (permissions, times... | [
15,
1,
1
] | [] | [] | [
"file",
"linux",
"pyinotify",
"python"
] | stackoverflow_0003876348_file_linux_pyinotify_python.txt |
Q:
timeout a subprocess
I realize this might be a duplicate of Using module 'subprocess' with timeout. If it is, I apologize, just wanted to clarify something.
I'm creating a subprocess, which I want to run for a certain amount of time, and if it doesn't complete within that time, I want it to throw an error. Would something along the lines of the following code work or do we have to use a signal like answered in the other question? Thanks in advance!:
def run(self):
self.runTestCmd()
self.waitTestComplete(self.timeout)
def runTestCmd(self):
self.proc = subprocess.Popen("./configure", shell=True)
def waitTestComplete(self, timeout):
st = time.time()
while (time.time()-st) < timeout:
if self.proc.poll() == 0:
return True
else:
time.sleep(2)
raise TestError("timed out waiting for test to complete")
A:
It would, but it has a problem. The process will continue on doing whatever it is you asked it to do even after you've given up on it. You'll have to send the process a signal to kill it once you've given up on it if you really want it to stop.
Since you are spawning a new process (./configure which is presumably a configure script) that in turn creates a whole ton of sub-processes this is going to get a little more complex.
import os
def runTestCmd(self):
self.proc = subprocess.Popen(["./configure"], shell=False,
preexec_fn=os.setsid)
Then os.kill(-process.pid, signal.SIGKILL) should kill all the sub-processes. Basically what you are doing is using the preexec_fn to cause your new subprocess to acquire it's own session group. Then you are sending a signal to all processes in that session group.
Many processes that spawn subprocesses know that they need to clean up their subprocesses before they die. So it behooves you to try being nice to them if you can. Try os.signal(-process.pid, signal.SIGTERM) first, wait a second or two for the process to exit, then try SIGKILL. Something like this:
import time, os, errno, signal
def waitTestComplete(self, timeout):
st = time.time()
while (time.time()-st) < timeout:
if self.proc.poll() is not None: # 0 just means successful exit
# Only return True if process exited successfully,
# otherwise return False.
return self.proc.returncode == 0
else:
time.sleep(2)
# The process may exit between the time we check and the
# time we send the signal.
try:
os.kill(-self.proc.pid, signal.SIGTERM)
except OSError, e:
if e.errno != errno.ESRCH:
# If it's not because the process no longer exists,
# something weird is wrong.
raise
time.sleep(1)
if self.proc.poll() is None: # Still hasn't exited.
try:
os.kill(-self.proc.pid, signal.SIGKILL)
except OSError, e:
if e.errno != errno.ESRCH:
raise
raise TestError("timed out waiting for test to complete")
As a side note, never, ever use shell=True unless you know for absolute certain that's what you want. Seriously. shell=True is downright dangerous and the source of many security issues and mysterious behavior.
| timeout a subprocess | I realize this might be a duplicate of Using module 'subprocess' with timeout. If it is, I apologize, just wanted to clarify something.
I'm creating a subprocess, which I want to run for a certain amount of time, and if it doesn't complete within that time, I want it to throw an error. Would something along the lines of the following code work or do we have to use a signal like answered in the other question? Thanks in advance!:
def run(self):
self.runTestCmd()
self.waitTestComplete(self.timeout)
def runTestCmd(self):
self.proc = subprocess.Popen("./configure", shell=True)
def waitTestComplete(self, timeout):
st = time.time()
while (time.time()-st) < timeout:
if self.proc.poll() == 0:
return True
else:
time.sleep(2)
raise TestError("timed out waiting for test to complete")
| [
"It would, but it has a problem. The process will continue on doing whatever it is you asked it to do even after you've given up on it. You'll have to send the process a signal to kill it once you've given up on it if you really want it to stop.\nSince you are spawning a new process (./configure which is presumab... | [
6
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003876886_python_subprocess.txt |
Q:
Metaclass to parametrize Inheritance
I've read some tutorials on Python metaclasses. I've never used one before, but I need one for something relatively simple and all the tutorials seem geared towards much more complex use cases. I basically want to create a template class that has some pre-specified body, but takes its base class as a parameter. Since I got the idea from C++/D templates, here's an example of what the code I want to write would look like in C++:
template<class T>
class Foo : T {
void fun() {}
}
A:
Although it certainly can be done with metaclasses, you can do what you want without them because in Python classes are themselves objects. The means that—surprisingly—essentially nothing more than an almost one-to-one translation of the C++ code is required. Besides being relatively uncomplicated because of this, it'll also work without modification in both Python 2 & 3.
def template(class_T):
"""Factory function to create subclasses of class_T."""
class Foo(class_T):
def fun(self):
print('%s.fun()' % self.__class__.__name__)
Foo.__name__ += '_' + class_T.__name__ # rename the subclass to reflect its heritage
return Foo
class Base1:
def bar(self):
print('Base1.bar()')
class Base2:
def bar(self):
print('Base2.bar()')
Foo_Base1 = template(Base1)
print('Foo_Base1 base classes: {}'.format(Foo_Base1.__bases__))
Foo_Base2 = template(Base2)
print('Foo_Base2 base classes: {}'.format(Foo_Base2.__bases__))
subclass1 = Foo_Base1()
subclass1.fun()
subclass1.bar()
subclass2 = Foo_Base2()
subclass2.fun()
subclass2.bar()
Output:
Foo_Base1 base classes: (<class __main__.Base1 at 0x00A79C38>,)
Foo_Base2 base classes: (<class __main__.Base2 at 0x00A79DC0>,)
Foo_Base1.fun()
Base1.bar()
Foo_Base2.fun()
Base2.bar()
The code in the (unimaginatively-named) template() function is an example of what is commonly called a class factory or an implementation of the Factory pattern. So, incidentally, you might find my answer to the question What exactly is a Class Factory? informative.
Edit: Added code to create different class names for each subclass returned—which was inspired by @aaronasterling's insight (in a now deleted comment) about potential confusion when debugging if the class manufactured always has the same name.
A:
This is meaningless in Python, since it does not have templates. My understanding of parameterized templates in C++ (which is rather vague, since it is many years since I have looked at them), is that it acts like a class factory, and can create a subclass of whatever class you give it that has additional methods or attributes added.
In Python you can do this with a factory function that takes a class and returns a new class at runtime:
In [1]: def subclassFactory(cls):
...: class Foo(cls):
...: def fun(self):
...: return "this is fun"
...: return Foo
...:
In [2]: class A(object):
...: pass
...:
In [5]: C = subclassFactory(A)
In [6]: C
Out[6]: <class '__main__.Foo'>
In [7]: c = C()
In [9]: c.fun()
Out[9]: 'this is fun'
In [10]: isinstance(c, A)
Out[10]: True
| Metaclass to parametrize Inheritance | I've read some tutorials on Python metaclasses. I've never used one before, but I need one for something relatively simple and all the tutorials seem geared towards much more complex use cases. I basically want to create a template class that has some pre-specified body, but takes its base class as a parameter. Since I got the idea from C++/D templates, here's an example of what the code I want to write would look like in C++:
template<class T>
class Foo : T {
void fun() {}
}
| [
"Although it certainly can be done with metaclasses, you can do what you want without them because in Python classes are themselves objects. The means that—surprisingly—essentially nothing more than an almost one-to-one translation of the C++ code is required. Besides being relatively uncomplicated because of this,... | [
10,
0
] | [] | [] | [
"c++",
"metaclass",
"metaprogramming",
"python",
"templates"
] | stackoverflow_0003876921_c++_metaclass_metaprogramming_python_templates.txt |
Q:
Why does id({}) == id({}) and id([]) == id([]) in CPython?
Why does CPython (no clue about other Python implementations) have the following behavior?
tuple1 = ()
tuple2 = ()
dict1 = {}
dict2 = {}
list1 = []
list2 = []
# makes sense, tuples are immutable
assert(id(tuple1) == id(tuple2))
# also makes sense dicts are mutable
assert(id(dict1) != id(dict2))
# lists are mutable too
assert(id(list1) != id(list2))
assert(id(()) == id(()))
# why no assertion error on this?
assert(id({}) == id({}))
# or this?
assert(id([]) == id([]))
I have a few ideas why it may, but can't find a concrete reason why.
EDIT
To further prove Glenn's and Thomas' point:
[1] id([])
4330909912
[2] x = []
[3] id(x)
4330909912
[4] id([])
4334243440
A:
When you call id({}), Python creates a dict and passes it to the id function. The id function takes its id (its memory location), and throws away the dict. The dict is destroyed. When you do it twice in quick succession (without any other dicts being created in the mean time), the dict Python creates the second time happens to use the same block of memory as the first time. (CPython's memory allocator makes that a lot more likely than it sounds.) Since (in CPython) id uses the memory location as the object id, the id of the two objects is the same. This obviously doesn't happen if you assign the dict to a variable and then get its id(), because the dicts are alive at the same time, so their id has to be different.
Mutability does not directly come into play, but code objects caching tuples and strings do. In the same code object (function or class body or module body) the same literals (integers, strings and certain tuples) will be re-used. Mutable objects can never be re-used, they're always created at runtime.
In short, an object's id is only unique for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id.
A:
CPython is garbage collecting objects as soon as they go out of scope, so the second [] is created after the first [] is collected. So, most of the time it ends up in the same memory location.
This shows what's happening very clearly (the output is likely to be different in other implementations of Python):
class A:
def __init__(self): print("a")
def __del__(self): print("b")
# a a b b False
print(A() is A())
# a b a b True
print(id(A()) == id(A()))
| Why does id({}) == id({}) and id([]) == id([]) in CPython? | Why does CPython (no clue about other Python implementations) have the following behavior?
tuple1 = ()
tuple2 = ()
dict1 = {}
dict2 = {}
list1 = []
list2 = []
# makes sense, tuples are immutable
assert(id(tuple1) == id(tuple2))
# also makes sense dicts are mutable
assert(id(dict1) != id(dict2))
# lists are mutable too
assert(id(list1) != id(list2))
assert(id(()) == id(()))
# why no assertion error on this?
assert(id({}) == id({}))
# or this?
assert(id([]) == id([]))
I have a few ideas why it may, but can't find a concrete reason why.
EDIT
To further prove Glenn's and Thomas' point:
[1] id([])
4330909912
[2] x = []
[3] id(x)
4330909912
[4] id([])
4334243440
| [
"When you call id({}), Python creates a dict and passes it to the id function. The id function takes its id (its memory location), and throws away the dict. The dict is destroyed. When you do it twice in quick succession (without any other dicts being created in the mean time), the dict Python creates the second ti... | [
45,
42
] | [
"The == operator on lists and dicts do not compare the object IDs to see if they the same object - use obj1 is obj2 for that.\nInstead the == operator compares the members of the list of dict to see if they are the same. \n"
] | [
-6
] | [
"cpython",
"identity",
"python",
"python_internals"
] | stackoverflow_0003877230_cpython_identity_python_python_internals.txt |
Q:
Python - question about decimal arithmetic
I have 3 questions pertaining to decimal arithmetic in Python, all 3 of which are best asked inline:
1)
>>> from decimal import getcontext, Decimal
>>> getcontext().prec = 6
>>> Decimal('50.567898491579878') * 1
Decimal('50.5679')
>>> # How is this a precision of 6? If the decimal counts whole numbers as
>>> # part of the precision, is that actually still precision?
>>>
and
2)
>>> from decimal import getcontext, Decimal
>>> getcontext().prec = 6
>>> Decimal('50.567898491579878')
Decimal('50.567898491579878')
>>> # Shouldn't that have been rounded to 6 digits on instantiation?
>>> Decimal('50.567898491579878') * 1
Decimal('50.5679')
>>> # Instead, it only follows my precision setting set when operated on.
>>>
3)
>>> # Now I want to save the value to my database as a "total" with 2 places.
>>> from decimal import Decimal
>>> # Is the following the correct way to get the value into 2 decimal places,
>>> # or is there a "better" way?
>>> x = Decimal('50.5679').quantize(Decimal('0.00'))
>>> x # Just wanted to see what the value was
Decimal('50.57')
>>> foo_save_value_to_db(x)
>>>
A:
Precision follows sig figs, not fractional digits. The former is more useful in scientific applications.
Raw data should never be mangled. Instead it does the mangling when operated upon.
This is how it's done.
| Python - question about decimal arithmetic | I have 3 questions pertaining to decimal arithmetic in Python, all 3 of which are best asked inline:
1)
>>> from decimal import getcontext, Decimal
>>> getcontext().prec = 6
>>> Decimal('50.567898491579878') * 1
Decimal('50.5679')
>>> # How is this a precision of 6? If the decimal counts whole numbers as
>>> # part of the precision, is that actually still precision?
>>>
and
2)
>>> from decimal import getcontext, Decimal
>>> getcontext().prec = 6
>>> Decimal('50.567898491579878')
Decimal('50.567898491579878')
>>> # Shouldn't that have been rounded to 6 digits on instantiation?
>>> Decimal('50.567898491579878') * 1
Decimal('50.5679')
>>> # Instead, it only follows my precision setting set when operated on.
>>>
3)
>>> # Now I want to save the value to my database as a "total" with 2 places.
>>> from decimal import Decimal
>>> # Is the following the correct way to get the value into 2 decimal places,
>>> # or is there a "better" way?
>>> x = Decimal('50.5679').quantize(Decimal('0.00'))
>>> x # Just wanted to see what the value was
Decimal('50.57')
>>> foo_save_value_to_db(x)
>>>
| [
"\nPrecision follows sig figs, not fractional digits. The former is more useful in scientific applications.\nRaw data should never be mangled. Instead it does the mangling when operated upon.\nThis is how it's done.\n\n"
] | [
8
] | [] | [] | [
"decimal",
"math",
"python"
] | stackoverflow_0003877299_decimal_math_python.txt |
Q:
How to parallelize this situation with robots
I'm working on a robotic problem. The situation is something like this:
There are N number of robots (generally N>100) initially all at rest.
Each robot attracts all other robots which are with in its radius r.
I've set of equations with which I can compute acceleration, velocity & hence the position of the robot after time deltat. Simply put, I can find the position of each robot after deltat time.
All I need to do is for a given deltat. I need to display position of each robot for every deltat.
Problem is actually very simple. Algo will be something like:
del_t = ;its given
initialPositions = ;its given
num_robots = ;its given
The following code executes for every del_t
robots = range(1,no_robots)
for R in robots:
for r in robots:
if distanceBetween(r,R) <= radius and r is not R:
acceleration_along_X[R] += xAcceleration( position(r), position(R) )
acceleration_along_Y[R] += yAcceleration( position(r), position(R) )
currVelocity_along_X[R] = prevVelocity_along_X[R] + acceleration_along_X[R] * del_t
currVelocity_along_Y[R] = prevVelocity_along_Y[R] + acceleration_along_Y[R] * del_t
curr_X_coordinate[R] = prev_X_coordinate[R] + currVelocity_along_X[R] * del_t
curr_Y_coordinate[R] = prev_Y_coordinate[R] + currVelocity_along_Y[R] * del_t
print 'Position of robot ' + str(R) + ' is (' + curr_X_coordinate[R] + ', ' + curr_Y_coordinate[R] +' ) \n'
prev_X_coordinate[R] = curr_X_coordinate[R]
prev_Y_coordinate[R] = curr_Y_coordinate[R]
prevVelocity_along_X[R] = currVelocity_along_X[R]
prevVelocity_along_Y[R] = currVelocity_along_Y[R]
Now I need to parallelize the algorithm and set up the Cartesian grid of MPI processes.
Because computation for each robot is an independent task. computation for each Robot
can be done by an independent thread. Right?
I don't know anything about MPI. What does this "Cartesian grid of MPI processes" mean? How can I setup this grid? I've no clue about this.
EDIT:
Now the problem turned interesting. Actually, it isn't as simple as I thought. After reading Unode's answer. I went on to apply his method two by parallelizing using multiprocessing.
This is the code. printPositionOfRobot is my serial algo. Basically, it is supposed to print the position of robot (with id robot_id) t=1,2,3,4,5,6,7,8,9,10. (Here del_t is taken as 1. num_iterations = 10. Each of the robot prints message like this: Robot8 : Position at t = 9 is (21.1051065245, -53.8757356694 )
There is bug in this code. t=0 locations of bots are given by position() for determining xAcceleration & yAcceleration. We need use the positions of previous iterations of all other particles.
from multiprocessing import Pool
import math
def printPositionOfRobot(robot_id):
radius = 3
del_t = 1
num_iterations = 10
no_robots = 10
prevVelocity_along_X = 0
prevVelocity_along_Y = 0
acceleration_along_X = 0
acceleration_along_Y = 0
(prev_X_coordinate,prev_Y_coordinate) = position(robot_id)#!!it should call initialPosition()
for i in range(1,num_iterations+1):
for r in range(no_robots):
if distanceBetween(r,robot_id) <= radius and r is not robot_id:
acceleration_along_X += xAcceleration( position(r), position(robot_id) ) #!! Problem !!
acceleration_along_Y += yAcceleration( position(r), position(robot_id) )#!! Problem !!
currVelocity_along_X = prevVelocity_along_X + acceleration_along_X * del_t
currVelocity_along_Y = prevVelocity_along_Y + acceleration_along_Y * del_t
curr_X_coordinate = prev_X_coordinate + currVelocity_along_X * del_t
curr_Y_coordinate = prev_Y_coordinate + currVelocity_along_Y * del_t
print 'Robot' + str(robot_id) + ' : Position at t = '+ str(i*del_t) +' is (' + str(curr_X_coordinate) + ', ' + str(curr_Y_coordinate) +' ) \n'
prev_X_coordinate = curr_X_coordinate
prev_Y_coordinate = curr_Y_coordinate
prevVelocity_along_X = currVelocity_along_X
prevVelocity_along_Y = currVelocity_along_Y
def xAcceleration((x1,y1),(x2,y2)):
s = distance((x1,y1),(x2,y2))
return 12*(x2-x1)*( pow(s,-15) - pow(s,-7) + 0.00548*s )
def yAcceleration((x1,y1),(x2,y2)):
s = distance((x1,y1),(x2,y2))
return 12*(y2-y1)*( pow(s,-15) - pow(s,-7) + 0.00548*s )
def distanceBetween(r,robot_id):
return distance(position(r), position(robot_id))
def distance((x1,y1),(x2,y2)):
return math.sqrt( (x2-x1)**2 + (y2-y1)**2 )
def Position(r): #!!name of this function should be initialPosition
k = [(-8.750000,6.495191) , (-7.500000,8.660254) , (-10.000000,0.000000) , (-8.750000,2.165064) , (-7.500000,4.330127) , (-6.250000,6.495191) , (-5.000000,8.660254) , (-10.000000,-4.330127) , (-8.750000,-2.165064) , (-7.500000,0.000000) ]
return k[r]
if __name__ == "__main__":
no_robots = 10 # Number of robots you need
p = Pool(no_robots) # Spawn a pool of processes (one per robot in this case)
p.map(printPositionOfRobot, range(no_robots))
the position function in acceleration_along_X & acceleration_along_Y should return the latest position of the robot.By latest I mean the position at the end of that previous iteration. So, each processes must inform other processes about its latest position. Until the latest position of the bot is know the process must wait.
Other way can be that all processes edit a global location.(I wonder if its possible, because each process have its own Virtual address space). If a process has not yet reached that iteration all other processes must wait.
Any ideas about how to go about it? I guess this is why MPI was suggested in the problem.
A:
Note: Python's threads still run on the same processor. If you want to use the full range of processors of your machine you should use multiprocessing (python2.6+).
Using MPI will only bring you clear benefits if the computation is going to be spread over multiple computers.
There are two approaches to your problem. Since you have completely independent processes, you could simply launch the algorithm (passing a unique identifier for each robot) as many times as needed and let the operating system handle the concurrency.
1 - A short Linux shell script (or something equivalent in Windows BATCH language):
#!/bin/sh
for i in {0..99}; do
echo "Running $i"
python launch.py $i &
done
Note: the & after the launch.py this ensures that you actually launch all processes in consecutive way, rather than waiting for one to finish and then launch the next one.
2 - If instead you want to do it all in python, you can use the following simple parallelization approach:
from multiprocessing import Pool
def your_algorithm(robot_id):
print(robot_id)
if __name__ == "__main__":
robots = 100 # Number of robots you need
p = Pool(robots) # Spawn a pool of processes (one per robot in this case)
p.map(your_algorithm, range(robots))
The map function takes care of dispatching one independent operation per robot.
If you do require the use of MPI I suggest mpi4py.
As for information on what Cartesian grid stands for, try this
A:
So the trick here is that at each step, all of the robots have to see the data at some point from all the other robots. This makes efficient parallelizations hard!
One simple approach is to have each process chuging away on its own robots, calculating the self-interactions first, then getting one by one the data from the other processors and calculating those forces. Note that this is not the only approach! Also, real-world solvers for this sort of thing (molecular dynamics, or most astrophsical N-body simulations) take a different tack entirely, treating distant objects only approximately since far away objects don't matter as much as near ones.
Below is a simple python implementation of that approach using two mpi processes (using mpi4py and matplotlib/pylab for plotting). The generalization of this would be a pipeline; each processor sends its chunk of data to the next neighbour, does the force calcs, and this process repeats until everyone has seen everyone's data. Ideally you'd update plot as the pipeline progressed, so that no one has to have all of the data in memory at once.
You'd run this program with mpirun -np 2 ./robots.py ; note that you need the MPI libraries installed, and then the mpi4py needs to know where to find these libraries.
Note too that I'm being very wasteful in sending all of the robot data along to the neighbour; all the neighbour cares about is the positions.
#!/usr/bin/env python
import numpy
import pylab
from mpi4py import MPI
class Robot(object):
def __init__(self, id, x, y, vx, vy, mass):
self.id = id
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.ax = 0.
self.ay = 0.
self.mass = mass
def rPrint(self):
print "Robot ",self.id," at (",self.x,",",self.y,")"
def interact(self, robot2):
dx = (self.x-robot2.x)
dy = (self.y-robot2.y)
eps = 0.25
idist3 = numpy.power(numpy.sqrt(dx*dx +dy*dy + eps*eps),-3)
numerator = -self.mass*robot2.mass
self.ax += numerator*dx*idist3
self.ay += numerator*dy*idist3
robot2.ax -= numerator*dx*idist3
robot2.ay -= numerator*dy*idist3
def updatePos(self, dt):
self.x += 0.5*self.vx*dt
self.y += 0.5*self.vy*dt
self.vx += self.ax*dt
self.vy += self.ay*dt
self.x += 0.5*self.vx*dt
self.y += 0.5*self.vy*dt
self.ax = 0.
self.ay = 0.
def init(nRobots):
myRobotList = []
vx = 0.
vy = 0.
mass = 1.
for i in range(nRobots):
randpos = numpy.random.uniform(-3,+3,2)
rx = randpos[0]
ry = randpos[1]
myRobotList.append(Robot(i, rx, ry, vx, vy, mass))
return myRobotList
def selfForces(robotList):
nRobots = len(robotList)
for i in range(nRobots-1):
for j in range (i+1, nRobots):
robotList[i].interact(robotList[j])
def otherRobotForces(myRobotList, otherRobotList):
for i in myRobotList:
for j in otherRobotList:
i.interact(j)
def plotRobots(robotList):
xl = []
yl = []
vxl = []
vyl = []
for i in robotList:
xl.append(i.x)
yl.append(i.y)
vxl.append(i.vx)
vyl.append(i.vy)
pylab.subplot(1,1,1)
pylab.plot(xl,yl,'o')
pylab.quiver(xl,yl,vxl,vyl)
pylab.show()
if __name__ == "__main__":
comm = MPI.COMM_WORLD
nprocs = comm.Get_size()
rank = comm.Get_rank()
if (nprocs != 2):
print "Only doing this for 2 for now.."
sys.exit(-1)
neigh = (rank + 1) % nprocs
robotList = init(50)
for i in range (10):
print "[",rank,"] Doing step ", i
selfForces(robotList)
request = comm.isend(robotList, dest=neigh, tag=11)
otherRobotList = comm.recv(source=neigh, tag=11)
otherRobotForces(robotList,otherRobotList)
request.Wait()
for r in robotList:
r.updatePos(0.05)
if (rank == 0):
print "plotting Robots"
plotRobots(robotList + otherRobotList)
A:
My solution too I similar to Unode but I prefer using apply_async method in multiprocessing as it's asynchronous.
from multiprocessing import Pool
def main():
po = Pool(100) #subprocesses
po.apply_async(function_to_execute, (function_params,), callback=after_processing)
po.close() #close all processes
po.join() #join the output of all processes
return
| How to parallelize this situation with robots | I'm working on a robotic problem. The situation is something like this:
There are N number of robots (generally N>100) initially all at rest.
Each robot attracts all other robots which are with in its radius r.
I've set of equations with which I can compute acceleration, velocity & hence the position of the robot after time deltat. Simply put, I can find the position of each robot after deltat time.
All I need to do is for a given deltat. I need to display position of each robot for every deltat.
Problem is actually very simple. Algo will be something like:
del_t = ;its given
initialPositions = ;its given
num_robots = ;its given
The following code executes for every del_t
robots = range(1,no_robots)
for R in robots:
for r in robots:
if distanceBetween(r,R) <= radius and r is not R:
acceleration_along_X[R] += xAcceleration( position(r), position(R) )
acceleration_along_Y[R] += yAcceleration( position(r), position(R) )
currVelocity_along_X[R] = prevVelocity_along_X[R] + acceleration_along_X[R] * del_t
currVelocity_along_Y[R] = prevVelocity_along_Y[R] + acceleration_along_Y[R] * del_t
curr_X_coordinate[R] = prev_X_coordinate[R] + currVelocity_along_X[R] * del_t
curr_Y_coordinate[R] = prev_Y_coordinate[R] + currVelocity_along_Y[R] * del_t
print 'Position of robot ' + str(R) + ' is (' + curr_X_coordinate[R] + ', ' + curr_Y_coordinate[R] +' ) \n'
prev_X_coordinate[R] = curr_X_coordinate[R]
prev_Y_coordinate[R] = curr_Y_coordinate[R]
prevVelocity_along_X[R] = currVelocity_along_X[R]
prevVelocity_along_Y[R] = currVelocity_along_Y[R]
Now I need to parallelize the algorithm and set up the Cartesian grid of MPI processes.
Because computation for each robot is an independent task. computation for each Robot
can be done by an independent thread. Right?
I don't know anything about MPI. What does this "Cartesian grid of MPI processes" mean? How can I setup this grid? I've no clue about this.
EDIT:
Now the problem turned interesting. Actually, it isn't as simple as I thought. After reading Unode's answer. I went on to apply his method two by parallelizing using multiprocessing.
This is the code. printPositionOfRobot is my serial algo. Basically, it is supposed to print the position of robot (with id robot_id) t=1,2,3,4,5,6,7,8,9,10. (Here del_t is taken as 1. num_iterations = 10. Each of the robot prints message like this: Robot8 : Position at t = 9 is (21.1051065245, -53.8757356694 )
There is bug in this code. t=0 locations of bots are given by position() for determining xAcceleration & yAcceleration. We need use the positions of previous iterations of all other particles.
from multiprocessing import Pool
import math
def printPositionOfRobot(robot_id):
radius = 3
del_t = 1
num_iterations = 10
no_robots = 10
prevVelocity_along_X = 0
prevVelocity_along_Y = 0
acceleration_along_X = 0
acceleration_along_Y = 0
(prev_X_coordinate,prev_Y_coordinate) = position(robot_id)#!!it should call initialPosition()
for i in range(1,num_iterations+1):
for r in range(no_robots):
if distanceBetween(r,robot_id) <= radius and r is not robot_id:
acceleration_along_X += xAcceleration( position(r), position(robot_id) ) #!! Problem !!
acceleration_along_Y += yAcceleration( position(r), position(robot_id) )#!! Problem !!
currVelocity_along_X = prevVelocity_along_X + acceleration_along_X * del_t
currVelocity_along_Y = prevVelocity_along_Y + acceleration_along_Y * del_t
curr_X_coordinate = prev_X_coordinate + currVelocity_along_X * del_t
curr_Y_coordinate = prev_Y_coordinate + currVelocity_along_Y * del_t
print 'Robot' + str(robot_id) + ' : Position at t = '+ str(i*del_t) +' is (' + str(curr_X_coordinate) + ', ' + str(curr_Y_coordinate) +' ) \n'
prev_X_coordinate = curr_X_coordinate
prev_Y_coordinate = curr_Y_coordinate
prevVelocity_along_X = currVelocity_along_X
prevVelocity_along_Y = currVelocity_along_Y
def xAcceleration((x1,y1),(x2,y2)):
s = distance((x1,y1),(x2,y2))
return 12*(x2-x1)*( pow(s,-15) - pow(s,-7) + 0.00548*s )
def yAcceleration((x1,y1),(x2,y2)):
s = distance((x1,y1),(x2,y2))
return 12*(y2-y1)*( pow(s,-15) - pow(s,-7) + 0.00548*s )
def distanceBetween(r,robot_id):
return distance(position(r), position(robot_id))
def distance((x1,y1),(x2,y2)):
return math.sqrt( (x2-x1)**2 + (y2-y1)**2 )
def Position(r): #!!name of this function should be initialPosition
k = [(-8.750000,6.495191) , (-7.500000,8.660254) , (-10.000000,0.000000) , (-8.750000,2.165064) , (-7.500000,4.330127) , (-6.250000,6.495191) , (-5.000000,8.660254) , (-10.000000,-4.330127) , (-8.750000,-2.165064) , (-7.500000,0.000000) ]
return k[r]
if __name__ == "__main__":
no_robots = 10 # Number of robots you need
p = Pool(no_robots) # Spawn a pool of processes (one per robot in this case)
p.map(printPositionOfRobot, range(no_robots))
the position function in acceleration_along_X & acceleration_along_Y should return the latest position of the robot.By latest I mean the position at the end of that previous iteration. So, each processes must inform other processes about its latest position. Until the latest position of the bot is know the process must wait.
Other way can be that all processes edit a global location.(I wonder if its possible, because each process have its own Virtual address space). If a process has not yet reached that iteration all other processes must wait.
Any ideas about how to go about it? I guess this is why MPI was suggested in the problem.
| [
"Note: Python's threads still run on the same processor. If you want to use the full range of processors of your machine you should use multiprocessing (python2.6+).\nUsing MPI will only bring you clear benefits if the computation is going to be spread over multiple computers.\nThere are two approaches to your prob... | [
2,
1,
0
] | [] | [] | [
"mpi",
"parallel_processing",
"python"
] | stackoverflow_0003875036_mpi_parallel_processing_python.txt |
Q:
Named replaces in strings with Mako
When creating a template in Mako, I would need to write things like : ${_('Hello, %(fname)s %(lname)s') % {'fname':'John','lname':'Doe'}}
I keep getting SyntaxException: (SyntaxError) unexpected EOF while parsing when writing that. Is there wny way to do the same ?
${_('Hello, %s %s') % ('John', 'Doe')} works, but it does not allow to change the order of the replacements when changing language, if needed.
Thanks.
A:
Using {} inside Mako's ${} is complicated; apparently Mako stops parsing the expression after finding the first }. A possible workaround is to use dict() instead of {}:
${_('Hello, %(fname)s %(lname)s') % dict(fname='John', lname='Doe')}
A:
Try the new Python string formatting:
>>> "{foo} {bar}".format(foo="foo", bar="bar")
'foo bar'
>>> "{foo} {bar}".format(**{"foo": "Hello", "bar": "World!"})
'Hello World!'
It looks nicer and is futureproof.
| Named replaces in strings with Mako | When creating a template in Mako, I would need to write things like : ${_('Hello, %(fname)s %(lname)s') % {'fname':'John','lname':'Doe'}}
I keep getting SyntaxException: (SyntaxError) unexpected EOF while parsing when writing that. Is there wny way to do the same ?
${_('Hello, %s %s') % ('John', 'Doe')} works, but it does not allow to change the order of the replacements when changing language, if needed.
Thanks.
| [
"Using {} inside Mako's ${} is complicated; apparently Mako stops parsing the expression after finding the first }. A possible workaround is to use dict() instead of {}:\n${_('Hello, %(fname)s %(lname)s') % dict(fname='John', lname='Doe')}\n\n",
"Try the new Python string formatting:\n>>> \"{foo} {bar}\".format(... | [
2,
0
] | [] | [] | [
"mako",
"python"
] | stackoverflow_0003875520_mako_python.txt |
Q:
I embedded a matplotlib graph of a sphere into Tkinter, and can no longer orbit it!
I embedded a matplotlib graph of a sphere into Tkinter. Now for some reason I've lost the ability to orbit the object, when dragging the mouse. Anyone have an idea of why this happened and how to fix this?
#!/usr/bin/env python
import matplotlib
matplotlib.use('TkAgg')
from mpl_toolkits.mplot3d import axes3d,Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter
import Tkinter
import sys
class E(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.protocol("WM_DELETE_WINDOW", self.dest)
self.main()
def main(self):
self.fig = plt.figure()
self.fig = plt.figure(figsize=(3.5,3.5))
ax = Axes3D(self.fig)
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
t = ax.plot_surface(x, y, z, rstride=4, cstride=4,color='lightgreen',linewidth=0)
self.frame = Tkinter.Frame(self)
self.frame.pack(padx=15,pady=15)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame)
self.canvas.get_tk_widget().pack(side='top', fill='both')
self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)
self.toolbar = NavigationToolbar2TkAgg( self.canvas, self )
self.toolbar.update()
self.toolbar.pack()
self.btn = Tkinter.Button(self,text='button',command=self.alt)
self.btn.pack(ipadx=250)
def alt (self):
print 9
def dest(self):
self.destroy()
sys.exit()
if __name__ == "__main__":
app = E(None)
app.title('Embedding in TK')
app.mainloop()
A:
You need to setup your canvas before you plot, so move the block of code below to after this line self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)
#Move this Code
ax = Axes3D(self.fig)
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
t = ax.plot_surface(x, y, z, rstride=4, cstride=4,color='lightgreen',linewidth=0)
| I embedded a matplotlib graph of a sphere into Tkinter, and can no longer orbit it! | I embedded a matplotlib graph of a sphere into Tkinter. Now for some reason I've lost the ability to orbit the object, when dragging the mouse. Anyone have an idea of why this happened and how to fix this?
#!/usr/bin/env python
import matplotlib
matplotlib.use('TkAgg')
from mpl_toolkits.mplot3d import axes3d,Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter
import Tkinter
import sys
class E(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.protocol("WM_DELETE_WINDOW", self.dest)
self.main()
def main(self):
self.fig = plt.figure()
self.fig = plt.figure(figsize=(3.5,3.5))
ax = Axes3D(self.fig)
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
t = ax.plot_surface(x, y, z, rstride=4, cstride=4,color='lightgreen',linewidth=0)
self.frame = Tkinter.Frame(self)
self.frame.pack(padx=15,pady=15)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame)
self.canvas.get_tk_widget().pack(side='top', fill='both')
self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)
self.toolbar = NavigationToolbar2TkAgg( self.canvas, self )
self.toolbar.update()
self.toolbar.pack()
self.btn = Tkinter.Button(self,text='button',command=self.alt)
self.btn.pack(ipadx=250)
def alt (self):
print 9
def dest(self):
self.destroy()
sys.exit()
if __name__ == "__main__":
app = E(None)
app.title('Embedding in TK')
app.mainloop()
| [
"You need to setup your canvas before you plot, so move the block of code below to after this line self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)\n #Move this Code \n ax = Axes3D(self.fig)\n u = np.linspace(0, 2 * np.pi, 100)\n v = np.linspace(0, np.pi, 100)\n x = 1... | [
4
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0003877411_matplotlib_python_tkinter.txt |
Q:
Regex find numbers in specific position
hi i have a string like this
track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false;
i want to use some regular expression so i would end up with groups
pid = 1234
p1 = 21
p2 = 4343
A:
import re
s = "track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false;"
pattern = re.compile(r'.*lisen\((?P<pid>\d+),\s*(?P<p1>\d+),\s*(?P<p2>\d+)\).*')
pid, p1, p2 = map(int, pattern.match(s).groups())
Note: I used named capturing groups, but that is not necessary in this case.
A:
Why regular expression? you can do it will simple string manipulations
>>> s="track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false;"
>>> s.split("lisen(")[-1].split(")")[0].split(",")
['1234', ' 21', ' 4343']
| Regex find numbers in specific position | hi i have a string like this
track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false;
i want to use some regular expression so i would end up with groups
pid = 1234
p1 = 21
p2 = 4343
| [
"import re\n\ns = \"track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false;\"\n\npattern = re.compile(r'.*lisen\\((?P<pid>\\d+),\\s*(?P<p1>\\d+),\\s*(?P<p2>\\d+)\\).*')\n\npid, p1, p2 = map(int, pattern.match(s).groups())\n\nNote: I used named capturing groups, but that is not necessary in thi... | [
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003875475_python_regex.txt |
Q:
Google App Engine (Python)- Strange behaviour of REMOTE_ADDR
In order to make the registration process on my website easy, I allow users to enter their email address which I will send a verification code to or alternatively they can solve a captcha.
The problem is that in order to prevent robots from registering accounts (with fake emails) I limit the number of registrations allowed per IP address and if this limit is exceeded I trigger a warning in the logs.
However ... what seems to be happening is that I am using os.environ['REMOTE_ADDR'] to check the remote address -- but it seems that I am triggering warnings on addresses that are owned by Google (66.249.65.XXX). It is possible that this is happening only after I change the version (but not confirmed). Does anyone know how/why this might be happening? Shouldn't the REMOTE_ADDR return the address of the client computer (and hopefully in all cases it would do this)?
I am curious if there is some behind the scenes re-directions going on, and if this is a normal event or if it only happens when a new version is installed (perhaps when a new version is installed the original server then proxies the user to the new server, therefore creating the illusion that the IP address is an internal IP?)
A:
I believe that I have figured out the reason for seeing so many warnings from google server IP addresses. It seems that immediately after a new user registers, the google crawlers are going to the same (registration) webpage (which I send information to as a GET instead of a POST for reasons which I will not get into). Of course, since many users are registering, but there are only a few crawler computers that are checking periodic updates to my website, I am triggering warning messages that a particular (google) IP is accessing a registration area repeatedly.
| Google App Engine (Python)- Strange behaviour of REMOTE_ADDR | In order to make the registration process on my website easy, I allow users to enter their email address which I will send a verification code to or alternatively they can solve a captcha.
The problem is that in order to prevent robots from registering accounts (with fake emails) I limit the number of registrations allowed per IP address and if this limit is exceeded I trigger a warning in the logs.
However ... what seems to be happening is that I am using os.environ['REMOTE_ADDR'] to check the remote address -- but it seems that I am triggering warnings on addresses that are owned by Google (66.249.65.XXX). It is possible that this is happening only after I change the version (but not confirmed). Does anyone know how/why this might be happening? Shouldn't the REMOTE_ADDR return the address of the client computer (and hopefully in all cases it would do this)?
I am curious if there is some behind the scenes re-directions going on, and if this is a normal event or if it only happens when a new version is installed (perhaps when a new version is installed the original server then proxies the user to the new server, therefore creating the illusion that the IP address is an internal IP?)
| [
"I believe that I have figured out the reason for seeing so many warnings from google server IP addresses. It seems that immediately after a new user registers, the google crawlers are going to the same (registration) webpage (which I send information to as a GET instead of a POST for reasons which I will not get i... | [
0
] | [] | [] | [
"google_app_engine",
"ip_address",
"python"
] | stackoverflow_0003877631_google_app_engine_ip_address_python.txt |
Q:
Help editing a picture in python
I have to suppose I'm given a picture, there shouldnt be any user inputs or calls to media.chose file, so given a picture return the average red value of all the Pixels in that Picture (as an int). If the average calculation results in a non-integer value, then truncate the result. For example, if you average the values 10, 6 and 4, the result would be 6.
A:
The question is almost answered here
How can I read the RGB value of a given pixel in Python?
Use PIL to load the image, read it pixel by pixel and do your calculation.
A:
Python Imaging Library
| Help editing a picture in python | I have to suppose I'm given a picture, there shouldnt be any user inputs or calls to media.chose file, so given a picture return the average red value of all the Pixels in that Picture (as an int). If the average calculation results in a non-integer value, then truncate the result. For example, if you average the values 10, 6 and 4, the result would be 6.
| [
"The question is almost answered here \n\nHow can I read the RGB value of a given pixel in Python?\n\nUse PIL to load the image, read it pixel by pixel and do your calculation.\n",
"Python Imaging Library\n"
] | [
1,
0
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0003877878_image_processing_python.txt |
Q:
Determine if a dice roll contains certain combinations?
I am writing a dice game simulator in Python. I represent a roll by using a list containing integers from 1-6. So I might have a roll like this:
[1,2,1,4,5,1]
I need to determine if a roll contains scoring combinations, such as 3 of a kind, 4 of a kind, 2 sets of 3, and straights.
Is there a simple Pythonic way of doing this? I've tried several approaches, but they all have turned out to be messy.
A:
Reorganize into a dict with value: count and test for presence of various patterns.
A:
There are two ways to do this:
def getCounts(L):
d = {}
for i in range(1, 7):
d[i] = L.count(i)
return d # d is the dictionary which contains the occurrences of all possible dice values
# and has a 0 if it doesn't occur in th roll
This one is inspired by Ignacio Vazquez-Abrams and dkamins
def getCounts(L):
d = {}
for i in set(L):
d[i] = L.count(i)
return d # d is the dictionary which contains the occurrences of
# all and only the values in the roll
A:
I have written code like this before (but with cards for poker). A certain amount of code-sprawl is unavoidable to encode all of the rules of the game. For example, the code to look for n-of-a-kind will be completely different from the code to look for a straight.
Let's consider n-of-a-kind first. As others have suggested, create a dict containing the counts of each element. Then:
counts = sorted(d.values())
if counts[-1] == 4:
return four_of_a_kind
if counts[-1] and counts[-2] == 3:
return two_sets_of_three
# etc.
Checking for straights requires a different approach. When checking for n-of-a-kind, you need to get the counts and ignore the values. Now we need to examine the values and ignore the counts:
ranks = set(rolls)
if len(ranks) == 6: # all six values are present
return long_straight
# etc.
In general, you should be able to identify rules with a similar flavor, abstract out code that helps with those kinds of rules, and then write just a few lines per rule. Some rules may be completely unique and will not be able to share code with other rules. That's just the way the cookie crumbles.
| Determine if a dice roll contains certain combinations? | I am writing a dice game simulator in Python. I represent a roll by using a list containing integers from 1-6. So I might have a roll like this:
[1,2,1,4,5,1]
I need to determine if a roll contains scoring combinations, such as 3 of a kind, 4 of a kind, 2 sets of 3, and straights.
Is there a simple Pythonic way of doing this? I've tried several approaches, but they all have turned out to be messy.
| [
"Reorganize into a dict with value: count and test for presence of various patterns.\n",
"There are two ways to do this:\ndef getCounts(L):\n d = {}\n for i in range(1, 7):\n d[i] = L.count(i)\n return d # d is the dictionary which contains the occurrences of all possible dice values\n ... | [
4,
2,
2
] | [] | [] | [
"algorithm",
"dice",
"dictionary",
"list",
"python"
] | stackoverflow_0003877909_algorithm_dice_dictionary_list_python.txt |
Q:
How to catch login failures with PySVN?
I'm new to Python and PySVN in general, and I'm trying to export my SVN repository using pysvn. Here's my code:
#set up svn login data
def svn_credentials (realm, username, may_save):
return True, svn_login_name, svn_login_password, False
#establish connection
svn_client = pysvn.Client ()
svn_client.callback_get_login = svn_credentials
#export data
svn_client.export('server-path-goes-here', 'client-path-goes-here', force=True)
Which works fine, but if the password is wrong or the user name is unknown, this code just sits. I believe it's being presented with a user login prompt on the SVN side, but I'm at a loss as to how to check what's happening with callback_get_login. Any help would be greatly appreciated.
A:
If the credentials are wrong pysvn will call the callback, if the credentials are still wrong it will call it again, and again, and it will just keep doing that until the credentials are correct.
For an automated script you are probably better off not setting the callback and instead setting the default username and password by calling set_default_username and set_default_password on the pysvn.Client instance.
With that setup incorrect credentials will result in pysvn propagating an exception suggesting that you set the callback which you can catch and turn into a meaningful error message.
A:
Are you using SSH? In which case, perhaps it's SSH presenting the login prompt and PySVN can't do much about that. You could try messing with the SSH configuration on the client side to disable keyboard interactive prompts:
http://www.ssh.com/support/documentation/online/ssh/adminguide/32/Configuring_the_Server_and_Client.html
| How to catch login failures with PySVN? | I'm new to Python and PySVN in general, and I'm trying to export my SVN repository using pysvn. Here's my code:
#set up svn login data
def svn_credentials (realm, username, may_save):
return True, svn_login_name, svn_login_password, False
#establish connection
svn_client = pysvn.Client ()
svn_client.callback_get_login = svn_credentials
#export data
svn_client.export('server-path-goes-here', 'client-path-goes-here', force=True)
Which works fine, but if the password is wrong or the user name is unknown, this code just sits. I believe it's being presented with a user login prompt on the SVN side, but I'm at a loss as to how to check what's happening with callback_get_login. Any help would be greatly appreciated.
| [
"If the credentials are wrong pysvn will call the callback, if the credentials are still wrong it will call it again, and again, and it will just keep doing that until the credentials are correct.\nFor an automated script you are probably better off not setting the callback and instead setting the default username ... | [
4,
1
] | [] | [] | [
"infinite_loop",
"pysvn",
"python"
] | stackoverflow_0002625344_infinite_loop_pysvn_python.txt |
Q:
Why are main runnable Python scripts not compiled to pyc files like modules?
I understand that when you import a module, that file is compiled into a .pyc file to make it faster? Why is the main file also not compiled to a .pyc? Does this slow things down? Would it be better to keep the main file as small as possible then, or does it not matter?
A:
When a module is loaded, the py file is "byte compiled" to pyc files. The time stamp is recorded in pyc files.
This is done not to make it run faster but to load faster.
Hence, it makes sense to "byte compile" modules when you load them.
http://docs.python.org/tutorial/modules.html#compiled-python-files
[Edit : To include notes, references]
From PEP 3147 on "Byte code
compilation":
CPython compiles its source code into "byte code", and for performance reasons,
it caches this byte code on the file system whenever the source file has changes.
This makes loading of Python modules much faster because the compilation phase
can be bypassed. When your source file is foo.py, CPython caches the byte
code in a foo.pyc file right next to the source.
How byte code compiled files are
tracked with respect to Python version
and "py" file changes:
It also inserts a magic number in the compiled byte code ".pyc" files.
This changes whenever Python changes the byte code format, usually in major releases.
This ensures that pyc files built for previous versions of the VM won't cause problems.
The timestamp is used to make sure that the pyc file match the py file that was
used to create it. When either the magic number or timestamp do not match,
the py file is recompiled and a new pyc file is written.
"pyc" files are not compatible across Python major releases. When Python finds a pyc
file with a non-matching magic number, it falls back to the slower process of
recompiling the source.
Thats the reason, if you simply distribute the ".pyc" files compiled for the same platform will not work any more, if the python version changes.
In Nutshell
If there is a byte compiled file ".pyc" and it's timestamp indicates that it is recent then it will be loaded up other wise python will fallback on the slower approach of loading the ".py" files. The execution performance of the ".py" file is not affected but the loading of the ".pyc" files is faster than ".py" files.
Consider executing a.py which imports b.py
Typical total performance = loading time (A.py) + execution time (A.py) +
loading time (B.py) + execution time (B.py)
Since loading time (B.pyc) < loading time (B.py)
You should see a better performance by using the byte compiled "pyc" files.
That said, if you have a large script file X.py, modularizing it and moving contents to other modules results in taking advantage of lower load time for byte code compiled file.
Another inference is that modules tend to be more stable than the script or the main file. Hence it is not byte compiled at all.
References
http://effbot.org/zone/python-compile.htm
http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html
A:
Compiling the main script would be annoying for scripts in e.g. /usr/bin. The .pyc file is generated in the same directory, thus polluting the public location.
| Why are main runnable Python scripts not compiled to pyc files like modules? | I understand that when you import a module, that file is compiled into a .pyc file to make it faster? Why is the main file also not compiled to a .pyc? Does this slow things down? Would it be better to keep the main file as small as possible then, or does it not matter?
| [
"When a module is loaded, the py file is \"byte compiled\" to pyc files. The time stamp is recorded in pyc files.\nThis is done not to make it run faster but to load faster. \nHence, it makes sense to \"byte compile\" modules when you load them.\n\nhttp://docs.python.org/tutorial/modules.html#compiled-python-files\... | [
35,
0
] | [] | [] | [
"python"
] | stackoverflow_0003878479_python.txt |
Q:
Strange Problem with RPy2
After installing RPy2 from
http://rpy.sourceforge.net/rpy2.html
I'm trying to use it in Python 2.6 IDLE but I'm getting this error:
>>> import rpy2.robjects as robjects
>>> robjects.r['pi']
<RVector - Python:0x0121D8F0 / R:0x022A1760>
What I'm doing wrong?
A:
Have you tried looking at the vector that's returned?
>>> pi = robjects.r['pi']
>>> pi[0]
3.14159265358979
A:
To expand on Shane's answer. rpy2 uses the following Python objects to represent the basic R types:
RVector: R scalars and vectors, R Lists are represented as RVectors with names, see below
RArray: an R matrix, essentially the RVector with a dimension
RDataFrame: an R data.frame
To coerce back to basic Python types look here.
As an example, I use this to convert an R List to a python dict:
rList = ro.r('''list(name1=1,name2=c(1,2,3))''')
pyDict = {}
for name,value in zip([i for i in rList.getnames()],[i for i in rList]):
if len(value) == 1: pyDict[name] = value[0]
else: pyDict[name] = [i for i in value]
A:
In the Python interactive interpreter if an expression returns a value then that value is automatically printed. For example if you create a dictionary and extract a value from it the value is automatically printed, but if this was in an executing script this would not be the case. Look at the following simple example this is not an error but simply python printing the result of the expression:
>>> mymap = {"a":23}
>>> mymap["a"]
23
The same code in a python script would produce no output at all.
In your code you are accessing a map like structure with the code:
>>> robjects.r['pi']
This is returning some R2Py object for which the default string representation is: <RVector - Python:0x0121D8F0 / R:0x022A1760>
If you changed the code to something like:
pi = robjects.r['pi']
you would see no output but the result of the call (a vector) will be assigned to the variable pi and be available for you to use.
Looking at the R2Py documentation It seems many of the objects are by default printed as a type in <> brackets and some memory address information.
A:
This is not an error, it's simply the 'repr' of the returned robject:
>>> r['pi']
<RVector - Python:0x2c14bd8 / R:0x3719538>
>>> repr(r['pi'])
'<RVector - Python:0x4b77908 / R:0x3719538>'
>>> str(r['pi'])
'[1] 3.141593'
>>> print r['pi']
[1] 3.141593
You can get the value of 'pi' accessing it by index
>>> r['pi'][0]
3.1415926535897931
To access element of named lists (the 'object$attribute' R syntax) I use
>>> l = r.list(a=r.c(1,2,3), b=r.c(4,5,6))
>>> print l
$a
[1] 1 2 3
$b
[1] 4 5 6
>>> print dict(zip(l.names, l))['a']
[1] 1 2 3
but I think there must be a better solution...
A:
I found this as the only sensible, short discussion of how to go back and forth from R objects and python. naufraghi's solution prompted the following approach to converting a data.frame, which retains the nicer slicing capabilities of the dataframe:
In [69]: import numpy as np
In [70]: import rpy2.robjects as ro
In [71]: df = ro.r['data.frame'](a=r.c(1,2,3), b=r.c(4.0,5.0,6.3))
In [72]: df
Out[72]: <RDataFrame - Python:0x5492200 / R:0x4d00a28>
In [73]: print(df)
a b
1 1 4.0
2 2 5.0
3 3 6.3
In [74]: recdf = np.rec.fromarrays(df, names=tuple(df.names))
In [75]: recdf
Out[75]:
rec.array([(1, 4.0), (2, 5.0), (3, 6.2999999999999998)],
dtype=[('a', '<i4'), ('b', '<f8')])
Seems a bit off-topic at this point, but I'm not sure what the appropriate procedure would be to capture this question & answer of mine!
| Strange Problem with RPy2 | After installing RPy2 from
http://rpy.sourceforge.net/rpy2.html
I'm trying to use it in Python 2.6 IDLE but I'm getting this error:
>>> import rpy2.robjects as robjects
>>> robjects.r['pi']
<RVector - Python:0x0121D8F0 / R:0x022A1760>
What I'm doing wrong?
| [
"Have you tried looking at the vector that's returned?\n >>> pi = robjects.r['pi']\n >>> pi[0]\n 3.14159265358979\n\n",
"To expand on Shane's answer. rpy2 uses the following Python objects to represent the basic R types:\n\nRVector: R scalars and vectors, R Lists are represented as RVectors with names, see below... | [
8,
5,
1,
1,
0
] | [] | [] | [
"python",
"python_idle",
"r"
] | stackoverflow_0001649503_python_python_idle_r.txt |
Q:
Lisp's apply and funcall vs Python's apply
Lisp's APPLY is for calling functions with computed argument stored in lists.(Modified from Rainer's comment)
For example, the following code changes (list 1 2 3) to (+ 1 2 3).
(apply #'+ '(1 2 3))
However, Python's apply does what Lisp's funcall does, except for some minor differences (input is given as tuple/list)
(defun add (x y) (+ x y))
(funcall #'add 1 2)
or
(funcall #'(lambda (x y) (+ x y)) 10 2)
apply(lambda x,y : x+y, [1,2])
What do you think? Are there more differences between Lisp's funcall and Python's apply?
A:
Is there any reason why Python chose the name apply not funcall?
Because it's Python, not LISP. No need to have the same name, funcall is a LISP command and apply is something different in Python.
apply is deprecated in Python, use the extended call syntax.
Old syntax:
apply(foo, args, kwargs)
New syntax:
foo(*args, **kwargs)
A:
In Common Lisp (funcall #'fun 1 (list 2 3 4)) is exactly the same as (fun 1 (list 2 3 4)), whereas (apply #'fun 1 (list 2 3 4)) would mean different things depending on the arity of fun.
* (defun bleargh (a &rest b) (cons a b))
BLEARGH
* (funcall #'bleargh 1 (list 1 2 3))
(1 (1 2 3))
* (apply #'bleargh 1 (list 1 2 3))
(1 1 2 3)
So FUNCALL and APPLY do very different things, as it were.
A:
Just a note:
Deprecated since version 2.3: Use the extended call syntax with *args and **keywords instead.
removed in py3k.
A:
I don't see why you claim Lisp's apply() would do anything different than Python's. Both functions take a function and a list and then call the function with the list elements as arguments. ((+ 1 2 3) is an call to + with arguments 1, 2 and 3, isn't it?) To me it looks like both applys do exactly the same thing.
funcall on the other hand tales a function and several separate arguments (not a list containing arguments) and applies the function to these arguments.
A:
Both Lisp's and Python's apply function do the same thing -- given a function f and a list of parameters p, apply f to p. The only difference is that Python's apply also accepts a dictionary for keyword arguments. In Lisp, these would be included in the parameter list as :keyword arguments.
| Lisp's apply and funcall vs Python's apply | Lisp's APPLY is for calling functions with computed argument stored in lists.(Modified from Rainer's comment)
For example, the following code changes (list 1 2 3) to (+ 1 2 3).
(apply #'+ '(1 2 3))
However, Python's apply does what Lisp's funcall does, except for some minor differences (input is given as tuple/list)
(defun add (x y) (+ x y))
(funcall #'add 1 2)
or
(funcall #'(lambda (x y) (+ x y)) 10 2)
apply(lambda x,y : x+y, [1,2])
What do you think? Are there more differences between Lisp's funcall and Python's apply?
| [
"\nIs there any reason why Python chose the name apply not funcall?\n\nBecause it's Python, not LISP. No need to have the same name, funcall is a LISP command and apply is something different in Python.\napply is deprecated in Python, use the extended call syntax.\nOld syntax:\napply(foo, args, kwargs)\n\nNew synta... | [
8,
4,
2,
2,
1
] | [] | [] | [
"common_lisp",
"lisp",
"python",
"python_2.x"
] | stackoverflow_0003856917_common_lisp_lisp_python_python_2.x.txt |
Q:
Python HTTP Redirect requests forbidden
I'm trying to scrape a website where the URL is redirected, however programmatically trying this gives me an 403 Error code (Forbidden). I can place the URL in the browser and the browser will properly follow the url though...
to show a simple example i'm trying to go to :
http://en.wikipedia.org/w/index.php?title=Mike_tyson
I've tried urllib2 and mechanize however both do not work. I am fairly new to web programming and was wondering whether there are some other tricks I need to do in order to follow the redirect!
Thanks!
EDIT
Okay, so this is really messed. I was originally looking into alternative methods because I was trying to scrape an Mp3. I was managing to succesfully downloading the mp3 but it was all mangled.
Turns out it was somehow related to me downloading it on windows or my current Python version.
I tested the code on my Ubuntu distro and the mp3 file downloaded perfectly fine....
So I just used simple urllib2.openurl and it worked perfect!
I wonder why downloading on Windows mangled the mp3?
A:
Try changing the mechanize flag to not respect robots.txt. Also, consider changing the User-Agent HTTP header:
>>> import mechanize
>>> br = mechanize.Browser()
>>> br.set_handle_robots(False)
>>> br.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]
Web servers will now treat you like you were running MS Internet Explorer 6, rather than a bot. Even if they do restrict you with robots.txt, your bot will continue to work until it is blocked.
>>> br.open('http://en.wikipedia.org/w/index.php?title=Mike_tyson')
<response_seek_wrapper at 0x... whose wrapped object = <closeable_response at 0x... whose fp = <socket._fileobject object at 0x...>>> #doctest: +ELLIPSIS
A:
Okay, so this is really messed. I was originally looking into alternative methods because I was trying to scrape an Mp3. I was managing to succesfully downloading the mp3 but it was all mangled.
Turns out it was somehow related to me downloading it on windows or my current Python version. I tested the code on my Ubuntu distro and the mp3 file downloaded perfectly fine....
So I just used simple urllib2.openurl and it worked perfect!
I wonder why downloading on Windows mangled the mp3?
| Python HTTP Redirect requests forbidden | I'm trying to scrape a website where the URL is redirected, however programmatically trying this gives me an 403 Error code (Forbidden). I can place the URL in the browser and the browser will properly follow the url though...
to show a simple example i'm trying to go to :
http://en.wikipedia.org/w/index.php?title=Mike_tyson
I've tried urllib2 and mechanize however both do not work. I am fairly new to web programming and was wondering whether there are some other tricks I need to do in order to follow the redirect!
Thanks!
EDIT
Okay, so this is really messed. I was originally looking into alternative methods because I was trying to scrape an Mp3. I was managing to succesfully downloading the mp3 but it was all mangled.
Turns out it was somehow related to me downloading it on windows or my current Python version.
I tested the code on my Ubuntu distro and the mp3 file downloaded perfectly fine....
So I just used simple urllib2.openurl and it worked perfect!
I wonder why downloading on Windows mangled the mp3?
| [
"Try changing the mechanize flag to not respect robots.txt. Also, consider changing the User-Agent HTTP header:\n>>> import mechanize\n>>> br = mechanize.Browser()\n>>> br.set_handle_robots(False)\n>>> br.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]\n\nWeb servers will no... | [
3,
0
] | [] | [] | [
"http",
"python",
"redirect",
"urllib2"
] | stackoverflow_0003878257_http_python_redirect_urllib2.txt |
Q:
Downloading Mp3 using Python in Windows mangles the song however in Linux it doesn't
I've setup a script to download an mp3 using urllib2 in Python.
url = 'example.com'
req2 = urllib2.Request(url)
response = urllib2.urlopen(req2)
#grab the data
data = response.read()
mp3Name = "song.mp3"
song = open(mp3Name, "w")
song.write(data) # was data2
song.close()
Turns out it was somehow related to me downloading it on Windows or my current Python version. I tested the code on my Ubuntu distro and the mp3 file downloaded perfectly fine... So I just used the simple urllib2.openurl method and it worked perfect!
To summarize:
I am using urllib2.openurl in Python on an Ubuntu distro.
I am using a newer version of Python but I feel like it can't be that.
The mp3 are encoded in LAME.
Does anyone have any clue what was causing the weird issue running the code on my Windows box? I wonder why downloading on Windows mangled the mp3?
A:
Try binary file mode. open(mp3Name, "wb")
You're probably getting line ending translations.
The file is binary, yes. It's the mode that wasn't. When a file is opened, it can be set to read as a text file (this is default). When it does this, it will convert line endings to match the platform. On Windows, line ends are \r\n In most other places it's either \r or \n. This change messes up the data stream.
| Downloading Mp3 using Python in Windows mangles the song however in Linux it doesn't | I've setup a script to download an mp3 using urllib2 in Python.
url = 'example.com'
req2 = urllib2.Request(url)
response = urllib2.urlopen(req2)
#grab the data
data = response.read()
mp3Name = "song.mp3"
song = open(mp3Name, "w")
song.write(data) # was data2
song.close()
Turns out it was somehow related to me downloading it on Windows or my current Python version. I tested the code on my Ubuntu distro and the mp3 file downloaded perfectly fine... So I just used the simple urllib2.openurl method and it worked perfect!
To summarize:
I am using urllib2.openurl in Python on an Ubuntu distro.
I am using a newer version of Python but I feel like it can't be that.
The mp3 are encoded in LAME.
Does anyone have any clue what was causing the weird issue running the code on my Windows box? I wonder why downloading on Windows mangled the mp3?
| [
"Try binary file mode. open(mp3Name, \"wb\")\nYou're probably getting line ending translations.\nThe file is binary, yes. It's the mode that wasn't. When a file is opened, it can be set to read as a text file (this is default). When it does this, it will convert line endings to match the platform. On Windows, line ... | [
15
] | [] | [] | [
"httpwebrequest",
"mp3",
"python",
"web_scraping"
] | stackoverflow_0003878882_httpwebrequest_mp3_python_web_scraping.txt |
Q:
"Unable to find vcvarsall.bat" error when trying to install qrcode-0.2.1
Please help me to solve this error
C:\Python26\Lib\site-packages\pyqrcode\encoder>python setup.py install
running install
running bdist_egg
running egg_info
writing qrcode.egg-info\PKG-INFO
writing top-level names to qrcode.egg-info\top_level.txt
writing dependency_links to qrcode.egg-info\dependency_links.txt
package init file 'qrcode\__init__.py' not found (or not a regular file)
writing manifest file 'qrcode.egg-info\SOURCES.txt'
installing library code to build\bdist.win32\egg
running install_lib
running build_py
running build_ext
building 'qrcode.Encoder' extension
error: Unable to find vcvarsall.bat
Thanks,
manu
A:
Distutils does not play well with MS Compiler tool chain.
This file is required to setup the environment which will help distutils to use MS compiler tool chains.
There are quite a few ways in which this has been made to work.
Please look at the following post which may help you.
Compile Python 2.7 Packages With Visual Studio 2010 Express†
† The link goes to archive.org, since the original page went away.
A:
This was a known bug, and should not be an issue anymore.
If using MinGW, try:
setup.py install build ––compiler=mingw32
| "Unable to find vcvarsall.bat" error when trying to install qrcode-0.2.1 | Please help me to solve this error
C:\Python26\Lib\site-packages\pyqrcode\encoder>python setup.py install
running install
running bdist_egg
running egg_info
writing qrcode.egg-info\PKG-INFO
writing top-level names to qrcode.egg-info\top_level.txt
writing dependency_links to qrcode.egg-info\dependency_links.txt
package init file 'qrcode\__init__.py' not found (or not a regular file)
writing manifest file 'qrcode.egg-info\SOURCES.txt'
installing library code to build\bdist.win32\egg
running install_lib
running build_py
running build_ext
building 'qrcode.Encoder' extension
error: Unable to find vcvarsall.bat
Thanks,
manu
| [
"Distutils does not play well with MS Compiler tool chain.\nThis file is required to setup the environment which will help distutils to use MS compiler tool chains.\nThere are quite a few ways in which this has been made to work.\nPlease look at the following post which may help you.\n\nCompile Python 2.7 Packages ... | [
17,
4
] | [] | [] | [
"installation",
"python",
"qr_code"
] | stackoverflow_0003879014_installation_python_qr_code.txt |
Q:
Created HTTP response to be the same as accessing .jpg in Python
I want to server an image file but accept some attributes for processing before hand using Python and google app engine.
Where I would normally have
'http://www.domain.com/image/desiredImage.jpg'
as the image to server.
I want to be able to add some tracking to it so I can do something similar to
'http://www.domain.com/image/desiredImage.jpg?ref_val=customerID'
I figured the best way to do this would be to have a "proxy" for image requests like
'http://www.domain.com/imageproxy?img=imgID&ref_val=customerID'
and have the imageproxy url process the ref_val value and serve the image based off the imgID value from the datastore db.Blob value.
When I access the proxy URL it shows the image and processes fine. When I used the URL in other 3rd party javascript JSON requests looking for an image url, I get nothing to show up.
I guess the root of my question is how is accessing
'http://www.domain.com/image.jpg'
different from accessing
'http://www.domain.com/script_that_returns_image'
where the latter URL is a python script that outputs
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(image) #image a db.Blob property in google app engine
A:
Could be a couple issues. By overloading the image and providing arguments to it as if it were a script, you might be triggering javascript sandboxing/security stuff meant to prevent cross-site scripting attacks.
Another issue might be 'dumbness' of the client app, some clients might expect '.jpg' regardless of the content-type.
Open up your javascript console and see what error you're getting on the image in question as a first step.
Alternatively, you might want to be more devious about how you're encoding your uniqueness element, instead of making it CGI-ish, try something like
http://domain.com/image-ref_val-customerID.jpg, where customerID would be dynamically updated.
| Created HTTP response to be the same as accessing .jpg in Python | I want to server an image file but accept some attributes for processing before hand using Python and google app engine.
Where I would normally have
'http://www.domain.com/image/desiredImage.jpg'
as the image to server.
I want to be able to add some tracking to it so I can do something similar to
'http://www.domain.com/image/desiredImage.jpg?ref_val=customerID'
I figured the best way to do this would be to have a "proxy" for image requests like
'http://www.domain.com/imageproxy?img=imgID&ref_val=customerID'
and have the imageproxy url process the ref_val value and serve the image based off the imgID value from the datastore db.Blob value.
When I access the proxy URL it shows the image and processes fine. When I used the URL in other 3rd party javascript JSON requests looking for an image url, I get nothing to show up.
I guess the root of my question is how is accessing
'http://www.domain.com/image.jpg'
different from accessing
'http://www.domain.com/script_that_returns_image'
where the latter URL is a python script that outputs
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(image) #image a db.Blob property in google app engine
| [
"Could be a couple issues. By overloading the image and providing arguments to it as if it were a script, you might be triggering javascript sandboxing/security stuff meant to prevent cross-site scripting attacks. \nAnother issue might be 'dumbness' of the client app, some clients might expect '.jpg' regardless of ... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003879038_google_app_engine_python.txt |
Q:
Interacting with a c struct containing only function pointers using ctypes in python
I have a struct in a dll that only contains function pointers (ie a vtable) that I would like to interact with in python (for test purposes). I am having a bit of trouble working out how to do this using ctypes.
What I have is:
struct ITest
{
virtual char const *__cdecl GetName() = 0;
virtual void __cdecl SetName(char const *name) = 0;
};
/* Factory function to create 'real' Test object */
extern "C" __declspec(dllexport) struct ITest * CALLCONV make_Test(char const * name);
A 'real' Test object will fill in the struct as appropriate. This gets compiled into a DLL (test.dll). I'd like, in python, to be able to call the factory method to get back a pointer to my Test struct and then call the function pointers contained in the struct, but I just can't seem to get my head around how it would work using ctypes. Does anyone have any pointers / examples of doing something similar or should I be using something like SWIG or Boost?
Thanks for any help.
A:
Something like this should be a good starting point (I don't have your DLL compiled to test)
from ctypes import Structure, CFUNCTYPE, POINTER, c_char_p, windll
class ITest(Structure):
_fields_ = [
('GetName', CFUNCTYPE(c_char_p)),
('SetName', CFUNCTYPE(None, c_char_p)
]
test = windll.LoadLibrary('test.dll')
test.make_Test.restype = POINTER(ITest)
After this, you'll need to call make_Test() to get the struct, and try calling the functions. Perhaps with code like this:
itest = test.make_Test().contents
itest.SetName('asdf')
print itest.GetName()
Provide the dll or test and give me your results and I can help more if you still have problems.
A:
The ctypes documentation says that you can create a ctypes.PYFUNCTYPE from an address.
If you get the address of the functions in your structure then you can wrap it as a Python function thanks to ctypes.PYFUNCTYPE and then call it as a regular ctype function.
I didn't test it myself but I think it maybe something to explore in your case
See http://docs.python.org/library/ctypes.html#ctypes.PYFUNCTYPE
I hope it helps
| Interacting with a c struct containing only function pointers using ctypes in python | I have a struct in a dll that only contains function pointers (ie a vtable) that I would like to interact with in python (for test purposes). I am having a bit of trouble working out how to do this using ctypes.
What I have is:
struct ITest
{
virtual char const *__cdecl GetName() = 0;
virtual void __cdecl SetName(char const *name) = 0;
};
/* Factory function to create 'real' Test object */
extern "C" __declspec(dllexport) struct ITest * CALLCONV make_Test(char const * name);
A 'real' Test object will fill in the struct as appropriate. This gets compiled into a DLL (test.dll). I'd like, in python, to be able to call the factory method to get back a pointer to my Test struct and then call the function pointers contained in the struct, but I just can't seem to get my head around how it would work using ctypes. Does anyone have any pointers / examples of doing something similar or should I be using something like SWIG or Boost?
Thanks for any help.
| [
"Something like this should be a good starting point (I don't have your DLL compiled to test)\nfrom ctypes import Structure, CFUNCTYPE, POINTER, c_char_p, windll\nclass ITest(Structure):\n _fields_ = [\n ('GetName', CFUNCTYPE(c_char_p)),\n ('SetName', CFUNCTYPE(None, c_char_p)\n ]\n\... | [
3,
1
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003854388_ctypes_python.txt |
Q:
Python programs on different Operating Systems
If I write a python script using only python standard libraries, using Python 2.6 will it work on all Operating Systems as long as python 2.6 is installed?
A:
Depends. There are a few parts of the Python standard libraries that are only available on certain platforms. These parts are noted in the Python documentation.
You also need to be careful of how you handle things like file paths - using os.path.join() and such to make sure paths are formatted in the right way.
A:
You need to be careful when you are reading binary files. Always use 'rb', 'wb', etc file opening modes. You can get away with 'r' etc on Unix/Linux/etc, but it really matters on Windows. Unintuitively, CSV files are binary.
Instructive exercise: work out why this code produces 26 on Windows instead of the 128 that it would produce on a non-Windows box:
>>> s = ''.join(map(chr,range(128)))
>>> len(s)
128
>>> f = open('junk.txt', 'w')
>>> f.write(s)
>>> f.close()
>>> len(open('junk.txt').read())
26
Avoid hard-coding file paths.
Don't assume that you can splat unicode (or utf8-encoded unicode) at the console and have it rendered legibly or at all.
Some Python modules are not automatically installed on some Linux distros ... you need a separate "dev" package.
Not exactly an operating system problem, but some operating systems run on bigendian boxes so if you are doing any work writing/reading binary formats, you need to take endianness into account.
A:
yes, unless you are using modules that are os dependent.
Edit : My reply seemed short
and not too the point based on
comments
I am not addressing portable programming in general.
That would mean taking care of binary data packing and manipulation, c extension issues, paths as in windows/unix, "\r\n" in windows text and many others.
But with regard to portability of the python modules, there is no question.
They are portable.
How ever, there are modules that are available on specific platform only and if you use them, then your portability will be curtailed.
| Python programs on different Operating Systems | If I write a python script using only python standard libraries, using Python 2.6 will it work on all Operating Systems as long as python 2.6 is installed?
| [
"Depends. There are a few parts of the Python standard libraries that are only available on certain platforms. These parts are noted in the Python documentation.\nYou also need to be careful of how you handle things like file paths - using os.path.join() and such to make sure paths are formatted in the right way.\n... | [
8,
7,
0
] | [] | [] | [
"python"
] | stackoverflow_0003878593_python.txt |
Q:
How best to get map from key list/value list in groovy?
In python, I can do the following:
keys = [1, 2, 3]
values = ['a', 'b', 'c']
d = dict(zip(keys, values))
assert d == {1: 'a', 2: 'b', 3: 'c'}
Is there a nice way to construct a map in groovy, starting from a list of keys and a list of values?
A:
There's also the collectEntries function in Groovy 1.8
def keys = [1, 2, 3]
def values = ['a', 'b', 'c']
[keys,values].transpose().collectEntries { it }
A:
Try this:
def keys = [1, 2, 3]
def values = ['a', 'b', 'c']
def pairs = [keys, values].transpose()
def map = [:]
pairs.each{ k, v -> map[k] = v }
println map
Alternatively:
def map = [:]
pairs.each{ map << (it as MapEntry) }
A:
There isn't anything built directly in to groovy, but there are a number of ways to solve it easily, here's one:
def zip(keys, values) {
keys.inject([:]) { m, k -> m[k] = values[m.size()]; m }
}
def result = zip([1, 2, 3], ['a', 'b', 'c'])
assert result == [1: 'a', 2: 'b', 3: 'c']
| How best to get map from key list/value list in groovy? | In python, I can do the following:
keys = [1, 2, 3]
values = ['a', 'b', 'c']
d = dict(zip(keys, values))
assert d == {1: 'a', 2: 'b', 3: 'c'}
Is there a nice way to construct a map in groovy, starting from a list of keys and a list of values?
| [
"There's also the collectEntries function in Groovy 1.8\ndef keys = [1, 2, 3]\ndef values = ['a', 'b', 'c']\n[keys,values].transpose().collectEntries { it }\n\n",
"Try this:\ndef keys = [1, 2, 3]\ndef values = ['a', 'b', 'c']\ndef pairs = [keys, values].transpose()\n\ndef map = [:]\npairs.each{ k, v -> map[k] = v... | [
22,
12,
5
] | [] | [] | [
"dictionary",
"groovy",
"python"
] | stackoverflow_0003877454_dictionary_groovy_python.txt |
Q:
Mutable Default Argument Returns None
I have a simple code that finds paths using a graph stored in a dictionary. The code is exactly:
def find_path(dct, init, depth, path=[]):
if depth == 0:
return path
next_ = dct[init]
depth-=1
find_path(dct, next_, depth)
If I print the path right before return path it prints to screen the correct path (after an initial depth of 5). However, the value returned is None. I don't know what's going on!
Why would the value of path right above the return is correct, yet the returned path is not what I want?
A:
Shouldn't this
find_path(dct, next_, depth)
be
return find_path(dct, next_, depth)
# ^^^^
# Return
In Python (unlike in say, Ruby) you have to explicitly return a value. Otherwise None is returned.
A:
Because you're calling it with depth greater than 0, which is causing it to fall off the end and return None.
| Mutable Default Argument Returns None | I have a simple code that finds paths using a graph stored in a dictionary. The code is exactly:
def find_path(dct, init, depth, path=[]):
if depth == 0:
return path
next_ = dct[init]
depth-=1
find_path(dct, next_, depth)
If I print the path right before return path it prints to screen the correct path (after an initial depth of 5). However, the value returned is None. I don't know what's going on!
Why would the value of path right above the return is correct, yet the returned path is not what I want?
| [
"Shouldn't this \nfind_path(dct, next_, depth)\n\nbe \nreturn find_path(dct, next_, depth)\n# ^^^^\n# Return\n\nIn Python (unlike in say, Ruby) you have to explicitly return a value. Otherwise None is returned. \n",
"Because you're calling it with depth greater than 0, which is causing it to fall off the end and ... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003879307_python.txt |
Q:
Why do I have to put the project name when importing tasks when using Django with Celery?
I just installed and configured Celery with RabbitMQ for a Django project and I was having an issue running tasks when I imported them like so:
from someapp.tasks import SomeTask
It worked when I added the project name:
from myproject.someapp.tasks import SomeTask
I tried adding this into the settings.py file but it doesn't change anything:
CELERY_IMPORTS = ("myproject.someapp.tasks",)
I'm fine with leaving the project name on the import line since it works but I'd like to know if there's a way around it or why it has to be that way.
A:
It's probably because you have
INSTALLED_APPS = ("myproject.someapp", )
Instead you should add the directory containing the apps on the Python path (the project in
this case), and simply do
INSTALLED_APPS = ("someapp", )
IMHO this makes more sense for an "app" anyway.
| Why do I have to put the project name when importing tasks when using Django with Celery? | I just installed and configured Celery with RabbitMQ for a Django project and I was having an issue running tasks when I imported them like so:
from someapp.tasks import SomeTask
It worked when I added the project name:
from myproject.someapp.tasks import SomeTask
I tried adding this into the settings.py file but it doesn't change anything:
CELERY_IMPORTS = ("myproject.someapp.tasks",)
I'm fine with leaving the project name on the import line since it works but I'd like to know if there's a way around it or why it has to be that way.
| [
"It's probably because you have\nINSTALLED_APPS = (\"myproject.someapp\", )\n\nInstead you should add the directory containing the apps on the Python path (the project in \nthis case), and simply do \nINSTALLED_APPS = (\"someapp\", )\n\nIMHO this makes more sense for an \"app\" anyway.\n"
] | [
1
] | [] | [] | [
"celery",
"django",
"python",
"rabbitmq"
] | stackoverflow_0003869369_celery_django_python_rabbitmq.txt |
Q:
object oriented design question for gui application
guys, I am programming a GUI for an application, a cd container to insert cd, and currently I am not very clear and I think I need some help to clarify my understanding about object oriented design.
so, first, I use observer pattern to build abstract Model and View classes and also the concrete models(cd container) and concrete views(cd container view). Then I start to use the wxwidget framework to design and graphical appearance or layout (CDContainerWidget, from wxPanel) for the cd container and other gui controls MainFrame(from wxFrame), etc..
so now I have three classes: CDContainerModel (cd container), CDContainerView (the class for observer pattern), and CDContainerWidget (the gui controls).
then I become not that clear about what I should do with the CDContainerView and CDContainerWidget?
I think CDContainerWidget and CDContainerView both need CDContainerModel. I think about four approaches, but do not know which one is approriate:
1). associate CDContainerWidget into CDContainerView as a member variable, then put the CDContainerView into the Main Frame as a member variable.
class CDContainerView:
def __init__:
self.gui=CDContainerWidget
class MainFrame:
def __init__:
CDContainerView
2). CDContainerView subclass CDContainerWidget:
class CDContainerView(CDContainerWidget):
class MainFrame:
def __init__:
CDContainerView
3). CDContainerWidget subclass CDContainerView:
class CDContainerWidget(CDContainerView):
class MainFrame:
def __init__:
CDContainerWidget
4). instead of using CDContainerWidget and CDContainerView, use only a single class CDContainerBig which subclass the abstract class View and wxPanel
class CDContainerBig(View, wxPanel)
My question is what is the right solution? I have read the wiki page of MVC pattern, but I do not really understand its descrption and do not know how and also wonder if it is approriate to apply it to my problem.
well, I put some additional comments. originally, when i start to design to program, I did not think much and just choose, 2) approach. but now, I think 3) is good. since it is reasonable to put widget in widget(CDContainerWidget into MainFrame). but I am not really sure. Also it seems with observer pattern, the three classes are twisted and awkard. And sometimes, it appears to me that these 4 maybe are the same, just who includes who, or who sends messages to who. well, I think I really need clarification on this point.
Also, I am in favour of 3) because of a practical point.The CDContainerWidget actually contains several subwidget components (button, input box, etc.) and if we change something like set new values via a subcomponent widget, then for 1), we need CDContainerWidget to be aware of CDContainerView, to let CDContainerView to notify other views. for 2) even worse, CDContainerWidget has to be aware of its childen CDContainerView. for 3) CDContainerWidget itself is CDContainerView, so quite reasonable. for 4) well, easy but no logic separation. this is my own thought, do not know if it is correct.
Thanks!!
A:
Option 1 seems most appropriate. In general, you should avoid inheritance unless the pattern calls for it, or there's some other compelling reason to use it. Overuse of inheritance will make your code a lot more tightly integrated than it has to be.
A:
What might make this a bit easier for you to shed the coupling between classes would be implementing a signal slot pattern with something like Spiff Signal, or one of the other signal/slot modules available.
By decoupling the communication logic you can free yourself entirely of the need for modules to talk directly but rather use message passing with callbacks.
| object oriented design question for gui application | guys, I am programming a GUI for an application, a cd container to insert cd, and currently I am not very clear and I think I need some help to clarify my understanding about object oriented design.
so, first, I use observer pattern to build abstract Model and View classes and also the concrete models(cd container) and concrete views(cd container view). Then I start to use the wxwidget framework to design and graphical appearance or layout (CDContainerWidget, from wxPanel) for the cd container and other gui controls MainFrame(from wxFrame), etc..
so now I have three classes: CDContainerModel (cd container), CDContainerView (the class for observer pattern), and CDContainerWidget (the gui controls).
then I become not that clear about what I should do with the CDContainerView and CDContainerWidget?
I think CDContainerWidget and CDContainerView both need CDContainerModel. I think about four approaches, but do not know which one is approriate:
1). associate CDContainerWidget into CDContainerView as a member variable, then put the CDContainerView into the Main Frame as a member variable.
class CDContainerView:
def __init__:
self.gui=CDContainerWidget
class MainFrame:
def __init__:
CDContainerView
2). CDContainerView subclass CDContainerWidget:
class CDContainerView(CDContainerWidget):
class MainFrame:
def __init__:
CDContainerView
3). CDContainerWidget subclass CDContainerView:
class CDContainerWidget(CDContainerView):
class MainFrame:
def __init__:
CDContainerWidget
4). instead of using CDContainerWidget and CDContainerView, use only a single class CDContainerBig which subclass the abstract class View and wxPanel
class CDContainerBig(View, wxPanel)
My question is what is the right solution? I have read the wiki page of MVC pattern, but I do not really understand its descrption and do not know how and also wonder if it is approriate to apply it to my problem.
well, I put some additional comments. originally, when i start to design to program, I did not think much and just choose, 2) approach. but now, I think 3) is good. since it is reasonable to put widget in widget(CDContainerWidget into MainFrame). but I am not really sure. Also it seems with observer pattern, the three classes are twisted and awkard. And sometimes, it appears to me that these 4 maybe are the same, just who includes who, or who sends messages to who. well, I think I really need clarification on this point.
Also, I am in favour of 3) because of a practical point.The CDContainerWidget actually contains several subwidget components (button, input box, etc.) and if we change something like set new values via a subcomponent widget, then for 1), we need CDContainerWidget to be aware of CDContainerView, to let CDContainerView to notify other views. for 2) even worse, CDContainerWidget has to be aware of its childen CDContainerView. for 3) CDContainerWidget itself is CDContainerView, so quite reasonable. for 4) well, easy but no logic separation. this is my own thought, do not know if it is correct.
Thanks!!
| [
"Option 1 seems most appropriate. In general, you should avoid inheritance unless the pattern calls for it, or there's some other compelling reason to use it. Overuse of inheritance will make your code a lot more tightly integrated than it has to be.\n",
"What might make this a bit easier for you to shed the coup... | [
1,
1
] | [] | [] | [
"design_patterns",
"oop",
"python",
"user_interface",
"wxwidgets"
] | stackoverflow_0003838688_design_patterns_oop_python_user_interface_wxwidgets.txt |
Q:
how quick read 25k small txt file content with python
i download many html store in os,now get their content ,and extract data what i need to persistence to mysql,
i use the traditional load file one by one ,it's not efficant cost nealy 8 mins.
any advice is welcome
g_fields=[
'name',
'price',
'productid',
'site',
'link',
'smallImage',
'bigImage',
'description',
'createdOn',
'modifiedOn',
'size',
'weight',
'wrap',
'material',
'packagingCount',
'stock',
'location',
'popularity',
'inStock',
'categories',
] @cost_time
def batch_xml2csv():
"批量将xml导入到一个csv文件中"
delete(g_xml2csv_file)
f=open(g_xml2csv_file,"a")
import os.path
import mmap
for file in glob.glob(g_filter):
print "读入%s"%file
ff=open(file,"r+")
size=os.path.getsize(file)
data=mmap.mmap(ff.fileno(),size)
s=pq(data.read(size))
data.close()
ff.close()
#s=pq(open(file,"r").read())
line=[]
for field in g_fields:
r=s("field[@name='%s']"%field).text()
if r is None:
line.append("\N")
else:
line.append('"%s"'%r.replace('"','\"'))
f.write(",".join(line)+"\n")
f.close()
print "done!"
i tried mmap,it seems didn't work well
A:
If you've got 25,000 text files on disk, 'you're doing it wrong'. Depending on how you store them on disk, the slowness could literally be seeking on disk to find the files.
If you've got 25,0000 of anything it'll be faster if you put it in a database with an intelligent index -- even if you make the index field the filename it'll be faster.
If you have multiple directories that descend N levels deep, a database would still be faster.
A:
You can scan the files while downloading them in multiple threads if you use scrapy.
A:
If algorith is correct, using the psyco module can sometimes help quite a lot. It does not however work with Python 2.7 or Python 3+
| how quick read 25k small txt file content with python | i download many html store in os,now get their content ,and extract data what i need to persistence to mysql,
i use the traditional load file one by one ,it's not efficant cost nealy 8 mins.
any advice is welcome
g_fields=[
'name',
'price',
'productid',
'site',
'link',
'smallImage',
'bigImage',
'description',
'createdOn',
'modifiedOn',
'size',
'weight',
'wrap',
'material',
'packagingCount',
'stock',
'location',
'popularity',
'inStock',
'categories',
] @cost_time
def batch_xml2csv():
"批量将xml导入到一个csv文件中"
delete(g_xml2csv_file)
f=open(g_xml2csv_file,"a")
import os.path
import mmap
for file in glob.glob(g_filter):
print "读入%s"%file
ff=open(file,"r+")
size=os.path.getsize(file)
data=mmap.mmap(ff.fileno(),size)
s=pq(data.read(size))
data.close()
ff.close()
#s=pq(open(file,"r").read())
line=[]
for field in g_fields:
r=s("field[@name='%s']"%field).text()
if r is None:
line.append("\N")
else:
line.append('"%s"'%r.replace('"','\"'))
f.write(",".join(line)+"\n")
f.close()
print "done!"
i tried mmap,it seems didn't work well
| [
"If you've got 25,000 text files on disk, 'you're doing it wrong'. Depending on how you store them on disk, the slowness could literally be seeking on disk to find the files. \nIf you've got 25,0000 of anything it'll be faster if you put it in a database with an intelligent index -- even if you make the index field... | [
0,
0,
0
] | [] | [] | [
"file",
"performance",
"python"
] | stackoverflow_0003878918_file_performance_python.txt |
Q:
Downloading a webpage using urllib2 results in garbled junk? (only sometimes)
How come I hit this webpage, I get HTML text:
http://itunes.apple.com/us/app/mobile/id381057839
But when I hit this webpage, I get garbled junk?
http://itunes.apple.com/us/app/mobile/id375562663
I use the same download() function in python, which is here:
def download(source_url):
try:
socket.setdefaulttimeout(10)
agent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.10) Gecko/20100914 AlexaToolbar/alxf-1.54 Firefox/3.6.10 GTB7.1"
ree = urllib2.Request(source_url)
ree.add_header('User-Agent',agent)
ree.add_header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
ree.add_header("Accept-Language","en-us,en;q=0.5")
ree.add_header("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7")
ree.add_header("Accept-Encoding","gzip,deflate")
ree.add_header("Host","itunes.apple.com")
resp = urllib2.urlopen(ree)
htmlSource = resp.read()
return htmlSource
except Exception, e:
print e
A:
Solved. It was compression issue.
def download(source_url):
try:
socket.setdefaulttimeout(10)
agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U; en)']
ree = urllib2.Request(source_url)
ree.add_header('User-Agent',random.choice(agents))
ree.add_header('Accept-encoding', 'gzip')
opener = urllib2.build_opener()
h = opener.open(ree).read()
import StringIO
import gzip
compressedstream = StringIO.StringIO(h)
gzipper = gzip.GzipFile(fileobj=compressedstream)
data = gzipper.read()
return data
except Exception, e:
print e
return ""
| Downloading a webpage using urllib2 results in garbled junk? (only sometimes) | How come I hit this webpage, I get HTML text:
http://itunes.apple.com/us/app/mobile/id381057839
But when I hit this webpage, I get garbled junk?
http://itunes.apple.com/us/app/mobile/id375562663
I use the same download() function in python, which is here:
def download(source_url):
try:
socket.setdefaulttimeout(10)
agent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.10) Gecko/20100914 AlexaToolbar/alxf-1.54 Firefox/3.6.10 GTB7.1"
ree = urllib2.Request(source_url)
ree.add_header('User-Agent',agent)
ree.add_header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
ree.add_header("Accept-Language","en-us,en;q=0.5")
ree.add_header("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7")
ree.add_header("Accept-Encoding","gzip,deflate")
ree.add_header("Host","itunes.apple.com")
resp = urllib2.urlopen(ree)
htmlSource = resp.read()
return htmlSource
except Exception, e:
print e
| [
"Solved. It was compression issue.\ndef download(source_url):\n try:\n socket.setdefaulttimeout(10)\n agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U;... | [
2
] | [] | [] | [
"api",
"http",
"python",
"rest",
"urllib2"
] | stackoverflow_0003879633_api_http_python_rest_urllib2.txt |
Q:
how python manage object delete or destruction
guys, I am rather new to python and learning it to build a gui application (with wypython). I have a question related with object destruction in python.
e.g. in myFrame I have onNew (create a new document) and onOpen (open a file) method.
briefly, it looks like this.
def onNew
self.data=DataModel()
self.viewwindow=ViewWindow(self.data)
def onOpen
dlg = wx.FileDialog(self, "Open file", os.getcwd(), "", "*.*", wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.data=DataModel.from_file(...)
self.view=View(self.data)
now, I want to consider "if the user click open or new again, after he click either before."
so for the window classes, I could call the self.viewwindow.Destroy() to destry the windows. what about the data model object? If I first call new: self.data=DataModel(), then call open and re-assign self.data=DataModel.from_file(...), what about the old instance? Do I need destruct it myself or python will manage this destruction?
A:
Python has garbage collection. As long as you don't have any references to the old object hanging around it will be collected.
As soon as you say self.data = somethingElse then the old self.data won't have any references to it (unless another object had a reference to your object's self.data).
| how python manage object delete or destruction | guys, I am rather new to python and learning it to build a gui application (with wypython). I have a question related with object destruction in python.
e.g. in myFrame I have onNew (create a new document) and onOpen (open a file) method.
briefly, it looks like this.
def onNew
self.data=DataModel()
self.viewwindow=ViewWindow(self.data)
def onOpen
dlg = wx.FileDialog(self, "Open file", os.getcwd(), "", "*.*", wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.data=DataModel.from_file(...)
self.view=View(self.data)
now, I want to consider "if the user click open or new again, after he click either before."
so for the window classes, I could call the self.viewwindow.Destroy() to destry the windows. what about the data model object? If I first call new: self.data=DataModel(), then call open and re-assign self.data=DataModel.from_file(...), what about the old instance? Do I need destruct it myself or python will manage this destruction?
| [
"Python has garbage collection. As long as you don't have any references to the old object hanging around it will be collected.\nAs soon as you say self.data = somethingElse then the old self.data won't have any references to it (unless another object had a reference to your object's self.data).\n"
] | [
2
] | [] | [] | [
"destruction",
"object",
"oop",
"python"
] | stackoverflow_0003879860_destruction_object_oop_python.txt |
Q:
Python Extension Can't Use library_dirs
WHen specifying library_dirs in a Python distutils.core.Extension I get this error when trying to build:
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/dist.py:263: UserWarning: Unknown distribution option: 'library_dirs'
warnings.warn(msg)
Why is this? I am using Python 2.5 on Mac OS X.
A:
The error means you're not passing library_dirs to distutils.core.Extension, but to the distutils.core.setup function.
| Python Extension Can't Use library_dirs | WHen specifying library_dirs in a Python distutils.core.Extension I get this error when trying to build:
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/dist.py:263: UserWarning: Unknown distribution option: 'library_dirs'
warnings.warn(msg)
Why is this? I am using Python 2.5 on Mac OS X.
| [
"The error means you're not passing library_dirs to distutils.core.Extension, but to the distutils.core.setup function.\n"
] | [
1
] | [] | [] | [
"c",
"libraries",
"python",
"python_extensions"
] | stackoverflow_0003878673_c_libraries_python_python_extensions.txt |
Q:
How to create a list or tuple of empty lists in Python?
I need to incrementally fill a list or a tuple of lists. Something that looks like this:
result = []
firstTime = True
for i in range(x):
for j in someListOfElements:
if firstTime:
result.append([f(j)])
else:
result[i].append(j)
In order to make it less verbose an more elegant, I thought I will preallocate a list of empty lists
result = createListOfEmptyLists(x)
for i in range(x):
for j in someListOfElements:
result[i].append(j)
The preallocation part isn't obvious to me. When I do result = [[]] * x, I receive a list of x references to the same list, so that the output of the following
result[0].append(10)
print result
is:
[[10], [10], [10], [10], [10], [10], [10], [10], [10], [10]]
I can use a loop (result = [[] for i in range(x)]), but I wonder whether a "loopless" solution exists.
Is the only way to get what I'm looking for
A:
result = [list(someListOfElements) for _ in xrange(x)]
This will make x distinct lists, each with a copy of someListOfElements list (each item in that list is by reference, but the list its in is a copy).
If it makes more sense, consider using copy.deepcopy(someListOfElements)
Generators and list comprehensions and things are considered quite pythonic.
A:
There's not really a way to create such a list without a loop of some sort. There are multiple ways of hiding the loop, though, just like [[]] * x hides the loop. There's the list comprehension, which "hides" the loop in an expression (bit it's thankfully still obvious.) There's also map(list, [[]]*x) which has two hidden loops (the one in [[]] * x and the one in map that creates a copy of each list using list().)
There's also the possibility of not creating the list of lists beforehand. The other answers already cover the simple approach, but if that somehow doesn't fit your needs there are other ways. For example, you could make a function that append an empty list to the result list as necessary, and call that:
def append(L, idx, item):
while len(L) <= idx:
L.append([])
L[idx].append(item)
for i in range(x):
for j in someListOfElements:
append(result, i, j)
Or you could use a collections.defaultdict(list) instead of a list:
import collections
result = collections.defaultdict(list)
for i in range(x):
for j in someListOfElements:
result[i].append(j)
That has the benefit of using an already existing type, which is less work, but it does mean you now have a dict (indexed by integers) instead of a list, which may or may not be what you want. Or you could make a class that behaves almost like a list but appends new lists to itself instead of raising IndexError, such as:
import UserList
class defaultlist(UserList.UserList):
def __getitem__(self, idx):
while len(self) <= idx:
self.append([])
return UserList.UserList.__getitem__(self, idx)
result = defaultlist()
for i in range(x):
for j in someListOfElements:
result[i].append(j)
A:
You could write a quick generator function. This would have uses other than this particular case so I'll generalize it a little. Dig this:
def create(n, constructor=list):
for _ in xrange(n):
yield constructor()
Then to make a list of lists,
result = list(create(10))
to make a list of empty dicts,
result = list(create(20, dict))
and (for the sake of completeness) to make a list of empty Foos,
result = list(create(30, Foo))
Of course, you could also make a tuple of any of the above. It wouldn't be too hard to extend it to allow arguments to constructor either. I would probably have it accept a function which accepted an index and returned the arguments to be passed to the constructor.
One last thought is that, because the only requirement that we are placing on constructor is that it be a callable, you could even pass it anything that returns what you want in your list. A bound method that pulls results out of a database query for instance. It's quite a useful little three lines of code.
A:
Why not keep it simple by just appending the list in appropriate loop
result = []
for i in range(x):
result.append([])
for j in someListOfElements:
result[i].append(j)
[Edit: Adding example]
>>> someListOfElements = ['a', 'b', 'c']
>>> x = 3
>>> result = []
>>> for i in range(x):
... result.append([])
... for j in someListOfElements:
... result[i].append(j)
...
>>>
>>> result
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
A:
Please include runnable sample code, so we can run the code ourself to quickly see exactly what it is you want to do. It looks like you just want this:
result = []
for i in range(x):
data = []
for j in someListOfElements:
data.append(j)
# or data = [j for j in someListOfElements]
result.append(data)
| How to create a list or tuple of empty lists in Python? | I need to incrementally fill a list or a tuple of lists. Something that looks like this:
result = []
firstTime = True
for i in range(x):
for j in someListOfElements:
if firstTime:
result.append([f(j)])
else:
result[i].append(j)
In order to make it less verbose an more elegant, I thought I will preallocate a list of empty lists
result = createListOfEmptyLists(x)
for i in range(x):
for j in someListOfElements:
result[i].append(j)
The preallocation part isn't obvious to me. When I do result = [[]] * x, I receive a list of x references to the same list, so that the output of the following
result[0].append(10)
print result
is:
[[10], [10], [10], [10], [10], [10], [10], [10], [10], [10]]
I can use a loop (result = [[] for i in range(x)]), but I wonder whether a "loopless" solution exists.
Is the only way to get what I'm looking for
| [
"result = [list(someListOfElements) for _ in xrange(x)]\n\nThis will make x distinct lists, each with a copy of someListOfElements list (each item in that list is by reference, but the list its in is a copy).\nIf it makes more sense, consider using copy.deepcopy(someListOfElements)\nGenerators and list comprehensio... | [
53,
7,
5,
4,
0
] | [] | [] | [
"memory_management",
"python"
] | stackoverflow_0003880037_memory_management_python.txt |
Q:
Running a job on multiple nodes of a GridEngine cluster
I have access to a 128-core cluster on which I would like to run a parallelised job. The cluster uses Sun GridEngine and my program is written to run using Parallel Python, numpy, scipy on Python 2.5.8. Running the job on a single node (4-cores) yields an ~3.5x improvement over a single core. I would now like to take this to the next level and split the job across ~4 nodes. My qsub script looks something like this:
#!/bin/bash
# The name of the job, can be whatever makes sense to you
#$ -N jobname
# The job should be placed into the queue 'all.q'.
#$ -q all.q
# Redirect output stream to this file.
#$ -o jobname_output.dat
# Redirect error stream to this file.
#$ -e jobname_error.dat
# The batchsystem should use the current directory as working directory.
# Both files will be placed in the current
# directory. The batchsystem assumes to find the executable in this directory.
#$ -cwd
# request Bourne shell as shell for job.
#$ -S /bin/sh
# print date and time
date
# spython is the server's version of Python 2.5. Using python instead of spython causes the program to run in python 2.3
spython programname.py
# print date and time again
date
Does anyone have any idea of how to do this?
A:
Yes, you need to include the Grid Engine option -np 16 either in your script like this:
# Use 16 processors
#$ -np 16
or on the command line when you submit the script. Or, for more permanent arrangements, use an .sge_request file.
On all the GE installations I've ever used this will give you 16 processors (or processor cores these days) on as few nodes as necessary, so if your nodes have 4 cores you'll get 4 nodes, if they have 8 2 and so on. To place the job on, say 2 cores on 8 nodes (which you might want to do if you need a lot of memory for each process) is a little more complicated and you should consult your support team.
| Running a job on multiple nodes of a GridEngine cluster | I have access to a 128-core cluster on which I would like to run a parallelised job. The cluster uses Sun GridEngine and my program is written to run using Parallel Python, numpy, scipy on Python 2.5.8. Running the job on a single node (4-cores) yields an ~3.5x improvement over a single core. I would now like to take this to the next level and split the job across ~4 nodes. My qsub script looks something like this:
#!/bin/bash
# The name of the job, can be whatever makes sense to you
#$ -N jobname
# The job should be placed into the queue 'all.q'.
#$ -q all.q
# Redirect output stream to this file.
#$ -o jobname_output.dat
# Redirect error stream to this file.
#$ -e jobname_error.dat
# The batchsystem should use the current directory as working directory.
# Both files will be placed in the current
# directory. The batchsystem assumes to find the executable in this directory.
#$ -cwd
# request Bourne shell as shell for job.
#$ -S /bin/sh
# print date and time
date
# spython is the server's version of Python 2.5. Using python instead of spython causes the program to run in python 2.3
spython programname.py
# print date and time again
date
Does anyone have any idea of how to do this?
| [
"Yes, you need to include the Grid Engine option -np 16 either in your script like this:\n# Use 16 processors\n#$ -np 16\n\nor on the command line when you submit the script. Or, for more permanent arrangements, use an .sge_request file.\nOn all the GE installations I've ever used this will give you 16 processors ... | [
2
] | [] | [] | [
"python",
"qsub",
"sungridengine"
] | stackoverflow_0003872977_python_qsub_sungridengine.txt |
Q:
Lua equivalent to Python dis()?
In Python you have the ability to view the compiled bytecode of a user-defined function using dis.
Is there a builtin equivalent to this for Lua?
It would really useful!
A:
The luac utility that comes with standard lua can create an assembly listing from Lua source using its -l option. For example, compiling from source on stdin:
C:...> echo a=b | luac -l -
main (3 instructions, 12 bytes at 00334C30)
0+ params, 2 slots, 0 upvalues, 0 locals, 2 constants, 0 functions
1 [1] GETGLOBAL 0 -2 ; b
2 [1] SETGLOBAL 0 -1 ; a
3 [1] RETURN 0 1
C:...>
A:
Chunkspy might be what you're looking for. Quoting from the site:
ChunkSpy is a tool to disassemble a Lua 5 binary chunk into a verbose listing that can then be studied. Its output bears a resemblance to the output listing of assemblers. I wanted something that can tell me in great detail what goes on inside a Lua binary chunk file, not just the instructions. It is intended to be a tool for learning Lua internals as well.
A:
There is also lbci, a bytecode inspector library.
A:
You can also use luac -l to compile a lua file and output the disassembly.
| Lua equivalent to Python dis()? | In Python you have the ability to view the compiled bytecode of a user-defined function using dis.
Is there a builtin equivalent to this for Lua?
It would really useful!
| [
"The luac utility that comes with standard lua can create an assembly listing from Lua source using its -l option. For example, compiling from source on stdin:\n\nC:...> echo a=b | luac -l -\n\nmain (3 instructions, 12 bytes at 00334C30)\n0+ params, 2 slots, 0 upvalues, 0 locals, 2 constants, 0 functions\n ... | [
7,
5,
2,
0
] | [] | [] | [
"bytecode",
"disassembly",
"lua",
"python"
] | stackoverflow_0003872861_bytecode_disassembly_lua_python.txt |
Q:
Arithmetic Progression in Python without storing all the values
I'm trying to represent an array of evenly spaced floats, an arithmetic progression, starting at a0 and with elements a0, a0 + a1, a0 + 2a1, a0 + 3a1, ...
This is what numpy's arange() method does, but it seems to allocate memory for the whole array object and I'd like to do it using an iterator class which just stores a0, a1 and n (the total number of elements, which might be large).
Does anything that does this already exist in the standard Python packages?
I couldn't find it so, ploughed ahead with:
class mylist():
def __init__(self, n, a0, a1):
self._n = n
self._a0 = a0
self._a1 = a1
def __getitem__(self, i):
if i < 0 or i >= self._n:
raise IndexError
return self._a0 + i * self._a1
def __iter__(self):
self._i = 0
return self
def next(self):
if self._i >= self._n:
raise StopIteration
value = self.__getitem__(self._i)
self._i += 1
return value
Is this a sensible approach or am I revinventing the wheel?
A:
Well, one thing that you are doing wrong is that it should be for i, x in enumerate(a): print i, x.
Also, I'd probably use a generator method instead of the hassle with the __iter__ and next() methods, especially because your solution wouldn't allow you to iterate over the same mylist twice at the same time with two different iterators (as self._i is local to the class).
This is probably a better solution which gives you random access as well as an efficient iterator. The support for the in and len operators are thrown in as a bonus :)
class mylist(object):
def __init__(self, n, a0, a1, eps=1e-8):
self._n = n
self._a0 = a0
self._a1 = a1
self._eps = eps
def __contains__(self, x):
y = float(x - self._a0) / self._a1
return 0 <= int(y) < self._n and abs(y - int(y)) < self._eps
def __getitem__(self, i):
if 0 <= i < self._n:
return self._a0 + i * self._a1
raise IndexError
def __iter__(self):
current = self._a0
for i in xrange(self._n):
yield current
current += self._a1
def __len__(self):
return self._n
A:
Other answers answer the immediate problem. Note that if all you want is an iterator and you don't need random access, there's no need to write a whole iterator class.
def mylist(n, a0, a1):
for i in xrange(n):
yield a0 + i*a1
A:
Only for reasons that are probably obvious to someone out there, iterating over mylist: for i,x in enumerate(a): print i,a doesn't return the values I expect but just a whole lot of references to the mylist instance. What am I doing wrong?
The culprit is print i,a. You are printing a, which is an array. You ought to print x instead. Chane this line to:
print i,x
Also a couple of things:
Change you class name to TitleCase. For e.g. class MyList or class Mylist.
It is a good idea to inherit from object if you are using Python 2.x. So class MyList(object): ...
A:
You're enumerating over a, so printing it will print a lot of references to it. Print x instead.
A:
Yes, there's a built-in generator for this (Python 2.7 and up):
import itertools
mygen = itertools.count(a0,a1)
If you don't have Python 2.7 yet (Python 2.4 and up):
import itertools
mygen = (a0 + a1*i for i in itertools.count())
| Arithmetic Progression in Python without storing all the values | I'm trying to represent an array of evenly spaced floats, an arithmetic progression, starting at a0 and with elements a0, a0 + a1, a0 + 2a1, a0 + 3a1, ...
This is what numpy's arange() method does, but it seems to allocate memory for the whole array object and I'd like to do it using an iterator class which just stores a0, a1 and n (the total number of elements, which might be large).
Does anything that does this already exist in the standard Python packages?
I couldn't find it so, ploughed ahead with:
class mylist():
def __init__(self, n, a0, a1):
self._n = n
self._a0 = a0
self._a1 = a1
def __getitem__(self, i):
if i < 0 or i >= self._n:
raise IndexError
return self._a0 + i * self._a1
def __iter__(self):
self._i = 0
return self
def next(self):
if self._i >= self._n:
raise StopIteration
value = self.__getitem__(self._i)
self._i += 1
return value
Is this a sensible approach or am I revinventing the wheel?
| [
"Well, one thing that you are doing wrong is that it should be for i, x in enumerate(a): print i, x.\nAlso, I'd probably use a generator method instead of the hassle with the __iter__ and next() methods, especially because your solution wouldn't allow you to iterate over the same mylist twice at the same time with ... | [
3,
3,
1,
0,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0003880761_arrays_numpy_python.txt |
Q:
Standardizing camera input in OpenCV? (Contrast/Saturation/Brightness etc..)
I am building an application using OpenCV that uses the webcam and runs some vision algorithms. I would like to make this application available on the internet after I am done, but I am concerned about the vast differences in camera settings on every computer, and I am worried that the algorithm may break if the settings are too different from mine.
Is there any way, after capturing the frame, to post process it and make sure that the contrast is X, brightness is Y, and saturation is Z? I think the Camera settings themselves can not be changed from code directly using the current OpenCV Python bindings.
Would anyone be able to tell me about how I could calculate some of these parameters from the image and adjust them appropriately using OpenCV?
A:
You can post process your image in openCV several ways.
To set the contrast you can use equalizeHist function.
To set brightness and saturation you should first convert the image to HSV color space with cvtColor. Then you can modify the saturation and the value (brightness) to an appropriate value by directly accessing each image pixel.
A:
I'm kind of struggling with the same issue. Here's a piece of code that strips all value (brightness) information from an image making it perhaps a bit more stable in situations where the amount of light changes a lot. You can of course adjust any of the other parameters as well:
// img is an rgb image
cvCvtColor(img, img, CV_RGB2HSV);
for( int y=0; y<img->height; y++ ) {
uchar* ptr = (uchar*) (
img->imageData + y * img->widthStep
);
for( int x=0; x<img->width; x++ ) {
ptr[3*x+2] = 255; // maxes the value,
// use +1 for saturation, +0 for hue
}
}
// convert back for displaying
cvCvtColor(img, img, CV_HSV2RGB);
| Standardizing camera input in OpenCV? (Contrast/Saturation/Brightness etc..) | I am building an application using OpenCV that uses the webcam and runs some vision algorithms. I would like to make this application available on the internet after I am done, but I am concerned about the vast differences in camera settings on every computer, and I am worried that the algorithm may break if the settings are too different from mine.
Is there any way, after capturing the frame, to post process it and make sure that the contrast is X, brightness is Y, and saturation is Z? I think the Camera settings themselves can not be changed from code directly using the current OpenCV Python bindings.
Would anyone be able to tell me about how I could calculate some of these parameters from the image and adjust them appropriately using OpenCV?
| [
"You can post process your image in openCV several ways.\nTo set the contrast you can use equalizeHist function.\nTo set brightness and saturation you should first convert the image to HSV color space with cvtColor. Then you can modify the saturation and the value (brightness) to an appropriate value by directly ac... | [
3,
2
] | [] | [] | [
"camera",
"image_processing",
"opencv",
"python"
] | stackoverflow_0002733906_camera_image_processing_opencv_python.txt |
Q:
Require help in Django 'local variable 'form' referenced before assignment'
I am having problem in django. I have created a form in my app where I can take details of a client. Now I want to create a form which can allow me to edit a form. However I am having some problems when I go to /index/edit_client/1, I get this error.
local variable 'form' referenced before assignment
I do not know what the reason why I have got this error, but from what I have looked at, it does not help matters unless of course there is another way how to create an edit form to edit the clients form. Here are some output that can be helpful too.
# urls.py
urlpatterns = patterns('',
(r'^index/$', login_required(direct_to_template), { 'template': 'index.html' }),
(r'^index/clients/$', client_info),
(r'^index/clients_details/(?P<id>\d+)/$', clients_details),
(r'^index/edit_client/(?P<id>\d+)/$', edit_client),
)
# views.py
@login_required
def edit_client(request, id=1):
clients_list = Client.objects.filter(pk=id)
if request.method == 'POST':
form = ClientForm(request.POST or None)
if form.is_valid():
form.save()
return HttpResponseRedirect('/index/clients/')
else: form = ClientForm()
return render_to_response('edit_client.html', {'form': form}, context_instance=RequestContext(request))
#edit_client.html
{% extends "base.html" %}
{% block content %}
<font face="verdana,news gothic,arial,heltevica,serif">
<h3>Edit Client</h3>
</font>
<form method= "POST" action="">
<font face="verdana,news gothic,arial,heltevica,serif">
<div id="form">
<table>
{{form.as_table}}
</table>
<div align="center" STYLE=" margin-right:190px">
<input type="submit" value="Submit" STYLE="background-color:#E8E8E8; color:#181818 "/>
</div>
</div>
</form>
{% endblock %}
A:
This will always run:
return render_to_response('edit_client.html', {'form': form}
But if request.method is not POST, nothing is assigned to form.
Fixed code:
@login_required
def edit_client(request, id=1):
clients_list = Client.objects.filter(pk=id)
form = ClientForm()
if request.method == 'POST':
form = ClientForm(request.POST or None)
if form.is_valid():
form.save()
return HttpResponseRedirect('/index/clients/')
return render_to_response('edit_client.html', {'form': form}, context_instance=RequestContext(request))
A:
In your edit_client method, you pass form in the response, however, if the method wasn't a POST, you won't have initialized a form.
| Require help in Django 'local variable 'form' referenced before assignment' | I am having problem in django. I have created a form in my app where I can take details of a client. Now I want to create a form which can allow me to edit a form. However I am having some problems when I go to /index/edit_client/1, I get this error.
local variable 'form' referenced before assignment
I do not know what the reason why I have got this error, but from what I have looked at, it does not help matters unless of course there is another way how to create an edit form to edit the clients form. Here are some output that can be helpful too.
# urls.py
urlpatterns = patterns('',
(r'^index/$', login_required(direct_to_template), { 'template': 'index.html' }),
(r'^index/clients/$', client_info),
(r'^index/clients_details/(?P<id>\d+)/$', clients_details),
(r'^index/edit_client/(?P<id>\d+)/$', edit_client),
)
# views.py
@login_required
def edit_client(request, id=1):
clients_list = Client.objects.filter(pk=id)
if request.method == 'POST':
form = ClientForm(request.POST or None)
if form.is_valid():
form.save()
return HttpResponseRedirect('/index/clients/')
else: form = ClientForm()
return render_to_response('edit_client.html', {'form': form}, context_instance=RequestContext(request))
#edit_client.html
{% extends "base.html" %}
{% block content %}
<font face="verdana,news gothic,arial,heltevica,serif">
<h3>Edit Client</h3>
</font>
<form method= "POST" action="">
<font face="verdana,news gothic,arial,heltevica,serif">
<div id="form">
<table>
{{form.as_table}}
</table>
<div align="center" STYLE=" margin-right:190px">
<input type="submit" value="Submit" STYLE="background-color:#E8E8E8; color:#181818 "/>
</div>
</div>
</form>
{% endblock %}
| [
"This will always run:\nreturn render_to_response('edit_client.html', {'form': form}\n\nBut if request.method is not POST, nothing is assigned to form.\nFixed code:\n@login_required \ndef edit_client(request, id=1):\n clients_list = Client.objects.filter(pk=id) \n form = ClientForm()\n if request.method =... | [
5,
1
] | [] | [] | [
"django",
"django_forms",
"html",
"python",
"syntax_error"
] | stackoverflow_0003881601_django_django_forms_html_python_syntax_error.txt |
Q:
Problem with MPICH2 & mpi4py Installation
I'm on Windows XP2 32-bit machine. I'm trying to install MPICH2 & mpi4py.
I've downloaded & installed MPICH2-1.2.1p1
I've downloaded & mpi4py
When I run python setup.py install in mpi4pi\ directory. I get
running install
running build
running build_py
running build_ext
MPI configuration: directory 'C:\Program Files\MPICH2'
MPI C compiler: not found
MPI C++ compiler: not found
MPI linker: not found
checking for MPI compile and link ...
error: Unable to find vcvarsall.bat
My C:\Program Files\MPICH2\bin is added in $PATH & it contains:
clog2TOslog2.jar
irlog2rlog.exe
jumpshot.jar
jumpshot_launcher.jar
mpiexec.exe
smpd.exe
TraceInput.dll
traceTOslog2.jar
wmpiconfig.exe
wmpiexec.exe
wmpiregister.exe
I've Googled but no where I could find the solution.
EDIT: As per "High Performance" Mark's suggestion I've gone through that installation script and found that it is searching for mpicc , mpicxx, mpild MPI compiler wrappers. But these wrapper scripts are not installed with my MPICH2 installation. Where to get these? Whats the way now?
A:
I don't know much about Python but here goes anyway:
Your install script is failing to find a C compiler, C++ compiler or linker. Look inside the script and see where it is looking. Modify the script to look in the location where you have those items installed. You may (probably will) also find that you can specify an argument for the install script to point it at the right location without having to modify the script.
Don't forget, MPICH2 is a combination of libraries for linking to and a run-time system, for executing MPI jobs (that's your mpiexec.exe). I see you also have the Jumpshot profiler installed.
MPICH2 is not, and doesn't include, a compiler.
HTH
A:
It looks like the windows MPICH2 binary package doesn't set up the compiler wrappers; you'll probably have to pull down the sources and build it to get support for your devel tools.
| Problem with MPICH2 & mpi4py Installation | I'm on Windows XP2 32-bit machine. I'm trying to install MPICH2 & mpi4py.
I've downloaded & installed MPICH2-1.2.1p1
I've downloaded & mpi4py
When I run python setup.py install in mpi4pi\ directory. I get
running install
running build
running build_py
running build_ext
MPI configuration: directory 'C:\Program Files\MPICH2'
MPI C compiler: not found
MPI C++ compiler: not found
MPI linker: not found
checking for MPI compile and link ...
error: Unable to find vcvarsall.bat
My C:\Program Files\MPICH2\bin is added in $PATH & it contains:
clog2TOslog2.jar
irlog2rlog.exe
jumpshot.jar
jumpshot_launcher.jar
mpiexec.exe
smpd.exe
TraceInput.dll
traceTOslog2.jar
wmpiconfig.exe
wmpiexec.exe
wmpiregister.exe
I've Googled but no where I could find the solution.
EDIT: As per "High Performance" Mark's suggestion I've gone through that installation script and found that it is searching for mpicc , mpicxx, mpild MPI compiler wrappers. But these wrapper scripts are not installed with my MPICH2 installation. Where to get these? Whats the way now?
| [
"I don't know much about Python but here goes anyway:\nYour install script is failing to find a C compiler, C++ compiler or linker. Look inside the script and see where it is looking. Modify the script to look in the location where you have those items installed. You may (probably will) also find that you can sp... | [
3,
0
] | [] | [] | [
"installation",
"mpi",
"python"
] | stackoverflow_0003880231_installation_mpi_python.txt |
Q:
Deciding on RESTful Architecture for my Python code API
I would like to build something like this
Datastore | mycode.py | RESTful API | mywebapp.py(Django or Tornado)
I checked Piston for Django but it seems that this way I am going to be tied to Django, I would rather have a RESTful API for mycode.py that is consumable by more than one REST client and also can consume it from a REST client api inside my django app.
I checked stuff like Apache CFX, ApacheMQ, RabbitMQ, etc. with no real luck.
Any thoughts? thnx
A:
Hmm, if you're into Python and open to a Java element, you might want to consider using the Java framework Restlet with Python code running in Jython. I'm a big fan of Restlet; its API embodies RESTful principles, so it encourages one to structure one's code and thinking according to those principles. It's also just a really high-quality, easy to use, well supported, and lightweight -- it's a framework, but in practice it can feel like a library.
If you want to stick with pure Python, then I haven't been able to find any libraries or frameworks which directly embrace and encourage RESTful principles. However, there are some very good WSGI microframeworks which make it easy to implement RESTful applications -- you just need to devise your own approach to structuring your code -- not too big a deal. In particular I'd recommend Bottle and web.py, both of which can be used with more or less finagling with the excellent mimerender library for solid content negotiation.
| Deciding on RESTful Architecture for my Python code API | I would like to build something like this
Datastore | mycode.py | RESTful API | mywebapp.py(Django or Tornado)
I checked Piston for Django but it seems that this way I am going to be tied to Django, I would rather have a RESTful API for mycode.py that is consumable by more than one REST client and also can consume it from a REST client api inside my django app.
I checked stuff like Apache CFX, ApacheMQ, RabbitMQ, etc. with no real luck.
Any thoughts? thnx
| [
"Hmm, if you're into Python and open to a Java element, you might want to consider using the Java framework Restlet with Python code running in Jython. I'm a big fan of Restlet; its API embodies RESTful principles, so it encourages one to structure one's code and thinking according to those principles. It's also ju... | [
0
] | [] | [] | [
"java",
"python",
"rest"
] | stackoverflow_0003847803_java_python_rest.txt |
Q:
Future and stability of IronPython
I am currently looking for a possible way to integrate my C++/C# application with some of my Python scripts. At this point, IronPython seems like the way to go.
However, before proceeding, I would like to ask the following:
How stable is IronPython right now? Is it ready for production use? Are there any known major quirks/bugs?
What is the future of IronPython? Will it be maintained for bug fixes? Will there be new versions?
I am particularly interested in using IronPython to run a Python web framework such as Django or Web2py. I am very well aware that current Python web frameworks don't play very well with it. Therefore any insights on the future of IronPython's web framework support would be much appreciated as well.
A:
To answer your second question, yes, IronPython will be developed in the future. Right now, there is a "language change moratorium" on CPython, the main branch of Python (see PEP 3003. The Python folks want CPython, Jython, and other branches of Python development to catch up with CPython, and they've been doing just that. If all goes as planned, by the time the moratorium is over, IronPython and others will be up to speed and will have implementations that follow the syntax and features of Python 3.x. Also, since IronPython is backed by Microsoft and is a key part of their Dynamic Language Runtime (whatever that is), it's unlikely to get cancelled.
Right now, IronPython is making good progress. According to their svn, code is being changed fairly regularly (1 check-in every other day or so). A Python 2.7 compatible implementation is in the works, and the alpha was released July 16 (so IronPython 2.7 can be expected in the near future).
As for the stability of the interpreter, it seems rather stable. I haven't used IronPython extensively, but the 2.6.1 release behaves almost exactly like the CPython 2.6 interpreter, disregarding standard library.
A lot of the extensions for CPython don't work with IronPython. So, if you want to use Django or something like that, it's probably not smart to use IronPython because it isn't really cross-platform, doesn't work with some frameworks, and it performs worse than CPython. The real advantage to IronPython is access to everything that .NET has to offer, including ASP.NET (a web framework) and Silverlight.
If you want to use .NET, IronPython is the best route as far as scripting goes.
| Future and stability of IronPython | I am currently looking for a possible way to integrate my C++/C# application with some of my Python scripts. At this point, IronPython seems like the way to go.
However, before proceeding, I would like to ask the following:
How stable is IronPython right now? Is it ready for production use? Are there any known major quirks/bugs?
What is the future of IronPython? Will it be maintained for bug fixes? Will there be new versions?
I am particularly interested in using IronPython to run a Python web framework such as Django or Web2py. I am very well aware that current Python web frameworks don't play very well with it. Therefore any insights on the future of IronPython's web framework support would be much appreciated as well.
| [
"To answer your second question, yes, IronPython will be developed in the future. Right now, there is a \"language change moratorium\" on CPython, the main branch of Python (see PEP 3003. The Python folks want CPython, Jython, and other branches of Python development to catch up with CPython, and they've been doing... | [
9
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0003881418_ironpython_python.txt |
Q:
Python: How to distinguish between inherited methods
Newbie Python question. I have a class that inherits from several classes, and some of the specialization classes override some methods from the base class. In certain cases, I want to call the unspecialized method. Is this possible? If so, what's the syntax?
class Base(object):
def Foo(self):
print "Base.Foo"
def Bar(self):
self.Foo() # Can I force this to call Base.Foo even if Foo has an override?
class Mixin(object):
def Foo(self):
print "Mixin.Foo"
class Composite(Mixin, Base):
pass
x = Composite()
x.Foo() # executes Mixin.Foo, perfect
x.Bar() # indirectly executes Mixin.Foo, but I want Base.Foo
A:
you can specifically make the call you want using the syntax
Base.Foo(self)
in your case:
class Base(object):
# snipped
def Bar(self):
Base.Foo(self) # this will now call Base.Foo regardless of if a subclass
# overrides it
# snipped
x = Composite()
x.Foo() # executes Mixin.Foo, perfect
x.Bar() # prints "Base.Foo"
This works because Python executes calls to bound methods of the form
instance.method(argument)
as if they were a call to an unbound method
Class.method(instance, argument)
so making the call in that form gives you the desired result. Inside the methods, self is just the instance that the method was called on, i.e, the implicit first argument (that's explicit as a parameter)
Note however that if a subclass overrides Bar, then there's nothing (good) that you can effectively do about it AFAIK. But that's just the way things work in python.
| Python: How to distinguish between inherited methods | Newbie Python question. I have a class that inherits from several classes, and some of the specialization classes override some methods from the base class. In certain cases, I want to call the unspecialized method. Is this possible? If so, what's the syntax?
class Base(object):
def Foo(self):
print "Base.Foo"
def Bar(self):
self.Foo() # Can I force this to call Base.Foo even if Foo has an override?
class Mixin(object):
def Foo(self):
print "Mixin.Foo"
class Composite(Mixin, Base):
pass
x = Composite()
x.Foo() # executes Mixin.Foo, perfect
x.Bar() # indirectly executes Mixin.Foo, but I want Base.Foo
| [
"you can specifically make the call you want using the syntax\nBase.Foo(self)\n\nin your case:\nclass Base(object):\n # snipped\n\n def Bar(self):\n Base.Foo(self) # this will now call Base.Foo regardless of if a subclass\n # overrides it\n\n# snipped\n\n\nx = Composite()\nx.Foo... | [
6
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0003882109_inheritance_oop_python.txt |
Q:
Adding dynamic property to a python object
site = object()
mydict = {'name': 'My Site', 'location': 'Zhengjiang'}
for key, value in mydict.iteritems():
setattr(site, key, value)
print site.a # it doesn't work
The above code didn't work. Any suggestion?
A:
The easiest way to populate one dict with another is the update() method, so if you extend object to ensure your object has a __dict__ you could try something like this:
>>> class Site(object):
... pass
...
>>> site = Site()
>>> site.__dict__.update(dict)
>>> site.a
Or possibly even:
>>> class Site(object):
... def __init__(self,dict):
... self.__dict__.update(dict)
...
>>> site = Site(dict)
>>> site.a
A:
As docs say, object() returns featureless object, meaning it cannot have any attributes. It doesn't have __dict__.
What you could do is the following:
>>> site = type('A', (object,), {'a': 42})
>>> site.a
42
A:
class site(object):
pass
for k,v in dict.iteritems():
setattr(site,k,v)
print site.a #it does works
| Adding dynamic property to a python object | site = object()
mydict = {'name': 'My Site', 'location': 'Zhengjiang'}
for key, value in mydict.iteritems():
setattr(site, key, value)
print site.a # it doesn't work
The above code didn't work. Any suggestion?
| [
"The easiest way to populate one dict with another is the update() method, so if you extend object to ensure your object has a __dict__ you could try something like this:\n>>> class Site(object):\n... pass\n...\n>>> site = Site()\n>>> site.__dict__.update(dict)\n>>> site.a\n\nOr possibly even:\n>>> class Site(o... | [
7,
5,
1
] | [] | [] | [
"add",
"dynamic",
"properties",
"python"
] | stackoverflow_0003881895_add_dynamic_properties_python.txt |
Q:
IE7 vs. A Python Pickle Object
I have an issue with IE7 not wanting to pass a pickled object through a ajax call using HTMLTMPL. It works in IE8 (and in compatibility mode) as well as in Firefox.
I have pickled an object using the command:
newhash['pickled'] = pickle.dumps(hash)
Because JS didn't like the newlines, i regex them out using:
newhash['pickled'] = re.sub('\n', 'LINEBREAK', newhash['pickled'])
When I catch my pickled object in Python, it takes out LINEBREAK and puts back in \n. My ajax call looks like this:
$.getJSON('/folder/MyPython.py', {'mode':'MyFunction', 'pickled':"<TMPL_VAR pickled ESCAPE="NONE">"}, function(data){
I alert right before it and right after it and everything works as expected. If i alert in the function(data) section, nothing gets alerted. However, if i take out the 'pickled' key in the ajax call, everything works fine. The pickled object is all the variables needed for my python to do calculations, so simply not passing it is not an option.
My pickled object looks like this:
(dp0LINEBREAKS'rlbool'LINEBREAKp1LINEBREAKL1LLINEBREAKsS'class7'LINEBREAKp2LINEBREAKS'50'LINEBREAKp3LINEBREAKsS'fedxbool'LINEBREAKp4LINEBREAKL1LLINEBREAKsS'weight1'LINEBREAKp5LINEBREAKS'1500'LINEBREAKp6LINEBREAKsS'conwaybool'LINEBREAKp7LINEBREAKL1LLINEBREAKsS'originzip'LINEBREAKp8LINEBREAKS'37130'LINEBREAKp9LINEBREAKsS'company'LINEBREAKp10LINEBREAKS''LINEBREAKp11LINEBREAKsS'destinationzip'LINEBREAKp12LINEBREAKS'37130'LINEBREAKp13LINEBREAKsS'class6'LINEBREAKp14LINEBREAKS'50'LINEBREAKp15LINEBREAKsS'mode'LINEBREAKp16LINEBREAKS'Crawl'LINEBREAKp17LINEBREAKsS'averitlogin'LINEBREAKp18LINEBREAKS'QVSINC'LINEBREAKp19LINEBREAKsS'accessories'LINEBREAKp20LINEBREAK(lp21LINEBREAKsS'address'LINEBREAKp22LINEBREAKS'330%20Robert%20Rose%20Blvd.'LINEBREAKp23LINEBREAKsS'active'LINEBREAKp24LINEBREAKL1LLINEBREAKsS'averittbool'LINEBREAKp25LINEBREAKL1LLINEBREAKsS'id'LINEBREAKp26LINEBREAKL19LLINEBREAKsS'averitpass'LINEBREAKp27LINEBREAKS'MERIDIAN'LINEBREAKp28LINEBREAKsS'shipmentdate'LINEBREAKp29LINEBREAKS'2010-10-08'LINEBREAKp30LINEBREAKsS'city'LINEBREAKp31LINEBREAKS'Murfreesboro'LINEBREAKp32LINEBREAKsS'class5'LINEBREAKp33LINEBREAKS'50'LINEBREAKp34LINEBREAKsS'last'LINEBREAKp35LINEBREAKS'Morgan'LINEBREAKp36LINEBREAKsS'originstate'LINEBREAKp37LINEBREAKS'TN'LINEBREAKp38LINEBREAKsS'zip'LINEBREAKp39LINEBREAKS'37129'LINEBREAKp40LINEBREAKsS'phone'LINEBREAKp41LINEBREAKS'615%20713-5432'LINEBREAKp42LINEBREAKsS'destinationstate'LINEBREAKp43LINEBREAKS'TN'LINEBREAKp44LINEBREAKsS'Accessories'LINEBREAKp45LINEBREAK(lp46LINEBREAKsS'comments'LINEBREAKp47LINEBREAKg11LINEBREAKsS'estesbool'LINEBREAKp48LINEBREAKL1LLINEBREAKsS'origincity'LINEBREAKp49LINEBREAKS'Murfreesboro'LINEBREAKp50LINEBREAKsS'class8'LINEBREAKp51LINEBREAKS'50'LINEBREAKp52LINEBREAKsS'state'LINEBREAKp53LINEBREAKS'TN'LINEBREAKp54LINEBREAKsS'email'LINEBREAKp55LINEBREAKS'chris2'LINEBREAKp56LINEBREAKsS'vitranbool'LINEBREAKp57LINEBREAKL1LLINEBREAKsS'saiabool'LINEBREAKp58LINEBREAKL1LLINEBREAKsS'destinationcity'LINEBREAKp59LINEBREAKS'Murfreesboro'LINEBREAKp60LINEBREAKsS'class3'LINEBREAKp61LINEBREAKS'50'LINEBREAKp62LINEBREAKsS'class4'LINEBREAKp63LINEBREAKS'50'LINEBREAKp64LINEBREAKsS'class1'LINEBREAKp65LINEBREAKS'50'LINEBREAKp66LINEBREAKsS'class2'LINEBREAKp67LINEBREAKS'50'LINEBREAKp68LINEBREAKsS'address2'LINEBREAKp69LINEBREAKg11LINEBREAKsS'first'LINEBREAKp70LINEBREAKS'Chris'LINEBREAKp71LINEBREAKs.
I can only assume that there is some character in here that IE7 has a problem with.
Thanks in advance for all the help.
A:
First, read Why Python Pickle is Insecure. Don't use pickled objects that could be modified by users.
Instead, why not simply use JSON, which is obviously made for JavaScript. It is included in Python >= 2.6 and also available for older versions. As your data is just a dictionary, JSON should work just fine.
Another option would be base-64 encoding, which shouldn't get you into trouble with special characters.
A:
This means that the pickled data could be changed on the user's side? Would be a high security risk.
A:
The answer was URL length. The max request url length is 2083 and I was going over it. Fixed!
| IE7 vs. A Python Pickle Object | I have an issue with IE7 not wanting to pass a pickled object through a ajax call using HTMLTMPL. It works in IE8 (and in compatibility mode) as well as in Firefox.
I have pickled an object using the command:
newhash['pickled'] = pickle.dumps(hash)
Because JS didn't like the newlines, i regex them out using:
newhash['pickled'] = re.sub('\n', 'LINEBREAK', newhash['pickled'])
When I catch my pickled object in Python, it takes out LINEBREAK and puts back in \n. My ajax call looks like this:
$.getJSON('/folder/MyPython.py', {'mode':'MyFunction', 'pickled':"<TMPL_VAR pickled ESCAPE="NONE">"}, function(data){
I alert right before it and right after it and everything works as expected. If i alert in the function(data) section, nothing gets alerted. However, if i take out the 'pickled' key in the ajax call, everything works fine. The pickled object is all the variables needed for my python to do calculations, so simply not passing it is not an option.
My pickled object looks like this:
(dp0LINEBREAKS'rlbool'LINEBREAKp1LINEBREAKL1LLINEBREAKsS'class7'LINEBREAKp2LINEBREAKS'50'LINEBREAKp3LINEBREAKsS'fedxbool'LINEBREAKp4LINEBREAKL1LLINEBREAKsS'weight1'LINEBREAKp5LINEBREAKS'1500'LINEBREAKp6LINEBREAKsS'conwaybool'LINEBREAKp7LINEBREAKL1LLINEBREAKsS'originzip'LINEBREAKp8LINEBREAKS'37130'LINEBREAKp9LINEBREAKsS'company'LINEBREAKp10LINEBREAKS''LINEBREAKp11LINEBREAKsS'destinationzip'LINEBREAKp12LINEBREAKS'37130'LINEBREAKp13LINEBREAKsS'class6'LINEBREAKp14LINEBREAKS'50'LINEBREAKp15LINEBREAKsS'mode'LINEBREAKp16LINEBREAKS'Crawl'LINEBREAKp17LINEBREAKsS'averitlogin'LINEBREAKp18LINEBREAKS'QVSINC'LINEBREAKp19LINEBREAKsS'accessories'LINEBREAKp20LINEBREAK(lp21LINEBREAKsS'address'LINEBREAKp22LINEBREAKS'330%20Robert%20Rose%20Blvd.'LINEBREAKp23LINEBREAKsS'active'LINEBREAKp24LINEBREAKL1LLINEBREAKsS'averittbool'LINEBREAKp25LINEBREAKL1LLINEBREAKsS'id'LINEBREAKp26LINEBREAKL19LLINEBREAKsS'averitpass'LINEBREAKp27LINEBREAKS'MERIDIAN'LINEBREAKp28LINEBREAKsS'shipmentdate'LINEBREAKp29LINEBREAKS'2010-10-08'LINEBREAKp30LINEBREAKsS'city'LINEBREAKp31LINEBREAKS'Murfreesboro'LINEBREAKp32LINEBREAKsS'class5'LINEBREAKp33LINEBREAKS'50'LINEBREAKp34LINEBREAKsS'last'LINEBREAKp35LINEBREAKS'Morgan'LINEBREAKp36LINEBREAKsS'originstate'LINEBREAKp37LINEBREAKS'TN'LINEBREAKp38LINEBREAKsS'zip'LINEBREAKp39LINEBREAKS'37129'LINEBREAKp40LINEBREAKsS'phone'LINEBREAKp41LINEBREAKS'615%20713-5432'LINEBREAKp42LINEBREAKsS'destinationstate'LINEBREAKp43LINEBREAKS'TN'LINEBREAKp44LINEBREAKsS'Accessories'LINEBREAKp45LINEBREAK(lp46LINEBREAKsS'comments'LINEBREAKp47LINEBREAKg11LINEBREAKsS'estesbool'LINEBREAKp48LINEBREAKL1LLINEBREAKsS'origincity'LINEBREAKp49LINEBREAKS'Murfreesboro'LINEBREAKp50LINEBREAKsS'class8'LINEBREAKp51LINEBREAKS'50'LINEBREAKp52LINEBREAKsS'state'LINEBREAKp53LINEBREAKS'TN'LINEBREAKp54LINEBREAKsS'email'LINEBREAKp55LINEBREAKS'chris2'LINEBREAKp56LINEBREAKsS'vitranbool'LINEBREAKp57LINEBREAKL1LLINEBREAKsS'saiabool'LINEBREAKp58LINEBREAKL1LLINEBREAKsS'destinationcity'LINEBREAKp59LINEBREAKS'Murfreesboro'LINEBREAKp60LINEBREAKsS'class3'LINEBREAKp61LINEBREAKS'50'LINEBREAKp62LINEBREAKsS'class4'LINEBREAKp63LINEBREAKS'50'LINEBREAKp64LINEBREAKsS'class1'LINEBREAKp65LINEBREAKS'50'LINEBREAKp66LINEBREAKsS'class2'LINEBREAKp67LINEBREAKS'50'LINEBREAKp68LINEBREAKsS'address2'LINEBREAKp69LINEBREAKg11LINEBREAKsS'first'LINEBREAKp70LINEBREAKS'Chris'LINEBREAKp71LINEBREAKs.
I can only assume that there is some character in here that IE7 has a problem with.
Thanks in advance for all the help.
| [
"First, read Why Python Pickle is Insecure. Don't use pickled objects that could be modified by users.\nInstead, why not simply use JSON, which is obviously made for JavaScript. It is included in Python >= 2.6 and also available for older versions. As your data is just a dictionary, JSON should work just fine.\nAno... | [
3,
1,
0
] | [] | [] | [
"ajax",
"internet_explorer_7",
"pickle",
"python"
] | stackoverflow_0003881958_ajax_internet_explorer_7_pickle_python.txt |
Q:
Grab elements inside parentheses
How can I grab the elements inside the parentheses and put them in a file?
me (I)
you (You)
him (He)
her (She)
Thanks in advance,
Adia
A:
import re
txt = 'me (I) you (You) him (He) her (She)'
words = re.findall('\((.+?)\)', txt)
# words returns: ['I', 'You', 'He', 'She']
with open('filename.txt', 'w') as out:
out.write('\n'.join(words))
# file 'filename.txt' contains now:
I
You
He
She
A:
Have you checked out pyparsing?
from pyparsing import Word, alphas
text = "me (I) you (You) him (He) her (She)"
parser = "(" + Word(alphas).setResultsName("value") + ")"
out = open("myfile.txt", "w")
for token, start, end in parser.scanString(text):
print >>out, token.value
Output:
I
You
He
She
A:
Just a few simple string manipulation will do
>>> s="me (I) you (You) him (He) her (She)"
>>> for i in s.split(")"):
... if "(" in i:
... print i.split("(")[-1]
...
I
You
He
She
| Grab elements inside parentheses | How can I grab the elements inside the parentheses and put them in a file?
me (I)
you (You)
him (He)
her (She)
Thanks in advance,
Adia
| [
"import re\n\ntxt = 'me (I) you (You) him (He) her (She)'\nwords = re.findall('\\((.+?)\\)', txt)\n\n# words returns: ['I', 'You', 'He', 'She']\nwith open('filename.txt', 'w') as out:\n out.write('\\n'.join(words))\n\n# file 'filename.txt' contains now:\n\nI\nYou\nHe\nShe\n\n",
"Have you checked out pyparsing?... | [
5,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003882407_python_regex.txt |
Q:
Python 2.6 to 2.5 cheat sheet
I've written my code to target Python 2.6.5, but I now need to run it on a cluster that only has 2.5.4, something that wasn't on the horizon when I wrote the code. Backporting the code to 2.5 shouldn't be too hard, but I was wondering if there was either a cheat-sheet or an automated tool that would help me with this. For some things, like the with statement, the right __future__ imports will do the trick, but not for some other things.
A:
Have you read the What's New in Python 2.6 document? It describes the 2.5->2.6 direction, but you should be able to figure out the reverse from it.
As far as I know, there are no automated tools for 2.6 to 2.5. The only tool I know of is the 2to3 app for going to Python 3.
A:
Have you tried pyqver? It will tell you which is the minimum version of Python required by your code
I hope it helps
| Python 2.6 to 2.5 cheat sheet | I've written my code to target Python 2.6.5, but I now need to run it on a cluster that only has 2.5.4, something that wasn't on the horizon when I wrote the code. Backporting the code to 2.5 shouldn't be too hard, but I was wondering if there was either a cheat-sheet or an automated tool that would help me with this. For some things, like the with statement, the right __future__ imports will do the trick, but not for some other things.
| [
"Have you read the What's New in Python 2.6 document? It describes the 2.5->2.6 direction, but you should be able to figure out the reverse from it.\nAs far as I know, there are no automated tools for 2.6 to 2.5. The only tool I know of is the 2to3 app for going to Python 3.\n",
"Have you tried pyqver? It will ... | [
8,
4
] | [] | [] | [
"backport",
"python",
"python_2.5",
"python_2.6"
] | stackoverflow_0003881980_backport_python_python_2.5_python_2.6.txt |
Q:
Getting rid of \x## in strings (Python)
I need to extract a description from a file, which looks like this:
"TES4!\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00\x00\x00HEDR\x0c\x00\xd7\xa3p?h\x03\x00\x00\x00\x08\x00\xffCNAM\t\x00Martigen\x00SNAM\xaf\x00Mart's Mutant Mod - RC4\n\nDiverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, improved AI, improved factions, and much more.\n\n\x00MAST\r\x00Fallout3.esm\x00DATA\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00MAST\x16\x00Mart's Mutant Mod.esm\x00DATA\x08"
I've laready figured out how to get the part I need, but there's still some unwanted data in there that I don't know how to get rid of:
\xaf\x00Mart's Mutant Mod - RC4\n\nDiverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, improved AI, improved factions, and much more.\n\n\x00
should become:
Mart's Mutant Mod - RC4\n\nDiverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, improved AI, improved factions, and much more.\n\n\
Basically, I need a way to get rid of the \x## stuff (which if left in there will end up as weird characters when displayed in the GUI), but I haven't managed to get to successfully remove them.
[In case you were wondering, it's .esp files for FO3 I'm messing around with.]
A:
you could try:
import string
cleaneddata = ''.join(c for c in data if c in string.printable)
This assumes that you already have data in a string.
Here's how it works for me:
>>> s = """TES4!\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00\x00\x00HEDR\x0c\x00\xd7\xa3p?h\x03\x00\x00\x00\x08\x00\xffCNAM\t\x00Martigen\x00SNAM\xaf\x00Mart's Mutant Mod - RC4\n\nDiverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, improved AI, improved factions, and much more.\n\n\x00MAST\r\x00Fallout3.esm\x00DATA\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00MAST\x16\x00Mart's Mutant Mod.esm\x00DATA\x08"""
>>> print ''.join(c for c in s if c in string.printable)TES4!HEDR
p?hCNAM MartigenSNAMMart's Mutant Mod - RC4
Diverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, improved AI, improved factions, and much more.
Fallout3.esmDATAMASTMart's Mutant Mod.esmDATA
>>>
Not ideal as you can see but that might at least be a good first step.
A:
First thing we do is pull up some docs. If we take a look at the bottom it shows how the SNAM subrecord should be handled. So we use struct to read the length, then we grab that many bytes (I'm guessing that you forgot to open the file in binary mode, since the count is off in your example) from the string, null-terminated. And then there's nothing left to do, since we have what we came for.
A:
If you are up to the point of
\xaf\x00Mart's Mutant Mod -
RC4\n\nDiverse creatures & NPCs, new
creatures & NPCs, dynamic size and
stat scaling, increased spawns,
improved AI, improved factions, and
much more.\n\n\x00
you can do the following to get rid of the last unwanted \x## by doing:
exp = re.compile(r"\\x[\w]")
newStr = [s for s in str.split("\\x00") if not re.search(exp, s)]
newStr = "".join(newStr)
| Getting rid of \x## in strings (Python) | I need to extract a description from a file, which looks like this:
"TES4!\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00\x00\x00HEDR\x0c\x00\xd7\xa3p?h\x03\x00\x00\x00\x08\x00\xffCNAM\t\x00Martigen\x00SNAM\xaf\x00Mart's Mutant Mod - RC4\n\nDiverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, improved AI, improved factions, and much more.\n\n\x00MAST\r\x00Fallout3.esm\x00DATA\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00MAST\x16\x00Mart's Mutant Mod.esm\x00DATA\x08"
I've laready figured out how to get the part I need, but there's still some unwanted data in there that I don't know how to get rid of:
\xaf\x00Mart's Mutant Mod - RC4\n\nDiverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, improved AI, improved factions, and much more.\n\n\x00
should become:
Mart's Mutant Mod - RC4\n\nDiverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, improved AI, improved factions, and much more.\n\n\
Basically, I need a way to get rid of the \x## stuff (which if left in there will end up as weird characters when displayed in the GUI), but I haven't managed to get to successfully remove them.
[In case you were wondering, it's .esp files for FO3 I'm messing around with.]
| [
"you could try:\nimport string\n\ncleaneddata = ''.join(c for c in data if c in string.printable)\n\nThis assumes that you already have data in a string.\nHere's how it works for me:\n>>> s = \"\"\"TES4!\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0f\\x00\\x00\\x00HEDR\\x0c\\x00\\xd... | [
4,
4,
0
] | [] | [] | [
"file",
"python",
"string"
] | stackoverflow_0003882607_file_python_string.txt |
Q:
Caesar Cipher in python
The error which i am getting is
Traceback (most recent call last):
File "imp.py", line 52, in <module>
mode = getMode()
File "imp.py", line 8, in getMode
mode = input().lower()
File "<string>", line 1, in <module>
NameError: name 'encrypt' is not defined
Below is the code.
# Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
print('Enter your message:')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
A:
The problem is here:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
In Python 2.x input use raw_input() instead of input().
Python 2.x:
Read a string from standard input: raw_input()
Read a string from standard input and then evaluate it: input().
Python 3.x:
Read a string from standard input: input()
Read a string from standard input and then evaluate it: eval(input()).
A:
input() evaluates the expression you type. Use raw_input() instead.
| Caesar Cipher in python | The error which i am getting is
Traceback (most recent call last):
File "imp.py", line 52, in <module>
mode = getMode()
File "imp.py", line 8, in getMode
mode = input().lower()
File "<string>", line 1, in <module>
NameError: name 'encrypt' is not defined
Below is the code.
# Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
print('Enter your message:')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
| [
"The problem is here:\nprint('Do you wish to encrypt or decrypt a message?')\nmode = input().lower()\n\nIn Python 2.x input use raw_input() instead of input().\nPython 2.x:\n\nRead a string from standard input: raw_input()\nRead a string from standard input and then evaluate it: input().\n\nPython 3.x:\n\nRead a st... | [
7,
2
] | [] | [] | [
"input",
"python",
"python_2.x"
] | stackoverflow_0003883074_input_python_python_2.x.txt |
Q:
Qt Python Combo-Box "currentIndexChanged" firing twice
I have a combo, which is showing some awkward behavior. Given a list of options from the combo-box, the user should pick the name of a city clicking with the mouse. Here is the code:
QtCore.QObject.connect(self.comboCity, QtCore.SIGNAL("currentIndexChanged(QString)"), self.checkChosenCity)
def checkChosenCity(self):
self.cityName=self.comboCity.currentText()
print "the city chosen is:"
print "%s" % self.cityName
The problem is, each time a city is chosen, connect calls the function checkChosenCity twice.
This combo is a hierarchical combo, i.e. after in the first combo a customer is chosen, then in the second combo-box comes the list of cities for that customer.
I hope someone here can point out or guess why this is happening.
A:
I had exactly the same problem. After some debugging it turned out that using
currentIndexChanged(int)
instead of
currentIndexChanged(QString)
fixed it for me.
It still don't understand why the former fires twice.
| Qt Python Combo-Box "currentIndexChanged" firing twice | I have a combo, which is showing some awkward behavior. Given a list of options from the combo-box, the user should pick the name of a city clicking with the mouse. Here is the code:
QtCore.QObject.connect(self.comboCity, QtCore.SIGNAL("currentIndexChanged(QString)"), self.checkChosenCity)
def checkChosenCity(self):
self.cityName=self.comboCity.currentText()
print "the city chosen is:"
print "%s" % self.cityName
The problem is, each time a city is chosen, connect calls the function checkChosenCity twice.
This combo is a hierarchical combo, i.e. after in the first combo a customer is chosen, then in the second combo-box comes the list of cities for that customer.
I hope someone here can point out or guess why this is happening.
| [
"I had exactly the same problem. After some debugging it turned out that using \ncurrentIndexChanged(int)\ninstead of\ncurrentIndexChanged(QString)\nfixed it for me.\nIt still don't understand why the former fires twice.\n"
] | [
0
] | [
"Thanks Eli..\nHere is what I have:\ncombo1 : [customernames] - pick a customer.\ncombo2 : [cityList] - pick a city for the chosen customer.\ncombo3 : [emploeeList] - load employees for that city, given the chosen customer.\n\nWhat I find out is that, even when no city is chosen, the combox-box for city is activate... | [
-1
] | [
"combobox",
"pyqt",
"python",
"qt"
] | stackoverflow_0001997478_combobox_pyqt_python_qt.txt |
Q:
Handling HTTP/1.1 Upgrade requests in CherryPy
I'm using CherryPy for a web server, but would like it to handle HTTP/1.1 Upgrade requests. Thus, when a client sends:
OPTIONS * HTTP/1.1
Upgrade: NEW_PROTOCOL/1.0
Connection: Upgrade
I'd like the server to hand the connection off to some NEW_PROTOCOL handler after responding with the necessary HTTP/1.1 101 Switching Protocols..., as specified in RFC 2817.
I'm pretty new to CherryPy, and couldn't find anything in the documentation on how to handle specific client requests such as the above. If someone could point me to a tutorial or parts of the CherryPy documentation or even a solution, that would be very helpful.
A:
This is fairly easy to do in trunk (which will eventually be 3.2 final). I'm sure it's possible in older versions but much more convoluted.
All you need to do is make a new subclass of wsgiserver.Gateway that looks for the headers in question and then either hands off the conn or proceeds to the usual gateway. For example:
class UpgradeGateway(Gateway):
def respond(self):
h = self.req.inheaders
if h.get("Connection", "") == "Upgrade":
# Turn off auto-output of HTTP response headers
self.req.sent_headers = True
# Not sure exactly what you want to pass or how, here's a start...
return protocols[h['Upgrade']].handle(self.req.rfile, self.req.wfile)
else:
return old_gateway(self.req).respond()
old_gateway = cherrypy.server.httpserver.gateway
cherrypy.server.httpserver.gateway = UpgradeGateway
There may be a couple other fine points but that's the general technique.
| Handling HTTP/1.1 Upgrade requests in CherryPy | I'm using CherryPy for a web server, but would like it to handle HTTP/1.1 Upgrade requests. Thus, when a client sends:
OPTIONS * HTTP/1.1
Upgrade: NEW_PROTOCOL/1.0
Connection: Upgrade
I'd like the server to hand the connection off to some NEW_PROTOCOL handler after responding with the necessary HTTP/1.1 101 Switching Protocols..., as specified in RFC 2817.
I'm pretty new to CherryPy, and couldn't find anything in the documentation on how to handle specific client requests such as the above. If someone could point me to a tutorial or parts of the CherryPy documentation or even a solution, that would be very helpful.
| [
"This is fairly easy to do in trunk (which will eventually be 3.2 final). I'm sure it's possible in older versions but much more convoluted.\nAll you need to do is make a new subclass of wsgiserver.Gateway that looks for the headers in question and then either hands off the conn or proceeds to the usual gateway. Fo... | [
2
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0003859823_cherrypy_python.txt |
Q:
How do I cleanly bridge client connections between a frontend webserver and a backend running CherryPy?
The title may be a bit vague, but here's my goal: I have a frontend webserver which takes incoming HTTP requests, does some preprocessing on them, and then passes the requests off to my real webserver to get the HTTP response, which is then passed back to the client.
Currently, my frontend is built off of BaseHTTPServer.HTTPServer and the backend is CherryPy.
So the question is: Is there a way to take these HTTP requests / client connections and insert them into a CherryPy server to get the HTTP response? One obvious solution is to run an instance of the CherryPy backend on a local port or using UNIX domain sockets, and then the frontend webserver establishes a connection with the backend and relays any requests/responses. Obviously, this isn't ideal due to the overhead.
What I'd really like is for the CherryPy backend to not bind to any port, but just sit there waiting for the frontend to pass the client's socket (as well as the modified HTTP Request info), at which point it does its normal CherryPy magic and returns the request directly to the client.
I've been perusing the CherryPy source to find some way to accomplish this, and currently am attempting to modify wsgiserver.CherryPyWSGIServer, but it's getting pretty hairy and is probably not the best approach.
A:
Is your main app a wsgi application? If so, you could write some middleware that wraps around it and does all the request wrangling before passing on to the main application.
If this this is possible it would avoid you having to run two webservers and all the problems you are encountering.
A:
Answered the Upgrade question at Handling HTTP/1.1 Upgrade requests in CherryPy. Not sure if that addresses this one or not.
| How do I cleanly bridge client connections between a frontend webserver and a backend running CherryPy? | The title may be a bit vague, but here's my goal: I have a frontend webserver which takes incoming HTTP requests, does some preprocessing on them, and then passes the requests off to my real webserver to get the HTTP response, which is then passed back to the client.
Currently, my frontend is built off of BaseHTTPServer.HTTPServer and the backend is CherryPy.
So the question is: Is there a way to take these HTTP requests / client connections and insert them into a CherryPy server to get the HTTP response? One obvious solution is to run an instance of the CherryPy backend on a local port or using UNIX domain sockets, and then the frontend webserver establishes a connection with the backend and relays any requests/responses. Obviously, this isn't ideal due to the overhead.
What I'd really like is for the CherryPy backend to not bind to any port, but just sit there waiting for the frontend to pass the client's socket (as well as the modified HTTP Request info), at which point it does its normal CherryPy magic and returns the request directly to the client.
I've been perusing the CherryPy source to find some way to accomplish this, and currently am attempting to modify wsgiserver.CherryPyWSGIServer, but it's getting pretty hairy and is probably not the best approach.
| [
"Is your main app a wsgi application? If so, you could write some middleware that wraps around it and does all the request wrangling before passing on to the main application. \nIf this this is possible it would avoid you having to run two webservers and all the problems you are encountering.\n",
"Answered the Up... | [
1,
0
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0003875490_cherrypy_python.txt |
Q:
Stop-word elimination and stemmer in python
I have a somewhat large document and want to do stop-word elimination and stemming on the words of this document with Python. Does anyone know an of the shelf package for these?
If not a code which is fast enough for large documents is also welcome.
Thanks
A:
NLTK supports this.
A:
If for some reason you don't want to use NLTK, you can try PyStemmer. For stop words just download a list (google it) and filter them out.
| Stop-word elimination and stemmer in python | I have a somewhat large document and want to do stop-word elimination and stemming on the words of this document with Python. Does anyone know an of the shelf package for these?
If not a code which is fast enough for large documents is also welcome.
Thanks
| [
"NLTK supports this.\n",
"If for some reason you don't want to use NLTK, you can try PyStemmer. For stop words just download a list (google it) and filter them out.\n"
] | [
8,
4
] | [] | [] | [
"nlp",
"python",
"stemming",
"stop_words"
] | stackoverflow_0003882921_nlp_python_stemming_stop_words.txt |
Q:
How to change text on gtk.label in frequent intervals - PyGTK
I am coding a desktop application which shows contents from text file in a gtk.label, i update that text file, say once in every 15 mints. Are are there any methods to make the application to read the text file in constant intervals and display it without restarting the window
A:
On all platforms, you can call gobject.timeout_add() to read the file every once in a while, or gobject.idle_add() with an mtime check to do it when the app is idle.
On linux, I'd recommend using pyinotify to monitor the file and re-read it only when it's updated.
| How to change text on gtk.label in frequent intervals - PyGTK | I am coding a desktop application which shows contents from text file in a gtk.label, i update that text file, say once in every 15 mints. Are are there any methods to make the application to read the text file in constant intervals and display it without restarting the window
| [
"On all platforms, you can call gobject.timeout_add() to read the file every once in a while, or gobject.idle_add() with an mtime check to do it when the app is idle.\nOn linux, I'd recommend using pyinotify to monitor the file and re-read it only when it's updated.\n"
] | [
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003883431_gtk_pygtk_python.txt |
Q:
Adding Values to an Array and getting distinct values using Python
I have python code below that will loop through a table and print out values within a particular column. What is not shown is the form in which the user selects a Feature Layer. Once the Feature Layer is selected a second Dropdown is populated with all the Column Headings for that Feature and the user chooses which Column they want to focus on. Now within the python script, I simply print out each value within that column. But I want to store each value in a List or Array and get Distinct values. How can I do this in Python?
Also is there a more efficient way to loop through the table than to go row by row? That is very slow for some reason.
many thanks
# Import system modules
import sys, string, os, arcgisscripting
# Create the Geoprocessor object
gp = arcgisscripting.create(9.3)
gp.AddToolbox("E:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
# Declare our user input args
input_dataset = sys.argv[1] #This is the Feature Layer the User wants to Query against
Atts = sys.argv[2] #This is the Column Name The User Selected
#Lets Loop through the rows to get values from a particular column
fc = input_dataset
gp.AddMessage(Atts)
rows = gp.searchcursor(fc)
row = rows.next()
NewList = []
for row in gp.SearchCursor(fc):
##grab field values
fcValue = fields.getvalue(Atts)
NewList.add(fcValue)
A:
You can store distinct values in a set:
>>> a = [ 1, 2, 3, 1, 5, 3, 2, 1, 5, 4 ]
>>> b = set( a )
>>> b
{1, 2, 3, 4, 5}
>>> b.add( 5 )
>>> b
{1, 2, 3, 4, 5}
>>> b.add( 6 )
>>> b
{1, 2, 3, 4, 5, 6}
Also you can make your loop more pythonic, although I'm not sure why you loop over the row to begin with (given that you are not using it):
for row in gp.searchcursor( fc ):
##grab field values
fcValue = fields.getvalue(Atts)
gp.AddMessage(fcValue)
And btw, """ text """ is not a comment. Python only has single line comments starting with #.
A:
One way to get distinct values is to use a set to see if you've seen the value already, and display it only when it's a new value:
fcValues = set()
for row in gp.searchcursor(fc):
##grab field values
fcValue = fields.getvalue(Atts)
if fcValue not in fcValues:
gp.AddMessage(fcValue)
fcValues.add(fcValue)
| Adding Values to an Array and getting distinct values using Python | I have python code below that will loop through a table and print out values within a particular column. What is not shown is the form in which the user selects a Feature Layer. Once the Feature Layer is selected a second Dropdown is populated with all the Column Headings for that Feature and the user chooses which Column they want to focus on. Now within the python script, I simply print out each value within that column. But I want to store each value in a List or Array and get Distinct values. How can I do this in Python?
Also is there a more efficient way to loop through the table than to go row by row? That is very slow for some reason.
many thanks
# Import system modules
import sys, string, os, arcgisscripting
# Create the Geoprocessor object
gp = arcgisscripting.create(9.3)
gp.AddToolbox("E:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
# Declare our user input args
input_dataset = sys.argv[1] #This is the Feature Layer the User wants to Query against
Atts = sys.argv[2] #This is the Column Name The User Selected
#Lets Loop through the rows to get values from a particular column
fc = input_dataset
gp.AddMessage(Atts)
rows = gp.searchcursor(fc)
row = rows.next()
NewList = []
for row in gp.SearchCursor(fc):
##grab field values
fcValue = fields.getvalue(Atts)
NewList.add(fcValue)
| [
"You can store distinct values in a set:\n>>> a = [ 1, 2, 3, 1, 5, 3, 2, 1, 5, 4 ]\n>>> b = set( a )\n>>> b\n{1, 2, 3, 4, 5}\n>>> b.add( 5 )\n>>> b\n{1, 2, 3, 4, 5}\n>>> b.add( 6 )\n>>> b\n{1, 2, 3, 4, 5, 6}\n\nAlso you can make your loop more pythonic, although I'm not sure why you loop over the row to begin with ... | [
3,
1
] | [] | [] | [
"arcgis",
"python"
] | stackoverflow_0003883836_arcgis_python.txt |
Q:
Any dhcp python library?
Is there any library to help me instantiate a dhcp server in python?
A:
There are some in development and alpha verity :
http://ostatic.com/pydhcpd/
Other servers:
http://code.google.com/p/staticdhcpd/
And a library for working on dhcp too
http://nixbit.com/cat/programming/libraries/pydhcplib/
DHCP command line query and testing tool
http://code.google.com/p/dhquery/
A:
You might take a look at pydhcplib or anemon for starters.
| Any dhcp python library? | Is there any library to help me instantiate a dhcp server in python?
| [
"There are some in development and alpha verity :\n\nhttp://ostatic.com/pydhcpd/\n\nOther servers:\n\nhttp://code.google.com/p/staticdhcpd/\n\nAnd a library for working on dhcp too\n\nhttp://nixbit.com/cat/programming/libraries/pydhcplib/\n\nDHCP command line query and testing tool\n\nhttp://code.google.com/p/dhque... | [
8,
4
] | [] | [] | [
"dhcp",
"python"
] | stackoverflow_0003883811_dhcp_python.txt |
Q:
How to: remove part of a Unicode string in Python following a special character
first a short summery:
python ver: 3.1
system: Linux (Ubuntu)
I am trying to do some data retrieval through Python and BeautifulSoup.
Unfortunately some of the tables I am trying to process contains cells where the following text string exists:
789.82 ± 10.28
For this i to work i need two things:
How do i handle "weird" symbols such as: ±
and how do i remove the part of the string containing: ± and everything to the right of this?
Currently i get an error like: SyntaxError: Non-ASCII charecter '\xc2' in file ......
Thank you for your help
[edit]:
# dataretriveal from html files from DETHERM
# -*- coding: utf8 -*-
import sys,os,re
from BeautifulSoup import BeautifulSoup
sys.path.insert(0, os.getcwd())
raw_data = open('download.php.html','r')
soup = BeautifulSoup(raw_data)
for numdiv in soup.findAll('div', {"id" : "sec"}):
currenttable = numdiv.find('table',{"class" : "data"})
if currenttable:
numrow=0
for row in currenttable.findAll('td', {"class" : "dataHead"}):
numrow=numrow+1
for col in currenttable.findAll('td'):
col2 = ''.join(col.findAll(text=True))
if col2.index('±'):
col2=col2[:col2.indeindex('±')]
print(col)
print(numrow)
ref=numdiv.find('a')
niceref=''.join(ref.findAll(text=True))
print(niceref)
Now this code is followed by an error of:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
Where did the ASCII reference pop up from ?
A:
You need to have your Python file encoded in utf-8. Otherwise, it's quite trivial:
>>> s = '789.82 ± 10.28'
>>> s[:s.index('±')]
'789.82 '
>>> s.partition('±')
('789.82 ', '±', ' 10.28')
| How to: remove part of a Unicode string in Python following a special character | first a short summery:
python ver: 3.1
system: Linux (Ubuntu)
I am trying to do some data retrieval through Python and BeautifulSoup.
Unfortunately some of the tables I am trying to process contains cells where the following text string exists:
789.82 ± 10.28
For this i to work i need two things:
How do i handle "weird" symbols such as: ±
and how do i remove the part of the string containing: ± and everything to the right of this?
Currently i get an error like: SyntaxError: Non-ASCII charecter '\xc2' in file ......
Thank you for your help
[edit]:
# dataretriveal from html files from DETHERM
# -*- coding: utf8 -*-
import sys,os,re
from BeautifulSoup import BeautifulSoup
sys.path.insert(0, os.getcwd())
raw_data = open('download.php.html','r')
soup = BeautifulSoup(raw_data)
for numdiv in soup.findAll('div', {"id" : "sec"}):
currenttable = numdiv.find('table',{"class" : "data"})
if currenttable:
numrow=0
for row in currenttable.findAll('td', {"class" : "dataHead"}):
numrow=numrow+1
for col in currenttable.findAll('td'):
col2 = ''.join(col.findAll(text=True))
if col2.index('±'):
col2=col2[:col2.indeindex('±')]
print(col)
print(numrow)
ref=numdiv.find('a')
niceref=''.join(ref.findAll(text=True))
print(niceref)
Now this code is followed by an error of:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
Where did the ASCII reference pop up from ?
| [
"You need to have your Python file encoded in utf-8. Otherwise, it's quite trivial:\n>>> s = '789.82 ± 10.28'\n>>> s[:s.index('±')]\n'789.82 '\n>>> s.partition('±')\n('789.82 ', '±', ' 10.28')\n\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"special_characters",
"string",
"unicode"
] | stackoverflow_0003883976_beautifulsoup_python_special_characters_string_unicode.txt |
Q:
Maintaining a Python Object when embedding in C
Due to refactoring/reworking on a controller I've had to embed a Python Interpreter inside a C application. I can now call python functions and pass/get Objects into Python fine.
The python code is a controller for a robot (currently simulated), this now needs make use of some C code for comparisons I'm making.
Previously the Python code created objects, read sensors, ran control code and wrote the outputs to motors. All of this except the control code now needs to be done in C. The problem I have is that Objects which are created in an init function (in python) which, when I come to run the control code no longer exist.
What is the best way to solve this? My idea was to return the controllers from the init function and store references to them in the C, passing the reference to the controller each time it is called.
Thanks for any help.
A:
This may not be the answer you want, but there are ways of working with C and Python other than embedding an interpreter inside a C application.
Namely, why don't you do the opposite? Create C libraries for Python? You can control the general flow of your application in Python, which is much more comfortable, and call C code whenever you see fit.
Again, I'm not really addressing your actual question, so feel free to ignore me.
| Maintaining a Python Object when embedding in C | Due to refactoring/reworking on a controller I've had to embed a Python Interpreter inside a C application. I can now call python functions and pass/get Objects into Python fine.
The python code is a controller for a robot (currently simulated), this now needs make use of some C code for comparisons I'm making.
Previously the Python code created objects, read sensors, ran control code and wrote the outputs to motors. All of this except the control code now needs to be done in C. The problem I have is that Objects which are created in an init function (in python) which, when I come to run the control code no longer exist.
What is the best way to solve this? My idea was to return the controllers from the init function and store references to them in the C, passing the reference to the controller each time it is called.
Thanks for any help.
| [
"This may not be the answer you want, but there are ways of working with C and Python other than embedding an interpreter inside a C application.\nNamely, why don't you do the opposite? Create C libraries for Python? You can control the general flow of your application in Python, which is much more comfortable, and... | [
1
] | [] | [] | [
"c",
"embedded_language",
"python"
] | stackoverflow_0003883724_c_embedded_language_python.txt |
Q:
Designing an Python API: Fluent interface or arguments
I'm playing around with a simple port of the Protovis API to Python.
Consider the simple bar chart example, in Javascript:
var vis = new pv.Panel()
.width(150)
.height(150);
vis.add(pv.Bar)
.data([1, 1.2, 1.7, 1.5, .7, .3])
.width(20)
.height(function(d) d * 80)
.bottom(0)
.left(function() this.index * 25);
vis.render();
I'm debating whether to continue to use this fluent interface style API or use named parameters instead. With named parameters we could write:
vis = pv.Panel(width=150,
height=150)
vis = vis + pv.Bar(data=[1, 1.2],
width=20,
height=lambda d: d * 80,
bottom=0,
left=lambda: self.index * 25)
vis.render()
Is there a preferred Python style?
A:
My vote is anti-chaining, pro-named-params.
dot-chaining makes for poor code-intellisense since the empirical prototype is just an empty Panel() or Bar(), you can of course pydoc on it, but in this day and age intellisense is available in most IDEs and a great productivity booster.
Chaining makes programatically calling the class much more difficult. It's very nice to be able to pass in a list or dict as *args, **kwargs -- while possible with chaining you'd basically have to support both methods or a bunch of backflips to meta-create the class.
Chaining makes code more difficult to read because inevitably someone will do it all on one line, and wonder why things are all goofed up when they've passed in the same param twice -- you can prevent that but with a named param constructor dup filtering is basically built in.
| Designing an Python API: Fluent interface or arguments | I'm playing around with a simple port of the Protovis API to Python.
Consider the simple bar chart example, in Javascript:
var vis = new pv.Panel()
.width(150)
.height(150);
vis.add(pv.Bar)
.data([1, 1.2, 1.7, 1.5, .7, .3])
.width(20)
.height(function(d) d * 80)
.bottom(0)
.left(function() this.index * 25);
vis.render();
I'm debating whether to continue to use this fluent interface style API or use named parameters instead. With named parameters we could write:
vis = pv.Panel(width=150,
height=150)
vis = vis + pv.Bar(data=[1, 1.2],
width=20,
height=lambda d: d * 80,
bottom=0,
left=lambda: self.index * 25)
vis.render()
Is there a preferred Python style?
| [
"My vote is anti-chaining, pro-named-params.\n\ndot-chaining makes for poor code-intellisense since the empirical prototype is just an empty Panel() or Bar(), you can of course pydoc on it, but in this day and age intellisense is available in most IDEs and a great productivity booster.\nChaining makes programatical... | [
20
] | [] | [] | [
"interface_design",
"python"
] | stackoverflow_0003883907_interface_design_python.txt |
Q:
combining strings using string substitution - python
hey guys, i want to perform the following operation:
b = 'random'
c = 'stuff'
a = '%s' + '%s' %(b, c)
but i get the following error:
TypeError: not all arguments converted during string formatting
does any one of you know to do so ?
A:
'%s%s' % (b, c)
or
b + c
or the newstyle format way
'{0}{1}'.format(a, b)
A:
Depending on what you want :
>>> b = 'random'
>>> c = 'stuff'
>>> a = '%s' %b + '%s' % c
>>> a
'randomstuff'
>>>
>>> b + c
'randomstuff'
>>>
>>> z = '%s + %s' % (b, c)
>>> z
'random + stuff'
>>>
A:
Due to operator precedence, your program is first trying to substitue b and c into second '%s'. Therefore splitting such strings with + is meaningless, it's better to do
a = '%s %s' % (b,c)
| combining strings using string substitution - python | hey guys, i want to perform the following operation:
b = 'random'
c = 'stuff'
a = '%s' + '%s' %(b, c)
but i get the following error:
TypeError: not all arguments converted during string formatting
does any one of you know to do so ?
| [
"'%s%s' % (b, c)\n\nor \nb + c\n\nor the newstyle format way\n'{0}{1}'.format(a, b)\n\n",
"Depending on what you want :\n>>> b = 'random'\n>>> c = 'stuff'\n>>> a = '%s' %b + '%s' % c\n>>> a\n'randomstuff'\n>>> \n\n>>> b + c\n'randomstuff'\n>>> \n>>> z = '%s + %s' % (b, c)\n>>> z\n'random + stuff'\n>>> \n\n",
"... | [
4,
1,
1
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0003884061_python_syntax.txt |
Q:
How to deal with IndentationError?
I get the following error:
File "imp.py", line 55
key = get Key()
^
IndentationError: expected an indented block
With the following Code:
# Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt or brute force a message?')
mode = raw_input().lower()
if mode in 'encrypt e decrypt d brute b'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d" or "brute" or "b".')
def getMessage():
print('Enter your message:')
return raw_input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(raw_input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
if mode[0] != 'b':
key = getKey()
print('Your translated text is:')
if mode[0] != 'b':
print(getTranslatedMessage(mode, message, key))
else:
for key in range(1, MAX_KEY_SIZE + 1):
print(key, getTranslatedMessage('decrypt', message, key))
How can I fix this?
A:
Do not use += to build strings. Use ''.join(mylist)
Do as it asks: give it an indented block.
A:
From An Informal Introduction to Python, "The body of the loop is indented: indentation is Python’s way of grouping statements."
If you are familiar with C or Java, you might recognize this syntax:
if (...)
{
//do something
}
Python does this w/ indentations:
if ...
#do something
That said, the rest of your code seems to understand this point. That you were unable to recognize this when the error occurred means either you got very lucky or you're using someone else's code.
I hope, for your sake, that this isn't a homework assignment, because most universities take a very dim view of plagiarism.
| How to deal with IndentationError? | I get the following error:
File "imp.py", line 55
key = get Key()
^
IndentationError: expected an indented block
With the following Code:
# Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt or brute force a message?')
mode = raw_input().lower()
if mode in 'encrypt e decrypt d brute b'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d" or "brute" or "b".')
def getMessage():
print('Enter your message:')
return raw_input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(raw_input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
if mode[0] != 'b':
key = getKey()
print('Your translated text is:')
if mode[0] != 'b':
print(getTranslatedMessage(mode, message, key))
else:
for key in range(1, MAX_KEY_SIZE + 1):
print(key, getTranslatedMessage('decrypt', message, key))
How can I fix this?
| [
"\nDo not use += to build strings. Use ''.join(mylist)\nDo as it asks: give it an indented block.\n\n",
"From An Informal Introduction to Python, \"The body of the loop is indented: indentation is Python’s way of grouping statements.\"\nIf you are familiar with C or Java, you might recognize this syntax:\nif (..... | [
3,
2
] | [] | [] | [
"indentation",
"python",
"syntax"
] | stackoverflow_0003884006_indentation_python_syntax.txt |
Q:
How do I use regular expressions to parse HTML tags?
Was wondering how I would extrapolate the value of an html element using a regular expression (in python preferably).
For example, <a href="http://google.com"> Hello World! </a>
What regex would I use to extract Hello World! from the above html?
A:
Using regex to parse HTML has been covered extensively on SO. The consensus is that it shouldn't be done.
Here are some related links worth reading:
RegEx match open tags except XHTML self-contained tags
http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html
One trick I have used in the past to parse HTML files is convert it to XHTML and then treat it as an xml file and use xPath. If this is an option look at:
HTML Tidy
SGML Reader
A:
Regex + HTML...
But BeautifulSoup is a handy library.
>>> from BeautifulSoup import BeautifulSoup
>>> html = '<a href="http://google.com"> Hello World! </a>'
>>> soup = BeautifulSoup(html)
>>> soup.a.string
u' Hello World! '
This, for instance, would print out links on this page:
import urllib2
from BeautifulSoup import BeautifulSoup
q = urllib2.urlopen('https://stackoverflow.com/questions/3884419/')
soup = BeautifulSoup(q.read())
for link in soup.findAll('a'):
if link.has_key('href'):
print str(link.string) + " -> " + link['href']
elif link.has_key('id'):
print "ID: " + link['id']
else:
print "???"
Output:
Stack Exchange -> http://stackexchange.com
log in -> /users/login?returnurl=%2fquestions%2f3884419%2f
careers -> http://careers.stackoverflow.com
meta -> http://meta.stackoverflow.com
...
ID: flag-post-3884419
None -> /posts/3884419/revisions
...
A:
Ideally you wouldn't use a Regular expression - they are unsuitable for most parsing tasks, including HTML. Use a parsing library - I'm not an expert python user, but I'm sure there's one to be had.
| How do I use regular expressions to parse HTML tags? | Was wondering how I would extrapolate the value of an html element using a regular expression (in python preferably).
For example, <a href="http://google.com"> Hello World! </a>
What regex would I use to extract Hello World! from the above html?
| [
"Using regex to parse HTML has been covered extensively on SO. The consensus is that it shouldn't be done.\nHere are some related links worth reading:\n\nRegEx match open tags except XHTML self-contained tags\nhttp://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html\n\nOne trick I have used in th... | [
8,
7,
0
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0003884419_html_python_regex.txt |
Q:
Is there a processing python implementation?
There are javascript and actionscript ports of Processing.
Is there a python port ?
A:
There is pyprocessing, which is experimental.
A:
And there's the more pythonic: http://nodebox.net/code/index.php/Home
A:
Just to add to the existing answers: Field, via @yaxu
Update
As of 15.04.2014 (version 2.1.2) Processing includes a Python mode in development.
A:
pygame already comes pretty close to covering most of the features of processing, and is very pythonic
| Is there a processing python implementation? | There are javascript and actionscript ports of Processing.
Is there a python port ?
| [
"There is pyprocessing, which is experimental. \n",
"And there's the more pythonic: http://nodebox.net/code/index.php/Home\n",
"Just to add to the existing answers: Field, via @yaxu\n\n\n\nUpdate\nAs of 15.04.2014 (version 2.1.2) Processing includes a Python mode in development.\n",
"pygame already comes pret... | [
5,
3,
1,
1
] | [] | [] | [
"port",
"processing",
"python"
] | stackoverflow_0003398190_port_processing_python.txt |
Q:
How can I open a Python shell at a network path in Windows?
How can I open a Python interpreter at a specific network path in Windows?
In the Explorer address bar the path is in UNC form: \\myhost\myshare\....
I can't work out how to change to this directory from the Windows command line, nor in what format I could pass it as an argument to os.chdir.
I'm running Python 2.5 on Windows XP. IDLE is installed.
Thanks!
A:
Well, I'm going to ask it anyway because it has bit me before but have you tried something like this?
path = r'\\myhost\myshare\some_file.dat'
The r being the important bit here.See this post as well.
A:
You need to map it as a drive.
A:
hope this helps : http://www.blog.pythonlibrary.org/2008/05/12/mapping-drives-on-windows/
EDIT :
for root, dirs, files in os.walk(r'\\myhost\myshare\'):
print root, dirs
| How can I open a Python shell at a network path in Windows? | How can I open a Python interpreter at a specific network path in Windows?
In the Explorer address bar the path is in UNC form: \\myhost\myshare\....
I can't work out how to change to this directory from the Windows command line, nor in what format I could pass it as an argument to os.chdir.
I'm running Python 2.5 on Windows XP. IDLE is installed.
Thanks!
| [
"Well, I'm going to ask it anyway because it has bit me before but have you tried something like this?\npath = r'\\\\myhost\\myshare\\some_file.dat'\n\nThe r being the important bit here.See this post as well.\n",
"You need to map it as a drive.\n",
"hope this helps : http://www.blog.pythonlibrary.org/2008/05/1... | [
2,
0,
0
] | [] | [] | [
"python",
"windows_xp"
] | stackoverflow_0003884881_python_windows_xp.txt |
Q:
Parse dict of dicts to string
I have a dictionary with following structure :
{1: {'message': u'test', 'user': u'user1'},
2: {'message': u'test2', 'user': u'user2'}}
I'd like to create a string containing values from the inner dictionary in this form :
string = "<span>test1</span><span>user1</span><br />
<span>test2</span>..."
I've tried everything from dict.keys(), dict.values(), (k,v) for k, v in dict but I cannot make it work. What is the proper way ?
A:
>>> d={1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}
>>> ''.join('<span>%(message)s</span><span>%(user)s</span><br/>' % v for k,v in sorted(d.items()))
u'<span>test</span><span>user1</span><br/><span>test2</span><span>user2</span><br/>'
A:
How about something like this:
dod = {1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}
string = ""
for v in dod.values():
string = string + "<span>"+v['message'] + "</span><span>" + v['user'] + "</span><br />\n"
Or, in much better python style
string = '\n'.join( ("<span>"+v['message'] + "</span><span>" + v['user'] + "</span><br />" for v in dod.values()) )
If you need the users sorted, you could have
ksorted = sort(dod.keys())
for k in ksorted:
v = dod[k]
string = string + "<span>"+v['message'] + "</span><span>" + v['user'] + "</span><br />\n"
A:
data = {1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}
strg = "".join(["<span>%s</span><span>%s</span><br />" % (item['message'], item['user']) for item in x.values()])
print strg
A:
like this?
>>> d={1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}
>>> l=[]
>>> for k,v in d.iteritems():
... l.append('%s%s%s' % ('<span>', '</span><span>'.join(v.values()),'</span>'))
...
>>> print '<br/>\n'.join(l)
<span>test</span><span>user1</span><br/>
<span>test2</span><span>user2</span>
| Parse dict of dicts to string | I have a dictionary with following structure :
{1: {'message': u'test', 'user': u'user1'},
2: {'message': u'test2', 'user': u'user2'}}
I'd like to create a string containing values from the inner dictionary in this form :
string = "<span>test1</span><span>user1</span><br />
<span>test2</span>..."
I've tried everything from dict.keys(), dict.values(), (k,v) for k, v in dict but I cannot make it work. What is the proper way ?
| [
">>> d={1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}\n\n>>> ''.join('<span>%(message)s</span><span>%(user)s</span><br/>' % v for k,v in sorted(d.items()))\nu'<span>test</span><span>user1</span><br/><span>test2</span><span>user2</span><br/>'\n\n",
"How about something like... | [
4,
1,
1,
0
] | [] | [] | [
"dictionary",
"parsing",
"python"
] | stackoverflow_0003884990_dictionary_parsing_python.txt |
Q:
Why am I getting Name Error when importing a class?
I am just starting to learn Python, but I have already run into some errors. I have made a file called pythontest.py with the following contents:
class Fridge:
"""This class implements a fridge where ingredients can be added and removed individually
or in groups"""
def __init__(self, items={}):
"""Optionally pass in an initial dictionary of items"""
if type(items) != type({}):
raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
self.items = items
return
I want to create a new instance of the class in the interactive terminal, so I run the following commands in my terminal:
python3
>> import pythontest
>> f = Fridge()
I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Fridge' is not defined
The interactive console cannot find the class I made. The import worked successfully, though. There were no errors.
A:
No one seems to mention that you can do
from pythontest import Fridge
That way you can now call Fridge() directly in the namespace without importing using the wildcard
A:
You need to do:
>>> import pythontest
>>> f = pythontest.Fridge()
Bonus: your code would be better written like this:
def __init__(self, items=None):
"""Optionally pass in an initial dictionary of items"""
if items is None:
items = {}
if not isinstance(items, dict):
raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
self.items = items
A:
Try
import pythontest
f=pythontest.Fridge()
When you import pythontest, the variable name pythontest is added to the global namespace and is a reference to the module pythontest. To access objects in the pythontest namespace, you must preface their names with pythontest followed by a period.
import pythontest the preferred way to import modules and access objects within the module.
from pythontest import *
should (almost) always be avoided. The only times when I think it is acceptable is when setting up variables inside a package's __init__, and when working within an interactive session. Among the reasons why from pythontest import * should be avoided is that it makes it difficult to know where variables came from. This makes debugging and maintaining code harder. It also doesn't assist mocking and unit-testing. import pythontest gives pythontest its own namespace. And as the Zen of Python says, "Namespaces are one honking great idea -- let's do more of those!"
A:
You're supposed to import the names, i.e., either
import pythontest
f= pythontest.Fridge()
or,
from pythontest import *
f = Fridge()
| Why am I getting Name Error when importing a class? | I am just starting to learn Python, but I have already run into some errors. I have made a file called pythontest.py with the following contents:
class Fridge:
"""This class implements a fridge where ingredients can be added and removed individually
or in groups"""
def __init__(self, items={}):
"""Optionally pass in an initial dictionary of items"""
if type(items) != type({}):
raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
self.items = items
return
I want to create a new instance of the class in the interactive terminal, so I run the following commands in my terminal:
python3
>> import pythontest
>> f = Fridge()
I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Fridge' is not defined
The interactive console cannot find the class I made. The import worked successfully, though. There were no errors.
| [
"No one seems to mention that you can do \nfrom pythontest import Fridge\n\nThat way you can now call Fridge() directly in the namespace without importing using the wildcard\n",
"You need to do:\n>>> import pythontest\n>>> f = pythontest.Fridge()\n\nBonus: your code would be better written like this:\ndef __init_... | [
9,
5,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003885084_python.txt |
Q:
Determine IP address of CONNECTED interface (linux) in python
On my linux machine, 1 of 3 network interfaces may be actually connected to the internet. I need to get the IP address of the currently connected interface, keeping in mind that my other 2 interfaces may be assigned IP addresses, just not be connected.
I can just ping a website through each of my interfaces to determine which one has connectivity, but I'd like to get this faster than waiting for a ping time out. And I'd like to not have to rely on an external website being up.
Update:
All my interfaces may have ip addresses and gateways. This is for an embedded device. So we allow the user to choose between say eth0 and eth1. But if there's no connection on the interface that the user tells us to use, we fall back to say eth2 which (in theory) will always work.
So what I need to do is first check if the user's selection is connected and if so return that IP. Otherwise I need to get the ip of eth2. I can get the IPs of the interfaces just fine, it's just determining which one is actually connected.
A:
If the default gateway for the system is reliable, then grab that from the output from route -n the line that contains " UG " (note the spaces) will also contain the IP of the gateway and interface name of the active interface.
A:
the solution is here : http://code.activestate.com/recipes/439093-get-names-of-all-up-network-interfaces-linux-only/
import fcntl
import array
import struct
import socket
import platform
"""
global constants. If you don't like 'em here,
move 'em inside the function definition.
"""
SIOCGIFCONF = 0x8912
MAXBYTES = 8096
def localifs():
"""
Used to get a list of the up interfaces and associated IP addresses
on this machine (linux only).
Returns:
List of interface tuples. Each tuple consists of
(interface name, interface IP)
"""
global SIOCGIFCONF
global MAXBYTES
arch = platform.architecture()[0]
# I really don't know what to call these right now
var1 = -1
var2 = -1
if arch == '32bit':
var1 = 32
var2 = 32
elif arch == '64bit':
var1 = 16
var2 = 40
else:
raise OSError("Unknown architecture: %s" % arch)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * MAXBYTES)
outbytes = struct.unpack('iL', fcntl.ioctl(
sock.fileno(),
SIOCGIFCONF,
struct.pack('iL', MAXBYTES, names.buffer_info()[0])
))[0]
namestr = names.tostring()
return [(namestr[i:i+var1].split('\0', 1)[0], socket.inet_ntoa(namestr[i+20:i+24])) \
for i in xrange(0, outbytes, var2)]
print localifs()
| Determine IP address of CONNECTED interface (linux) in python | On my linux machine, 1 of 3 network interfaces may be actually connected to the internet. I need to get the IP address of the currently connected interface, keeping in mind that my other 2 interfaces may be assigned IP addresses, just not be connected.
I can just ping a website through each of my interfaces to determine which one has connectivity, but I'd like to get this faster than waiting for a ping time out. And I'd like to not have to rely on an external website being up.
Update:
All my interfaces may have ip addresses and gateways. This is for an embedded device. So we allow the user to choose between say eth0 and eth1. But if there's no connection on the interface that the user tells us to use, we fall back to say eth2 which (in theory) will always work.
So what I need to do is first check if the user's selection is connected and if so return that IP. Otherwise I need to get the ip of eth2. I can get the IPs of the interfaces just fine, it's just determining which one is actually connected.
| [
"If the default gateway for the system is reliable, then grab that from the output from route -n the line that contains \" UG \" (note the spaces) will also contain the IP of the gateway and interface name of the active interface.\n",
"the solution is here : http://code.activestate.com/recipes/439093-get-names-of... | [
0,
0
] | [] | [] | [
"ip_address",
"linux",
"networking",
"python"
] | stackoverflow_0003885160_ip_address_linux_networking_python.txt |
Q:
using function attributes to store results for lazy (potential) processing
I'm doing some collision detection and I would very much like to use the same function in two different contexts. In one context, I would like for it to be something like
def detect_collisions(item, others):
return any(collides(item, other) for other in others)
and in another, I would like it to be
def get_collisions(item, others):
return [other for other in others if collides(item, other)]
I really hate the idea of writing two functions here. Just keeping their names straight is one turnoff and complicating the interface to the collision detecting is another. so I was thinking:
def peek(gen):
try:
first = next(gen)
except StopIteration:
return False
else:
return it.chain((first,), gen)
def get_collisions(item, others):
get_collisions.all = peek(other for other in others if collides(item, other))
return get_collisions.all
Now when I just want to do a check, I can say:
if get_collisions(item, others):
# aw snap
or
if not get_collisions(item, others):
# w00t
and in the other context where I actually want to examine them, I can do:
if get_collisions(item, others):
for collision in get_collisions.all:
# fix it
and in both cases, I don't do any more processing than I need to.
I recognize that this is more code than the first two functions but it also has the advantage of:
Keeping my interface to the collision detection as a tree with the node at the top level instead of a mid level. This seems simpler.
Hooking myself up with a handy peek function. If I use it one other time, then I'm actually writing less code. (In response to YAGNI, if I have it, I will)
So. If you were the proverbial homicidal maniac that knows where I live, would I be expecting a visit from you if I wrote the above code? If so, how would you approach this situation?
A:
Just make get_collisions return a generator:
def get_collisions(item, others):
return (other for other in others if collides(item, other))
Then, if you want to do a check:
for collision in get_collisions(item, others):
print 'Collision!'
break
else:
print 'No collisions!'
A:
This is very similar to what we were discussing in "pythonic way to rewrite an assignment in an if statement", but this version only handles one positional or one keyword argument per call so one can always retrieve the actual valued cached (not just whether is a True value in the Pythonian boolean sense or not).
I never really cared for your proposal to accept multiple keywords and have differently named functions depending on whether you wanted all the results put through any() or all() -- but liked the idea of using keyword arguments which would allow a single function to be used in two or more spots simultaneously. Here's what I ended up with:
# can be called with a single unnamed value or a single named value
def cache(*args, **kwargs):
if len(args)+len(kwargs) == 1:
if args:
name, value = 'value', args[0] # default attr name 'value'
else:
name, value = kwargs.items()[0]
else:
raise NotImplementedError('"cache" calls require either a single value argument '
'or a name=value argument identifying an attribute.')
setattr(cache, name, value)
return value
# add a sub-function to clear the cache attributes (optional and a little weird)
cache.clear = lambda: cache.func_dict.clear()
# you could then use it either of these two ways
if get_collisions(item, others):
# no cached value
if cache(collisions=get_collisions(item, others)):
for collision in cache.collisions:
# fix them
By putting all the ugly details in a separate function, it doesn't affect the code in get_collisions() one way or the other, and is also available for use elsewhere.
| using function attributes to store results for lazy (potential) processing | I'm doing some collision detection and I would very much like to use the same function in two different contexts. In one context, I would like for it to be something like
def detect_collisions(item, others):
return any(collides(item, other) for other in others)
and in another, I would like it to be
def get_collisions(item, others):
return [other for other in others if collides(item, other)]
I really hate the idea of writing two functions here. Just keeping their names straight is one turnoff and complicating the interface to the collision detecting is another. so I was thinking:
def peek(gen):
try:
first = next(gen)
except StopIteration:
return False
else:
return it.chain((first,), gen)
def get_collisions(item, others):
get_collisions.all = peek(other for other in others if collides(item, other))
return get_collisions.all
Now when I just want to do a check, I can say:
if get_collisions(item, others):
# aw snap
or
if not get_collisions(item, others):
# w00t
and in the other context where I actually want to examine them, I can do:
if get_collisions(item, others):
for collision in get_collisions.all:
# fix it
and in both cases, I don't do any more processing than I need to.
I recognize that this is more code than the first two functions but it also has the advantage of:
Keeping my interface to the collision detection as a tree with the node at the top level instead of a mid level. This seems simpler.
Hooking myself up with a handy peek function. If I use it one other time, then I'm actually writing less code. (In response to YAGNI, if I have it, I will)
So. If you were the proverbial homicidal maniac that knows where I live, would I be expecting a visit from you if I wrote the above code? If so, how would you approach this situation?
| [
"Just make get_collisions return a generator:\ndef get_collisions(item, others):\n return (other for other in others if collides(item, other))\n\nThen, if you want to do a check:\nfor collision in get_collisions(item, others):\n print 'Collision!'\n break\nelse:\n print 'No collisions!'\n\n",
"This is... | [
4,
0
] | [] | [] | [
"function_attributes",
"python"
] | stackoverflow_0003881211_function_attributes_python.txt |
Q:
Is it possible to use a USB flash drive to serve files locally to a browser?
Using just python, is it possible to possible to use a USB flash drive to serve files locally to a browser, and save information off the online web?
Ideally I would only need python.
Where would I start?
A:
You can use portable python on the flash drive. Portable Python And code some sort of little python webserver, handling get and post extending the BaseHTTPRequestHandler class.
A:
This doesn't seem much different then serving files from a local hard drive. You could map the thumbdrive to always be something not currently used on your machine (like U:).
| Is it possible to use a USB flash drive to serve files locally to a browser? | Using just python, is it possible to possible to use a USB flash drive to serve files locally to a browser, and save information off the online web?
Ideally I would only need python.
Where would I start?
| [
"You can use portable python on the flash drive. Portable Python And code some sort of little python webserver, handling get and post extending the BaseHTTPRequestHandler class.\n",
"This doesn't seem much different then serving files from a local hard drive. You could map the thumbdrive to always be something n... | [
1,
0
] | [] | [] | [
"python",
"usb",
"web_services"
] | stackoverflow_0003885519_python_usb_web_services.txt |
Q:
Special character use in Python 2.6
I am more than a bit tired, but here goes:
I am doing tome HTML scraping in python 2.6.5 with BeautifulSoap on an ubuntubox
Reason for python 2.6.5: BeautifulSoap sucks under 3.1
I try to run the following code:
# dataretriveal from html files from DETHERM
# -*- coding: utf-8 -*-
import sys,os,re,csv
from BeautifulSoup import BeautifulSoup
sys.path.insert(0, os.getcwd())
raw_data = open('download.php.html','r')
soup = BeautifulSoup(raw_data)
for numdiv in soup.findAll('div', {"id" : "sec"}):
currenttable = numdiv.find('table',{"class" : "data"})
if currenttable:
numrow=0
numcol=0
data_list=[]
for row in currenttable.findAll('td', {"class" : "dataHead"}):
numrow=numrow+1
for ncol in currenttable.findAll('th', {"class" : "dataHead"}):
numcol=numcol+1
for col in currenttable.findAll('td'):
col2 = ''.join(col.findAll(text=True))
if col2.index('±'):
col2=col2[:col2.index('±')]
print(col2.encode("utf-8"))
ref=numdiv.find('a')
niceref=''.join(ref.findAll(text=True))
Now due to the ± signs i get the following error when trying to interprent the code with:
python code.py
Traceback (most recent call last):
File "detherm-wtest.py", line 25, in
if col2.index('±'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
How do i solve this? putting an u in so we have: '±' -> u'±' results in:
Traceback (most recent call last):
File "detherm-wtest.py", line 25, in
if col2.index(u'±'):
ValueError: substring not found
current code file encoding is utf-8
thank you
A:
Byte strings like "±" (in Python 2.x) are encoded in the source file's encoding, which might not be what you want. If col2 is really a Unicode object, you should use u"±" instead like you already tried. You might know that somestring.index raises an exception if it doesn't find an occurrence whereas somestring.find returns -1. Therefore, this
if col2.index('±'):
col2=col2[:col2.index('±')] # this is not indented correctly in the question BTW
print(col2.encode("utf-8"))
should be
if u'±' in col2:
col2=col2[:col2.index(u'±')]
print(col2.encode("utf-8"))
so that the if statement doesn't lead to an exception.
| Special character use in Python 2.6 | I am more than a bit tired, but here goes:
I am doing tome HTML scraping in python 2.6.5 with BeautifulSoap on an ubuntubox
Reason for python 2.6.5: BeautifulSoap sucks under 3.1
I try to run the following code:
# dataretriveal from html files from DETHERM
# -*- coding: utf-8 -*-
import sys,os,re,csv
from BeautifulSoup import BeautifulSoup
sys.path.insert(0, os.getcwd())
raw_data = open('download.php.html','r')
soup = BeautifulSoup(raw_data)
for numdiv in soup.findAll('div', {"id" : "sec"}):
currenttable = numdiv.find('table',{"class" : "data"})
if currenttable:
numrow=0
numcol=0
data_list=[]
for row in currenttable.findAll('td', {"class" : "dataHead"}):
numrow=numrow+1
for ncol in currenttable.findAll('th', {"class" : "dataHead"}):
numcol=numcol+1
for col in currenttable.findAll('td'):
col2 = ''.join(col.findAll(text=True))
if col2.index('±'):
col2=col2[:col2.index('±')]
print(col2.encode("utf-8"))
ref=numdiv.find('a')
niceref=''.join(ref.findAll(text=True))
Now due to the ± signs i get the following error when trying to interprent the code with:
python code.py
Traceback (most recent call last):
File "detherm-wtest.py", line 25, in
if col2.index('±'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
How do i solve this? putting an u in so we have: '±' -> u'±' results in:
Traceback (most recent call last):
File "detherm-wtest.py", line 25, in
if col2.index(u'±'):
ValueError: substring not found
current code file encoding is utf-8
thank you
| [
"Byte strings like \"±\" (in Python 2.x) are encoded in the source file's encoding, which might not be what you want. If col2 is really a Unicode object, you should use u\"±\" instead like you already tried. You might know that somestring.index raises an exception if it doesn't find an occurrence whereas somestring... | [
2
] | [] | [] | [
"beautifulsoup",
"python",
"special_characters"
] | stackoverflow_0003885569_beautifulsoup_python_special_characters.txt |
Q:
How to strip variable spaces in each line of a text file based on special condition - one-liner in Python?
I have some data (text files) that is formatted in the most uneven manner one could think of. I am trying to minimize the amount of manual work on parsing this data.
Sample Data :
Name Degree CLASS CODE EDU Scores
--------------------------------------------------------------------------------------
John Marshall CSC 78659944 89989 BE 900
Think Code DB I10 MSC 87782 1231 MS 878
Mary 200 Jones CIVIL 98993483 32985 BE 898
John G. S Mech 7653 54 MS 65
Silent Ghost Python Ninja 788505 88448 MS Comp 887
Conditions :
More than one spaces should be compressed to a delimiter (pipe better? End goal is to store these files in the database).
Except for the first column, the other columns won't have any spaces in them, so all those spaces can be compressed to a pipe.
Only the first column can have multiple words with spaces (Mary K Jones). The rest of the columns are mostly numbers and some alphabets.
First and second columns are both strings. They almost always have more than one spaces between them, so that is how we can differentiate between the 2 columns. (If there is a single space, that is a risk I am willing to take given the horrible formatting!).
The number of columns varies, so we don't have to worry about column names. All we want is to extract each column's data.
Hope I made sense! I have a feeling that this task can be done in a oneliner. I don't want to loop, loop, loop :(
Muchos gracias "Pythonistas" for reading all the way and not quitting before this sentence!
A:
It still seems tome that there's some format in your files:
>>> regex = r'^(.+)\b\s{2,}\b(.+)\s+(\d+)\s+(\d+)\s+(.+)\s+(\d+)'
>>> for line in s.splitlines():
lst = [i.strip() for j in re.findall(regex, line) for i in j if j]
print(lst)
[]
[]
['John Marshall', 'CSC', '78659944', '89989', 'BE', '900']
['Think Code DB I10', 'MSC', '87782', '1231', 'MS', '878']
['Mary 200 Jones', 'CIVIL', '98993483', '32985', 'BE', '898']
['John G. S', 'Mech', '7653', '54', 'MS', '65']
['Silent Ghost', 'Python Ninja', '788505', '88448', 'MS Comp', '887']
Regex is quite straightforward, the only things you need to pay attention to are the delimiters (\s) and the word breaks (\b) in case of the first delimiter. Note that when the line wouldn't match you get an empty list as lst. That would be a read flag to bring up the user interaction described below. Also you could skip the header lines by doing:
>>> file = open(fname)
>>> [next(file) for _ in range(2)]
>>> for line in file:
... # here empty lst indicates issues with regex
Previous variants:
>>> import re
>>> for line in open(fname):
lst = re.split(r'\s{2,}', line)
l = len(lst)
if l in (2,3):
lst[l-1:] = lst[l-1].split()
print(lst)
['Name', 'Degree', 'CLASS', 'CODE', 'EDU', 'Scores']
['--------------------------------------------------------------------------------------']
['John Marshall', 'CSC', '78659944', '89989', 'BE', '900']
['Think Code DB I10', 'MSC', '87782', '1231', 'MS', '878']
['Mary 200 Jones', 'CIVIL', '98993483', '32985', 'BE', '898']
['John G. S', 'Mech', '7653', '54', 'MS', '65']
another thing to do is simply allow user to decide what to do with questionable entries:
if l < 3:
lst = line.split()
print(lst)
iname = input('enter indexes that for elements of name: ') # use raw_input in py2k
idegr = input('enter indexes that for elements of degree: ')
Uhm, I was all the time under the impression that the second element might contain spaces, since it's not the case you could just do:
>>> for line in open(fname):
name, _, rest = line.partition(' ')
lst = [name] + rest.split()
print(lst)
A:
Variation on SilentGhost's answer, this time first splitting the name from the rest (separated by two or more spaces), then just splitting the rest, and finally making one list.
import re
for line in open(fname):
name, rest = re.split('\s{2,}', line, maxsplit=1)
print [name] + rest.split()
A:
This answer was written after the OP confessed to changing every tab ("\t") in his data to 3 spaces (and not mentioning it in his question).
Looking at the first line, it seems that this is a fixed-column-width report. It is entirely possible that your data contains tabs that if expanded properly might result in a non-crazy result.
Instead of doing line.replace('\t', ' ' * 3) try line.expandtabs().
Docs for expandtabs are here.
If the result looks sensible (columns of data line up), you will need to determine how you can work out the column widths programatically (if that is possible) -- maybe from the heading line.
Are you sure that the second line is all "-", or are there spaces between the columns?
The reason for asking is that I once needed to parse many different files from a database query report mechanism which presented the results like this:
RecordType ID1 ID2 Description
----------- -------------------- ----------- ----------------------
1 12345678 123456 Widget
4 87654321 654321 Gizmoid
and it was possible to write a completely general reader that inspected the second line to determine where to slice the heading line and the data lines. Hint:
sizes = map(len, dash_line.split())
If expandtabs() doesn't work, edit your question to show exactly what you do have i.e. show the result of print repr(line) for the first 5 or so lines (including the heading line). It might also be useful if you could say what software produces these files.
| How to strip variable spaces in each line of a text file based on special condition - one-liner in Python? | I have some data (text files) that is formatted in the most uneven manner one could think of. I am trying to minimize the amount of manual work on parsing this data.
Sample Data :
Name Degree CLASS CODE EDU Scores
--------------------------------------------------------------------------------------
John Marshall CSC 78659944 89989 BE 900
Think Code DB I10 MSC 87782 1231 MS 878
Mary 200 Jones CIVIL 98993483 32985 BE 898
John G. S Mech 7653 54 MS 65
Silent Ghost Python Ninja 788505 88448 MS Comp 887
Conditions :
More than one spaces should be compressed to a delimiter (pipe better? End goal is to store these files in the database).
Except for the first column, the other columns won't have any spaces in them, so all those spaces can be compressed to a pipe.
Only the first column can have multiple words with spaces (Mary K Jones). The rest of the columns are mostly numbers and some alphabets.
First and second columns are both strings. They almost always have more than one spaces between them, so that is how we can differentiate between the 2 columns. (If there is a single space, that is a risk I am willing to take given the horrible formatting!).
The number of columns varies, so we don't have to worry about column names. All we want is to extract each column's data.
Hope I made sense! I have a feeling that this task can be done in a oneliner. I don't want to loop, loop, loop :(
Muchos gracias "Pythonistas" for reading all the way and not quitting before this sentence!
| [
"It still seems tome that there's some format in your files:\n>>> regex = r'^(.+)\\b\\s{2,}\\b(.+)\\s+(\\d+)\\s+(\\d+)\\s+(.+)\\s+(\\d+)'\n>>> for line in s.splitlines():\n lst = [i.strip() for j in re.findall(regex, line) for i in j if j]\n print(lst)\n\n\n[]\n[]\n['John Marshall', 'CSC', '78659944', '89989'... | [
3,
2,
1
] | [] | [] | [
"delimiter",
"formatting",
"parsing",
"python",
"text_parsing"
] | stackoverflow_0003874117_delimiter_formatting_parsing_python_text_parsing.txt |
Q:
Ruby use case for nil, equivalent to Python None or JavaScript undefined
How does Ruby's nil manifest in code? For example, in Python you might use None for a default argument when it refers to another argument, but in Ruby you can refer to other arguments in the arg list (see this question). In JS, undefined pops up even more because you can't specify default arguments at all. Can you give an example of how RubyNone pops up and how it's dealt with?
I'm not looking for just an example using nil. Preferably it would be a real code snippet which had to use nil for some reason or other.
A:
Ruby's nil and Python's None are equivalent in the sense that they represent the absence of a value. However, people coming from Python may find some behavior surprising. First, Ruby returns nil in situations Python raises an exception:
Accessing arrays and hashes:
[1, 2, 3][999] # nil. But [].fetch(0) raises an IndexError
{"a" => 1, "b" => 2}["nonexistent"] # nil. But {}.fetch("nonexistent") raises an IndexError
Instance instance variables:
class MyClass
def hello
@thisdoesnotexist
end
end
MyClass.new.hello #=> nil
The second remarkable fact is that nil is an object with lots of methods. You can even convert it to an integer, float or string:
nil.to_i # 0
nil.to_f # 0.0 # But Integer(nil) or Float(nil) raise a TypeError.
nil.to_s # ""
A:
One use of nil you often see in Ruby code is the following:
a ||= 10 # or a = a || 10
This works because once a variable has been seen on the left hand side of an assignment, it implicitly has the value nil.
>> if false
.. x = y
.. z
.. end
=> nil
>> x
=> nil
>> z
NameError: undefined local variable or method `z' for main:Object
Thus when the a || 10 part is evaluated, it evaluates to nil || 10, which yields 10.
nil and false are also the only two values in Ruby that are logically false, so it's customary for methods to return nil in case of failure. There's a gem called andand that makes use of exactly this, so instead of something like
@first_name &&= @first_name.trim
you can write
@first_name.andand.trim
This basically translates to trim @first_name if it has a value other than nil, otherwise evaluate to nil. As you can imagine this is particularly useful when chaining methods where one of the intermediaries can potentially return nil.
Besides that nil is also returned when you are trying to access non-existing collection elements, e.g. in the case of arrays or hashes. Uninitialized instance variables also have the value nil.
I'm not overly versed in Python, but from what I've seen nil and None serve pretty much the same purpose.
A:
In addition to all explanations about nil, ruby also has 'defined?'.
a = nil
p defined?(a) #=> "local-variable"
p a.nil? #=> true
p defined?(b) #=> nil
A:
My Ruby-fu is very weak, but nil might be what you are looking for. Here is a quick illustration of using nil in a function as default argument.
irb(main):003:0> def foo(a = nil)
irb(main):004:1> puts a
irb(main):005:1> end
=> nil
irb(main):006:0> foo(1)
1
=> nil
irb(main):007:0> foo()
nil
=> nil
irb(main):008:0>
A:
They’re also used in place of void: In a static language the compiler will simply forbid you from using the return value of a void function, but in a dynamic language every procedure has to return something. So the special value nil is used.
| Ruby use case for nil, equivalent to Python None or JavaScript undefined | How does Ruby's nil manifest in code? For example, in Python you might use None for a default argument when it refers to another argument, but in Ruby you can refer to other arguments in the arg list (see this question). In JS, undefined pops up even more because you can't specify default arguments at all. Can you give an example of how RubyNone pops up and how it's dealt with?
I'm not looking for just an example using nil. Preferably it would be a real code snippet which had to use nil for some reason or other.
| [
"Ruby's nil and Python's None are equivalent in the sense that they represent the absence of a value. However, people coming from Python may find some behavior surprising. First, Ruby returns nil in situations Python raises an exception:\nAccessing arrays and hashes:\n[1, 2, 3][999] # nil. But [].fetch(0) raises an... | [
9,
2,
2,
0,
0
] | [] | [] | [
"javascript",
"null",
"python",
"ruby"
] | stackoverflow_0003884004_javascript_null_python_ruby.txt |
Q:
Windows platform programming
I am hired by my local company here which makes small accounting/billing/payroll softwares to manage its clients' companies. Most of them use windows platform and the softwares themselves will not be too complex ones. I want to ask which language should i opt for? Python, C#, VB.net or something else which will make the GUI programming task easier. thanks in advance.
A:
For programming on Windows you want to go with .NET and probably WPF for the presentation layer if you can wrap your head around MVVM as it gives you much more scope for delivering flexible UIs than forms.
For cross platform utility - probably python, but I'm not sure I'd want it to be my principal development tool (if I'm focusing on Windows applications).
A:
The advice to build upon what you already know is very good advice.
As you are thinking of Python, I feel i should warn you off Iron Python. I found it very very slow and WPF confused the heck out of me. The designer is nice. The error messages you get when importing the wrong namespaces are cryptic and comfusing (Example - "Error: expected X got X").
Qt, PyQt and Python appears to be acceptably quick (Python is no speed demon), well documented and stable. It will adopt the local styling, so it looks native XP or Win 7 with no changes.
Fair warning about Python. It boasts of being "batteries included". This is great until you find there are 4 different modules that might do what you want, and no decent documentation for any of them, to help you choose the most suitable.
A:
My personal preference is WPF/C#.
I say go with the latest technology (whichever YOU find easiest), it will be good for your career.
A:
If you decide on using Python, you probably want to look at pywinauto and the win32gui stuff from the brilliant Mark Hammond which comes with the Python Windows installation.
http://code.google.com/p/pywinauto/
| Windows platform programming | I am hired by my local company here which makes small accounting/billing/payroll softwares to manage its clients' companies. Most of them use windows platform and the softwares themselves will not be too complex ones. I want to ask which language should i opt for? Python, C#, VB.net or something else which will make the GUI programming task easier. thanks in advance.
| [
"For programming on Windows you want to go with .NET and probably WPF for the presentation layer if you can wrap your head around MVVM as it gives you much more scope for delivering flexible UIs than forms. \nFor cross platform utility - probably python, but I'm not sure I'd want it to be my principal development t... | [
2,
2,
0,
0
] | [] | [] | [
"c#",
"python",
"user_interface",
"vb.net"
] | stackoverflow_0003884405_c#_python_user_interface_vb.net.txt |
Q:
Calling a file in python
I'd like to call a .py file from within python. It is in the same directory. Effectivly, I would like the same behavior as calling python foo.py from the command line without using any of the command line tools. How should I do this?
A:
execfile('foo.py')
See also:
Further reading on execfile
A:
It's not quite clear (at least to me) what you mean by using "none of the command-line tools".
To run a program in a subprocess, one usually uses the subprocess module. However, if both the calling and the callee are python scripts, there is another alternative, which is to use the multiprocessing module.
For example, you can organize foo.py like this:
def main():
...
if __name__=='__main__':
main()
Then in the calling script, test.py:
import multiprocessing as mp
import foo
proc=mp.Process(target=foo.main)
proc.start()
# Do stuff while foo.main is running
# Wait until foo.main has ended
proc.join()
# Continue doing more stuff
A:
import module or __import__("module"), to load module.py.
Modules - Python v2.7 documentation
Importing Python modules
| Calling a file in python | I'd like to call a .py file from within python. It is in the same directory. Effectivly, I would like the same behavior as calling python foo.py from the command line without using any of the command line tools. How should I do this?
| [
"execfile('foo.py')\n\nSee also:\n\nFurther reading on execfile\n\n",
"It's not quite clear (at least to me) what you mean by using \"none of the command-line tools\". \nTo run a program in a subprocess, one usually uses the subprocess module. However, if both the calling and the callee are python scripts, there ... | [
4,
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0003885846_python.txt |
Q:
type of class in python
why if I do:
class C(): pass
type(C())
I got: <type 'instance'>, but if I do:
class C(object): pass
type(c())
I got: <class '__main__.c'> ?
The first is not very userfull
A:
Look up the difference between old-style and new-style classes. The former are the default, and the latter inherit explicitly from object.
All old-style objects were implemented with the built-in type instance. The fact that they are still the default and their type remains 'instance' is a result of retro-compatibility precautions.
This is extracted from the Python docs (http://docs.python.org/reference/datamodel.html)
3.3. New-style and classic classes Classes and instances come in two
flavors: old-style (or classic) and
new-style.
Up to Python 2.1, old-style classes
were the only flavour available to the
user. The concept of (old-style) class
is unrelated to the concept of type:
if x is an instance of an old-style
class, then x.class designates the
class of x, but type(x) is always
. This reflects the
fact that all old-style instances,
independently of their class, are
implemented with a single built-in
type, called instance.
New-style classes were introduced in
Python 2.2 to unify classes and types.
A new-style class is neither more nor
less than a user-defined type. If x is
an instance of a new-style class, then
type(x) is typically the same as
x> .class (although this is not
guaranteed - a new-style class
instance is permitted to override the
value returned for x.class).
The major motivation for introducing
new-style classes is to provide a
unified object model with a full
meta-model. It also has a number of
practical benefits, like the ability
to subclass most built-in types, or
the introduction of “descriptors”,
which enable computed properties.
For compatibility reasons, classes are
still old-style by default. New-style
classes are created by specifying
another new-style class (i.e. a type)
as a parent class, or the “top-level
type” object if no other parent is
needed. The behaviour of new-style
classes differs from that of old-style
classes in a number of important
details in addition to what type()
returns. Some of these changes are
fundamental to the new object model,
like the way special methods are
invoked. Others are “fixes” that could
not be implemented before for
compatibility concerns, like the
method resolution order in case of
multiple inheritance.
While this manual aims to provide
comprehensive coverage of Python’s
class mechanics, it may still be
lacking in some areas when it comes to
its coverage of new-style classes.
Please see
http://www.python.org/doc/newstyle/
for sources of additional information.
Old-style classes are removed in
Python 3.0, leaving only the semantics
of new-style classes.of new-style classes.
| type of class in python | why if I do:
class C(): pass
type(C())
I got: <type 'instance'>, but if I do:
class C(object): pass
type(c())
I got: <class '__main__.c'> ?
The first is not very userfull
| [
"Look up the difference between old-style and new-style classes. The former are the default, and the latter inherit explicitly from object.\nAll old-style objects were implemented with the built-in type instance. The fact that they are still the default and their type remains 'instance' is a result of retro-compati... | [
3
] | [] | [] | [
"class",
"new_style_class",
"python",
"types"
] | stackoverflow_0003886117_class_new_style_class_python_types.txt |
Q:
How to use session on Google app engine
I'm building an application using Google app engine with python, and I'm stuck with making sessions. Is there any app that already does that for app engine? Thank you.
A:
I recommend gae-sessions. The source includes demos which show how to use it, including how to integrate with the Users API or RPX/JanRain.
Disclaimer: I wrote gae-sessions, but for an informative comparison of it with alternatives, read this article.
| How to use session on Google app engine | I'm building an application using Google app engine with python, and I'm stuck with making sessions. Is there any app that already does that for app engine? Thank you.
| [
"I recommend gae-sessions. The source includes demos which show how to use it, including how to integrate with the Users API or RPX/JanRain.\nDisclaimer: I wrote gae-sessions, but for an informative comparison of it with alternatives, read this article.\n"
] | [
20
] | [] | [] | [
"authentication",
"google_app_engine",
"python",
"session"
] | stackoverflow_0003885996_authentication_google_app_engine_python_session.txt |
Q:
Python module paramiko cannot connect as paramiko.Transport((host,port)).connect(username = username, password = password)
This is an example which works fine on friend's computer:
import paramiko
host = "157.178.35.134"
port = 222
username = "stackoverflow"
password = "e2fghK3"
transport = paramiko.Transport((host, port))
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
import sys
path = './file.testy' #server
localpath = '/home/iwtu/test'
sftp.put(localpath, path)
sftp.close()
transport.close()
print 'Upload done.'
However I have the following problem.
>>> import paramiko
Warning (from warnings module):
File "C:\DevelopingTools\Python\lib\site-packages\Crypto\Util\randpool.py", line 40
RandomPool_DeprecationWarning)
RandomPool_DeprecationWarning: This application uses RandomPool, which is BROKEN in older releases. See http://www.pycrypto.org/randpool-broken
>>> host = '157.178.35.134'
>>> port = 222
>>> username = 'stackoverflow'
>>> password = 'e2fghK3'
>>> t = paramiko.Transport((host,port))
>>> t.connect(username = username, password = password)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
t.connect(username = username, password = password)
File "C:\DevelopingTools\Python\lib\site-packages\paramiko\transport.py", line 989, in connect
self.start_client()
File "C:\DevelopingTools\Python\lib\site-packages\paramiko\transport.py", line 458, in start_client
raise e
EOFError
I have googled a lot of hours, tried different version (Arch Linux 64-bit/Windows 7 64-bit, python 2.7 32/64-bit, python 2.6 32-bit, paramiko 1.7.6, pycrypto 2.0.1/2.1/2.2 but nothing helped. I want to program a simple sfpt client for automatic downloading and deleting files but I am really baffled. If anyone could help me I would be very grateful. Thanks.
A:
Can you try this and let me know how it goes:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("157.178.35.13", username="stackoverflow", password="e2fghK3")
ftp=ssh.open_sftp()
path = './file.testy' #server
localpath = '/home/iwtu/test'
ftp.put(localpath, path)
ftp.close()
Is your friend running it on a Linux box?
Are you running it on a Windows machine?
| Python module paramiko cannot connect as paramiko.Transport((host,port)).connect(username = username, password = password) | This is an example which works fine on friend's computer:
import paramiko
host = "157.178.35.134"
port = 222
username = "stackoverflow"
password = "e2fghK3"
transport = paramiko.Transport((host, port))
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
import sys
path = './file.testy' #server
localpath = '/home/iwtu/test'
sftp.put(localpath, path)
sftp.close()
transport.close()
print 'Upload done.'
However I have the following problem.
>>> import paramiko
Warning (from warnings module):
File "C:\DevelopingTools\Python\lib\site-packages\Crypto\Util\randpool.py", line 40
RandomPool_DeprecationWarning)
RandomPool_DeprecationWarning: This application uses RandomPool, which is BROKEN in older releases. See http://www.pycrypto.org/randpool-broken
>>> host = '157.178.35.134'
>>> port = 222
>>> username = 'stackoverflow'
>>> password = 'e2fghK3'
>>> t = paramiko.Transport((host,port))
>>> t.connect(username = username, password = password)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
t.connect(username = username, password = password)
File "C:\DevelopingTools\Python\lib\site-packages\paramiko\transport.py", line 989, in connect
self.start_client()
File "C:\DevelopingTools\Python\lib\site-packages\paramiko\transport.py", line 458, in start_client
raise e
EOFError
I have googled a lot of hours, tried different version (Arch Linux 64-bit/Windows 7 64-bit, python 2.7 32/64-bit, python 2.6 32-bit, paramiko 1.7.6, pycrypto 2.0.1/2.1/2.2 but nothing helped. I want to program a simple sfpt client for automatic downloading and deleting files but I am really baffled. If anyone could help me I would be very grateful. Thanks.
| [
"Can you try this and let me know how it goes:\nssh = paramiko.SSHClient()\nssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\nssh.connect(\"157.178.35.13\", username=\"stackoverflow\", password=\"e2fghK3\")\nftp=ssh.open_sftp()\npath = './file.testy' #server\nlocalpath = '/home/iwtu/test' \nftp.put(loca... | [
2
] | [] | [] | [
"eoferror",
"paramiko",
"python"
] | stackoverflow_0003410369_eoferror_paramiko_python.txt |
Q:
More efficient ways of doing this
for i in vr_world.getNodeNames():
if i != "_error_":
World[i] = vr_world.getChild(i)
vr_world.getNodeNames() returns me a gigantic list, vr_world.getChild(i) returns a specific type of object.
This is taking a long time to run, is there anyway to make it more efficient? I have seen one-liners for loops before that are supposed to be faster. Ideas?
A:
I don't think you can make it faster than what you have there. Yes, you can put the whole thing on one line but that will not make it any faster. The bottleneck obviously is getNodeNames(). If you can make it a generator, you will start populating the World dict with results sooner (if that matters to you) and if you make it filter out the "_error_" values, you will not have the deal with that at a later stage.
A:
kaloyan suggests using a generator. Here's why that may help.
If getNodeNames() builds a list, then your loop is basically going over the list twice: once to build it, and once when you iterate over the list.
If getNodeNames() is a generator, then your loop doesn't ever build the list; instead of creating the item and adding it to the list, it creates the item and yields it to the caller.
Whether or not this helps is contingent on a couple of things. First, it has to be possible to implement getNodeNames() as a generator. We don't know anything about the implementation details of that function, so it's not possible to say if that's the case. Next, the number of items you're iterating over needs to be pretty big.
Of course, none of this will have any effect at all if it turns out that the time-consuming operation in all of this is vr_world.getChild(). That's why you need to profile your code.
A:
World = dict((i, vr_world.getChild(i)) for i in vr_world.getNodeNames() if i != "_error_")
This is a one-liner, but not necessarily much faster than your solution...
A:
Maybe you can use a filter and a map, however I don't know if this would be any faster:
valid = filter(lambda i: i != "_error_", vr_world.getNodeNames())
World = map(lambda i: vr_world.getChild(i), valid)
Also, as you'll see a lot around here, profile first, and then optimize, otherwise you may be wasting time. You have two functions there, maybe they are the slow parts, not the iteration.
| More efficient ways of doing this | for i in vr_world.getNodeNames():
if i != "_error_":
World[i] = vr_world.getChild(i)
vr_world.getNodeNames() returns me a gigantic list, vr_world.getChild(i) returns a specific type of object.
This is taking a long time to run, is there anyway to make it more efficient? I have seen one-liners for loops before that are supposed to be faster. Ideas?
| [
"I don't think you can make it faster than what you have there. Yes, you can put the whole thing on one line but that will not make it any faster. The bottleneck obviously is getNodeNames(). If you can make it a generator, you will start populating the World dict with results sooner (if that matters to you) and if ... | [
1,
1,
0,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0003885352_optimization_python.txt |
Q:
How do I remove the y-axis from a Pylab-generated picture?
import pylab # matplotlib
x_list = [1,1,1,1,5,4]
y_list = [1,2,3,4,5,4]
pylab.plot(x_list, y_list, 'bo')
pylab.show()
What I want to do is remove the y-axis from the diagram, only keeping the x-axis.
And adding more margin to the diagram, we can see that a lot of dots are on the edge of the canvas and don't look good.
A:
ax = pylab.gca()
ax.yaxis.set_visible(False)
pylab.show()
| How do I remove the y-axis from a Pylab-generated picture? | import pylab # matplotlib
x_list = [1,1,1,1,5,4]
y_list = [1,2,3,4,5,4]
pylab.plot(x_list, y_list, 'bo')
pylab.show()
What I want to do is remove the y-axis from the diagram, only keeping the x-axis.
And adding more margin to the diagram, we can see that a lot of dots are on the edge of the canvas and don't look good.
| [
"ax = pylab.gca()\nax.yaxis.set_visible(False)\npylab.show()\n\n"
] | [
14
] | [] | [] | [
"matplotlib",
"python",
"python_imaging_library"
] | stackoverflow_0003886255_matplotlib_python_python_imaging_library.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.