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:
Command+W Support in wxPython
It's my understanding that in wxPython in OSX, ⌘+w support for closing wx.Window objects. In order to add it, I've had to bind to wx.EVT_KEY_DOWN, checking for event.MetaDown() and event.KeyCode == 'W' explicitly.
In my app, I need to have all windows and dialogs support this. I'm still in the process of layout out my GUI, but I got to thinking, and I'm wondering what the best way to add this support to an existing class easily is. I tried out Multiple Inheritance, but it didn't seem to be working (my event handler never got called).
I was thinking maybe a class decorator, but this is functionality that will be added at runtime, due to the dynamic nature of python. So I'm a little stumped.
PS: I know 'best' is subjective, but I'm honestly looking for anything here that might work that's not an exorbitant amount of code.
A:
I was thinking maybe a class
decorator, but this is functionality
that will be added at runtime, due to
the dynamic nature of python.
I don't understand why this makes you "a little stumped". The class decorator executes just after the end of the class statement -- yes, that's "at runtime", but, so is the clqss statement itself, all the def statement in it for its methods, and so forth. By the time you instantiate any of the classes thus decorated, the decorator will have run and so the class you're instantiating will have been modified accordingly by the decorator's code. Can you please give a small example of why this isn't working for you?
| Command+W Support in wxPython | It's my understanding that in wxPython in OSX, ⌘+w support for closing wx.Window objects. In order to add it, I've had to bind to wx.EVT_KEY_DOWN, checking for event.MetaDown() and event.KeyCode == 'W' explicitly.
In my app, I need to have all windows and dialogs support this. I'm still in the process of layout out my GUI, but I got to thinking, and I'm wondering what the best way to add this support to an existing class easily is. I tried out Multiple Inheritance, but it didn't seem to be working (my event handler never got called).
I was thinking maybe a class decorator, but this is functionality that will be added at runtime, due to the dynamic nature of python. So I'm a little stumped.
PS: I know 'best' is subjective, but I'm honestly looking for anything here that might work that's not an exorbitant amount of code.
| [
"\nI was thinking maybe a class\n decorator, but this is functionality\n that will be added at runtime, due to\n the dynamic nature of python.\n\nI don't understand why this makes you \"a little stumped\". The class decorator executes just after the end of the class statement -- yes, that's \"at runtime\", but, ... | [
0
] | [] | [] | [
"macos",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003765496_macos_python_user_interface_wxpython.txt |
Q:
using extended ascii characters for wikimedia api
I am writing a simple search algorithm for wikipedia. I am having trouble when I send a query with characters that have accents and other characters that are not seen in regular english. Queries that return in error are:
http://en.wikipedia.org/w/api.php?action=query&titles=Albrecht%20Dürer&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Ancien%20Régime&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Feigenbaum-Cvitanović&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Banach–Tarski%20paradox&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Grundzüge%20der%20Mengenlehre&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Grundzüge%20einer%20Theorie%20der%20geordneten%20Mengen&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Karl%20Bögel&prop=links&pllimit=33&format=xml
But the query works fine if there are simple character such as "Fractals". How should I change the format of the query to make this work?
My code is open sourced at: http://code.google.com/p/wikipediafoundation/source/browse/. Please look at hg/src/list.py.
A:
I don't see any trace in your Python source of how you're encoding any non-ascii characters you're sending in the query. For URLs (including query strings in them) using anything beyond ascii, you need to (make them unicode if they already aren't, then) encode them in utf-8 and percent-escape the result (for the latter use function urllib.quote_plus from the standard Python library module urllib, and for encoding, of course, the unicode string's .encode('utf8') method -- if you need to make a unicode string from a differently-encoded byte string, use the byte string's .decode('latin-1') -- or whatever the name of the encoding it's in, of course;-).
| using extended ascii characters for wikimedia api | I am writing a simple search algorithm for wikipedia. I am having trouble when I send a query with characters that have accents and other characters that are not seen in regular english. Queries that return in error are:
http://en.wikipedia.org/w/api.php?action=query&titles=Albrecht%20Dürer&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Ancien%20Régime&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Feigenbaum-Cvitanović&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Banach–Tarski%20paradox&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Grundzüge%20der%20Mengenlehre&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Grundzüge%20einer%20Theorie%20der%20geordneten%20Mengen&prop=links&pllimit=33&format=xml
http://en.wikipedia.org/w/api.php?action=query&titles=Karl%20Bögel&prop=links&pllimit=33&format=xml
But the query works fine if there are simple character such as "Fractals". How should I change the format of the query to make this work?
My code is open sourced at: http://code.google.com/p/wikipediafoundation/source/browse/. Please look at hg/src/list.py.
| [
"I don't see any trace in your Python source of how you're encoding any non-ascii characters you're sending in the query. For URLs (including query strings in them) using anything beyond ascii, you need to (make them unicode if they already aren't, then) encode them in utf-8 and percent-escape the result (for the ... | [
1
] | [] | [] | [
"api",
"mediawiki",
"python"
] | stackoverflow_0003765855_api_mediawiki_python.txt |
Q:
Signal handler, python
I have a multithreaded program and use the signal.signal(SIGINT,func) to kill all threads when ctrl c is pressed. The question I have is this:
I have to call signal.signal(...) from main in python. Do I have to call that on a loop or can I just set it once and whenever the user presses ctrl c, the signal will be caught?
A:
Only the main tread can handle signals. Just make all your threads "daemonic" ones (set the thread object's .daemon property to True before you start the thread) to ensure the threads terminate when the main thread does.
| Signal handler, python | I have a multithreaded program and use the signal.signal(SIGINT,func) to kill all threads when ctrl c is pressed. The question I have is this:
I have to call signal.signal(...) from main in python. Do I have to call that on a loop or can I just set it once and whenever the user presses ctrl c, the signal will be caught?
| [
"Only the main tread can handle signals. Just make all your threads \"daemonic\" ones (set the thread object's .daemon property to True before you start the thread) to ensure the threads terminate when the main thread does.\n"
] | [
2
] | [] | [] | [
"multithreading",
"python",
"sigint"
] | stackoverflow_0003765897_multithreading_python_sigint.txt |
Q:
Launching multiple processes of shell
I'm trying to use python to launch a command in multiple seperate instances of terminal simultaneously. What is the best way to do this? Right now I am trying to use the subprocess module with popen which works for one command but not multiple.
Thanks in advance.
Edit:
Here is what I am doing:
from subprocess import*
Popen('ant -Dport='+str(5555)+ ' -Dhost='+GetIP()+ ' -DhubURL=http://192.168.1.113:4444 -Denvironment=*firefox launch-remote-control $HOME/selenium-grid-1.0.8', shell=True)
The problem for me is this launches a java process in the terminal which I want to have keep running indefinatley. Secondly, I want to run a similar command multiple times in multiple different processes.
A:
This should stay open as long as the process is running. If you want to launch multiple simultanously, just wrap it in a thread
untested code, but you should get the general idea:
class PopenThread(threading.Thread):
def __init__(self, port):
threading.Thread.__init__(self)
self.port=port
def run(self):
Popen('ant -Dport='+str(self.port)+ ' -Dhost='+GetIP()+
' -DhubURL=http://192.168.1.113:4444'
' -Denvironment=*firefox launch-remote-control'
' $HOME/selenium-grid-1.0.8', shell=True)
if '__main__'==__name__:
PopenThread(5555).start()
PopenThread(5556).start()
PopenThread(5557).start()
EDIT: The double-fork method described down here: https://stackoverflow.com/a/3765162/450517 by Mike would be the proper way to launch a daemon, i.e. a long-running process which won't communicate per stdio.
A:
The simple answer I can come up with is to have Python use Popen to launch a shell script similar to:
gnome-terminal --window -e 'ant -Dport=5555 -Dhost=$IP1 -DhubURL=http://192.168.1.113:4444 -Denvironment=*firefox launch-remote-control $HOME/selenium-grid-1.0.8' &
disown
gnome-terminal --window -e 'ant -Dport=5555 -Dhost=$IP2 -DhubURL=http://192.168.1.113:4444 -Denvironment=*firefox launch-remote-control $HOME/selenium-grid-1.0.8' &
disown
# etc. ...
There's a fully-Python way to do this, but it's ugly, only works on Unix-like OSes, and I don't have time to write the code out. Basically, subprocess.Popen doesn't support it because it assumes you want to either wait for the subprocess to finish, interact with the subprocess, or monitor the subprocess. It doesn't support the "just launch it and don't bother me with it ever again" case.
The way that's done in Unix-like OSes is to:
Use fork to spawn a subprocess
Have that subprocess fork a subprocess of its own
Have the grandchild process redirect I/O to /dev/null and then use one of the exec functions to launch the process you really want to start (might be able to use Popen for this part)
The child process exits.
Now there's no link between the grandparent and grandchild, so if the grandchild terminates you don't get a SIGCHLD signal, and if the grandparent terminates it doesn't kill all the grandchildren.
I might be off in the details, but that's the gist. Backgrounding (&) and disowning in bash are supposed to accomplish the same thing.
A:
Here is a poor version of a blocking queue. You can fancify it with collections.deque or the like, or go even fancier with Twisted deferreds, or what not. Crummy parts include:
blocking
kill signals might not propagate down
season to taste!
import logging
basicConfig = dict(level=logging.INFO, format='%(process)s %(asctime)s %(lineno)s %(levelname)s %(name)s %(message)s')
logging.basicConfig(**basicConfig)
logger = logging.getLogger({"__main__":None}.get(__name__, __name__))
import subprocess
def wait_all(list_of_Popens,sleep_time):
""" blocking wait for all jobs to return.
Args:
list_of_Popens. list of possibly opened jobs
Returns:
list_of_Popens. list of possibly opened jobs
Side Effect:
block until all jobs complete.
"""
jobs = list_of_Popens
while None in [j.returncode for j in jobs]:
for j in jobs: j.poll()
logger.info("not all jobs complete, sleeping for %i", last_sleep)
time.sleep(sleep_time)
return jobs
jobs = [subprocess.Popen('sleep 1'.split()) for x in range(10)]
jobs = wait_all(jobs)
| Launching multiple processes of shell | I'm trying to use python to launch a command in multiple seperate instances of terminal simultaneously. What is the best way to do this? Right now I am trying to use the subprocess module with popen which works for one command but not multiple.
Thanks in advance.
Edit:
Here is what I am doing:
from subprocess import*
Popen('ant -Dport='+str(5555)+ ' -Dhost='+GetIP()+ ' -DhubURL=http://192.168.1.113:4444 -Denvironment=*firefox launch-remote-control $HOME/selenium-grid-1.0.8', shell=True)
The problem for me is this launches a java process in the terminal which I want to have keep running indefinatley. Secondly, I want to run a similar command multiple times in multiple different processes.
| [
"This should stay open as long as the process is running. If you want to launch multiple simultanously, just wrap it in a thread\nuntested code, but you should get the general idea:\n\nclass PopenThread(threading.Thread):\n\n def __init__(self, port):\n threading.Thread.__init__(self)\n self.port=p... | [
1,
1,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0003764499_linux_python.txt |
Q:
Run Python CGI Script on Windows XP
This exact question has been asked before but I am at my wits end! I've spend 4 hours trying to get a SIMPLE Python CGI script to work on Windows XP but I get errors. Please save my sanity!
Python Script register.py
#!c:/Python30/python.exe -u
print "Content-type: text/html"
print "<P>Hello, World!</p>"
Script is located in:
C:\Program Files\Apache Software Foundation\Apache2.2\cgi-bin\alerter
Apache Error Log:
[Tue Sep 21 19:06:36 2010] [error] [client 127.0.0.1] Premature end of script headers: register.py
[Tue Sep 21 19:06:36 2010] [error] [client 127.0.0.1] File "C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/alerter/register.py", line 3\r
[Tue Sep 21 19:06:36 2010] [error] [client 127.0.0.1] print "Content-type: text/html"\r
[Tue Sep 21 19:06:36 2010] [error] [client 127.0.0.1] ^\r
[Tue Sep 21 19:06:36 2010] [error] [client 127.0.0.1] SyntaxError: invalid syntax\r
httpd.conf:
LoadModule cgi_module modules/mod_cgi.so
<Directory "C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
Options +ExecCGI
AddHandler cgi-script .py
</Directory>
This should be VERY simple. Yes? I mus be missing that ONE thing that will make it finally work. I got PHP working a while back with no problems.
Any ideas? Thanks!!!
A:
Your error is:
Premature end of script headers
Note that the HTTP protocol specifies that the body of a HTTP response is separated from it's headers by a blank line (i.e. two times a carriage return and line feed). I'd go for something like:
import sys
sys.stdout.write("Content-type: text/html\r\n\r\n<p>Body</p>")
A:
It appears that if I use the parenthetical 'print' method it works.
#!C:/Python30/python.exe -u
print("Content-type: text/html\n\n<p>Body</p>")
Researching.
Ok, the answer is obvious now. Python 3.0 made 'print' a function, requiring parenthesis! When I run the script from the command-line it gives an identical syntax error.
I actually DID test from the command-line several times and it printed. However, at that point I was actually using version 2.5.1 from cygwin. During debugging I added Python 3.0 to my path and thus I was running the script from the 3.0 version from that point forward, not testing from the command-line again until now.
Whew! Problem solved. A very time-expensive problem.
I appreciate the input. It helped me find the solution!
A:
Changing
print "Content-type: text/html"
print "<P>Hello, World!</p>"
to
print "Content-type: text/html"
print
print "<P>Hello, World!</p>"
i.e., just inserting an empty print after you're done with the headers,
should work fine for you: you specify you're on Windows, so each print will insert the standards-required terminating \r\n sequence (I believe Apache's tolerant of the "missing-'\r'" problem so that would also work on Unix-y platforms, put I'm not 100% certain of that).
| Run Python CGI Script on Windows XP | This exact question has been asked before but I am at my wits end! I've spend 4 hours trying to get a SIMPLE Python CGI script to work on Windows XP but I get errors. Please save my sanity!
Python Script register.py
#!c:/Python30/python.exe -u
print "Content-type: text/html"
print "<P>Hello, World!</p>"
Script is located in:
C:\Program Files\Apache Software Foundation\Apache2.2\cgi-bin\alerter
Apache Error Log:
[Tue Sep 21 19:06:36 2010] [error] [client 127.0.0.1] Premature end of script headers: register.py
[Tue Sep 21 19:06:36 2010] [error] [client 127.0.0.1] File "C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/alerter/register.py", line 3\r
[Tue Sep 21 19:06:36 2010] [error] [client 127.0.0.1] print "Content-type: text/html"\r
[Tue Sep 21 19:06:36 2010] [error] [client 127.0.0.1] ^\r
[Tue Sep 21 19:06:36 2010] [error] [client 127.0.0.1] SyntaxError: invalid syntax\r
httpd.conf:
LoadModule cgi_module modules/mod_cgi.so
<Directory "C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
Options +ExecCGI
AddHandler cgi-script .py
</Directory>
This should be VERY simple. Yes? I mus be missing that ONE thing that will make it finally work. I got PHP working a while back with no problems.
Any ideas? Thanks!!!
| [
"Your error is:\n\nPremature end of script headers\n\nNote that the HTTP protocol specifies that the body of a HTTP response is separated from it's headers by a blank line (i.e. two times a carriage return and line feed). I'd go for something like:\nimport sys\nsys.stdout.write(\"Content-type: text/html\\r\\n\\r\\n... | [
4,
1,
0
] | [] | [] | [
"cgi",
"python",
"windows_xp"
] | stackoverflow_0003765440_cgi_python_windows_xp.txt |
Q:
Have python run script at X:00 am
Following up on,
With python: intervals at x:00 repeat
Using threading, How can I get a script to run starting at 8:00 am stop running at 5:00 pm
The solution should be coded within python, and be portable
tiA
A:
The time module has a function called asctime, which might be useful for you:
>>> from time import asctime
>>> asctime()
'Tue Sep 21 17:49:42 2010'
So, you could incorporate something like the following into your code:
sysTime = asctime()
timestamp = systime.split()[3]
separator = timestamp[2]
hour = timestamp.split(separator)[0]
while hour < 8:
# just wait
sysTime = asctime()
timestamp = systime.split()[3]
separator = timestamp[2]
hour = timestamp.split(separator)[0]
# now, it's just become 8:00 AM
while hour < 17: # until 5:00 PM
sysTime = asctime()
timestamp = systime.split()[3]
separator = timestamp[2]
hour = timestamp.split(separator)[0]
# start your thread to do whatever needs to be done
Start this script off once and let it keep running forever.
This is in response to @user428862's question asking if this can be run with "hour > 8 and hour <17". This is how the code would need to be adapted for that purpose:
while 1:
sysTime = asctime()
timestamp = systime.split()[3]
separator = timestamp[2]
hour = timestamp.split(separator)[0]
minute = timestamp.split(separator)[1]
if (hour > 8) and (hour<17 and minute<1):
# start your thread to do whatever needs to be done
Also , it just occurs to me that I have been imploying string splitting and that returns strings, so hour should be int(timestamp.split(separator)[0]) and so forth
A:
in the cron, and you need to run script starting at 8:00 am stop running at 5:00 pm
use crontab -e command in linux .
and add this line code for
* 8 * * * /YOUR/PATH/SCRIPT
and you stop it in 5 pm, in this example we will kill all python process in 5 pm
* 17 * * * killall -9 /usr/bin/python
and you can check crontab with crontab -l and crontab -r for reset to default (no any command will be executed)
| Have python run script at X:00 am | Following up on,
With python: intervals at x:00 repeat
Using threading, How can I get a script to run starting at 8:00 am stop running at 5:00 pm
The solution should be coded within python, and be portable
tiA
| [
"The time module has a function called asctime, which might be useful for you:\n>>> from time import asctime\n>>> asctime()\n'Tue Sep 21 17:49:42 2010'\n\nSo, you could incorporate something like the following into your code:\nsysTime = asctime()\ntimestamp = systime.split()[3]\nseparator = timestamp[2]\nhour = tim... | [
3,
0
] | [] | [] | [
"multithreading",
"python",
"solaris",
"time",
"windows"
] | stackoverflow_0003763787_multithreading_python_solaris_time_windows.txt |
Q:
Python: PIL replace a single RGBA color
I have already taken a look at this question: SO question and seem to have implemented a very similar technique for replacing a single color including the alpha values:
c = Image.open(f)
c = c.convert("RGBA")
w, h = c.size
cnt = 0
for px in c.getdata():
c.putpixel((int(cnt % w), int(cnt / w)), (255, 0, 0, px[3]))
cnt += 1
However, this is very slow. I found this recipe out on the interwebs, but have not had success using it thus far.
What I am trying to do is take various PNG images that consist of a single color, white. Each pixel is 100% white with various alpha values, including alpha = 0. What I want to do is basically colorize the image with a new set color, for instance #ff0000<00-ff>. SO my starting and resulting images would look like this where the left side is my starting image and the right is my ending image (NOTE: background has been changed to a light gray so you can see it since it is actually transparent and you wouldn't be able to see the dots on the left.)
Any better way to do this?
A:
If you have numpy, it provides a much, much faster way to operate on PIL images.
E.g.:
import Image
import numpy as np
im = Image.open('test.png')
im = im.convert('RGBA')
data = np.array(im) # "data" is a height x width x 4 numpy array
red, green, blue, alpha = data.T # Temporarily unpack the bands for readability
# Replace white with red... (leaves alpha values alone...)
white_areas = (red == 255) & (blue == 255) & (green == 255)
data[..., :-1][white_areas.T] = (255, 0, 0) # Transpose back needed
im2 = Image.fromarray(data)
im2.show()
Edit: It's a slow Monday, so I figured I'd add a couple of examples:
Just to show that it's leaving the alpha values alone, here's the results for a version of your example image with a radial gradient applied to the alpha channel:
Original:
Result:
A:
Try this , in this sample we set the color to black if color is not white .
#!/usr/bin/python
from PIL import Image
import sys
img = Image.open(sys.argv[1])
img = img.convert("RGBA")
pixdata = img.load()
# Clean the background noise, if color != white, then set to black.
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y] == (255, 255, 255, 255):
pixdata[x, y] = (0, 0, 0, 255)
you can use color picker in gimp to absorb the color and see that's rgba color
A:
The Pythonware PIL online book chapter for the Image module stipulates that putpixel() is slow and suggests that it can be sped up by inlining. Or depending on PIL version, using load() instead.
| Python: PIL replace a single RGBA color | I have already taken a look at this question: SO question and seem to have implemented a very similar technique for replacing a single color including the alpha values:
c = Image.open(f)
c = c.convert("RGBA")
w, h = c.size
cnt = 0
for px in c.getdata():
c.putpixel((int(cnt % w), int(cnt / w)), (255, 0, 0, px[3]))
cnt += 1
However, this is very slow. I found this recipe out on the interwebs, but have not had success using it thus far.
What I am trying to do is take various PNG images that consist of a single color, white. Each pixel is 100% white with various alpha values, including alpha = 0. What I want to do is basically colorize the image with a new set color, for instance #ff0000<00-ff>. SO my starting and resulting images would look like this where the left side is my starting image and the right is my ending image (NOTE: background has been changed to a light gray so you can see it since it is actually transparent and you wouldn't be able to see the dots on the left.)
Any better way to do this?
| [
"If you have numpy, it provides a much, much faster way to operate on PIL images.\nE.g.:\nimport Image\nimport numpy as np\n\nim = Image.open('test.png')\nim = im.convert('RGBA')\n\ndata = np.array(im) # \"data\" is a height x width x 4 numpy array\nred, green, blue, alpha = data.T # Temporarily unpack the bands ... | [
82,
11,
4
] | [] | [] | [
"colors",
"python",
"python_imaging_library"
] | stackoverflow_0003752476_colors_python_python_imaging_library.txt |
Q:
Customizing Django Admin Interface functionality
I am new to django and have gotten a bit stuck on trying to make the admin site work as I'd like it to. I am wondering if for making the admin functionality I want it is better to make a custom admin app with a template inheriting from admin/base_site.html, using the frontend login with a redirect when is_staff is true.
The initial details that make me think this:
I have a chain of foreignkeys and would like to display nested inlines on the parent admin page. I have tried using easymode, but it's got its own issues and requirements that may cause headaches later i can do without.
I would like to add a function allowing the admin to add an instance of a model, which triggers the creation of instances its related models and redirects etc. This requires adding some callables at least, which I havent figured out yet how to really do with any success in the admin model, and at the moment seems easier to just quickly do this in the views.py of my own app rather than trying to toy with the admin views.
In general, creating a custom admin app (using a is_staff=true redirect on the FrontEnd login) seems more flexible in the long run, and will result in a more designed and intuitive admin interface for the client - so I suppose my question is, what are the semi-pros doing? (if you know how to hack the admin views and templates to your heart's content you are not a semi-pro :) )
Thanks for any advice you can offer, Im still getting my feet wet and this kind of advice could save me alot of time and headache.
A:
Slow down. Relax. Follow the Django philosophy.
You have an "app". It presents data. Focus on presentation.
You have a default, built-in admin for your "app". It updates data and it's already there.
If the admin app doesn't meet your needs update Forms and update Models to get close. But don't strain yourself messing with admin. Get as close as you can. But relax about it.
[Also, "more intuitive admin" is sometimes not an accurate description of what you're trying to do. It could be, but I've seen some "more intuitive" that actually wasn't.]
a more designed and intuitive admin interface for the client.
Is this part of the app? Does the app do more than simply present data?
If the app is transactional -- add, change, delete -- crud rules -- that kind of thing, then that's your app. If you want a fancy UI, that's not admin any more. There's no redirect. That's your app.
It's just coding. Stop messing with admin and start writing your app.
Hint: Use generic views as much as possible.
Other than that, you're talking about your app, not hacking the admin stuff that already works.
if you know how to hack the admin views and templates to your heart's content you are not a semi-pro
Wrong. All the source is there. You can read it, also. That's what the pros do. We read the source. And we don't hack the admin app.
If you have complex transactions, you have a first-class, for-real, actual application. Not default admin, but a part of your app that has forms.
If you have forms, then, well, you have forms. This does not require hacking the admin app, it's just coding more of your app.
A:
Go through the links mentioned in this post as well. This may be helpful for you.
Is Django admin difficult to customize?
| Customizing Django Admin Interface functionality | I am new to django and have gotten a bit stuck on trying to make the admin site work as I'd like it to. I am wondering if for making the admin functionality I want it is better to make a custom admin app with a template inheriting from admin/base_site.html, using the frontend login with a redirect when is_staff is true.
The initial details that make me think this:
I have a chain of foreignkeys and would like to display nested inlines on the parent admin page. I have tried using easymode, but it's got its own issues and requirements that may cause headaches later i can do without.
I would like to add a function allowing the admin to add an instance of a model, which triggers the creation of instances its related models and redirects etc. This requires adding some callables at least, which I havent figured out yet how to really do with any success in the admin model, and at the moment seems easier to just quickly do this in the views.py of my own app rather than trying to toy with the admin views.
In general, creating a custom admin app (using a is_staff=true redirect on the FrontEnd login) seems more flexible in the long run, and will result in a more designed and intuitive admin interface for the client - so I suppose my question is, what are the semi-pros doing? (if you know how to hack the admin views and templates to your heart's content you are not a semi-pro :) )
Thanks for any advice you can offer, Im still getting my feet wet and this kind of advice could save me alot of time and headache.
| [
"Slow down. Relax. Follow the Django philosophy.\n\nYou have an \"app\". It presents data. Focus on presentation.\nYou have a default, built-in admin for your \"app\". It updates data and it's already there.\nIf the admin app doesn't meet your needs update Forms and update Models to get close. But don't strai... | [
9,
0
] | [] | [] | [
"admin",
"customization",
"django",
"python"
] | stackoverflow_0003758509_admin_customization_django_python.txt |
Q:
Multithreaded repeater in Python
I have small repeater Below that keeps ending, How can fix so more stable from crashes, and not stop running....
I would I add a heartbeat to the gui to see that its still running. In Wxpthon, my menu bar goes blank or white.
def TimerSetup():
import threading, time
invl = 300
def dothis():
try:
FetchUpdates()
except Exception as e:
pass
class Repeat(threading.Thread):
def run(self):
dothis()
if __name__ == '__main__':
for x in range(7000):
thread = Repeat(name = "Thread-%d" % (x + 1))
thread.start()
time.sleep(invl)
A:
This runs for 7000 iterations. So if your runtime is at about 7000*300 s, it "works exactly as coded" :-) However, possibly the number of threads or the things you do in FetchUpdates could be a problem. Is there any traceback when it stops? Are reaching a user limit?
A:
seems you need join() to wait the start thread
def TimerSetup():
import threading, time
invl = 300
def dothis():
try:
FetchUpdates()
except Exception as e:
pass
class Repeat(threading.Thread):
def run(self):
dothis()
if __name__ == '__main__':
for x in range(7000):
thread = Repeat(name = "Thread-%d" % (x + 1))
thread.start()
thread.join()
time.sleep(invl)
| Multithreaded repeater in Python | I have small repeater Below that keeps ending, How can fix so more stable from crashes, and not stop running....
I would I add a heartbeat to the gui to see that its still running. In Wxpthon, my menu bar goes blank or white.
def TimerSetup():
import threading, time
invl = 300
def dothis():
try:
FetchUpdates()
except Exception as e:
pass
class Repeat(threading.Thread):
def run(self):
dothis()
if __name__ == '__main__':
for x in range(7000):
thread = Repeat(name = "Thread-%d" % (x + 1))
thread.start()
time.sleep(invl)
| [
"This runs for 7000 iterations. So if your runtime is at about 7000*300 s, it \"works exactly as coded\" :-) However, possibly the number of threads or the things you do in FetchUpdates could be a problem. Is there any traceback when it stops? Are reaching a user limit? \n",
"seems you need join() to wait the sta... | [
0,
0
] | [] | [] | [
"heartbeat",
"multithreading",
"python"
] | stackoverflow_0003754745_heartbeat_multithreading_python.txt |
Q:
How to make a file which is on local server download-able over HTTP in python?
Framework: Django
Language: Python
OS: Ubuntu
For example, let us assume that I have a file "xyz.pdf" at "/home/username/project/". I have a webpage with download button. So if people click on that download button, the file xyz.pdf should be downloaded.
What I have done,
Created a webpage with download button with href as "download/" (as you all know this url does not matter much)
it is redirected to urls.py and finds the appropriate view say for example "xyzdownload"
at xyzdownload I have following code,
response = urllib2.urlopen('./project/xyz.pdf')
html = response.read()
The error I am getting is unknown url type: ./project/xyz.pdf
Please let me know if you guys need more clarification.
Thanks a lot
A:
Generally, you'd want to just host the file in apache etc., and provide a link to the location. If the file is generated dynamically, or you want to "embargo" it, here's how you might do it with cherrypy:
@cherrypy.expose
def download(self, filename):
"""
Download the specified XML file
"""
# only if it's one of these files
if filename not in "foo.xml bar.xml".split():
return "Nice try"
content = open("/path/to/media/" + filename).read()
cherrypy.response.headers['Content-Type'] = 'application/xml'
cherrypy.response.headers['Content-Length'] = len(content)
disp = 'attachment; filename=%s' filename
cherrypy.response.headers['Content-Disposition'] = disp
cherrypy.response.headers['filename'] = 'application/xml'
cherrypy.response.headers['pragma'] = ""
cherrypy.response.headers['content-cache'] = ""
return content
The link would be like this:
http://example.com/download/foo.xml
A:
The error I am getting is unknown url type: ./project/xyz.pdf
That's simple: ./project/xyz.pdf is not a URL. Wikipedia says:
Every URL consists of some of the
following: the scheme name (commonly
called protocol), followed by a colon,
then, depending on scheme, a hostname
(alternatively, IP address), a port
number, the path of the resource to be
fetched or the program to be run,
then, for programs such as Common
Gateway Interface (CGI) scripts, a
query string, and with HTML
documents, an anchor (optional) for
where the page should start to be
displayed.
You didn't provide the scheme name and the hostname. However, I don't understand why you do this. Calling urlopen means: download this file on my pc. It doesn't mean "give the file to the user".
BTW, the xyzdownload view should be defined as @Ryan Ginstrom suggested you. Of course, you've to adapt the code to Django.
To read some examples, look at here. And of course, you should read this question because it's almost the same one you did.
A:
you may try mechanize for text clicking and url followers by regex it
import mechanize
br = mechanize.Browser()
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# Want debugging messages?
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)
# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
# Download xyz.pdf ;)
f = br.retrieve('http://www.site.com/xyz.pdf')[0]
print f
fh = open(f)
# or you may try with click download just uncomment
# br.click_link(text_regex="download")
# or by url regex
# br.click_link(url_regex="project/xyz.pdf", nr=0)
and check huge resource and tutorial here http://wwwsearch.sourceforge.net/mechanize/
| How to make a file which is on local server download-able over HTTP in python? | Framework: Django
Language: Python
OS: Ubuntu
For example, let us assume that I have a file "xyz.pdf" at "/home/username/project/". I have a webpage with download button. So if people click on that download button, the file xyz.pdf should be downloaded.
What I have done,
Created a webpage with download button with href as "download/" (as you all know this url does not matter much)
it is redirected to urls.py and finds the appropriate view say for example "xyzdownload"
at xyzdownload I have following code,
response = urllib2.urlopen('./project/xyz.pdf')
html = response.read()
The error I am getting is unknown url type: ./project/xyz.pdf
Please let me know if you guys need more clarification.
Thanks a lot
| [
"Generally, you'd want to just host the file in apache etc., and provide a link to the location. If the file is generated dynamically, or you want to \"embargo\" it, here's how you might do it with cherrypy:\n@cherrypy.expose\ndef download(self, filename):\n \"\"\"\n Download the specified XML file\n \"\"\... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003748205_django_python.txt |
Q:
Using Mercurial to separate three versions: official/development/testing/
I'm working on deploying a Python module composed of several dozen files and folders; I use Mercurial for managing the software changes.
I want to keep the same module in three branches: the official one (which the team uses), the development one (this may be more than one development branch), and the testing branch (not the testing of the official branch, but a collection of test related to a third party module used by my module - regression testing when the third party module makes new releases).
How can I accomplish this in Mercurial? Simply name three branches in the same folder or cloning one version into three places an maintain them separately?
Any insight on how to manage this in general would be appreciated.
Thank you.
A:
The "official" way would be cloning your repo in as many branch as you need.
But named branches within a repo is also acceptable, especially if you don't need to work simultaneously on different development efforts (each associated to their respective branch)
I find the "Guide to Branching Model in Mercurial" very instructive on this kind of choice.
Other information on Mercurial branches in this SO question as well.
| Using Mercurial to separate three versions: official/development/testing/ | I'm working on deploying a Python module composed of several dozen files and folders; I use Mercurial for managing the software changes.
I want to keep the same module in three branches: the official one (which the team uses), the development one (this may be more than one development branch), and the testing branch (not the testing of the official branch, but a collection of test related to a third party module used by my module - regression testing when the third party module makes new releases).
How can I accomplish this in Mercurial? Simply name three branches in the same folder or cloning one version into three places an maintain them separately?
Any insight on how to manage this in general would be appreciated.
Thank you.
| [
"The \"official\" way would be cloning your repo in as many branch as you need.\nBut named branches within a repo is also acceptable, especially if you don't need to work simultaneously on different development efforts (each associated to their respective branch)\nI find the \"Guide to Branching Model in Mercurial\... | [
3
] | [] | [] | [
"mercurial",
"python",
"version_control"
] | stackoverflow_0003766657_mercurial_python_version_control.txt |
Q:
Python threading passing statuses
Basically what I'm trying to do is fetch a couple of websites using proxies and process the data. The problem is that the requests rarely fail in a convincing way, setting socket timeouts wasnt very helpful either because they often didn't work.
So what I did is:
q = Queue()
s = ['google.com','ebay.com',] # And so on
for item in s:
q.put(item)
def worker():
item = q.get()
data = fetch(item) # This is the buggy part
# Process the data, yadayada
for i in range(workers):
t = InterruptableThread(target=worker)
t.start()
# Somewhere else
if WorkerHasLivedLongerThanTimeout:
worker.terminate()
(InterruptableThread class)
The problem is that I only want to kill threads which are still stuck on the fetching part. Also, I want the item to return to the queue. Ie:
def worker():
self.status = 0
item = q.get()
data = fetch(item) # This is the buggy part
self.status = 1 # Don't kill me now, bro!
# Process the data, yadayada
# Somewhere else
if WorkerHasLivedLongerThanTimeout and worker.status != 1:
q.put(worker.item)
worker.terminate()
How can this be done?
A:
edit: breaking news; see below · · · ······
I decided recently that I wanted to do something pretty similar, and what came out of it was the pqueue_fetcher module. It ended up being mainly a learning endeavour: I learned, among other things, that it's almost certainly better to use something like twisted than to try to kill Python threads with any sort of reliability.
That being said, there's code in that module that more or less answers your question. It basically consists of a class whose objects can be set up to get locations from a priority queue and feed them into a fetch function that's supplied at object instantiation. If the location's resources get successfully received before their thread is killed, they get forwarded on to the results queue; otherwise they're returned to the locations queue with a downgraded priority. Success is determined by a passed-in function that defaults to bool.
Along the way I ended up creating the terminable_thread module, which just packages the most mature variation I could find of the code you linked to as InterruptableThread. It also adds a fix for 64-bit machines, which I needed in order to use that code on my ubuntu box. terminable_thread is a dependency of pqueue_fetcher.
Probably the biggest stumbling block I hit is that raising an asynchronous exception as do terminable_thread, and the InterruptableThread you mentioned, can have some weird results. In the test suite for pqueue_fetcher, the fetch function blocks by calling time.sleep. I found that if a thread is terminate()d while so blocking, and the sleep call is the last (or not even the last) statement in a nested try block, execution will actually bounce to the except clause of the outer try block, even if the inner one has an except matching the raised exception. I'm still sort of shaking my head in disbelief, but there's a test case in pqueue_fetcher that reenacts this. I believe "leaky abstraction" is the correct term here.
I wrote a hacky workaround that just does some random thing (in this case getting a value from a generator) to break up the "atomicity" (not sure if that's actually what it is) of that part of the code. This workaround can be overridden via the fission parameter to pqueue_fetcher.Fetcher. It (i.e. the default one) seems to work, but certainly not in any way that I would consider particularly reliable or portable.
So my call after discovering this interesting piece of data was to heretofore avoid using this technique (i.e. calling ctypes.pythonapi.PyThreadState_SetAsyncExc) altogether.
In any case, this still won't work if you need to guarantee that any request whose entire data set has been received (and i.e. acknowledged to the server) gets forwarded on to results. In order to be sure of that, you have to guarantee that the bit that does that last network transaction and the forwarding is guarded from being interrupted, without guarding the entire retrieval operation from being interrupted (since this would prevent timeouts from working..). And in order to do that you need to basically rewrite the retrieval operation (i.e. the socket code) to be aware of whichever exception you're going to raise with terminable_thread.Thread.raise_exc.
I've yet to learn twisted, but being the Premier Python Asynchronous Networking Framework©™®, I expect it must have some elegant or at least workable way of dealing with such details. I'm hoping it provides a parallel way to implement fetching from non-network sources (e.g. a local filestore, or a DB, or an etc.), since I'd like to build an app that can glean data from a variety of sources in a medium-agnostic way.
Anyhow, if you're still intent on trying to work out a way to manage the threads yourself, you can perhaps learn from my efforts. Hope this helps.
· · · · ······ this just in:
I've realized that the tests that I thought had stabilized have actually not, and are giving inconsistent results. This appears to be related to the issues mentioned above with exception handling and the use of the fission function. I'm not really sure what's going on with it, and don't plan to investigate in the immediate future unless I end up having a need to actually do things this way.
| Python threading passing statuses | Basically what I'm trying to do is fetch a couple of websites using proxies and process the data. The problem is that the requests rarely fail in a convincing way, setting socket timeouts wasnt very helpful either because they often didn't work.
So what I did is:
q = Queue()
s = ['google.com','ebay.com',] # And so on
for item in s:
q.put(item)
def worker():
item = q.get()
data = fetch(item) # This is the buggy part
# Process the data, yadayada
for i in range(workers):
t = InterruptableThread(target=worker)
t.start()
# Somewhere else
if WorkerHasLivedLongerThanTimeout:
worker.terminate()
(InterruptableThread class)
The problem is that I only want to kill threads which are still stuck on the fetching part. Also, I want the item to return to the queue. Ie:
def worker():
self.status = 0
item = q.get()
data = fetch(item) # This is the buggy part
self.status = 1 # Don't kill me now, bro!
# Process the data, yadayada
# Somewhere else
if WorkerHasLivedLongerThanTimeout and worker.status != 1:
q.put(worker.item)
worker.terminate()
How can this be done?
| [
"edit: breaking news; see below · · · ······\nI decided recently that I wanted to do something pretty similar, and what came out of it was the pqueue_fetcher module. It ended up being mainly a learning endeavour: I learned, among other things, that it's almost certainly better to use something like twisted than to... | [
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003746288_multithreading_python.txt |
Q:
Python: binary tree traversal iterators without using conditionals
I am trying to create a module in python for iterating over a binary tree using the 4 standard tree traversals (inorder, preorder, postorder and levelorder) without using conditionals and only using polymorphic method dispatch or iterators. The following examples should work.
for e in t.preorder():
print(e)
for e in t.postorder():
print(e)
for e in t.inorder():
print(e)
for e in t.levelorder():
print(e)
So far I have come up with the following
def build_tree(preord, inord):
tree = BinaryTree()
tree.root = buildTreeHelper(preord, inord)
return tree
def buildTreeHelper(preorder, inorder):
if len(inorder) == 0:
return None
elem = preorder[0]
elemInorderIndex = inorder.find(elem)
if elemInorderIndex > -1:
leftPreorder = preorder[1:elemInorderIndex + 1]
rightPreorder = preorder[elemInorderIndex + 1:]
leftInorder = inorder[0:elemInorderIndex]
rightInorder = inorder[elemInorderIndex + 1:]
left = buildTreeHelper(leftPreorder, leftInorder)
right = buildTreeHelper(rightPreorder, rightInorder)
return BinaryTreeNode(elem, left, right)
else:
return "No valid tree for the given args"
class BinaryTree:
def __init__(self):
self.root = None
def preorder(self):
return self.root.preorder()
def inorder(self):
return self.root.inorder()
def postoder(self):
return self.root.postorder()
class BinaryTreeNode:
def __init__(self, element, left=None, right=None):
self.element = element
self.left = left
self.right = right
def preorder(self):
yield self.element
for e in self.left.preorder():
yield e
for e in self.right.preorder():
yield e
def inorder(self):
for e in self.left.inorder():
yield e
yield self.element
for e in self.right.inorder():
yield e
def postorder(self):
for e in self.left.postorder():
yield e
for e in self.right.postorder():
yield e
yield self.element
if __name__ == "__main__":
t = build_tree("BAC", "ABC")
for e in t.inorder():
print(e)
When I try to run one of the iterators like at the bottom of the code I get an
AttributeError: 'NoneType' object has no attribute 'inorder'
error message. I think this is because I never raise StopIteration. Any ideas on how to fix this and start implementing levelorder?
A:
You said you wanted to use polymorphism, but you don't actually seem to have done so. Replace all occurrences of 'None' in your code with a special object that supports your methods but returns an empty sequence and it will all work.
Also you should take more care of the indentation when posting Python questions. The code you posted won't run as is.
def build_tree(preord, inord):
tree = BinaryTree()
tree.root = buildTreeHelper(preord, inord)
return tree
def buildTreeHelper(preorder, inorder):
if len(inorder) == 0:
return empty
elem = preorder[0]
elemInorderIndex = inorder.find(elem)
if elemInorderIndex > -1:
leftPreorder = preorder[1:elemInorderIndex + 1]
rightPreorder = preorder[elemInorderIndex + 1:]
leftInorder = inorder[0:elemInorderIndex]
rightInorder = inorder[elemInorderIndex + 1:]
left = buildTreeHelper(leftPreorder, leftInorder)
right = buildTreeHelper(rightPreorder, rightInorder)
return BinaryTreeNode(elem, left, right)
else:
return "No valid tree for the given args"
class BinaryTree:
def __init__(self):
self.root = empty
def preorder(self):
return self.root.preorder()
def inorder(self):
return self.root.inorder()
def postorder(self):
return self.root.postorder()
class EmptyNode:
def preorder(self):
return ()
inorder = postorder = preorder
empty = EmptyNode()
class BinaryTreeNode:
def __init__(self, element, left=empty, right=empty):
self.element = element
self.left = left
self.right = right
def preorder(self):
yield self.element
for e in self.left.preorder():
yield e
for e in self.right.preorder():
yield e
def inorder(self):
for e in self.left.inorder():
yield e
yield self.element
for e in self.right.inorder():
yield e
def postorder(self):
for e in self.left.postorder():
yield e
for e in self.right.postorder():
yield e
yield self.element
if __name__ == "__main__":
t = build_tree("BAC", "ABC")
for e in t.inorder():
print(e)
| Python: binary tree traversal iterators without using conditionals | I am trying to create a module in python for iterating over a binary tree using the 4 standard tree traversals (inorder, preorder, postorder and levelorder) without using conditionals and only using polymorphic method dispatch or iterators. The following examples should work.
for e in t.preorder():
print(e)
for e in t.postorder():
print(e)
for e in t.inorder():
print(e)
for e in t.levelorder():
print(e)
So far I have come up with the following
def build_tree(preord, inord):
tree = BinaryTree()
tree.root = buildTreeHelper(preord, inord)
return tree
def buildTreeHelper(preorder, inorder):
if len(inorder) == 0:
return None
elem = preorder[0]
elemInorderIndex = inorder.find(elem)
if elemInorderIndex > -1:
leftPreorder = preorder[1:elemInorderIndex + 1]
rightPreorder = preorder[elemInorderIndex + 1:]
leftInorder = inorder[0:elemInorderIndex]
rightInorder = inorder[elemInorderIndex + 1:]
left = buildTreeHelper(leftPreorder, leftInorder)
right = buildTreeHelper(rightPreorder, rightInorder)
return BinaryTreeNode(elem, left, right)
else:
return "No valid tree for the given args"
class BinaryTree:
def __init__(self):
self.root = None
def preorder(self):
return self.root.preorder()
def inorder(self):
return self.root.inorder()
def postoder(self):
return self.root.postorder()
class BinaryTreeNode:
def __init__(self, element, left=None, right=None):
self.element = element
self.left = left
self.right = right
def preorder(self):
yield self.element
for e in self.left.preorder():
yield e
for e in self.right.preorder():
yield e
def inorder(self):
for e in self.left.inorder():
yield e
yield self.element
for e in self.right.inorder():
yield e
def postorder(self):
for e in self.left.postorder():
yield e
for e in self.right.postorder():
yield e
yield self.element
if __name__ == "__main__":
t = build_tree("BAC", "ABC")
for e in t.inorder():
print(e)
When I try to run one of the iterators like at the bottom of the code I get an
AttributeError: 'NoneType' object has no attribute 'inorder'
error message. I think this is because I never raise StopIteration. Any ideas on how to fix this and start implementing levelorder?
| [
"You said you wanted to use polymorphism, but you don't actually seem to have done so. Replace all occurrences of 'None' in your code with a special object that supports your methods but returns an empty sequence and it will all work.\nAlso you should take more care of the indentation when posting Python questions.... | [
1
] | [] | [] | [
"binary_tree",
"iterator",
"python",
"python_3.x"
] | stackoverflow_0003767014_binary_tree_iterator_python_python_3.x.txt |
Q:
Python - Speed up generation of permutations of a list (and process of checking if permuations in Dict)
I need a faster way to generate all permutations of a list, then check if each one is in a dictionary.
for x in range (max_combo_len, 0, -1):
possible_combos = []
permutations = list(itertools.permutations(bag,x))
for item in permutations:
possible_combos.append(" ".join(item))
#then check to see if each possible combo is in a specific Dict
If it helps, the lists are all going to be lists of strings. ['such as', 'this', 'one']
My solution works, but it's very slow. It could be that I need to stop using Python, but I thought I'd run it by you experts first!
Best,
Gary
A:
A very basic optimization:
permutations = list(itertools.permutations(bag,x))
for item in permutations:
can become...
for item in itertools.permutations(bag,x):
A:
I can't test it very well without better input cases, but here are a few improvements:
for x in xrange(max_combo_len, 0, -1):
possible_combos = (" ".join(item) for item in itertools.permutations(bag,x))
#then check to see if each possible combo is in a specific Dict
combos = (c for c in possible_combos if c in specific_dict)
First, assuming you're using Python 2.x, xrange will help by not constructing an explicit list, but rather just yielding each x as you need it.
More importantly, you can throw the main effort into generator expressions and have it yield values on demand.
A:
for x in xrange(max_combo_len, 0, -1):
for item in itertools.permutations(bag,x):
combo = " ".join(item)
if combo in specificDict:
yield combo
This way you don't have any large (and getting larger) lists, you just yield the passing comobs out of the function.
A:
you can get rid of the many usesless (thrown away) join operations, if you prepare your special dict: just split the values or the keys, depending what you compare. This assumes of course that the dict is smaller than the number of all combos.
If you need the join, you have to slightly alter this. I think without you being more descriptive the problem isn't any better optimizable than this. And it's not gonna be much faster just by using another language.
(filtered_combo for filtered_combo in
itertools.chain.from_iterable(
combo for combo in (itertools.permutations(bag, x)
for x in xrange(max_combo_len, 0, -1)))
if filtered_combo in special_dict)
A:
Something like this?
sentences = ['such as', 'this', 'ten eggs', 'one book', 'six eggs']
bag_of_words = set(['such', 'one','ten','book','eggs'])
possible = [sentence
for sentence in sentences
if all(word in bag_of_words for word in sentence.split())
]
print 'Possible to produce from bag words are:\n\t%s' % '\n\t'.join(possible)
| Python - Speed up generation of permutations of a list (and process of checking if permuations in Dict) | I need a faster way to generate all permutations of a list, then check if each one is in a dictionary.
for x in range (max_combo_len, 0, -1):
possible_combos = []
permutations = list(itertools.permutations(bag,x))
for item in permutations:
possible_combos.append(" ".join(item))
#then check to see if each possible combo is in a specific Dict
If it helps, the lists are all going to be lists of strings. ['such as', 'this', 'one']
My solution works, but it's very slow. It could be that I need to stop using Python, but I thought I'd run it by you experts first!
Best,
Gary
| [
"A very basic optimization:\npermutations = list(itertools.permutations(bag,x))\nfor item in permutations:\n\ncan become...\nfor item in itertools.permutations(bag,x):\n\n",
"I can't test it very well without better input cases, but here are a few improvements:\nfor x in xrange(max_combo_len, 0, -1):\n possibl... | [
5,
1,
1,
1,
0
] | [] | [] | [
"dictionary",
"list",
"permutation",
"python",
"python_itertools"
] | stackoverflow_0003766661_dictionary_list_permutation_python_python_itertools.txt |
Q:
Python: How to catch this kind of exception?
I'm making a program for AIX 5.3 in Python 2.6.1 that interfaces with an IMAP server. I'm getting an exception which I don't know how to catch - it doesn't seem to have a name that I can use with "except". The error seems to be some kind of timeout in the connection to the server.
The last part of the stack trace looks like this:
File "/home/chenf/python-2.6.1/lib/python2.6/imaplib.py", line 890, in _command_complete
raise self.abort('command: %s => %s' % (name, val))
abort: command: SEARCH => socket error: EOF
I only want to catch this specific error, so that I can reconnect to the IMAP server when it happens. What's the syntax for catching this kind of exception?
A:
The exception is imaplib.IMAP4.abort (Python doc) so catching that should work
A:
you can try to catch it and find out the type:
import sys,traceback,pprint
try:
do what you want to do
except:
type, value, tb = sys.exc_info()
pprint.pprint(type)
print("\n" + ''.join(traceback.format_exception(type, value, tb)).strip("\n"))
| Python: How to catch this kind of exception? | I'm making a program for AIX 5.3 in Python 2.6.1 that interfaces with an IMAP server. I'm getting an exception which I don't know how to catch - it doesn't seem to have a name that I can use with "except". The error seems to be some kind of timeout in the connection to the server.
The last part of the stack trace looks like this:
File "/home/chenf/python-2.6.1/lib/python2.6/imaplib.py", line 890, in _command_complete
raise self.abort('command: %s => %s' % (name, val))
abort: command: SEARCH => socket error: EOF
I only want to catch this specific error, so that I can reconnect to the IMAP server when it happens. What's the syntax for catching this kind of exception?
| [
"The exception is imaplib.IMAP4.abort (Python doc) so catching that should work\n",
"you can try to catch it and find out the type:\nimport sys,traceback,pprint\ntry:\n do what you want to do\nexcept:\n type, value, tb = sys.exc_info()\n pprint.pprint(type)\n print(\"\\n\" + ''.join(traceback.format_e... | [
10,
3
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0003767432_exception_python.txt |
Q:
Python or C++? Programming for mobile devices
I am interested in programming for Mobile Devices.
Now I have a phone which runs Symbian S60 3rd, which is one of my motivations for programming for mobile devices.
Now, my question is, which one is better to go for?
Python or C++?
I have a good background in C++ (ANSI), Java and C#.
Thanks.
A:
There's a large learning curve associated with Symbian C++, if you want to do a quick prototype probably do it in Python.
It depends on what you want your application to do. I believe the Symbian Python implementation was done in some Symbian developers spare time so it may not give you access to everything on the phone. Symbian C++ will give you access to almost everything.
Also, Java and MIDP may be useful to you too.
A:
Python is more easy to use, but you have to know that a mobile is normally a very strict environment, so is possible that C++ be a better alternative.
A:
If you want to program for your Symbian phone, why not download some tools, read some tutorials, and try it? It looks like they lean towards C++ and Qt.
A:
If you want to get into mobile development, C++ can definitely help you with Microsoft Windows Mobile development.
However, just as S.Lott stated, each platform may require an entirely different IDE, let alone an entirely new language. For example, in order to program for the Android and BlackBerry platform, developers use Java; for the iPhone, developers use Objective-C.
Unfortunately, I'm not familiar with any mobile platforms on which developers can create GUI apps using python.
A:
Python could work , C++ could work, but you should also consider JAVA MOBILE.
Python is nothing more than wrapping of C++ libraries, but that means you will have to do some wrapping as it is not programming language supported by the operation systems of mobile phones with the exception of Android.
Another option is Javascript, the only way to make sure your apps will work anywhere , with no recoding . Pyjamas can help you translate your python code to javascript code.
If I were you I would given Pyjamas a serious try.
http://pyjs.org/
Obviously using javascript imposes some restrictions , the biggest one is that your app will not run natively but from inside a browser. However in case of iphone os Apple has been quite vocal about JAvascript and HTML5. What happens however with the thousands other mobile devices ? What about those that do not browse the net and dont have a browser or have a broswer and is pathetic ?
The choice is yours.
| Python or C++? Programming for mobile devices | I am interested in programming for Mobile Devices.
Now I have a phone which runs Symbian S60 3rd, which is one of my motivations for programming for mobile devices.
Now, my question is, which one is better to go for?
Python or C++?
I have a good background in C++ (ANSI), Java and C#.
Thanks.
| [
"There's a large learning curve associated with Symbian C++, if you want to do a quick prototype probably do it in Python.\nIt depends on what you want your application to do. I believe the Symbian Python implementation was done in some Symbian developers spare time so it may not give you access to everything on th... | [
2,
1,
1,
0,
0
] | [] | [] | [
"c++",
"python",
"symbian"
] | stackoverflow_0003763766_c++_python_symbian.txt |
Q:
Namespaces in C# vs imports in Java and Python
In the Java and Python world, you look at a source file and know where all the imports come from (i.e. you know in which file the imported classes are defined). For example:
In Java:
import javafoo.Bar;
public class MyClass {
private Bar myBar = new Bar();
}
You immediately see that the Bar-class is imported from javafoo. So, Bar is declared in /javafoo/Bar.java
In Python
import pythonbaz
from pythonfoo import Bar
my_bar = Bar()
my_other = pythonbaz.Other()
Here, it is clear that Bar comes from the pythonfoo package and Other is obviously from pythonbaz.
In C# (correct me if I'm wrong):
using foo
using baz
using anothernamespace
...
public class MyClass
{
private Bar myBar = new Bar();
}
Two questions:
1) How do I know where the Bar-class is declared? Does it come from the namespace foo, or bar, or anothernamespace? (edit: without using Visual Studio)
2) In Java, the package names correspond to directory names (or, it is a very strong convention). Thus, when you see which package a class comes from, you know its directory in the file system.
In C#, there does not seem to be such a convention for namespaces, or am I missing something? So, how do I know which directory and file to look in (without Visual Studio)? (after figuring out which namespace the class came from).
Edit clarification: I am aware that Python and/or Java allow wildcard imports, but the 'culture' in those languages frowns upon them (at least in Python, in Java I'm not sure). Also, in Java IDEs usually help you create minimal imports (as Mchl. commented below)
A:
1) Well, you can do the same thing in Java too:
import java.util.*;
import java.io.*;
...
InputStream x = ...;
Does InputStream come from java.util or java.io? Of course, you can choose not to use that feature.
Now, in theory I realise this means when you're looking with a text editor, you can't tell where the types come from in C#... but in practice, I don't find that to be a problem. How often are you actually looking at code and can't use Visual Studio?
2) You can use the same convention in .NET too, of course - and I do, although I don't have empty directories going up the chain... so if I'm creating a project with a default namespace of X.Y, then X.Y.Foo would be in Foo.cs, and X.Y.Z.Bar would be in Z\Bar.cs
That's also what Visual Studio will do by default - if you create a subfolder, it will create new classes using a namespace based on the project default and the folder structure.
Of course, you can also declare types in any old file - but mostly people will follow the normal convention of declaring a type with a corresponding filename. Before generics made delegate declarations rarer, I used to have a Delegates.cs file containing all the delegate declarations for a particular namespace (rather than having a bunch of single-declaration files) but these days that's less of an issue.
A:
1) You're right. There is no "direct" way to know where your class comes from at first glance, but, as you said, you can jump to it in the IDE. But declaring the class this way is just the shortest way to do it. If you wanted, and assuming your Bar class comes from the Foo one, you could declare it
private foo.Bar myBar = new foo.Bar();
This way it would help knowing where your classes come from at first look.
2)When you add a reference to your class, the Add reference windows gives you the informations you are looking for.
And if you want to know where they come from after you declared it, there is a window named "Solution Explorer" where you can find these informations, under the "References" tree node.
You can set it to be always visible (which it is by default)
A:
For Java and Python this is indeed an issue with conventions - import the class you need, not the entire package using wildcards.
In C# you can't do a using directive for the specific class you want, since it only works for namespaces (as the following error reveals). It would seem that C# remained true to the C++ concept of namespaces, and merged it with the #include directive for one easy way of referencing external classes.
using System.Net.Sockets.Socket; // Gives the following error:
// A using namespace directive can only be applied to namespaces;
// 'System.Net.Sockets.Socket' is a type not a namespace
And about the double Bar deceleration, it's simple - if the compiler has no way of knowing it will give an error:
using Foo; // Has class Bar {}
using Goo; // Has class Bar {}
Bar b = new Bar(); // Gives the following error:
// 'Bar' is an ambiguous reference between 'Foo.Bar' and 'Goo.Bar'
A:
How do I know where the Bar-class is
declared? Does it come from the
namespace foo, or bar, or
anothernamespace? Visual Studio allows
me to jump there, of course, but what
if I am just taking a quick look at a
source file in my editor?
Essentially, you don't - but IntelliSense is helping. You cannot actually be sure by just taking a quick glance at the code, but you can hover over the symbol with your cursor, for example. But this is also possible in Python:
from foobar import *
from bazbaz import *
a_bar = Bar()
Where does Bar come from now?
In C#, there does not seem to be such
a convention for namespaces, or am I
missing something? So, how do I know
which directory and file to look in?
(after figuring out which namespace
the class came from).
No, assemblies do not correspond to directory structures, which, IMHO, is a good thing. The solution explorer is offering a view of all the references added to your project. These references being assemblies, have a concrete representation as a PE file somewhere on your machine. You can easily look at the properties of a reference to see where the physical file is located.
Edit: In order not to contradict other answers in this thread and create confusion: What I mean by saying assembly names do not correspond to directory names is that it is not actually enforced.
A:
In C#, there does not seem to be such a convention for namespaces, or am I missing something?
I don’t know about other projects but I’m pretty sure that in every .NET project I have worked on, we used this convention, i.e. namespaces always corresponded to folder names (except for the outermost namespace(s) which correspond to the assembly from which the namespace comes).
A:
Usually, the tooltip when you mouse-over the type name reveals some extra information. Else you could always right-click the type name, and 'Go to definition'.
| Namespaces in C# vs imports in Java and Python | In the Java and Python world, you look at a source file and know where all the imports come from (i.e. you know in which file the imported classes are defined). For example:
In Java:
import javafoo.Bar;
public class MyClass {
private Bar myBar = new Bar();
}
You immediately see that the Bar-class is imported from javafoo. So, Bar is declared in /javafoo/Bar.java
In Python
import pythonbaz
from pythonfoo import Bar
my_bar = Bar()
my_other = pythonbaz.Other()
Here, it is clear that Bar comes from the pythonfoo package and Other is obviously from pythonbaz.
In C# (correct me if I'm wrong):
using foo
using baz
using anothernamespace
...
public class MyClass
{
private Bar myBar = new Bar();
}
Two questions:
1) How do I know where the Bar-class is declared? Does it come from the namespace foo, or bar, or anothernamespace? (edit: without using Visual Studio)
2) In Java, the package names correspond to directory names (or, it is a very strong convention). Thus, when you see which package a class comes from, you know its directory in the file system.
In C#, there does not seem to be such a convention for namespaces, or am I missing something? So, how do I know which directory and file to look in (without Visual Studio)? (after figuring out which namespace the class came from).
Edit clarification: I am aware that Python and/or Java allow wildcard imports, but the 'culture' in those languages frowns upon them (at least in Python, in Java I'm not sure). Also, in Java IDEs usually help you create minimal imports (as Mchl. commented below)
| [
"1) Well, you can do the same thing in Java too:\nimport java.util.*;\nimport java.io.*;\n\n...\n\nInputStream x = ...;\n\nDoes InputStream come from java.util or java.io? Of course, you can choose not to use that feature.\nNow, in theory I realise this means when you're looking with a text editor, you can't tell w... | [
7,
3,
3,
2,
2,
1
] | [] | [] | [
"c#",
"java",
"namespaces",
"package",
"python"
] | stackoverflow_0003767910_c#_java_namespaces_package_python.txt |
Q:
How can I make this Python2.6 function work with Unicode?
I've got this function, which I modified from material in chapter 1 of the online NLTK book. It's been very useful to me but, despite reading the chapter on Unicode, I feel just as lost as before.
def openbookreturnvocab(book):
fileopen = open(book)
rawness = fileopen.read()
tokens = nltk.wordpunct_tokenize(rawness)
nltktext = nltk.Text(tokens)
nltkwords = [w.lower() for w in nltktext]
nltkvocab = sorted(set(nltkwords))
return nltkvocab
When I tried it the other day on Also Sprach Zarathustra, it clobbered words with an umlat over the o's and u's. I'm sure some of you will know why that happened. I'm also sure that it's quite easy to fix. I know that it just has to do with calling a function that re-encodes the tokens into unicode strings. If so, that it seems to me it might not happen inside that function definition at all, but here, where I prepare to write to file:
def jotindex(jotted, filename, readmethod):
filemydata = open(filename, readmethod)
jottedf = '\n'.join(jotted)
filemydata.write(jottedf)
filemydata.close()
return 0
I heard that what I had to do was encode the string into unicode after reading it from the file. I tried amending the function like so:
def openbookreturnvocab(book):
fileopen = open(book)
rawness = fileopen.read()
unirawness = rawness.decode('utf-8')
tokens = nltk.wordpunct_tokenize(unirawness)
nltktext = nltk.Text(tokens)
nltkwords = [w.lower() for w in nltktext]
nltkvocab = sorted(set(nltkwords))
return nltkvocab
But that brought this error, when I used it on Hungarian. When I used it on German, I had no errors.
>>> import bookroutines
>>> elles1 = bookroutines.openbookreturnvocab("lk1-les1")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bookroutines.py", line 9, in openbookreturnvocab
nltktext = nltk.Text(tokens)
File "/usr/lib/pymodules/python2.6/nltk/text.py", line 285, in __init__
self.name = " ".join(map(str, tokens[:8])) + "..."
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not in range(128)
I fixed the function that files the data like so:
def jotindex(jotted, filename, readmethod):
filemydata = open(filename, readmethod)
jottedf = u'\n'.join(jotted)
filemydata.write(jottedf)
filemydata.close()
return 0
However, that brought this error, when I tried to file the German:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bookroutines.py", line 23, in jotindex
filemydata.write(jottedf)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 414: ordinal not in range(128)
>>>
...which is what you get when you try to write the u'\n'.join'ed data.
>>> jottedf = u'/n'.join(elles1)
>>> filemydata.write(jottedf)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 504: ordinal not in range(128)
A:
For each string that you read from your file, you can convert them to unicode by calling rawness.decode('utf-8'), if you have the text in UTF-8. You will end up with unicode objects. Also, I don't know what "jotted" is, but you may want to make sure it's a unicode object and use u'\n'.join(jotted) instead.
Update:
It appears that the NLTK library doesn't like unicode objects. Fine, then you have to make sure that you are using str instances with UTF-8 encoded text. Try using this:
tokens = nltk.wordpunct_tokenize(unirawness)
nltktext = nltk.Text([token.encode('utf-8') for token in tokens])
and this:
jottedf = u'\n'.join(jotted)
filemydata.write(jottedf.encode('utf-8'))
but if jotted is really a list of UTF-8-encoded str, then you don't need this and this should be enough:
jottedf = '\n'.join(jotted)
filemydata.write(jottedf)
By the way, it looks as though NLTK isn't very cautious with respect to unicode and encoding (at least, the demos). Better be careful and check that it has processed your tokens correctly. Also, and this may have caused the fact that you get errors with Hungarian text and not German text, check your encodings.
| How can I make this Python2.6 function work with Unicode? | I've got this function, which I modified from material in chapter 1 of the online NLTK book. It's been very useful to me but, despite reading the chapter on Unicode, I feel just as lost as before.
def openbookreturnvocab(book):
fileopen = open(book)
rawness = fileopen.read()
tokens = nltk.wordpunct_tokenize(rawness)
nltktext = nltk.Text(tokens)
nltkwords = [w.lower() for w in nltktext]
nltkvocab = sorted(set(nltkwords))
return nltkvocab
When I tried it the other day on Also Sprach Zarathustra, it clobbered words with an umlat over the o's and u's. I'm sure some of you will know why that happened. I'm also sure that it's quite easy to fix. I know that it just has to do with calling a function that re-encodes the tokens into unicode strings. If so, that it seems to me it might not happen inside that function definition at all, but here, where I prepare to write to file:
def jotindex(jotted, filename, readmethod):
filemydata = open(filename, readmethod)
jottedf = '\n'.join(jotted)
filemydata.write(jottedf)
filemydata.close()
return 0
I heard that what I had to do was encode the string into unicode after reading it from the file. I tried amending the function like so:
def openbookreturnvocab(book):
fileopen = open(book)
rawness = fileopen.read()
unirawness = rawness.decode('utf-8')
tokens = nltk.wordpunct_tokenize(unirawness)
nltktext = nltk.Text(tokens)
nltkwords = [w.lower() for w in nltktext]
nltkvocab = sorted(set(nltkwords))
return nltkvocab
But that brought this error, when I used it on Hungarian. When I used it on German, I had no errors.
>>> import bookroutines
>>> elles1 = bookroutines.openbookreturnvocab("lk1-les1")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bookroutines.py", line 9, in openbookreturnvocab
nltktext = nltk.Text(tokens)
File "/usr/lib/pymodules/python2.6/nltk/text.py", line 285, in __init__
self.name = " ".join(map(str, tokens[:8])) + "..."
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not in range(128)
I fixed the function that files the data like so:
def jotindex(jotted, filename, readmethod):
filemydata = open(filename, readmethod)
jottedf = u'\n'.join(jotted)
filemydata.write(jottedf)
filemydata.close()
return 0
However, that brought this error, when I tried to file the German:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bookroutines.py", line 23, in jotindex
filemydata.write(jottedf)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 414: ordinal not in range(128)
>>>
...which is what you get when you try to write the u'\n'.join'ed data.
>>> jottedf = u'/n'.join(elles1)
>>> filemydata.write(jottedf)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 504: ordinal not in range(128)
| [
"For each string that you read from your file, you can convert them to unicode by calling rawness.decode('utf-8'), if you have the text in UTF-8. You will end up with unicode objects. Also, I don't know what \"jotted\" is, but you may want to make sure it's a unicode object and use u'\\n'.join(jotted) instead.\nU... | [
4
] | [] | [] | [
"nlp",
"nltk",
"python",
"python_2.6",
"unicode"
] | stackoverflow_0003768373_nlp_nltk_python_python_2.6_unicode.txt |
Q:
Keep SSL keyfile open in Python
I'm using Python's ssl library with an encrypted keyfile. However every time I wrap a socket, I'm prompted for the passphrase.
Enter PEM pass phrase:
How can I give the passphrase just once, and have Python hold the decrypted key open for the lifetime of the process?
I'm very interested in the canonical openssl command line or C equivalent for this functionality also (assuming it assists in this situation).
I'd rather not resort to using subprocess and explicitly decoding/deleting the decrypted key. However if there is no alternative, a clean, secure suggestion guaranteeing the destruction and privacy of the decrypted key is welcome.
A:
This issue is fixed in Python 2.7, and Python 3.2.
| Keep SSL keyfile open in Python | I'm using Python's ssl library with an encrypted keyfile. However every time I wrap a socket, I'm prompted for the passphrase.
Enter PEM pass phrase:
How can I give the passphrase just once, and have Python hold the decrypted key open for the lifetime of the process?
I'm very interested in the canonical openssl command line or C equivalent for this functionality also (assuming it assists in this situation).
I'd rather not resort to using subprocess and explicitly decoding/deleting the decrypted key. However if there is no alternative, a clean, secure suggestion guaranteeing the destruction and privacy of the decrypted key is welcome.
| [
"This issue is fixed in Python 2.7, and Python 3.2.\n"
] | [
1
] | [] | [] | [
"passphrase",
"pem",
"python",
"security",
"ssl"
] | stackoverflow_0003140011_passphrase_pem_python_security_ssl.txt |
Q:
Python compare dictonaries for different values
I have 2 lists of dictonaries and want to return items which have the same id but different title. i.e.
list1 = [{'id': 1, 'title': 'title1'}, {'id': 2, 'title': 'title2'}, {'id': 3, 'title': 'title3'}]
list2 = [{'id': 1, 'title': 'title1'}, {'id': 2, 'title': 'title3'}, {'id': 3, 'title': 'title4'}]
Would return [{'id': 2, 'title': 'title2'}, {'id': 3, 'title': 'title3'}] as the titles are different in list2 to list1.
A:
I propose that you refactor your design to not be a list of dictionaries, but 2 dictionaries of id: title pairs. The algorithm is trivial at that point and the performance is better.
Code example (edited to reflect SilentGhost's correct assertion):
titles1 = {1: "title1", 2: "title2", 3: "title3"}
titles2 = {1: "title1", 2: "not_title2", 3: "title3"}
for id, title in titles1.iteritems():
# verify the key is in titles2, compare title to titles2[id]
Code example to convert list of dictionary to dictionary with id as key:
titles1 = dict([(x["id"], x) for x in list1])
A:
[dc for dc in list1 if dc['id'] in [d["id"] for d in list2] and dc not in list2]
A:
Different dictionaries are equal if their contents are equal. So you can just do:
for i in list1:
if i not in list2:
result.append(i)
A:
If you refactor your data structure (assuming id is unique within one dictionary), a comparison could be implemented more efficiently (namely in O(n). Dictionary lookups are O(1). Example:
#!/usr/bin/env python
d1 = {
1 : {"title" : "title1"},
2 : {"title" : "title2"},
3 : {"title" : "title3"},
}
d2 = {
1 : {"title" : "title1"},
2 : {"title" : "title3"},
3 : {"title" : "title4"},
}
for key, value in d1.items():
if not value == d2[key]:
print "@", key, "values differ:", d1[key], "vs", d2[key]
# @ 2 values differ: {'title': 'title2'} vs {'title': 'title3'}
# @ 3 values differ: {'title': 'title3'} vs {'title': 'title4'}
Or shorter:
print [ (k, (d1[k], d2[k])) for k in d1 if not d2[k] == d1[k] ]
# [(2, ({'title': 'title2'}, {'title': 'title3'})), \
# (3, ({'title': 'title3'}, {'title': 'title4'}))]
| Python compare dictonaries for different values | I have 2 lists of dictonaries and want to return items which have the same id but different title. i.e.
list1 = [{'id': 1, 'title': 'title1'}, {'id': 2, 'title': 'title2'}, {'id': 3, 'title': 'title3'}]
list2 = [{'id': 1, 'title': 'title1'}, {'id': 2, 'title': 'title3'}, {'id': 3, 'title': 'title4'}]
Would return [{'id': 2, 'title': 'title2'}, {'id': 3, 'title': 'title3'}] as the titles are different in list2 to list1.
| [
"I propose that you refactor your design to not be a list of dictionaries, but 2 dictionaries of id: title pairs. The algorithm is trivial at that point and the performance is better.\nCode example (edited to reflect SilentGhost's correct assertion):\ntitles1 = {1: \"title1\", 2: \"title2\", 3: \"title3\"}\ntitles2... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003768543_python.txt |
Q:
Python lists and list item matches - can my code/reasoning be improved?
query level: beginner
As part of a learning exercise I have written code that must check if a string (as it is build up through raw_input) matches the beginning of any list item and if it equals any list item.
wordlist = ['hello', 'bye']
handlist = []
letter = raw_input('enter letter: ')
handlist.append(letter)
hand = "".join(handlist)
for item in wordlist:
if item.startswith(hand):
while item.startswith(hand):
if hand not in wordlist:
letter = raw_input('enter letter: ')
handlist.append(letter)
hand = "".join(handlist)
else: break
else: break
print 'you loose'
This code works but how can my code (and my reasoning/approach) be improved?
I have the feeling that my nesting of IF, WHILE and FOR statements is overkill.
EDIT
Thanks to Dave, I was able to considerably shorten and optimise my code.
wordlist = ['hello','hamburger', 'bye', 'cello']
hand = ''
while any(item.startswith(hand) for item in wordlist):
if hand not in wordlist:
hand += raw_input('enter letter: ')
else: break
print 'you loose'
I'm surprised my original code worked at all...
A:
Firstly, you don't need the handlist variable; you can just concatenate the value of raw_input with hand.
You can save the first raw_input by starting the while loop with hand as an empty string since every string has startswith("") as True.
Finally, we need work out best way to see if any of the items in wordlist starts with hand. We could use a list comprehension for this:
[item for item in wordlist if item.startswith(hand)]
and then check the length of the returned list if greater than zero.
However, even better, python has the any() function which is perfect for this: it returns True if any element of an iterable is True, so we just evaluate startswith() for each member of wordlist.
Putting this all together we get:
wordlist = ['hello', 'bye']
hand = ""
while any(item.startswith(hand) for item in wordlist):
hand += raw_input('enter letter: ')
print 'you loose'
| Python lists and list item matches - can my code/reasoning be improved? | query level: beginner
As part of a learning exercise I have written code that must check if a string (as it is build up through raw_input) matches the beginning of any list item and if it equals any list item.
wordlist = ['hello', 'bye']
handlist = []
letter = raw_input('enter letter: ')
handlist.append(letter)
hand = "".join(handlist)
for item in wordlist:
if item.startswith(hand):
while item.startswith(hand):
if hand not in wordlist:
letter = raw_input('enter letter: ')
handlist.append(letter)
hand = "".join(handlist)
else: break
else: break
print 'you loose'
This code works but how can my code (and my reasoning/approach) be improved?
I have the feeling that my nesting of IF, WHILE and FOR statements is overkill.
EDIT
Thanks to Dave, I was able to considerably shorten and optimise my code.
wordlist = ['hello','hamburger', 'bye', 'cello']
hand = ''
while any(item.startswith(hand) for item in wordlist):
if hand not in wordlist:
hand += raw_input('enter letter: ')
else: break
print 'you loose'
I'm surprised my original code worked at all...
| [
"Firstly, you don't need the handlist variable; you can just concatenate the value of raw_input with hand.\nYou can save the first raw_input by starting the while loop with hand as an empty string since every string has startswith(\"\") as True.\nFinally, we need work out best way to see if any of the items in word... | [
7
] | [] | [] | [
"list",
"python",
"while_loop"
] | stackoverflow_0003768702_list_python_while_loop.txt |
Q:
Django getting executable raw sql for a QuerySet
I know that you can get the SQL of a given QuerySet using
print query.query
but as we know from a previous question ( Potential Django Bug In QuerySet.query? ) the returned SQL is not properly quoted. See http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py
Is there any way that is it possible to get the raw, executable SQL (quoted) for a given QuerySet without actually executing it?
A:
Django never creates the raw sql, so no. To prevent SQL injection, django passes the parameters separately to the database drivers at the last step. The best way to get the actual SQL is to look at your query log, which you cannot do before you execute the query.
| Django getting executable raw sql for a QuerySet | I know that you can get the SQL of a given QuerySet using
print query.query
but as we know from a previous question ( Potential Django Bug In QuerySet.query? ) the returned SQL is not properly quoted. See http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py
Is there any way that is it possible to get the raw, executable SQL (quoted) for a given QuerySet without actually executing it?
| [
"Django never creates the raw sql, so no. To prevent SQL injection, django passes the parameters separately to the database drivers at the last step. The best way to get the actual SQL is to look at your query log, which you cannot do before you execute the query.\n"
] | [
9
] | [] | [] | [
"django",
"orm",
"python",
"sql"
] | stackoverflow_0003769093_django_orm_python_sql.txt |
Q:
Are there tools that can spot errors like this one?
I found the following mistake in my code this week:
import datetime
d = datetime.date(2010,9,24)
if d.isoweekday == 5:
pass
Yes, it should be d.isoweekday() instead.
I know, if I had had a test-case for this I would have been saved.
Comparing a function with 5 is not very useful. Oh, I'm not blaming Python for this.
My question: Are there tools that can spot errors like this one?
A:
As an alternative, most Python projects are unit tested and system tested. If you have both (or even just unit tests) you'll find your problem along with pretty much any other issue.
As dekomote said, this is syntaxically valid. Python is not statically typed so this cannot be caught as an error. At most it could be a warning.
EDIT: Python is strongly typed just the type is checked at run time.
A:
Check out pylint it may be able to get that. It does find many errors.
A:
Well, this is not an error in python per se because in Python, the functions are callable objects. You can make any object callable by implementing __call__. So d.isoweekday == 5 is valid statement. This will be False.
As for other errors, i suggest checking out pyflakes - http://divmod.org/trac/wiki/DivmodPyflakes
| Are there tools that can spot errors like this one? | I found the following mistake in my code this week:
import datetime
d = datetime.date(2010,9,24)
if d.isoweekday == 5:
pass
Yes, it should be d.isoweekday() instead.
I know, if I had had a test-case for this I would have been saved.
Comparing a function with 5 is not very useful. Oh, I'm not blaming Python for this.
My question: Are there tools that can spot errors like this one?
| [
"As an alternative, most Python projects are unit tested and system tested. If you have both (or even just unit tests) you'll find your problem along with pretty much any other issue.\nAs dekomote said, this is syntaxically valid. Python is not statically typed so this cannot be caught as an error. At most it could... | [
7,
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0003769196_python.txt |
Q:
Setting basedirlist in setup.cfg and PREFIX in make to point to virtualenv
In SO question 3692928, I showed how I compiled and installed matplotlib in a virtualenv. One thing I did was suboptimal though—I manually set the basedirlist in setup.cfg and PREFIX in make.osx.
setup.cfg
[directories]
basedirlist = /Users/matthew/.virtualenvs/matplotlib-test
make.osx
PREFIX=/Users/matthew/.virtualenvs/matplotlib-test
Is there a way that I can automatically set these to the currently activated virtualenv?
A:
Use the VIRTUAL_ENV environment variable:
setup.cfg
[directories]
basedirlist = ${VIRTUAL_ENV}
make.osx
PREFIX=${VIRTUAL_ENV}
| Setting basedirlist in setup.cfg and PREFIX in make to point to virtualenv | In SO question 3692928, I showed how I compiled and installed matplotlib in a virtualenv. One thing I did was suboptimal though—I manually set the basedirlist in setup.cfg and PREFIX in make.osx.
setup.cfg
[directories]
basedirlist = /Users/matthew/.virtualenvs/matplotlib-test
make.osx
PREFIX=/Users/matthew/.virtualenvs/matplotlib-test
Is there a way that I can automatically set these to the currently activated virtualenv?
| [
"Use the VIRTUAL_ENV environment variable:\nsetup.cfg\n[directories]\nbasedirlist = ${VIRTUAL_ENV}\n\nmake.osx\nPREFIX=${VIRTUAL_ENV}\n\n"
] | [
1
] | [] | [] | [
"makefile",
"python",
"setuptools",
"virtualenv"
] | stackoverflow_0003709898_makefile_python_setuptools_virtualenv.txt |
Q:
How to use importlib for rewriting bytecode?
I'm looking for a way to use importlib in Python 2.x to rewrite bytecode of imported modules on-the-fly. In other words, I need to hook my own function between the compilation and execution step during import. Besides that I want the import function to work just as the built-in one.
I've already did that with imputil, but that library doesn't cover all cases and is deprecated anyway.
A:
Having had a look through the importlib source code, I believe you could subclass PyLoader in the _bootstrap module and override get_code:
class PyLoader:
...
def get_code(self, fullname):
"""Get a code object from source."""
source_path = self.source_path(fullname)
if source_path is None:
message = "a source path must exist to load {0}".format(fullname)
raise ImportError(message)
source = self.get_data(source_path)
# Convert to universal newlines.
line_endings = b'\n'
for index, c in enumerate(source):
if c == ord(b'\n'):
break
elif c == ord(b'\r'):
line_endings = b'\r'
try:
if source[index+1] == ord(b'\n'):
line_endings += b'\n'
except IndexError:
pass
break
if line_endings != b'\n':
source = source.replace(line_endings, b'\n')
# modified here
code = compile(source, source_path, 'exec', dont_inherit=True)
return rewrite_code(code)
I assume you know what you're doing, but on behalf of programmers everywhere I believe I should say: ugh =p
| How to use importlib for rewriting bytecode? | I'm looking for a way to use importlib in Python 2.x to rewrite bytecode of imported modules on-the-fly. In other words, I need to hook my own function between the compilation and execution step during import. Besides that I want the import function to work just as the built-in one.
I've already did that with imputil, but that library doesn't cover all cases and is deprecated anyway.
| [
"Having had a look through the importlib source code, I believe you could subclass PyLoader in the _bootstrap module and override get_code:\nclass PyLoader:\n ...\n\n def get_code(self, fullname):\n \"\"\"Get a code object from source.\"\"\"\n source_path = self.source_path(fullname)\n if source_path... | [
2
] | [] | [] | [
"bytecode_manipulation",
"import",
"python"
] | stackoverflow_0003769336_bytecode_manipulation_import_python.txt |
Q:
Organizing and building a numpy array for a dynamic equation input
I'm not sure if my post question makes lots of sense; however, I'm building an input array for a class/function that takes in a lot of user inputed data and outputs a numpy array.
# I'm trying to build an input array that should include following information:
'''
* zone_id - id from db - int
* model size - int
* type of analysis - one of the following:
* type 1 - int or string
* type 2 - int or string
* type 3 - int or string
* model purposes:
* default: ONE, TWO, THREE #this is just a title of the purpose
* Custom: default + others (anywhere from 0 to 15 purposes)
* Modeling step 1: some socio economic factors #produces results 1
* Modeling step 2:
* Default: equation coefficients for retail/non retail
* Custom: equation coefficients for each extra activities as defined by
the user
* produces results 2
Example array:
def_array = (zone_id, model_size, analysis_type,
model_purpose[],
socio_economics[],
socio_coefficients[] )
'''
# Numerical example:
my_arr = [np.array([ 10001, 1, 2,
[ 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE' ],
[ {'retail':500, 'non_retail':300, 'school':300', 'other':900} ],
[ {'retail':500, 'non_retail':300, 'school':300', 'other':900} ],
[ {'ONE':{'retail':.5, 'non_retail':1.7, 'school':.4', 'other':4.7},
{'TWO':{'retail':.2, 'non_retail':2.5, 'school':.5', 'other':4.3},
{'THREE':{'retail':.3, 'non_retail':2.3, 'school':.6', 'other':2.2},
{'FOUR':{'retail':.4, 'non_retail':1.1, 'school':.7', 'other':1.0},
{'FIVE':{'retail':7, 'non_retail':2, 'school':3', 'other':1} ] ])
# this array will be inserted into 3 functions and together should return the following array:
arr_results = [np.array([ 10001, one_1, TWO_1, THREE_1, FOUR_1, FIVE_1, ONE_2, TWO_2, THREE_2, FOUR_2, FIVE_2],
[10002, .... ,] ])
What are/is my best option(s) in defining the input array(s)?
A:
Numpy arrays are the wrong datatype here: they are designed for numeric manipulations of large amounts of similar data (e.g. large matrices). It looks like you could just use a dict:
options = {
"zone_id": 10001,
"model_size": 1,
"analysis_type": 2,
"model_purposes": [ "ONE", ... ]
...
}
You could then pass this on to a function, either as the dictionary or by unpacking it into names arguments using **:
def do_stuff(zone_id=10001, model_size=1, ...):
...
do_stuff(**options)
If you want a more complicated options datatype (e.g. if some of the options need to be calculated on the fly or depend on others), you could use a specialised Options class (though be warned, this is almost certainly overkill);
class Options:
def __init__(self):
# set some default values
self.zone_id = 10001
def populate_values(self):
# maybe handle some user input?
self.name = input("name: ")
# use a property to calculate model_size on the fly
@property
def model_size(self):
return 2-1
and then
options = Options()
options.populate_values()
print(options.model_size)
| Organizing and building a numpy array for a dynamic equation input | I'm not sure if my post question makes lots of sense; however, I'm building an input array for a class/function that takes in a lot of user inputed data and outputs a numpy array.
# I'm trying to build an input array that should include following information:
'''
* zone_id - id from db - int
* model size - int
* type of analysis - one of the following:
* type 1 - int or string
* type 2 - int or string
* type 3 - int or string
* model purposes:
* default: ONE, TWO, THREE #this is just a title of the purpose
* Custom: default + others (anywhere from 0 to 15 purposes)
* Modeling step 1: some socio economic factors #produces results 1
* Modeling step 2:
* Default: equation coefficients for retail/non retail
* Custom: equation coefficients for each extra activities as defined by
the user
* produces results 2
Example array:
def_array = (zone_id, model_size, analysis_type,
model_purpose[],
socio_economics[],
socio_coefficients[] )
'''
# Numerical example:
my_arr = [np.array([ 10001, 1, 2,
[ 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE' ],
[ {'retail':500, 'non_retail':300, 'school':300', 'other':900} ],
[ {'retail':500, 'non_retail':300, 'school':300', 'other':900} ],
[ {'ONE':{'retail':.5, 'non_retail':1.7, 'school':.4', 'other':4.7},
{'TWO':{'retail':.2, 'non_retail':2.5, 'school':.5', 'other':4.3},
{'THREE':{'retail':.3, 'non_retail':2.3, 'school':.6', 'other':2.2},
{'FOUR':{'retail':.4, 'non_retail':1.1, 'school':.7', 'other':1.0},
{'FIVE':{'retail':7, 'non_retail':2, 'school':3', 'other':1} ] ])
# this array will be inserted into 3 functions and together should return the following array:
arr_results = [np.array([ 10001, one_1, TWO_1, THREE_1, FOUR_1, FIVE_1, ONE_2, TWO_2, THREE_2, FOUR_2, FIVE_2],
[10002, .... ,] ])
What are/is my best option(s) in defining the input array(s)?
| [
"Numpy arrays are the wrong datatype here: they are designed for numeric manipulations of large amounts of similar data (e.g. large matrices). It looks like you could just use a dict:\noptions = {\n \"zone_id\": 10001,\n \"model_size\": 1,\n \"analysis_type\": 2,\n \"model_purposes\": [ \"ONE\", ... ]\n... | [
3
] | [] | [] | [
"arrays",
"numpy",
"python",
"scipy"
] | stackoverflow_0003769386_arrays_numpy_python_scipy.txt |
Q:
Problematic Class
Im trying to create a class called Record, though when I try to use it, something goes wrong. Im sure im overlooking something simple. Does anyone mind taking a look?
class Record:
def __init__(self, model):
self.model= model
self.doc_date = []
self.doc_pn = []
print("Record %s has been added.\n") % self
def add_doc_date(self, declaration_date):
self.doc_date.append(declaration_date)
def add_doc_pn(self, declaration_pn):
self.doc_pn.append(declaration_pn)
def __str__(self):
res = "Name: " + self.model + "\n"
res = res + "Standard Part Numbers:" + str(self.std_pn) + "\n"
res = res + "Declaration Part Numbers" + str(self.doc_pn) + "\n"
return res
A:
res = res + "Standard Part Numbers:" + str(self.std_pn) + "\n"
I don't see self.std_pn defined anywhere.
A:
class Record:
def __init__(self, model):
self.model= model
self.doc_date = []
self.doc_pn = []
self.std_pn = []
print("Record %s has been added.\n") % self
def add_doc_date(self, declaration_date):
self.doc_date.append(declaration_date)
def add_doc_pn(self, declaration_pn):
self.doc_pn.append(declaration_pn)
def __str__(self):
res = "Name: " + self.model + "\n"
res = res + "Doc Date:" + str(self.doc_date) + "\n"
res = res + "Standard Part Numbers:" + str(self.std_pn) + "\n"
res = res + "Declaration Part Numbers" + str(self.doc_pn) + "\n"
return res
>>> t=Record("rec1")
Record Name: rec1
Doc Date:[]
Standard Part Numbers:[]
Declaration Part Numbers[]
has been added.
>>> t.add_doc_date("2010-10-10")
>>> t.add_doc_pn("30")
>>> print t
Name: rec1
Doc Date:['2010-10-10']
Standard Part Numbers:[]
Declaration Part Numbers['30']
>>>
| Problematic Class | Im trying to create a class called Record, though when I try to use it, something goes wrong. Im sure im overlooking something simple. Does anyone mind taking a look?
class Record:
def __init__(self, model):
self.model= model
self.doc_date = []
self.doc_pn = []
print("Record %s has been added.\n") % self
def add_doc_date(self, declaration_date):
self.doc_date.append(declaration_date)
def add_doc_pn(self, declaration_pn):
self.doc_pn.append(declaration_pn)
def __str__(self):
res = "Name: " + self.model + "\n"
res = res + "Standard Part Numbers:" + str(self.std_pn) + "\n"
res = res + "Declaration Part Numbers" + str(self.doc_pn) + "\n"
return res
| [
"res = res + \"Standard Part Numbers:\" + str(self.std_pn) + \"\\n\"\n\nI don't see self.std_pn defined anywhere.\n",
"class Record:\n def __init__(self, model):\n self.model= model\n self.doc_date = []\n self.doc_pn = []\n self.std_pn = []\n print(\"Record %s has been ... | [
6,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0003769284_class_python.txt |
Q:
Using PSI Filter objects from Python
I'm working with SharePoint and ProjectServer 2007 via PSI with Python.
I can't find any documentation on how Filter Class (Microsoft.Office.Project.Server.Library) objects work internally to emulate its behaviour in Python.
Any ideas?
A:
Take a look at Colby Africa's blog post. Also, msdn docs are here.
Edit
The generated filter is just XML. Here is a filter that returns the data from the "LookupTables" table (list of all the lookup tables):
<?xml version="1.0" encoding="utf-16"?>
<Filter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" filterTableName="LookupTables" xmlns="http://microsoft.com/ProjectServer/FilterSchema.xsd">
<Fields>
<Field tableName="" fieldName="LT_UID" />
<Field tableName="" fieldName="LT_NAME" />
<Field tableName="" fieldName="LT_SORT_ORDER_ENUM" />
<Field tableName="" fieldName="LT_PRIMARY_LCID" />
<Field tableName="" fieldName="LT_FILL_ALL_LEVELS" />
<Field tableName="" fieldName="LT_CHECKOUTBY" />
<Field tableName="" fieldName="LT_CHECKOUTDATE" />
<Field tableName="" fieldName="MOD_DATE" />
</Fields>
<Criteria />
</Filter>
Here is another example of the filters required for getting all the data for one table...
Step 1: Get the row for the LookupTable (general table info)
<?xml version="1.0" encoding="utf-16"?>
<Filter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" filterTableName="LookupTables" xmlns="http://microsoft.com/ProjectServer/FilterSchema.xsd">
<Fields>
<Field tableName="" fieldName="LT_UID" />
<Field tableName="" fieldName="LT_NAME" />
<Field tableName="" fieldName="LT_SORT_ORDER_ENUM" />
<Field tableName="" fieldName="LT_PRIMARY_LCID" />
<Field tableName="" fieldName="LT_FILL_ALL_LEVELS" />
<Field tableName="" fieldName="LT_CHECKOUTBY" />
<Field tableName="" fieldName="LT_CHECKOUTDATE" />
<Field tableName="" fieldName="MOD_DATE" />
</Fields>
<Criteria>
<FieldOperator fieldOperationType="Equal">
<Field fieldName="LT_UID" />
<Operand xmlns:q1="http://microsoft.com/wsdl/types/" xsi:type="q1:guid">20870732-12b6-48e2-acf4-94d934dfc27a</Operand>
</FieldOperator>
</Criteria>
</Filter>
Step 2: Get all the data from the LookupTableStructures table (hierarchy info)
<?xml version="1.0" encoding="utf-16"?>
<Filter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" filterTableName="LookupTableStructures" xmlns="http://microsoft.com/ProjectServer/FilterSchema.xsd">
<Fields>
<Field tableName="" fieldName="LT_STRUCT_UID" />
<Field tableName="" fieldName="LT_UID" />
<Field tableName="" fieldName="LT_PARENT_STRUCT_UID" />
<Field tableName="" fieldName="LT_STRUCT_COOKIE" />
</Fields>
<Criteria>
<FieldOperator fieldOperationType="Equal">
<Field fieldName="LT_UID" />
<Operand xmlns:q1="http://microsoft.com/wsdl/types/" xsi:type="q1:guid">20870732-12b6-48e2-acf4-94d934dfc27a</Operand>
</FieldOperator>
</Criteria>
</Filter>
Step 3: Get all of the values in this lookup table
<?xml version="1.0" encoding="utf-16"?>
<Filter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" filterTableName="LookupTableValues" xmlns="http://microsoft.com/ProjectServer/FilterSchema.xsd">
<Fields>
<Field tableName="" fieldName="LT_STRUCT_UID" />
<Field tableName="" fieldName="LCID" />
<Field tableName="" fieldName="LT_UID" />
<Field tableName="" fieldName="LT_VALUE_DUR" />
<Field tableName="" fieldName="LT_VALUE_NUM" />
<Field tableName="" fieldName="LT_VALUE_DUR_FMT" />
<Field tableName="" fieldName="LT_VALUE_DATE" />
<Field tableName="" fieldName="LT_VALUE_TEXT" />
<Field tableName="" fieldName="LT_VALUE_PHONETIC" />
<Field tableName="" fieldName="LT_VALUE_FULL" />
<Field tableName="" fieldName="LT_VALUE_DESC" />
<Field tableName="" fieldName="LT_VALUE_SORT_INDEX" />
<Field tableName="" fieldName="LT_VALUE_LOCALIZED_COOKIE" />
</Fields>
<Criteria>
<FieldOperator fieldOperationType="Equal">
<Field fieldName="LT_UID" />
<Operand xmlns:q1="http://microsoft.com/wsdl/types/" xsi:type="q1:guid">20870732-12b6-48e2-acf4-94d934dfc27a</Operand>
</FieldOperator>
</Criteria>
</Filter>
It requires three separate filters to get all this data because it is split across three separate tables. In C#, I am calling the ReadLookupTablesMultiLang function with each of these filters and then merging the returned datatables.
| Using PSI Filter objects from Python | I'm working with SharePoint and ProjectServer 2007 via PSI with Python.
I can't find any documentation on how Filter Class (Microsoft.Office.Project.Server.Library) objects work internally to emulate its behaviour in Python.
Any ideas?
| [
"Take a look at Colby Africa's blog post. Also, msdn docs are here.\nEdit\nThe generated filter is just XML. Here is a filter that returns the data from the \"LookupTables\" table (list of all the lookup tables):\n<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<Filter xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-inst... | [
0
] | [] | [] | [
"project_server",
"psi",
"python"
] | stackoverflow_0003769320_project_server_psi_python.txt |
Q:
Why do exceptions/errors evaluate to True in python?
In several places I have to retrieve some value from a dict, but need to check if the key for that value exists, and if it doesn't I use some default value :
if self.data and self.data.has_key('key'):
value = self.data['key']
else:
value = self.default
....
One thing I like about python, is that and/or boolean operators return one of their operands. I'm not sure, but if exceptions evaluated to false, the above code could be rewriten as follows:
value = self.data['key'] or self.default
I think its intuitive that errors should evaluate to false(like in bash programming). Is there any special reason for python treating exceptions as true?
EDIT:
I just want to show my point of view on the 'exception handling' subject. From wikipedia:
"
From the point of view of the author of a routine, raising an exception is a useful way to signal that a routine could not execute normally. For example, when an input argument is invalid (e.g. a zero denominator in division) or when a resource it relies on is unavailable (like a missing file, or a hard disk error). In systems without exceptions, routines would need to return some special error code. However, this is sometimes complicated by the semipredicate problem, in which users of the routine need to write extra code to distinguish normal return values from erroneous ones.
"
As I said, raising exceptions are just a fancy way of returning from a function. 'Exception objects' are just a pointer to a data structure that contains information about the error and how that is handled on high level languages depend only on the implementation of the VM. I decided to look at how python 2.6.6 deals with exceptions by looking at output from the 'dis' module:
>>> import dis
>>> def raise_exception():
... raise Exception('some error')
...
>>> dis.dis(raise_exception)
2 0 LOAD_GLOBAL 0 (Exception)
3 LOAD_CONST 1 ('some error')
6 CALL_FUNCTION 1
9 RAISE_VARARGS 1
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
Its clear that python has the exception concept at bytecode level, but even if it didnt, it could still make exception handling constructs behave like they do. Take the following function:
def raise_exception():
... return Exception('some error')
...
>>> dis.dis(raise_exception)
2 0 LOAD_GLOBAL 0 (Exception)
3 LOAD_CONST 1 ('some error')
6 CALL_FUNCTION 1
9 RETURN_VALUE
Both functions create the exception object in the same way as show in 0, 3 and 6. The difference is that the first call the RAISE_VARARGS instruction on the object(and stills returns None) and the second will just return the exception object to calling code. Now take the following bytecode(I'm not sure if this is correct) :
0 LOAD_GLOBAL (isinstance) #Loads the function 'isinstance'
3 LOAD_GLOBAL (raise_exception) #loads the function 'raise_exception'
6 CALL_FUNCTION #call the function raise_exception(which will push an Exception instance to the stack
9 LOAD_GLOBAL (Exception) #load the Exception class
12 CALL_FUNCTION #call the 'isinstance function'(which will push 'True to the stack)
15 JUMP_IF_TRUE (to 27) #Will jump to instruction 33 if the object at the top of stack evaluates to true
18 LOAD_CONS ('No exceptions were raised')
21 PRINT_ITEM
24 PRINT_NEWLINE
27 LOAD_CONS ('Exception caught!')
21 PRINT_ITEM
24 PRINT_NEWLINE
The above translates to something equivalent to this:
if isinstance(raise_exception(), Exception):
print 'Exception caught!'
else:
print 'No exceptions were raised'
However, the compiler could generate something like the above instructions when it finds a try block. With this implementation someone could either test a block for an exception or treat functions that return an exception as a 'False' value.
A:
You are misunderstanding the use of exceptions. An exception is something gone wrong. It's not just a return value, and it shouldn't be treated as such.
Explicit is better than implicit.
Because an exception is raised when something goes wrong, you must explicitly write code to catch them. That's deliberate -- you shouldn't be able to ignore exceptions as merely False, because they're more than that.
If you swallowed exceptions as you seem to suggest, you wouldn't be able to tell when code went wrong. What would happen if you referenced an unbound variable? That should give you a NameError, but it would give you... False?!
Consider your code block:
value = self.data['key'] or self.default
You want self.data['key'] to return False if key is not a key of self.data. Do you see any problems with this approach? What if self.data == {'key': False}? You couldn't distinguish between the case of False being stored in the dictionary and False being returned because of a missing key.
Further, if this were changed more generally, so that all exceptions were swallowed (!), how would you distinguish between a KeyError ('key' not in self.data) and say a NameError (self.data not defined)? Both would evaluate to False.
Explicitly writing code to catch the exception solves this problem, because you can catch exactly those exception that you want:
try:
value = self.data['key']
except KeyError:
value = self.default
There is a data structure already written that does this for you, though, because default dictionaries are very commonly needed. It's in collections:
>>> import collections
>>> data = collections.defaultdict(lambda: False)
>>> data['foo'] = True
>>> data['foo']
True
>>> data['bar']
False
A:
Why do exceptions/errors evaluate to True in python?
Instances of Exception evaluate to True (EDIT See @THC4k's comment below. Quite relevant information). That doesn't prevent them from being thrown.
I'm not sure, but if exceptions evaluated to false
In your context it wouldn't suffice that Exceptions evaluate to False. They should also not get thrown and be propagated down the call stack. Rather, they will have to be "stopped" on the spot and then evaluate to False.
I'll leave it to more experienced Pythonistas to comment on why Exceptions do not (or should not) get "stopped" and evaluate to True or False. I'd guess that this is because they are expected to be thrown and propagated. In fact they would cease to be "exceptions" if they were to be stopped and interrogated =P.
but need to check if the key for that value exists, and if it doesn't I use some default value
I can think of two options two ways to get a default value in the absence of a key in a dictionary. One is to use defaultdict. The other is to use the get method.
>>> from collections import defaultdict
>>> d = defaultdict(lambda: "default")
>>> d['key']
'default'
>>> d = dict()
>>> d.get('key', 'default')
'default'
>>>
PS: if key in dict is preferred to dict.has_key(key). In fact has_key() has been removed in Python 3.0.
A:
You can use get:
value = self.data.get('key', self.default)
Update: You are misinterpreting the or keyword there. The self.default value is only used if self.data['key'] evaluates to False, not if 'key' does not exist in self.data. If self.data contains no 'key', an exception is still raised.
In the expression:
self.data['key'] or self.default
the Python interpreter will evaluate self.data['key'] first, then check whether it evaluates to True. If it is True, then it is the result of the entire expression. If it is false, self.default is the result of the expression. However, in evaluating self.data['key'], 'key' is not in self.data, then an exception is raised, and the evaluation of the entire expression is aborted, and indeed the containing block until a matching except block is found somewhere along the stack. The assignment is also not executed in case an exception is raised, and value remains at whatever initial value it had.
A:
You had
if self.data and self.data.has_key('key'):
value = self.data['key']
else:
value = self.default
This is the same:
if self.data.has_key('key'): # if it has the key, it's not empty anyways
value = self.data['key']
else:
value = self.default
Now we write it nicer:
if 'key' in self.data: # `in` does just what you expect
value = self.data['key']
else:
value = self.default
It's easy to transform this into a inline if:
value = (self.data['key'] if 'key' in self.data else self.default)
In this case it is simply:
value = self.data.get('key', self.default)
But not if you want to do something like this:
value = (self.data['key'] if 'key' in self.data else self.get_default('key'))
This is different from this
value = self.data.get('key', self.get_default('key'))
because self.get_default('key') will be called unconditionally (before the call to get)!
A:
To answer what you are trying to do, rather than your problem with exceptions, if self.datawas a defaultdictwith a default value of Nonethen if the key wasn't found it would return Nonewhich would evaluate as Falseand then you would get self.defaultas desired.
Note that this would cause problems if the value found in self.datawas 0, False, None or any other value that evaluates as False. If these values might be in there then I think you will have to go with katrielalex's try/except answer.
| Why do exceptions/errors evaluate to True in python? | In several places I have to retrieve some value from a dict, but need to check if the key for that value exists, and if it doesn't I use some default value :
if self.data and self.data.has_key('key'):
value = self.data['key']
else:
value = self.default
....
One thing I like about python, is that and/or boolean operators return one of their operands. I'm not sure, but if exceptions evaluated to false, the above code could be rewriten as follows:
value = self.data['key'] or self.default
I think its intuitive that errors should evaluate to false(like in bash programming). Is there any special reason for python treating exceptions as true?
EDIT:
I just want to show my point of view on the 'exception handling' subject. From wikipedia:
"
From the point of view of the author of a routine, raising an exception is a useful way to signal that a routine could not execute normally. For example, when an input argument is invalid (e.g. a zero denominator in division) or when a resource it relies on is unavailable (like a missing file, or a hard disk error). In systems without exceptions, routines would need to return some special error code. However, this is sometimes complicated by the semipredicate problem, in which users of the routine need to write extra code to distinguish normal return values from erroneous ones.
"
As I said, raising exceptions are just a fancy way of returning from a function. 'Exception objects' are just a pointer to a data structure that contains information about the error and how that is handled on high level languages depend only on the implementation of the VM. I decided to look at how python 2.6.6 deals with exceptions by looking at output from the 'dis' module:
>>> import dis
>>> def raise_exception():
... raise Exception('some error')
...
>>> dis.dis(raise_exception)
2 0 LOAD_GLOBAL 0 (Exception)
3 LOAD_CONST 1 ('some error')
6 CALL_FUNCTION 1
9 RAISE_VARARGS 1
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
Its clear that python has the exception concept at bytecode level, but even if it didnt, it could still make exception handling constructs behave like they do. Take the following function:
def raise_exception():
... return Exception('some error')
...
>>> dis.dis(raise_exception)
2 0 LOAD_GLOBAL 0 (Exception)
3 LOAD_CONST 1 ('some error')
6 CALL_FUNCTION 1
9 RETURN_VALUE
Both functions create the exception object in the same way as show in 0, 3 and 6. The difference is that the first call the RAISE_VARARGS instruction on the object(and stills returns None) and the second will just return the exception object to calling code. Now take the following bytecode(I'm not sure if this is correct) :
0 LOAD_GLOBAL (isinstance) #Loads the function 'isinstance'
3 LOAD_GLOBAL (raise_exception) #loads the function 'raise_exception'
6 CALL_FUNCTION #call the function raise_exception(which will push an Exception instance to the stack
9 LOAD_GLOBAL (Exception) #load the Exception class
12 CALL_FUNCTION #call the 'isinstance function'(which will push 'True to the stack)
15 JUMP_IF_TRUE (to 27) #Will jump to instruction 33 if the object at the top of stack evaluates to true
18 LOAD_CONS ('No exceptions were raised')
21 PRINT_ITEM
24 PRINT_NEWLINE
27 LOAD_CONS ('Exception caught!')
21 PRINT_ITEM
24 PRINT_NEWLINE
The above translates to something equivalent to this:
if isinstance(raise_exception(), Exception):
print 'Exception caught!'
else:
print 'No exceptions were raised'
However, the compiler could generate something like the above instructions when it finds a try block. With this implementation someone could either test a block for an exception or treat functions that return an exception as a 'False' value.
| [
"You are misunderstanding the use of exceptions. An exception is something gone wrong. It's not just a return value, and it shouldn't be treated as such.\n\nExplicit is better than implicit.\n\nBecause an exception is raised when something goes wrong, you must explicitly write code to catch them. That's deliberate ... | [
9,
5,
3,
2,
0
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0003768438_exception_handling_python.txt |
Q:
Using Drupal 7 or developing a new system: What's better for a website relaunch with a community of 15.000 users?
I have to make a decision for our (eXma german) community webpage. We will relauching it with a new system.
There are two sites:
The first is to develop a whole new system on e.g. Django and Python.
The second is to use the new Drupal 7.
Personally I have a lot more experiences with Drupal 6 and now since I'm testing Drupal 7 on my local system, I think it's a very good system with a very good API to build a growing community page with some custom module developments.
But the other side thinks it will be better to develop a whole new system based on Django / Python (because PHP is a bad language in their mind... but I think it's never mind) because Drupal does not scale as good as a system with python (but we have only 15000 users at the moment...) and a own system is better to manage because we know the code.
Can you help me to make a good decision? I prefere Drupal 7 with some own modules, we will develop. Because Drupal has a solid core of the central modules we will need for our community.
A:
Drupal can be used as a very solid base upon which to build your site. It's well tested, has a variety of ready to use modules, and it is successfully used for busy sites.
It does have a relatively steep learning curve, but the documentation and community are excellent. However you mention you do have experience with Drupal 6, so the learning curve may not be that steep for you.
On the other hand, if you feel confident about it (and even not, it will be a great learning experience), developing it from scratch yourself will definitely be more comfortable when maintaining and understanding how it works. You will be, however, rediscovering the wheel in many occasions.
A:
Go with what you feel comfortable with and what you feel nicer to maintain / extend.
I'd choose Python for perfomance reasons (comparing to PHP), although proper system with opcode cache can speed things up a lot.
| Using Drupal 7 or developing a new system: What's better for a website relaunch with a community of 15.000 users? | I have to make a decision for our (eXma german) community webpage. We will relauching it with a new system.
There are two sites:
The first is to develop a whole new system on e.g. Django and Python.
The second is to use the new Drupal 7.
Personally I have a lot more experiences with Drupal 6 and now since I'm testing Drupal 7 on my local system, I think it's a very good system with a very good API to build a growing community page with some custom module developments.
But the other side thinks it will be better to develop a whole new system based on Django / Python (because PHP is a bad language in their mind... but I think it's never mind) because Drupal does not scale as good as a system with python (but we have only 15000 users at the moment...) and a own system is better to manage because we know the code.
Can you help me to make a good decision? I prefere Drupal 7 with some own modules, we will develop. Because Drupal has a solid core of the central modules we will need for our community.
| [
"Drupal can be used as a very solid base upon which to build your site. It's well tested, has a variety of ready to use modules, and it is successfully used for busy sites. \nIt does have a relatively steep learning curve, but the documentation and community are excellent. However you mention you do have experience... | [
3,
1
] | [] | [] | [
"django",
"drupal",
"php",
"python",
"webpage"
] | stackoverflow_0003770067_django_drupal_php_python_webpage.txt |
Q:
Python function to solve Ax = b by back substitution
Okay, for my numerical methods class I have the following question:
Write a Python function to solve Ax = b by back substitution, where A is an upper triangular nonsingular matrix. MATLAB code for this is on page 190 which you can use as a pseudocode guide if you wish. The function should take as input A and b and return x. Your function need not check that A is nonsingular. That is, assume that only nonsingular A will be passed to your function.
The MATLAB code that it refers to is:
x(n) = c(u)/U(n,n)
for i = n-1 : -1 : 1
x(i) = c(i);
for j = i+1 : n
x(i) = x(i) - U(i,j)*x(j);
end
x(i) = x(i)/U(i,i);
end
My Python code, which I wrote using the MATLAB code snippet, is with an upper triangular test matrix(not sure if its nonsingular! How do I test for singularity?):
from scipy import mat
c=[3,2,1]
U=([[6,5,1],[0,1,7],[0,0,2]])
a=0
x=[]
while a<3:
x.append(1)
a=a+1
n=3
i=n-1
x[n-1]=c[n-1]/U[n-1][n-1]
while i>1:
x[i]=c[i]
j=i+1
while j<n-1:
x[i]=x[i]-U[i][j]*x[j];
x[i]=x[i]/U[i][i]
i=i-1
print mat(x)
The answer I am getting is [[1 1 0]] for x. I not sure if I am doing this correctly. I assume it is wrong and can't figure out what to do next. Any clues?
A:
j=i+1
while j<n-1:
x[i]=x[i]-U[i][j]*x[j];
is infinite ... and never gets executed
your indexing is fubared:
for i in range(n-2,-1,-1):
....
for j in range(i+1,n):
notice, range is half open unlike matlab
A:
One problem I see is that your input consists of integers, which means that Python is going to do integer division on them, which will turn 3/4 into 0 when what you want is floating point division. You can tell python to do floating point division by default by adding
from __future__ import division
To the top of your code. From the use of scipy, I'm assuming you're using Python 2.x here.
A:
You ask how to test for singularity of an upper triangular matrix?
Please don't compute the determinant!
Simply look at the diagonal elements. Which ones are zero? Are any zero?
How about effective numerical singularity? Compare the smallest absolute value to the largest in absolute value. If that ratio is smaller than something on the order of eps, it is effectively singular.
| Python function to solve Ax = b by back substitution | Okay, for my numerical methods class I have the following question:
Write a Python function to solve Ax = b by back substitution, where A is an upper triangular nonsingular matrix. MATLAB code for this is on page 190 which you can use as a pseudocode guide if you wish. The function should take as input A and b and return x. Your function need not check that A is nonsingular. That is, assume that only nonsingular A will be passed to your function.
The MATLAB code that it refers to is:
x(n) = c(u)/U(n,n)
for i = n-1 : -1 : 1
x(i) = c(i);
for j = i+1 : n
x(i) = x(i) - U(i,j)*x(j);
end
x(i) = x(i)/U(i,i);
end
My Python code, which I wrote using the MATLAB code snippet, is with an upper triangular test matrix(not sure if its nonsingular! How do I test for singularity?):
from scipy import mat
c=[3,2,1]
U=([[6,5,1],[0,1,7],[0,0,2]])
a=0
x=[]
while a<3:
x.append(1)
a=a+1
n=3
i=n-1
x[n-1]=c[n-1]/U[n-1][n-1]
while i>1:
x[i]=c[i]
j=i+1
while j<n-1:
x[i]=x[i]-U[i][j]*x[j];
x[i]=x[i]/U[i][i]
i=i-1
print mat(x)
The answer I am getting is [[1 1 0]] for x. I not sure if I am doing this correctly. I assume it is wrong and can't figure out what to do next. Any clues?
| [
"j=i+1\nwhile j<n-1:\n x[i]=x[i]-U[i][j]*x[j];\n\nis infinite ... and never gets executed\nyour indexing is fubared:\nfor i in range(n-2,-1,-1):\n....\n for j in range(i+1,n):\n\nnotice, range is half open unlike matlab\n",
"One problem I see is that your input consists of integers, which means that Python ... | [
2,
2,
1
] | [] | [] | [
"matlab",
"matrix",
"python"
] | stackoverflow_0003766700_matlab_matrix_python.txt |
Q:
signal.alarm function with resolution greater than 1 second?
I'm trying to build a python timeout exception that runs in milliseconds.
The python signal.alarm function has a 1 second resolution.
How would one get an equivalent function that requests a SIGALRM signal to a given process in, say milliseconds, as opposed to seconds?
I've found no simple solutions as of yet.
Thanks in advance for your input.
A:
Use signal.setitimer() instead.
| signal.alarm function with resolution greater than 1 second? | I'm trying to build a python timeout exception that runs in milliseconds.
The python signal.alarm function has a 1 second resolution.
How would one get an equivalent function that requests a SIGALRM signal to a given process in, say milliseconds, as opposed to seconds?
I've found no simple solutions as of yet.
Thanks in advance for your input.
| [
"Use signal.setitimer() instead.\n"
] | [
16
] | [] | [] | [
"alarm",
"python",
"signals"
] | stackoverflow_0003770711_alarm_python_signals.txt |
Q:
Django subquery using QuerySet
Is it possible to perform a subquery on a QuerySet using another QuerySet?
For example:
q = Something.objects.filter(x=y).extra(where=query_set2)
A:
Short answer: No. The extra method doesn't expect querysets to be passed in.
If you think about it a bit, it makes sense. Querysets are an abstraction used to represent the results of a fetch operation on the database and extra is a convenient way of attaching custom fields from the database to a queryset. Unless you change the fundamental nature of extra to mean "custom filtering with another queryset" this will not work.
A:
I may understand your question in two ways.
You can specify multiple variables
in your filter parameters, for
example :
q = Something.objects.filter(x=y, w=z)
You want to make what is called a "join" in SQL. This can be done via the aggregation system of Django, see the official Django Official Documentation.
| Django subquery using QuerySet | Is it possible to perform a subquery on a QuerySet using another QuerySet?
For example:
q = Something.objects.filter(x=y).extra(where=query_set2)
| [
"Short answer: No. The extra method doesn't expect querysets to be passed in. \nIf you think about it a bit, it makes sense. Querysets are an abstraction used to represent the results of a fetch operation on the database and extra is a convenient way of attaching custom fields from the database to a queryset. Unles... | [
6,
2
] | [] | [] | [
"database",
"django",
"orm",
"python"
] | stackoverflow_0003769367_database_django_orm_python.txt |
Q:
How to serve data from UDP stream over HTTP in Python?
I am currently working on exposing data from legacy system over the web. I have a (legacy) server application that sends and receives data over UDP. The software uses UDP to send sequential updates to a given set of variables in (near) real-time (updates every 5-10 ms). thus, I do not need to capture all UDP data -- it is sufficient that the latest update is retrieved.
In order to expose this data over the web, I am considering building a lightweight web server that reads/write UDP data and exposes this data over HTTP.
As I am experienced with Python, I am considering to use it.
The question is the following: how can I (continuously) read data from UDP and send snapshots of it over TCP/HTTP on-demand with Python? So basically, I am trying to build a kind of "UDP2HTTP" adapter to interface with the legacy app so that I wouldn't need to touch the legacy code.
A solution that is WSGI compliant would be much preferred. Of course any tips are very welcome and MUCH appreciated!
A:
Twisted would be very suitable here. It supports many protocols (UDP, HTTP) and its asynchronous nature makes it possible to directly stream UDP data to HTTP without shooting yourself in the foot with (blocking) threading code. It also support wsgi.
A:
Here's a quick "proof of concept" app using the twisted framework. This assumes that the legacy UDP service is listening on localhost:8000 and will start sending UDP data in response to a datagram containing "Send me data". And that the data is 3 32bit integers. Additionally it will respond to an "HTTP GET /" on port 2080.
You could start this with twistd -noy example.py:
example.py
from twisted.internet import protocol, defer
from twisted.application import service
from twisted.python import log
from twisted.web import resource, server as webserver
import struct
class legacyProtocol(protocol.DatagramProtocol):
def startProtocol(self):
self.transport.connect(self.service.legacyHost,self.service.legacyPort)
self.sendMessage("Send me data")
def stopProtocol(self):
# Assume the transport is closed, do any tidying that you need to.
return
def datagramReceived(self,datagram,addr):
# Inspect the datagram payload, do sanity checking.
try:
val1, val2, val3 = struct.unpack("!iii",datagram)
except struct.error, err:
# Problem unpacking data log and ignore
log.err()
return
self.service.update_data(val1,val2,val3)
def sendMessage(self,message):
self.transport.write(message)
class legacyValues(resource.Resource):
def __init__(self,service):
resource.Resource.__init__(self)
self.service=service
self.putChild("",self)
def render_GET(self,request):
data = "\n".join(["<li>%s</li>" % x for x in self.service.get_data()])
return """<html><head><title>Legacy Data</title>
<body><h1>Data</h1><ul>
%s
</ul></body></html>""" % (data,)
class protocolGatewayService(service.Service):
def __init__(self,legacyHost,legacyPort):
self.legacyHost = legacyHost #
self.legacyPort = legacyPort
self.udpListeningPort = None
self.httpListeningPort = None
self.lproto = None
self.reactor = None
self.data = [1,2,3]
def startService(self):
# called by application handling
if not self.reactor:
from twisted.internet import reactor
self.reactor = reactor
self.reactor.callWhenRunning(self.startStuff)
def stopService(self):
# called by application handling
defers = []
if self.udpListeningPort:
defers.append(defer.maybeDeferred(self.udpListeningPort.loseConnection))
if self.httpListeningPort:
defers.append(defer.maybeDeferred(self.httpListeningPort.stopListening))
return defer.DeferredList(defers)
def startStuff(self):
# UDP legacy stuff
proto = legacyProtocol()
proto.service = self
self.udpListeningPort = self.reactor.listenUDP(0,proto)
# Website
factory = webserver.Site(legacyValues(self))
self.httpListeningPort = self.reactor.listenTCP(2080,factory)
def update_data(self,*args):
self.data[:] = args
def get_data(self):
return self.data
application = service.Application('LegacyGateway')
services = service.IServiceCollection(application)
s = protocolGatewayService('127.0.0.1',8000)
s.setServiceParent(services)
Afterthought
This isn't a WSGI design. The idea for this would to use be to run this program daemonized and have it's http port on a local IP and apache or similar to proxy requests. It could be refactored for WSGI. It was quicker to knock up this way, easier to debug.
A:
The software uses UDP to send sequential updates to a given set of variables in (near) real-time (updates every 5-10 ms). thus, I do not need to capture all UDP data -- it is sufficient that the latest update is retrieved
What you must do is this.
Step 1.
Build a Python app that collects the UDP data and caches it into a file. Create the file using XML, CSV or JSON notation.
This runs independently as some kind of daemon. This is your listener or collector.
Write the file to a directory from which it can be trivially downloaded by Apache or some other web server. Choose names and directory paths wisely and you're done.
Done.
If you want fancier results, you can do more. You don't need to, since you're already done.
Step 2.
Build a web application that allows someone to request this data being accumulated by the UDP listener or collector.
Use a web framework like Django for this. Write as little as possible. Django can serve flat files created by your listener.
You're done. Again.
Some folks think relational databases are important. If so, you can do this. Even though you're already done.
Step 3.
Modify your data collection to create a database that the Django ORM can query. This requires some learning and some adjusting to get a tidy, simple ORM model.
Then write your final Django application to serve the UDP data being collected by your listener and loaded into your Django database.
| How to serve data from UDP stream over HTTP in Python? | I am currently working on exposing data from legacy system over the web. I have a (legacy) server application that sends and receives data over UDP. The software uses UDP to send sequential updates to a given set of variables in (near) real-time (updates every 5-10 ms). thus, I do not need to capture all UDP data -- it is sufficient that the latest update is retrieved.
In order to expose this data over the web, I am considering building a lightweight web server that reads/write UDP data and exposes this data over HTTP.
As I am experienced with Python, I am considering to use it.
The question is the following: how can I (continuously) read data from UDP and send snapshots of it over TCP/HTTP on-demand with Python? So basically, I am trying to build a kind of "UDP2HTTP" adapter to interface with the legacy app so that I wouldn't need to touch the legacy code.
A solution that is WSGI compliant would be much preferred. Of course any tips are very welcome and MUCH appreciated!
| [
"Twisted would be very suitable here. It supports many protocols (UDP, HTTP) and its asynchronous nature makes it possible to directly stream UDP data to HTTP without shooting yourself in the foot with (blocking) threading code. It also support wsgi.\n",
"Here's a quick \"proof of concept\" app using the twisted ... | [
6,
6,
4
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0003768019_python_wsgi.txt |
Q:
Python os.walk + follow symlinks
How do I get this piece to follow symlinks in python 2.6?
def load_recursive(self, path):
for subdir, dirs, files in os.walk(path):
for file in files:
if file.endswith('.xml'):
file_path = os.path.join(subdir, file)
try:
do_stuff(file_path)
except:
continue
A:
Set followlinks to True. This is the fourth argument to the os.walk method, reproduced below:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
This option was added in Python 2.6.
EDIT 1
Be careful when using followlinks=True. According to the documentation:
Note: Be aware that setting followlinks to True can lead to
infinite recursion if a link points to a parent directory of itself.
walk() does not keep track of the directories it visited already.
| Python os.walk + follow symlinks | How do I get this piece to follow symlinks in python 2.6?
def load_recursive(self, path):
for subdir, dirs, files in os.walk(path):
for file in files:
if file.endswith('.xml'):
file_path = os.path.join(subdir, file)
try:
do_stuff(file_path)
except:
continue
| [
"Set followlinks to True. This is the fourth argument to the os.walk method, reproduced below:\nos.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])\n\nThis option was added in Python 2.6.\nEDIT 1\nBe careful when using followlinks=True. According to the documentation:\n\nNote: Be aware that setting fo... | [
64
] | [] | [] | [
"directory_traversal",
"python",
"symlink",
"symlink_traversal",
"traversal"
] | stackoverflow_0003771696_directory_traversal_python_symlink_symlink_traversal_traversal.txt |
Q:
PyQT QtGui.QTableWidgetItem
I have a QtGui.QTableWidgetItem that I added to a table by the createRow function below:
def createRow(self, listA):
rowNum = self.table.rowCount()
self.table.insertRow(rowNum)
i = 0
for val in listA:
self.table.setItem(rowNum, i, QtGui.QTableWidgetItem(val))
i += 1
Now I have a thread that will update the row values periodically. The function called by the thread is the following:
def updateRow(self, listB):
row = 0
numRows = self.table.rowCount()
i = 0
while i < numRows:
if listB[0] == self.table.item(i,0):
row = i
i+=1
j = 0
for val in listB:
self.table.setItem(row, j, QtGui.QTableWidgetItem(val))
j += 1
However, this is not working, because listB[0] is a string and self.table.item(i,0) is a QTableWidgetItem. Anyone know how I could solve this?
In the end, all I want is to update the row for the items that match the first item in the list this function takes as an input (listB).
A:
Use QTableWidgetItem.text(self) (i.e.: self.table.item(i,0).text()) to get the contents of a cell/QTableWidgetItem.
| PyQT QtGui.QTableWidgetItem | I have a QtGui.QTableWidgetItem that I added to a table by the createRow function below:
def createRow(self, listA):
rowNum = self.table.rowCount()
self.table.insertRow(rowNum)
i = 0
for val in listA:
self.table.setItem(rowNum, i, QtGui.QTableWidgetItem(val))
i += 1
Now I have a thread that will update the row values periodically. The function called by the thread is the following:
def updateRow(self, listB):
row = 0
numRows = self.table.rowCount()
i = 0
while i < numRows:
if listB[0] == self.table.item(i,0):
row = i
i+=1
j = 0
for val in listB:
self.table.setItem(row, j, QtGui.QTableWidgetItem(val))
j += 1
However, this is not working, because listB[0] is a string and self.table.item(i,0) is a QTableWidgetItem. Anyone know how I could solve this?
In the end, all I want is to update the row for the items that match the first item in the list this function takes as an input (listB).
| [
"Use QTableWidgetItem.text(self) (i.e.: self.table.item(i,0).text()) to get the contents of a cell/QTableWidgetItem.\n"
] | [
5
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0003771566_pyqt_python.txt |
Q:
Authentication on App Engine / Python / Django non-rel over JSON
I'm building a site on Google App Engine, running python and Django non-rel. Everything is working great for HTML and posting/reading data. But as I'm moving forward I'd like to do many of the updates with AJAX, and eventually also over mobile devices like Android and iPhone.
My pages use django non-rel and my login/logout authentication works great for the HTML. But update information sent over JSON would have to be authenticated that the user can make the changes. I see how doing authentication for just AJAX calls wouldn't be too difficult since your still hitting the website, but what about when throwing in mobile phone authentication?
So I'm new to this, where do I start?
How can I set up services on gae so I can do authenticated CRUD operations? Ideally I'd like to use the exact same REST services for ajax, android, etc.
A:
Python makes this pretty easy, you can just create a decorator method of checking the auth and add the decorator to any method requiring auth credentials.
def admin(handler_method):
"""
This decorator requires admin, 403 if not.
"""
def auth_required(self, *args, **kwargs):
if users.is_current_user_admin():
handler_method(self, *args, **kwargs)
else:
self.error(403)
return auth_required
...
@admin
def crudmethod_update(self, *args, **kwargs):
...
Mind you, this assumes a few things about how you are grabbing user data and such but the principal is the same with any setup. The notion you may be laboring under is that ajax calls are handled somehow differently on the server, but just like any restful method you are really getting the same headers. If you can check the authentication on the standard html request you can quite literally hijack the form submission with an ajax request and get the same result back. You may want to get JSON back instead or a smaller piece of HTML and for that you want to either:
Add something you can check in the request to know that it is an ajax request and adjust accordingly.
Implement an RPC Model for handling ajax requests specifically.
For actually handling authentication you can use the google.appengine.ext users library and ride on the google accounts auth or you can write your own. Writing your own of course means implementing a session mechanism (for retaining state across the user session) and storing the passwords in a hashed and salted state for verification.
| Authentication on App Engine / Python / Django non-rel over JSON | I'm building a site on Google App Engine, running python and Django non-rel. Everything is working great for HTML and posting/reading data. But as I'm moving forward I'd like to do many of the updates with AJAX, and eventually also over mobile devices like Android and iPhone.
My pages use django non-rel and my login/logout authentication works great for the HTML. But update information sent over JSON would have to be authenticated that the user can make the changes. I see how doing authentication for just AJAX calls wouldn't be too difficult since your still hitting the website, but what about when throwing in mobile phone authentication?
So I'm new to this, where do I start?
How can I set up services on gae so I can do authenticated CRUD operations? Ideally I'd like to use the exact same REST services for ajax, android, etc.
| [
"Python makes this pretty easy, you can just create a decorator method of checking the auth and add the decorator to any method requiring auth credentials. \ndef admin(handler_method):\n \"\"\"\n This decorator requires admin, 403 if not.\n \"\"\"\n def auth_required(self, *args, **kwargs):\n if users.is_cur... | [
2
] | [] | [] | [
"authentication",
"django_nonrel",
"google_app_engine",
"json",
"python"
] | stackoverflow_0003771610_authentication_django_nonrel_google_app_engine_json_python.txt |
Q:
python 3.1 - DictType not part of types module?
This is what I found in my install of Python 3.1 on Windows.
Where can I find other types, specifically DictType and StringTypes?
>>> print('\n'.join(dir(types)))
BuiltinFunctionType
BuiltinMethodType
CodeType
FrameType
FunctionType
GeneratorType
GetSetDescriptorType
LambdaType
MemberDescriptorType
MethodType
ModuleType
TracebackType
__builtins__
__doc__
__file__
__name__
__package__
>>>
A:
According to the doc of the types module (http://docs.python.org/py3k/library/types.html),
This module defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are. ...
Typical use is for isinstance() or issubclass() checks.
Since the dictionary type can be used with dict, there is no need to introduce such a type in this module.
>>> isinstance({}, dict)
True
>>> isinstance('', str)
True
>>> isinstance({}, str)
False
>>> isinstance('', dict)
False
(The examples on int and str are outdated too.)
A:
Grepping /usr/lib/python3.1 for 'DictType' shows its only occurrence is in /usr/lib/python3.1/lib2to3/fixes/fix_types.py. There, _TYPE_MAPPING maps DictType to dict.
_TYPE_MAPPING = {
'BooleanType' : 'bool',
'BufferType' : 'memoryview',
'ClassType' : 'type',
'ComplexType' : 'complex',
'DictType': 'dict',
'DictionaryType' : 'dict',
'EllipsisType' : 'type(Ellipsis)',
#'FileType' : 'io.IOBase',
'FloatType': 'float',
'IntType': 'int',
'ListType': 'list',
'LongType': 'int',
'ObjectType' : 'object',
'NoneType': 'type(None)',
'NotImplementedType' : 'type(NotImplemented)',
'SliceType' : 'slice',
'StringType': 'bytes', # XXX ?
'StringTypes' : 'str', # XXX ?
'TupleType': 'tuple',
'TypeType' : 'type',
'UnicodeType': 'str',
'XRangeType' : 'range',
}
So I think in Python3 DictType is replaced by dict.
| python 3.1 - DictType not part of types module? | This is what I found in my install of Python 3.1 on Windows.
Where can I find other types, specifically DictType and StringTypes?
>>> print('\n'.join(dir(types)))
BuiltinFunctionType
BuiltinMethodType
CodeType
FrameType
FunctionType
GeneratorType
GetSetDescriptorType
LambdaType
MemberDescriptorType
MethodType
ModuleType
TracebackType
__builtins__
__doc__
__file__
__name__
__package__
>>>
| [
"According to the doc of the types module (http://docs.python.org/py3k/library/types.html),\n\nThis module defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are. ...\nTypical use is for isinstance() or issubclass() checks.\n\nSince the ... | [
7,
3
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003772049_python_python_3.x.txt |
Q:
pythonic way to wrap xmlrpclib calls in similar multicalls
I'm writing a class that interfaces to a MoinMoin wiki via xmlrpc (simplified code follows):
class MoinMoin(object):
token = None
def __init__(self, url, username=None, password=None):
self.wiki = xmlrpclib.ServerProxy(url + '/?action=xmlrpc2')
if username and password:
self.token = self.wiki.getAuthToken(username, password)
# some sample methods:
def searchPages(self, regexp):
def getPage(self, page):
def putPage(self, page):
now each of my methods needs to call the relevant xmlrpc method alone if there isn't authentication involved, or to wrap it in a multicall if there's auth. Example:
def getPage(self, page):
if not self.token:
result = self.wiki.getPage(page)
else:
mc = xmlrpclib.MultiCall(self.wiki) # build an XML-RPC multicall
mc.applyAuthToken(self.token) # call 1
mc.getPage(page) # call 2
result = mc()[-1] # run both, keep result of the latter
return result
is there any nicer way to do it other than repeating that stuff for each and every method?
Since I have to call arbitrary methods, wrap them with stuff, then call the identically named method on another class, select relevant results and give them back, I suspect the solution would involve meta-classes or similar esoteric (for me) stuff. I should probably look at xmlrpclib sources and see how it's done, then maybe subclass their MultiCall to add my stuff...
But maybe I'm missing something easier. The best I've come out with is something like:
def _getMultiCall(self):
mc = xmlrpclib.MultiCall(self.wiki)
if self.token:
mc.applyAuthToken(self.token)
return mc
def fooMethod(self, x):
mc = self._getMultiCall()
mc.fooMethod(x)
return mc()[-1]
but it still repeats the same three lines of code for each and every method I need to implement, just changing the called method name. Any better?
A:
Python function are objects so they can be passed quite easily to other function.
def HandleAuthAndReturnResult(self, method, arg):
mc = xmlrpclib.MultiCall(self.wiki)
if self.token:
mc.applyAuthToken(self.token)
method(mc, arg)
return mc()[-1]
def fooMethod(self, x):
HandleAuthAndReturnResult(xmlrpclib.MultiCall.fooMethod, x)
There may be other way but I think it should work. Of course, the arg part needs to be aligned with what is needed for the method but all your methods take one argument.
Edit: I didn't understand that MultiCall was a proxy object. Even if the real method call ultimately is the one in your ServerProxy, you should not pass this method object in case MultiCall ever overrides(define) it. In this case, you could use the getattribute method with the method name you want to call and then call the returned function object. Take care to handle the AttributeError exception.
Methods would now look like:
def HandleAuthAndReturnResult(self, methodName, arg):
mc = xmlrpclib.MultiCall(self.wiki)
if self.token:
mc.applyAuthToken(self.token)
try:
methodToCall = getattr(mc, methodName)
except AttributeError:
return None
methodToCall(arg)
return mc()[-1]
def fooMethod(self, x):
HandleAuthAndReturnResult('fooMethod', x)
| pythonic way to wrap xmlrpclib calls in similar multicalls | I'm writing a class that interfaces to a MoinMoin wiki via xmlrpc (simplified code follows):
class MoinMoin(object):
token = None
def __init__(self, url, username=None, password=None):
self.wiki = xmlrpclib.ServerProxy(url + '/?action=xmlrpc2')
if username and password:
self.token = self.wiki.getAuthToken(username, password)
# some sample methods:
def searchPages(self, regexp):
def getPage(self, page):
def putPage(self, page):
now each of my methods needs to call the relevant xmlrpc method alone if there isn't authentication involved, or to wrap it in a multicall if there's auth. Example:
def getPage(self, page):
if not self.token:
result = self.wiki.getPage(page)
else:
mc = xmlrpclib.MultiCall(self.wiki) # build an XML-RPC multicall
mc.applyAuthToken(self.token) # call 1
mc.getPage(page) # call 2
result = mc()[-1] # run both, keep result of the latter
return result
is there any nicer way to do it other than repeating that stuff for each and every method?
Since I have to call arbitrary methods, wrap them with stuff, then call the identically named method on another class, select relevant results and give them back, I suspect the solution would involve meta-classes or similar esoteric (for me) stuff. I should probably look at xmlrpclib sources and see how it's done, then maybe subclass their MultiCall to add my stuff...
But maybe I'm missing something easier. The best I've come out with is something like:
def _getMultiCall(self):
mc = xmlrpclib.MultiCall(self.wiki)
if self.token:
mc.applyAuthToken(self.token)
return mc
def fooMethod(self, x):
mc = self._getMultiCall()
mc.fooMethod(x)
return mc()[-1]
but it still repeats the same three lines of code for each and every method I need to implement, just changing the called method name. Any better?
| [
"Python function are objects so they can be passed quite easily to other function.\ndef HandleAuthAndReturnResult(self, method, arg):\n mc = xmlrpclib.MultiCall(self.wiki)\n if self.token:\n mc.applyAuthToken(self.token)\n method(mc, arg)\n return mc()[-1]\ndef fooMethod(self, x):\n HandleAuth... | [
1
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0003771859_class_methods_python.txt |
Q:
pyfacebook doesn't have set_status in that object anymore?
i just try this
import facebook
fb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY')
fb.auth.createToken()
fb.login()
fb.auth.getSession()
fb.set_status('Checking out StackOverFlow.com')
and got this
gunslinger@c0debreaker:~$ python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information.
>>> import facebook
>>> fb = facebook.Facebook('MY_API_KEY', 'MY_SECRET_KEY')
>>> fb.auth.createToken() u'SECRET'
>>> fb.login()
>>> fb.auth.getSession() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.linux-i686/egg/facebook/__init__.py", line 670, in getSession
File "build/bdist.linux-i686/egg/facebook/__init__.py", line 1123, in __call__
File "build/bdist.linux-i686/egg/facebook/__init__.py", line 1056, in _parse_response
File "build/bdist.linux-i686/egg/facebook/__init__.py", line 1007, in _check_error
facebook.FacebookError: Error 100: Invalid parameter
>>> fb.set_status('Checking out StackOverFlow.com') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Facebook' object has no attribute 'set_status'
>>>
pyfacebook remove set_status() function in newest pyfacebook ?
A:
From looking at the source code, it looks like you need to use fb.status.set()
| pyfacebook doesn't have set_status in that object anymore? | i just try this
import facebook
fb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY')
fb.auth.createToken()
fb.login()
fb.auth.getSession()
fb.set_status('Checking out StackOverFlow.com')
and got this
gunslinger@c0debreaker:~$ python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information.
>>> import facebook
>>> fb = facebook.Facebook('MY_API_KEY', 'MY_SECRET_KEY')
>>> fb.auth.createToken() u'SECRET'
>>> fb.login()
>>> fb.auth.getSession() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.linux-i686/egg/facebook/__init__.py", line 670, in getSession
File "build/bdist.linux-i686/egg/facebook/__init__.py", line 1123, in __call__
File "build/bdist.linux-i686/egg/facebook/__init__.py", line 1056, in _parse_response
File "build/bdist.linux-i686/egg/facebook/__init__.py", line 1007, in _check_error
facebook.FacebookError: Error 100: Invalid parameter
>>> fb.set_status('Checking out StackOverFlow.com') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Facebook' object has no attribute 'set_status'
>>>
pyfacebook remove set_status() function in newest pyfacebook ?
| [
"From looking at the source code, it looks like you need to use fb.status.set()\n"
] | [
1
] | [] | [] | [
"pyfacebook",
"python"
] | stackoverflow_0003769229_pyfacebook_python.txt |
Q:
Optimizing Python Code for Database Access
I am building an application with objects which have their data stored in mysql tables (across multiple tables). When I need to work with the object (retrieve object attributes / change the attributes) I am querying the sql database using mysqldb (select / update). However, since the application is quite computation intensive, the execution time is killing me.
Wanted to understand if there are approaches where all of the data is loaded into python, the computations / modifications are done on those objects and then subsequently a full data update is done to the mysql database? Will loading the data initially into lists of those objects in one go from the database improve the performance? Also since the db size is close to around 25 mb, will it cause any memory problems.
Thanks in advance.
A:
25Mb is tiny. Microscopic. SQL is slow. Glacial.
Do not waste time on SQL unless you have transactions (with locking and multiple users).
If you're doing "analysis", especially computationally-intensive analysis, load all the data into memory.
In the unlikely event that data doesn't fit into memory, then do this.
Query data into flat files. This can be fast. It's fastest if you don't use Python, but use the database native tools to extract data into CSV or something small.
Read flat files and do computations, writing flat files. This is really fast.
Do bulk updates from the flat files. Again, this is fastest if you use database native toolset for insert or update.
If you didn't need SQL in the first place, consider the data as you originally received it and what you're going to do with it.
Read the original file once, parse it, create your Python objects and pickle the entire list or dictionary. This means that each subsequent program can simply load the pickled file and start doing analysis. However. You can't easily update the pickled file. You have to create a new one. This is not a bad thing. It gives you complete processing history.
Read the original file once, parse it, create your Python objects using shelve. This means you can
update the file.
Read the original file once, parse it, create your Python objects and save the entire list or dictionary as a JSON or YAML file. This means that each subsequent program can simply load the JSON (or YAML) file and start doing analysis. However. You can't easily update the file. You have to create a new one. This is not a bad thing. It gives you complete processing history.
This will probably be slightly slower than pickling. And it will require that you write some helpers so that the JSON objects are dumped and loaded properly. However, you can read JSON (and YAML) giving you some advantages in working with the file.
A:
Please check sqlalchemy, an Object Relational Mapper for Python.
sqlalchemy allows you to map database tables to Python objects. When you do this, all the operations can be done on the Python objects (once the data is loaded), and when you are done processing, you can update the database.
Assuming you have a baseline of-the-shelf computer, 25 MB is absolutely no big deal, you can cache the entire database into memory.
| Optimizing Python Code for Database Access | I am building an application with objects which have their data stored in mysql tables (across multiple tables). When I need to work with the object (retrieve object attributes / change the attributes) I am querying the sql database using mysqldb (select / update). However, since the application is quite computation intensive, the execution time is killing me.
Wanted to understand if there are approaches where all of the data is loaded into python, the computations / modifications are done on those objects and then subsequently a full data update is done to the mysql database? Will loading the data initially into lists of those objects in one go from the database improve the performance? Also since the db size is close to around 25 mb, will it cause any memory problems.
Thanks in advance.
| [
"25Mb is tiny. Microscopic. SQL is slow. Glacial.\nDo not waste time on SQL unless you have transactions (with locking and multiple users).\nIf you're doing \"analysis\", especially computationally-intensive analysis, load all the data into memory.\nIn the unlikely event that data doesn't fit into memory, then d... | [
5,
0
] | [] | [] | [
"mysql",
"optimization",
"python"
] | stackoverflow_0003770394_mysql_optimization_python.txt |
Q:
Python YouTube Gdata Api: DeletePlaylist
I have correctly initialized YouTubeService. I can move/delete/rename playlist entries, but when I try to delete playlist I get unhelpfull exception:
_service = None
def get_service():
global _service
if _service is None:
_service = YouTubeService()
gdata.alt.appengine.run_on_appengine(_service)
_service.developer_key = settings.YTMANAGER_DEVELOPER_KEY
if 'token' in get_request().session:
_service.SetAuthSubToken(get_request().session['token'])
return _service
def test(request):
get_service().DeletePlaylist('http://gdata.youtube.com/feeds/api/playlists/921AC6352FE6931F')
return HttpResponse('ok')
Exception:
Exception Type: RequestError
Exception Value: {'status': 400, 'body': 'Invalid request URI', 'reason': ''}
Exception Location: \gdata\service.py in Delete, line 1454
A:
Documentation (http://code.google.com/apis/youtube/1.0/developers_guide_python.html#DeletePlaylists) is outdated or this is bug, but DeletePlaylist requires "full" link:
http://gdata.youtube.com/feeds/api/users/username/playlists/921AC6352FE6931F
since GetYouTubePlaylistVideoFeed method requires "short" link in order to use max-results parameter:
http://gdata.youtube.com/feeds/api/playlists/921AC6352FE6931F
| Python YouTube Gdata Api: DeletePlaylist | I have correctly initialized YouTubeService. I can move/delete/rename playlist entries, but when I try to delete playlist I get unhelpfull exception:
_service = None
def get_service():
global _service
if _service is None:
_service = YouTubeService()
gdata.alt.appengine.run_on_appengine(_service)
_service.developer_key = settings.YTMANAGER_DEVELOPER_KEY
if 'token' in get_request().session:
_service.SetAuthSubToken(get_request().session['token'])
return _service
def test(request):
get_service().DeletePlaylist('http://gdata.youtube.com/feeds/api/playlists/921AC6352FE6931F')
return HttpResponse('ok')
Exception:
Exception Type: RequestError
Exception Value: {'status': 400, 'body': 'Invalid request URI', 'reason': ''}
Exception Location: \gdata\service.py in Delete, line 1454
| [
"Documentation (http://code.google.com/apis/youtube/1.0/developers_guide_python.html#DeletePlaylists) is outdated or this is bug, but DeletePlaylist requires \"full\" link:\nhttp://gdata.youtube.com/feeds/api/users/username/playlists/921AC6352FE6931F\n\nsince GetYouTubePlaylistVideoFeed method requires \"short\" li... | [
0
] | [] | [] | [
"gdata_python_client",
"google_app_engine",
"python"
] | stackoverflow_0003769069_gdata_python_client_google_app_engine_python.txt |
Q:
Google App Engine python Filter "property of property"
Having these models on google app engine:
class Choice(db.Model):
poll = db.ReferenceProperty(Poll, collection_name = 'choices' )
text = db.StringProperty()
class Vote(db.Model):
choice = db.ReferenceProperty(Choice, collection_name = 'votes' )
ip = db.StringProperty()
date = db.DateTimeProperty(auto_now=1)
How do I do this django query?
same_vote = Vote.filter(ip=self.ip, choice__poll=self.choice.poll)
A:
The App Engine datastore isn't capable of doing a query like this, which requires a join. To perform such a query, you'll need to denormalize your data so your Vote entities include information about which Poll they apply to.
| Google App Engine python Filter "property of property" | Having these models on google app engine:
class Choice(db.Model):
poll = db.ReferenceProperty(Poll, collection_name = 'choices' )
text = db.StringProperty()
class Vote(db.Model):
choice = db.ReferenceProperty(Choice, collection_name = 'votes' )
ip = db.StringProperty()
date = db.DateTimeProperty(auto_now=1)
How do I do this django query?
same_vote = Vote.filter(ip=self.ip, choice__poll=self.choice.poll)
| [
"The App Engine datastore isn't capable of doing a query like this, which requires a join. To perform such a query, you'll need to denormalize your data so your Vote entities include information about which Poll they apply to.\n"
] | [
3
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003772495_django_google_app_engine_python.txt |
Q:
Using data from a specific class in python
storage = []
...
after running program
storage = [ <main.Record instance at 0x032E8530> ]
inside the instance of Record are:
"Model No."
"Standard: Part Number"
"Standard: Issue Date"
"Date of Declaration"
"Declaration Document Number"
Question: How do I use specific data from within the Record?
A:
What do you mean by use?
storage[0] will give you a reference to the record.
From there you can just use whatever methods main.Record exposes to access its data.
| Using data from a specific class in python | storage = []
...
after running program
storage = [ <main.Record instance at 0x032E8530> ]
inside the instance of Record are:
"Model No."
"Standard: Part Number"
"Standard: Issue Date"
"Date of Declaration"
"Declaration Document Number"
Question: How do I use specific data from within the Record?
| [
"What do you mean by use?\nstorage[0] will give you a reference to the record.\nFrom there you can just use whatever methods main.Record exposes to access its data.\n"
] | [
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0003772981_class_python.txt |
Q:
Pythonic way to perform a large case/switch
I'm pretty sure this is a really fundamental concept in Python, I'd love it if someone could help me understand how to do the following in a pythonic/clean way. I'm really new to coding so I will just show an example. I think it will be obvious what I am trying to do.
for textLine in textLines:
foo = re.match('[1-100]', thing)
if foo:
list = db.GqlQuery("SELECT * FROM Bar").fetch(100)
if thing == '1':
item = list[0]
elif thing == '2':
item = list[1]
elif thing == '3':
item = list[2]
.
.
.
elif thing == '100':
item = list[99]
Thanks for the help!
A:
Why not just do this
item = list[int(thing) - 1]
In more complex cases, you should use a dictionary mapping inputs to outputs.
A:
For the specific code you're showing, the pythonic thing would be to replace the entire if-ladder with:
item = list[int(thing)-1]
Of course, it's possible that your real code doesn't lend itself to collapsing like this.
| Pythonic way to perform a large case/switch | I'm pretty sure this is a really fundamental concept in Python, I'd love it if someone could help me understand how to do the following in a pythonic/clean way. I'm really new to coding so I will just show an example. I think it will be obvious what I am trying to do.
for textLine in textLines:
foo = re.match('[1-100]', thing)
if foo:
list = db.GqlQuery("SELECT * FROM Bar").fetch(100)
if thing == '1':
item = list[0]
elif thing == '2':
item = list[1]
elif thing == '3':
item = list[2]
.
.
.
elif thing == '100':
item = list[99]
Thanks for the help!
| [
"Why not just do this\nitem = list[int(thing) - 1]\n\nIn more complex cases, you should use a dictionary mapping inputs to outputs.\n",
"For the specific code you're showing, the pythonic thing would be to replace the entire if-ladder with:\nitem = list[int(thing)-1]\n\nOf course, it's possible that your real cod... | [
11,
7
] | [] | [] | [
"python"
] | stackoverflow_0003773079_python.txt |
Q:
learning python - point to keep in mind w.r.t idioms!
I've been an avid learner of the Python language for quite some time. Having more than 6 years of Java[professional] experience, coupled with a bit of C++ [hobby] experience - it's fair to say my perspective is deeply entrenched in the idioms brought forth by such statically typed, strongly bound languages. In short - i could say the old school way of thinking has significant influence on my programming style.
My reason to pick up Python, and not say Ruby, was primarily a coincidence since i got some part time work i could help out w/ using Python. it's been 2 weeks, and things have been nothing short of a revolution! armed w/ IDLE and the Python Essential Reference, it's been one revelation after another. it's like how a classical physicist would feel if gravity ceased to exist!
Anyways, i understand that to be effective w/ python it's going to take some time of real hands-on work. more than the syntax, i feel it's because of the way my mind thinks. however, prepared as much as i am, there's one particular thing which bothers me quite a bit -
python offers way too many idioms to perform the same thing. For example, list comprehension and filter(...), apply(...) and eval(...), etc. while these idioms aren't completely substitutable, but i find that their primary purposes overlap to a great extent.
i understand that there must be underlying performance gains vis-a-vis their usages. however, as a beginner, what's the best way to get on w/ the education and curb the distraction of 'n' ways to solve the same thing?
A:
list comprehension and filter(...),
apply(...) and eval(...), etc. while
these idioms aren't completely
substitutable, but i find that their
primary purposes overlap to a great
extent
The pythonic way would be: use simple for-loops or list comprehensions. filter and map are remnants of older versions of the language. Guido wanted them removed at one point but it turned out there are some valid use cases and enough people who would like them to stay (also see this thread). Don't use eval.
Don't worry about performance unless it becomes a problem (and in that case the easiest way - trying make to use of the highly optimized functions in the standard library - is the best way most of the time).
I think in general Python is really straightforward in trying to provide one (obvious) way to do things, although valid (bigger or smaller) variations do occur and opinions on some topics do differ, of course.
Picking up the Python idioms can be as easy as browsing this site and paying special attention to highly upvoted answers on Python questions (most of the time there's some kind of consensus on the best way to do things).
A:
Since you're coming from a Java background, I recommend reading Python is not Java. Not to mention most of the other articles in the sidebar. The article gives some good pointers on how Java programmers can unintentionally mis-use Python (and how not to).
A:
For starters, you should read this:
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
A:
Be sure to read Idioms and Anti-idioms which is part of the official Python documentation. Also be sure to read PEP8 on Python style.
A:
Type
import this
into IDLE
A:
Sorry, if my answer is not as long as your question, but, anyway, here goes:
First of all about listcomps/filter/apply/eval. If you are about to use filter or apply you are much better off using a list comprehension (or a generator expression) or a for loop, - filter, map, reduce and apply are, basically, atavisms as far as I know and can be ignored safely. Eval does not have anything to do with either of those, it just evaluates a string as python code. You probably should not use it, unless you have an extremely good reason to od so (hint: you don't).
Re idioms: well, for the most part, in python for a given problem there is an optimal 'way to do it', that should be used for 99% of similar cases. Examples: need to parse/transform/generate xml? Use lxml. Need to do networking/pretty much any other kind of i/o ? Use twisted. And so on. Of course there are alternatives, but most of the time there is indeed one optimal way of doing things. This is even more relevant if you are just working with the standard library, as it provides lots of optimal solutions to common problems (although it does contain some rather useless stuff).
A:
Funny you should say this: "it's been one revelation after another. it's like how a classical physicist would feel if gravity ceased to exist!": http://xkcd.com/353/
| learning python - point to keep in mind w.r.t idioms! | I've been an avid learner of the Python language for quite some time. Having more than 6 years of Java[professional] experience, coupled with a bit of C++ [hobby] experience - it's fair to say my perspective is deeply entrenched in the idioms brought forth by such statically typed, strongly bound languages. In short - i could say the old school way of thinking has significant influence on my programming style.
My reason to pick up Python, and not say Ruby, was primarily a coincidence since i got some part time work i could help out w/ using Python. it's been 2 weeks, and things have been nothing short of a revolution! armed w/ IDLE and the Python Essential Reference, it's been one revelation after another. it's like how a classical physicist would feel if gravity ceased to exist!
Anyways, i understand that to be effective w/ python it's going to take some time of real hands-on work. more than the syntax, i feel it's because of the way my mind thinks. however, prepared as much as i am, there's one particular thing which bothers me quite a bit -
python offers way too many idioms to perform the same thing. For example, list comprehension and filter(...), apply(...) and eval(...), etc. while these idioms aren't completely substitutable, but i find that their primary purposes overlap to a great extent.
i understand that there must be underlying performance gains vis-a-vis their usages. however, as a beginner, what's the best way to get on w/ the education and curb the distraction of 'n' ways to solve the same thing?
| [
"\nlist comprehension and filter(...),\n apply(...) and eval(...), etc. while\n these idioms aren't completely\n substitutable, but i find that their\n primary purposes overlap to a great\n extent\n\nThe pythonic way would be: use simple for-loops or list comprehensions. filter and map are remnants of older ve... | [
4,
3,
2,
2,
2,
1,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0003772989_python_syntax.txt |
Q:
Django, where to import your modules
I always thought it was OK to just import all of your modules at the top of a view file. Then if you ever change a model name you can just edit the import at the top and not go digging through every view function that you need it imported in.
Well, I just ran into an instance where I had imported a model at the top of a view file, and then used it in a function, but for some reason django threw an unbound variable error when I tried to use the model to do a query, which leads me to believe that I do need to do my imports for each function?
So, my question is, what is the proper way to do it? Import everything at the top of the file or in each function as needed.
Thanks
A:
There is no requirement in Django that you import modules at function scope. You can, but that is true of python generally. I'd like to see your code and error message. I don't think that your problem is due to the cause you attribute it to.
| Django, where to import your modules | I always thought it was OK to just import all of your modules at the top of a view file. Then if you ever change a model name you can just edit the import at the top and not go digging through every view function that you need it imported in.
Well, I just ran into an instance where I had imported a model at the top of a view file, and then used it in a function, but for some reason django threw an unbound variable error when I tried to use the model to do a query, which leads me to believe that I do need to do my imports for each function?
So, my question is, what is the proper way to do it? Import everything at the top of the file or in each function as needed.
Thanks
| [
"There is no requirement in Django that you import modules at function scope. You can, but that is true of python generally. I'd like to see your code and error message. I don't think that your problem is due to the cause you attribute it to.\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003773208_django_python.txt |
Q:
How can I selectively mask arbitrary data being sent over an insecure link?
I'm using an offsite error logging package for my python web application. When I send an error I include the contents of (among other things) the POST variable and some template data. Some of this data must not be sent to the error logging service (passwords, some other template data).
How can I take a payload that consists of a mix of data -- objects, dicts, et al -- and mask out (say) every field or entry named my_private_data?
What I'd expect is that if an object has a string or integer property (the private data will always be a number or a string) my_private_data=SOME SECRET, it would be transmitted as my_private_data=**********
How do I accomplish this?
A:
If you have the POST data as a string, you can use the standard modules "urlparse" and "urllib" to remove certain parameters:
import urlparse
import urllib
postDataAsDict = urlparse.parse_qs("a=5&b=3&c=%26escaped", strict_parsing = True)
print postDataAsDict # prints {'a': ['5'], 'b': ['3'], 'c': ['&escaped']}
del postDataAsDict["a"] # in your case "my_private_data"
print urllib.urlencode(postDataAsDict, True) # prints c=%26escaped&b=3
Note that parse_qs correctly supports multiple parameters that have the same name, so don't worry about that.
| How can I selectively mask arbitrary data being sent over an insecure link? | I'm using an offsite error logging package for my python web application. When I send an error I include the contents of (among other things) the POST variable and some template data. Some of this data must not be sent to the error logging service (passwords, some other template data).
How can I take a payload that consists of a mix of data -- objects, dicts, et al -- and mask out (say) every field or entry named my_private_data?
What I'd expect is that if an object has a string or integer property (the private data will always be a number or a string) my_private_data=SOME SECRET, it would be transmitted as my_private_data=**********
How do I accomplish this?
| [
"If you have the POST data as a string, you can use the standard modules \"urlparse\" and \"urllib\" to remove certain parameters:\nimport urlparse\nimport urllib\n\npostDataAsDict = urlparse.parse_qs(\"a=5&b=3&c=%26escaped\", strict_parsing = True)\nprint postDataAsDict # prints {'a': ['5'], 'b': ['3'], 'c': ['&es... | [
1
] | [] | [] | [
"python",
"sanitization",
"security",
"web_services"
] | stackoverflow_0003773440_python_sanitization_security_web_services.txt |
Q:
Python average tabular data help
Ok I have the following working program. It opens of a file of data in columns that is too large for excel and finds the average value for each column:
Sample data is:
Joe Sam Bob
1 2 3
2 1 3
And it returns
Joe Sam Bob
1.5 1.5 3
This is good. The problem is some columns have NA as a value. I want to skip this NA and calculate the average of the remaining values
So
Bobby
1
NA
2
Should output as
Bobby
1.5
Here is my existing program built with help from here. Any help is appreciated!
with open('C://avy.txt', "rtU") as f:
columns = f.readline().strip().split(" ")
numRows = 0
sums = [0] * len(columns)
for line in f:
# Skip empty lines
if not line.strip():
continue
values = line.split(" ")
for i in xrange(len(values)):
sums[i] += int(values[i])
numRows += 1
with open('c://finished.txt', 'w') as ouf:
for index, summedRowValue in enumerate(sums):
print>>ouf, columns[index], 1.0 * summedRowValue / numRows
Now I have this:
with open('C://avy.txt', "rtU") as f:
def get_averages(f):
headers = f.readline().split()
ncols = len(headers)
sumx0 = [0] * ncols
sumx1 = [0.0] * ncols
lino = 1
for line in f:
lino += 1
values = line.split()
for colindex, x in enumerate(values):
if colindex >= ncols:
print >> sys.stderr, "Extra data %r in row %d, column %d" %(x, lino, colindex+1)
continue
try:
value = float(x)
except ValueError:
continue
sumx0[colindex] += 1
sumx1[colindex] += value
print headers
print sumx1
print sumx0
averages = [
total / count if count else None
for total, count in zip(sumx1, sumx0)
]
print averages
and it says:
Traceback (most recent call last):
File "C:/avy10.py", line 11, in
lino += 1
NameError: name 'lino' is not defined
A:
Here is a functional solution:
text = """Joe Sam Bob
1 2 3
2 1 3
NA 2 3
3 5 NA"""
def avg( lst ):
""" returns the average of a list """
return 1. * sum(lst)/len(lst)
# split that text
parts = [line.split() for line in text.splitlines()]
#remove the headers
names = parts.pop(0)
# zip(*m) does something like transpose a matrix :-)
columns = zip(*parts)
# convert to numbers and leave out the NA
numbers = [[int(x) for x in column if x != 'NA' ] for column in columns]
# all left is averaging
averages = [avg(col) for col in numbers]
# and printing
for name, x in zip( names, averages):
print name, x
I wrote a lot of list comprehensions here so you can print out intermediate steps, but those can be generators of cause.
A:
[edited for clarity]
When reading items from a text file, they are imported as strings, not numbers. This means that if your text file has the number 3 and you read it into Python, you would need to convert the string to a number before carrying on arithmetic operations.
Now, you have a text file with colums. Each column has a header and a collection of items. Each item is either a number or not. If it is a number, it will correctly be converted by the function float, if it is not a valid number (this is, if the conversion does not exist) the conversion will raise an exception called ValueError.
So you loop through your list and items as it has been correctly explained in more than one answer. If you can convert to float, accumulate the statistic. If not, go on ignoring that entry.
If you need more info about what is "duck typing" (a paradigm which can be resumed as "better to ask for forgiveness that for permission") please check the Wikipedia link. If you are getting into Python you will hear the term very often.
Below I present a class which can accumulate an statistic (you are interested in the mean). You can use an instance of that class for every column in your table.
class Accumulator(object):
"""
Used to accumulate the arithmetic mean of a stream of
numbers. This implementation does not allow to remove items
already accumulated, but it could easily be modified to do
so. also, other statistics could be accumulated.
"""
def __init__(self):
# upon initialization, the numnber of items currently
# accumulated (_n) and the total sum of the items acumulated
# (_sum) are set to zero because nothing has been accumulated
# yet.
self._n = 0
self._sum = 0.0
def add(self, item):
# the 'add' is used to add an item to this accumulator
try:
# try to convert the item to a float. If you are
# successful, add the float to the current sum and
# increase the number of accumulated items
self._sum += float(item)
self._n += 1
except ValueError:
# if you fail to convert the item to a float, simply
# ignore the exception (pass on it and do nothing)
pass
@property
def mean(self):
# the property 'mean' returns the current mean accumulated in
# the object
if self._n > 0:
# if you have more than zero items accumulated, then return
# their artithmetic average
return self._sum / self._n
else:
# if you have no items accumulated, return None (you could
# also raise an exception)
return None
# using the object:
# Create an instance of the object "Accumulator"
my_accumulator = Accumulator()
print my_accumulator.mean
# prints None because there are no items accumulated
# add one (a number)
my_accumulator.add(1)
print my_accumulator.mean
# prints 1.0
# add two (a string - it will be converted to a float)
my_accumulator.add('2')
print my_accumulator.mean
# prints 1.5
# add a 'NA' (will be ignored because it cannot be converted to float)
my_accumulator.add('NA')
print my_accumulator.mean
# prints 1.5 (notice that it ignored the 'NA')
Cheers.
A:
The following code handles varying counts properly, and also detects extra data ... in other words, it's rather robust. It could be improved by explicit messages (1) if the file is empty (2) if the header line is empty. Another possibility is testing explicitly for "NA", and issuing an error message if a field is neither "NA" nor floatable.
>>> import sys, StringIO
>>>
>>> data = """\
... Jim Joe Billy Bob
... 1 2 3 x
... 2 x x x 666
...
... 3 4 5 x
... """
>>>
>>> def get_averages(f):
... headers = f.readline().split()
... ncols = len(headers)
... sumx0 = [0] * ncols
... sumx1 = [0.0] * ncols
... lino = 1
... for line in f:
... lino += 1
... values = line.split()
... for colindex, x in enumerate(values):
... if colindex >= ncols:
... print >> sys.stderr, "Extra data %r in row %d, column %d" %
(x, lino, colindex+1)
... continue
... try:
... value = float(x)
... except ValueError:
... continue
... sumx0[colindex] += 1
... sumx1[colindex] += value
... print headers
... print sumx1
... print sumx0
... averages = [
... total / count if count else None
... for total, count in zip(sumx1, sumx0)
... ]
... print averages
Edit add here:
... return headers, averages
...
>>> sio = StringIO.StringIO(data)
>>> get_averages(sio)
Extra data '666' in row 3, column 5
['Jim', 'Joe', 'Billy', 'Bob']
[6.0, 6.0, 8.0, 0.0]
[3, 2, 2, 0]
[2.0, 3.0, 4.0, None]
>>>
Edit
Normal usage:
with open('myfile.text') as mf:
hdrs, avgs = get_averages(mf)
| Python average tabular data help | Ok I have the following working program. It opens of a file of data in columns that is too large for excel and finds the average value for each column:
Sample data is:
Joe Sam Bob
1 2 3
2 1 3
And it returns
Joe Sam Bob
1.5 1.5 3
This is good. The problem is some columns have NA as a value. I want to skip this NA and calculate the average of the remaining values
So
Bobby
1
NA
2
Should output as
Bobby
1.5
Here is my existing program built with help from here. Any help is appreciated!
with open('C://avy.txt', "rtU") as f:
columns = f.readline().strip().split(" ")
numRows = 0
sums = [0] * len(columns)
for line in f:
# Skip empty lines
if not line.strip():
continue
values = line.split(" ")
for i in xrange(len(values)):
sums[i] += int(values[i])
numRows += 1
with open('c://finished.txt', 'w') as ouf:
for index, summedRowValue in enumerate(sums):
print>>ouf, columns[index], 1.0 * summedRowValue / numRows
Now I have this:
with open('C://avy.txt', "rtU") as f:
def get_averages(f):
headers = f.readline().split()
ncols = len(headers)
sumx0 = [0] * ncols
sumx1 = [0.0] * ncols
lino = 1
for line in f:
lino += 1
values = line.split()
for colindex, x in enumerate(values):
if colindex >= ncols:
print >> sys.stderr, "Extra data %r in row %d, column %d" %(x, lino, colindex+1)
continue
try:
value = float(x)
except ValueError:
continue
sumx0[colindex] += 1
sumx1[colindex] += value
print headers
print sumx1
print sumx0
averages = [
total / count if count else None
for total, count in zip(sumx1, sumx0)
]
print averages
and it says:
Traceback (most recent call last):
File "C:/avy10.py", line 11, in
lino += 1
NameError: name 'lino' is not defined
| [
"Here is a functional solution:\ntext = \"\"\"Joe Sam Bob\n1 2 3\n2 1 3\nNA 2 3\n3 5 NA\"\"\"\n\ndef avg( lst ):\n \"\"\" returns the average of a list \"\"\"\n return 1. * sum(lst)/len(lst)\n\n# split that text\nparts = [line.split() for line in text.splitlines()]\n#remove the headers\nnames = parts.... | [
3,
2,
-1
] | [
"Change your inner-most loop to:\n values = line.split(\" \")\n for i in xrange(len(values)):\n if values[i] == \"NA\":\n continue\n sums[i] += int(values[i])\n numRows += 1\n\n",
"Much smaller code:\nwith open('in', \"rtU\") as f:\n lines = [l for l in f if l.strip()]\n na... | [
-1,
-1
] | [
"python"
] | stackoverflow_0003771424_python.txt |
Q:
Piping output of subprocess.Popen to files
I need to launch a number of long-running processes with subprocess.Popen, and would like to have the stdout and stderr from each automatically piped to separate log files. Each process will run simultaneously for several minutes, and I want two log files (stdout and stderr) per process to be written to as the processes run.
Do I need to continually call p.communicate() on each process in a loop in order to update each log file, or is there some way to invoke the original Popen command so that stdout and stderr are automatically streamed to open file handles?
A:
You can pass stdout and stderr as parameters to Popen()
subprocess.Popen(self, args, bufsize=0, executable=None, stdin=None, stdout=None,
stderr=None, preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False, startupinfo=None,
creationflags=0)
For example
>>> import subprocess
>>> with open("stdout.txt","wb") as out, open("stderr.txt","wb") as err:
... subprocess.Popen("ls",stdout=out,stderr=err)
...
<subprocess.Popen object at 0xa3519ec>
>>>
A:
Per the docs,
stdin, stdout and stderr specify the
executed programs’ standard input,
standard output and standard error
file handles, respectively. Valid
values are PIPE, an existing file
descriptor (a positive integer), an
existing file object, and None.
So just pass the open-for-writing file objects as named arguments stdout= and stderr= and you should be fine!
A:
I am simultaneously running two subprocesses, and saving the output from both into a single log file. I have also built in a timeout to handle hung subprocesses. When the output gets too big, the timeout always triggers, and none of the stdout from either subprocess gets saved to the log file. The answer posed by Alex above does not solve it.
# Currently open log file.
log = None
# If we send stdout to subprocess.PIPE, the tests with lots of output fill up the pipe and
# make the script hang. So, write the subprocess's stdout directly to the log file.
def run(cmd, logfile):
#print os.getcwd()
#print ("Running test: %s" % cmd)
global log
p = subprocess.Popen(cmd, shell=True, universal_newlines = True, stderr=subprocess.STDOUT, stdout=logfile)
log = logfile
return p
# To make a subprocess capable of timing out
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
log.flush()
raise Alarm
####
## This function runs a given command with the given flags, and records the
## results in a log file.
####
def runTest(cmd_path, flags, name):
log = open(name, 'w')
print >> log, "header"
log.flush()
cmd1_ret = run(cmd_path + "command1 " + flags, log)
log.flush()
cmd2_ret = run(cmd_path + "command2", log)
#log.flush()
sys.stdout.flush()
start_timer = time.time() # time how long this took to finish
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(5) #seconds
try:
cmd1_ret.communicate()
except Alarm:
print "myScript.py: Oops, taking too long!"
kill_string = ("kill -9 %d" % cmd1_ret.pid)
os.system(kill_string)
kill_string = ("kill -9 %d" % cmd2_ret.pid)
os.system(kill_string)
#sys.exit()
end_timer = time.time()
print >> log, "closing message"
log.close()
| Piping output of subprocess.Popen to files | I need to launch a number of long-running processes with subprocess.Popen, and would like to have the stdout and stderr from each automatically piped to separate log files. Each process will run simultaneously for several minutes, and I want two log files (stdout and stderr) per process to be written to as the processes run.
Do I need to continually call p.communicate() on each process in a loop in order to update each log file, or is there some way to invoke the original Popen command so that stdout and stderr are automatically streamed to open file handles?
| [
"You can pass stdout and stderr as parameters to Popen()\nsubprocess.Popen(self, args, bufsize=0, executable=None, stdin=None, stdout=None,\n stderr=None, preexec_fn=None, close_fds=False, shell=False,\n cwd=None, env=None, universal_newlines=False, startupinfo=None, \n ... | [
91,
41,
3
] | [] | [] | [
"python",
"stdout",
"subprocess"
] | stackoverflow_0002331339_python_stdout_subprocess.txt |
Q:
PyPi issues - Upload failed (401): You must be identified to edit package information
Im encountering a problem with pypi similar to this one, except that I'm running windows and the mentioned solution page is down.
Does anyone know how to work around this? I'm using python 2.5.
python setup.py sdist register upload
running register
We need to know who you are, so please choose either:
1. use your existing login,
2. register as a new user,
3. have the server generate a new password for you (and email it to you), or
4. quit
Your selection [default 1]: 1
Username: tschellenbach
Password:
Server response (200): OK
running upload
Submitting dist\django-ogone-1.0.0.zip to http://pypi.python.org/pypi
Upload failed (401): You must be identified to edit package information
A:
the answer for this seems not very non-windows-specific, give it a try:
accepted answer It says basically, that you need a file .pypirc with the following section:
[server-login]
username:tschellenbach
password:******** (the real one)
also, this is the relevant documentation (about .pypirc):
On windows, an you’ll need to set a HOME environ var to point to the directory where this file lives.
| PyPi issues - Upload failed (401): You must be identified to edit package information | Im encountering a problem with pypi similar to this one, except that I'm running windows and the mentioned solution page is down.
Does anyone know how to work around this? I'm using python 2.5.
python setup.py sdist register upload
running register
We need to know who you are, so please choose either:
1. use your existing login,
2. register as a new user,
3. have the server generate a new password for you (and email it to you), or
4. quit
Your selection [default 1]: 1
Username: tschellenbach
Password:
Server response (200): OK
running upload
Submitting dist\django-ogone-1.0.0.zip to http://pypi.python.org/pypi
Upload failed (401): You must be identified to edit package information
| [
"the answer for this seems not very non-windows-specific, give it a try:\naccepted answer It says basically, that you need a file .pypirc with the following section:\n\n[server-login]\nusername:tschellenbach\npassword:******** (the real one)\n\nalso, this is the relevant documentation (about .pypirc):\n\nOn windows... | [
55
] | [] | [] | [
"pypi",
"python"
] | stackoverflow_0003773613_pypi_python.txt |
Q:
Write conditions based on a list
I'm writing an if statement in Python with a lot of OR conditions. Is there an elegant way to do this with a list, within in the condition rather than looping through the list?
In other words, what would be prettier than the following:
if foo == 'a' or foo == 'b' or foo == 'c' or foo == 'd':
I've just taken up Python, and the language has me wanting to write better.
A:
if foo in ('a', 'b', 'c', 'd'):
#...
I will also note that your answer is wrong for several reasons:
You should remove parentheses.. python does need the outer ones and it takes room.
You're using an assignment operator, not an equality operator (=, not ==)
What you meant to write as foo == 'a' or foo == 'b' or ..., what you wrote wasn't quite correct.
A:
if foo in ("a", "b", "c", "d"):
in, of course, works for most containers. You can check if a string contains a substring ("foo" in "foobar"), or if a dict contains a certain key ("a" in {"a": "b"}), or many things like that.
A:
checking_set = set(("a", "b", "c", "d")) # initialisation; do this once
if foo in checking_set: # when you need it
Advantages: (1) give the set of allowable values a name (2) may be faster if the number of entries is large
Edit some timings in response to "usually much slower" when only "a handful of entries" comment:
>python -mtimeit -s"ctnr=('a','b','c','d')" "'a' in ctnr"
10000000 loops, best of 3: 0.148 usec per loop
>python -mtimeit -s"ctnr=('a','b','c','d')" "'d' in ctnr"
1000000 loops, best of 3: 0.249 usec per loop
>python -mtimeit -s"ctnr=('a','b','c','d')" "'x' in ctnr"
1000000 loops, best of 3: 0.29 usec per loop
>python -mtimeit -s"ctnr=set(('a','b','c','d'))" "'a' in ctnr"
10000000 loops, best of 3: 0.157 usec per loop
>python -mtimeit -s"ctnr=set(('a','b','c','d'))" "'d' in ctnr"
10000000 loops, best of 3: 0.158 usec per loop
>python -mtimeit -s"ctnr=set(('a','b','c','d'))" "'x' in ctnr"
10000000 loops, best of 3: 0.159 usec per loop
(Python 2.7, Windows XP)
A:
>>> foo = 6
>>> my_list = list(range(10))
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print any(foo == x for x in my_list)
True
>>> my_list = list(range(0))
>>> print any(foo == x for x in my_list)
False
Alternatively:
>>> foo = 6
>>> my_list = set(range(10))
>>> foo in my_list
True
>>> my_list = set(range(0))
>>> foo in my_list
False
| Write conditions based on a list | I'm writing an if statement in Python with a lot of OR conditions. Is there an elegant way to do this with a list, within in the condition rather than looping through the list?
In other words, what would be prettier than the following:
if foo == 'a' or foo == 'b' or foo == 'c' or foo == 'd':
I've just taken up Python, and the language has me wanting to write better.
| [
"if foo in ('a', 'b', 'c', 'd'):\n #...\n\nI will also note that your answer is wrong for several reasons:\n\nYou should remove parentheses.. python does need the outer ones and it takes room.\nYou're using an assignment operator, not an equality operator (=, not ==)\nWhat you meant to write as foo == 'a' or foo... | [
7,
2,
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003773666_list_python.txt |
Q:
Implement a userEdited signal to QDateTimeEdit?
QLineEdit has a textEdited signal which is emitted whenever the text is changed by user interaction, but not when the text is changed programatically. However, QDateTimeEdit has only a general dateTimeChanged signal that does not distinguish between these two types of changes. Since my app depends on knowing if the field was edited by the user or not, I'm looking for ways to implement it.
My (currently working) strategy was to create an eventFilter to the edit field, intercept key press and mouse wheel events and use them to determine if the field was modified by the user (storing this info in an object), and finally connecting the dateTimeChanged signal to a function that decides if the change was by the user or done programatically. Here are the relevant parts of the code (python):
class UserFilter(QObject):
def __init__(self, parent):
QObject.__init__(self, parent)
self.parent = parent
def eventFilter(self, object, event):
if event.type() == QEvent.KeyPress or event.type() == QEvent.Wheel:
self.parent.edited = True
else:
pass
return False
class DockThumb(QWidget):
def __init__(self, parent):
QWidget.__init__(self, parent)
self.parent = parent
self.edited = False
self.dateedit = QDateTimeEdit(self)
self.userfilter = UserFilter(self)
self.dateedit.installEventFilter(self.userfilter)
...
self.connect(self.dateedit,
SIGNAL('dateTimeChanged(QDateTime)'),
self.edited_or_not)
def edited_or_not(self):
if self.edited:
# User interacted! Go for it.
self.parent.runtimer()
# self.edited returns to False once data is saved.
else:
# User did not edited. Wait.
pass
Is there a more objective way of doing it? I tried subclasssing QDateTimeEdit, but failed to deal with events... Expected user interactions are direct typing, up/down arrow keys to spin through dates and copy/pasting the whole string.
A:
The idiomatic Qt way of achieving this is indeed subclassing QDateTimeEdit and adding the functionality you require. I understand you tried it and "failed to deal with events", but that's a separate issue, and perhaps you should describe those problems - since they should be solvable.
A:
Since I'm not entirely sure about what you are trying to do, I would agree with Eli Bendersky. Short of that, if you know when you will be programatically changing the QDateTimeEdit, set some flag that you can check in the slot handler that will indicate a programatic change is occurring and clear it when you are done.
| Implement a userEdited signal to QDateTimeEdit? | QLineEdit has a textEdited signal which is emitted whenever the text is changed by user interaction, but not when the text is changed programatically. However, QDateTimeEdit has only a general dateTimeChanged signal that does not distinguish between these two types of changes. Since my app depends on knowing if the field was edited by the user or not, I'm looking for ways to implement it.
My (currently working) strategy was to create an eventFilter to the edit field, intercept key press and mouse wheel events and use them to determine if the field was modified by the user (storing this info in an object), and finally connecting the dateTimeChanged signal to a function that decides if the change was by the user or done programatically. Here are the relevant parts of the code (python):
class UserFilter(QObject):
def __init__(self, parent):
QObject.__init__(self, parent)
self.parent = parent
def eventFilter(self, object, event):
if event.type() == QEvent.KeyPress or event.type() == QEvent.Wheel:
self.parent.edited = True
else:
pass
return False
class DockThumb(QWidget):
def __init__(self, parent):
QWidget.__init__(self, parent)
self.parent = parent
self.edited = False
self.dateedit = QDateTimeEdit(self)
self.userfilter = UserFilter(self)
self.dateedit.installEventFilter(self.userfilter)
...
self.connect(self.dateedit,
SIGNAL('dateTimeChanged(QDateTime)'),
self.edited_or_not)
def edited_or_not(self):
if self.edited:
# User interacted! Go for it.
self.parent.runtimer()
# self.edited returns to False once data is saved.
else:
# User did not edited. Wait.
pass
Is there a more objective way of doing it? I tried subclasssing QDateTimeEdit, but failed to deal with events... Expected user interactions are direct typing, up/down arrow keys to spin through dates and copy/pasting the whole string.
| [
"The idiomatic Qt way of achieving this is indeed subclassing QDateTimeEdit and adding the functionality you require. I understand you tried it and \"failed to deal with events\", but that's a separate issue, and perhaps you should describe those problems - since they should be solvable.\n",
"Since I'm not entire... | [
0,
0
] | [] | [] | [
"pyqt4",
"python",
"qt",
"signals"
] | stackoverflow_0003766360_pyqt4_python_qt_signals.txt |
Q:
Read/Write CSV as binary with Python
I just found out that I can save space\ speed up reads of CSV files.
Using the answer of my previous question
How do I create a CSV file from database in Python?
And 'wb' for opens
w = csv.writer(open(Fn,'wb'),dialect='excel')
How can I open all files in a directory and saves all files with the same name as starting name and use 'wb' to reformat all files. I guess convert all CSV's to binary CSV's.
A:
You can't "overwrite a file on the fly". You have two options:
if the files are small enough (smaller than the amount of available RAM by
a comfortable margin), just loop over them (os.listdir makes that loop
easy, or os.walk if you want to catch the whole tree of subdirectories,
not just one directory), and for each, read it in memory first, then
overwrite the on-disk copy.
otherwise, loop over them, and each time write to a new file (e.g. by
appending .new to the name), then move the new file over the old. This
is safer (no risk of running out of memory, no risk of damaging a file if
the computer crashes) but more complicated.
So, what is your situation: small-enough files (and backups for safeguard against computer and disk crashes), in which case I can if you wish show the simple code; or huge multi-GB files -- in which case it will have to be the complex code? Let us know!
| Read/Write CSV as binary with Python | I just found out that I can save space\ speed up reads of CSV files.
Using the answer of my previous question
How do I create a CSV file from database in Python?
And 'wb' for opens
w = csv.writer(open(Fn,'wb'),dialect='excel')
How can I open all files in a directory and saves all files with the same name as starting name and use 'wb' to reformat all files. I guess convert all CSV's to binary CSV's.
| [
"You can't \"overwrite a file on the fly\". You have two options:\n\nif the files are small enough (smaller than the amount of available RAM by\na comfortable margin), just loop over them (os.listdir makes that loop\neasy, or os.walk if you want to catch the whole tree of subdirectories,\nnot just one directory), ... | [
4
] | [] | [] | [
"csv",
"file_io",
"python"
] | stackoverflow_0003773894_csv_file_io_python.txt |
Q:
Django / Python, calling a specific class / function on every user Request
I was looking over the Django documentation on a way to do this but didn't see anything, though I may have missed it as I'm not sure exactly where to look... I want to be able to perform a specific action on every user request, such as instantiating a class and calling one of its functions, however the only way I know of to do this now is to put it in each view function. Is there a better way to do this, any advice is appreciated.
A:
You want to use Django's middleware functionality.
| Django / Python, calling a specific class / function on every user Request | I was looking over the Django documentation on a way to do this but didn't see anything, though I may have missed it as I'm not sure exactly where to look... I want to be able to perform a specific action on every user request, such as instantiating a class and calling one of its functions, however the only way I know of to do this now is to put it in each view function. Is there a better way to do this, any advice is appreciated.
| [
"You want to use Django's middleware functionality.\n"
] | [
6
] | [] | [] | [
"django",
"python",
"request"
] | stackoverflow_0003774005_django_python_request.txt |
Q:
Python vs Lua for embedded scripting/text processing engine
For a project I'm currently working on, I'm looking to embed a scripting engine into my C++ code to allow for some extensibility down the line. The application will require a fair amount of text processing and the use of regular expressions within these scripts.
I know Lua is generally the industry darling when it comes to embedded scripting, but I also know it doesn't support regular expressions (at least out of the box). This is causing me to lean toward python for my language to embed, as it seems to have the best support behind Lua and still offers powerful regex capabilities.
Is this the right choice? Should I be looking at another language? Is there a reason I should give Lua a second look?
A:
if you need specifically what is commonly known as 'regular expressions' (which aren't regular at all), then you have two choices:
go with Python. it's included regexp is similar enough to Perl's and sed/grep
use Lua and an external PCRE library
if, on the other hand, you need any good pattern matching, you can stay with Lua and either:
use Lua's included pattern matching, which aren't in the grep tradition but are quite capable. The missing functionality is subpattern alternatives (|)
use LPEG, which are far more powerful than regexps, and usually faster too.
As you can tell, i'm a big fan of the last. It not only lets you define very complex but deterministic patterns, it's a full grammar tool that you can use to create a whole parser. If you wish, the grammar can be described in a single multi-line string constant, with your own defined hooks to capture data and build your structures.
i've used it to quickly hack a JSON parser, a C call-tree, an xPath library, etc.
A:
Python and C++ integration is greatly helped with boost.python. You may find this much more convenient if those familiar with your C++ source are primarily the ones writing scripts.
Even if the scripters aren't familiar with your particular source, if they are more familiar with C-like syntax (C, C++, etc.), they should find Python easier to use—perhaps only slightly, Lua isn't hard. Good programmers can use a multitude of languages anyway, but you've not given any information about your audience.
Lua is much easier to sandbox than Python, so if you must restrict what scripts can do (e.g. spawn additional processes, read files), that may rule out Python.
A:
Having incorporated Lua in one of my C projects myself, I'll suggest Lua, as this is easier.
But that depends on what your scripting language needs to be capable of. Lua rose to the de-facto scripting language of games. If you need advanced scripting capabilities, you might use Python, but if it's just for easy scripting support, take Lua. From what I've seen, Lua is easier to learn for newbees, that aren't used to scripting.
I'd argue, that Lua is lighter, if you need to have external packages, you can add them, but the point is, the atomic part of Lua, is much smaller than that of Python.
A:
dont forget the grand-daddy of them all - tcl
there is a c++ wrapper for tcl which makes it incredibly easy to embed
i am using it in a current project
in previous (c#) project I used lua over python. In older c# projects I had used python;
I chose lua because the syntax is more normal for average scripter (used to vbscript or javascript). However I will change back to (iron)python for next c# project; lua is just too obscure
For c++ I will always use tcl from now on
EDIT: My new favorite is jint (.net javascriptt interpreter) v easy to use, nice interface. And nobody can complain about the language given that js is the cool language at the moment
| Python vs Lua for embedded scripting/text processing engine | For a project I'm currently working on, I'm looking to embed a scripting engine into my C++ code to allow for some extensibility down the line. The application will require a fair amount of text processing and the use of regular expressions within these scripts.
I know Lua is generally the industry darling when it comes to embedded scripting, but I also know it doesn't support regular expressions (at least out of the box). This is causing me to lean toward python for my language to embed, as it seems to have the best support behind Lua and still offers powerful regex capabilities.
Is this the right choice? Should I be looking at another language? Is there a reason I should give Lua a second look?
| [
"if you need specifically what is commonly known as 'regular expressions' (which aren't regular at all), then you have two choices:\n\ngo with Python. it's included regexp is similar enough to Perl's and sed/grep\nuse Lua and an external PCRE library\n\nif, on the other hand, you need any good pattern matching, yo... | [
19,
7,
5,
4
] | [] | [] | [
"c++",
"embedded_language",
"lua",
"python",
"scripting"
] | stackoverflow_0003774108_c++_embedded_language_lua_python_scripting.txt |
Q:
Making all variables in a scope global or importing a module inside another module
I have a package with two modules in it. One is the __init__ file, and the other is a separate part of the package. If I try from mypackage import separatepart, the code in the __init__ module is run, which will run unneeded code, slowing down the importing by a lot. The code in separate part won't cause any errors, and so users should be able to directly import it without importing the __init__ module.
Since I can't figure out a way to do this, I thought I should include a function in the __init__ file that does everything so nothing would be done directly, but in order to do this, I would need to have any variables set to be global. Is there any way to tell Python that all variables are global in a function, or to not run the __init__ module?
A:
dthat I know of, there is not way to specify that all variables are global but you can import the module while you are in the module. just make sure that you do it in a function that isn't called at the top level, you are playing with infinite recursion here but a simple use should be safe.
#module.py
foo = bar = 0 # global
def init()
import module as m
m.foo = 1
m.bar = 2 # access to globals
if init was called at the top level, then you have infinite recursion but it sounds like the whole point of this is to avoid this code running at the top level, so you should be safe. Since you want to do this in the __init__.py file, just import the top level of the package.
It occurred to me on a walk that there's no problem with recursion here because the top level code will only run once on initial import.
| Making all variables in a scope global or importing a module inside another module | I have a package with two modules in it. One is the __init__ file, and the other is a separate part of the package. If I try from mypackage import separatepart, the code in the __init__ module is run, which will run unneeded code, slowing down the importing by a lot. The code in separate part won't cause any errors, and so users should be able to directly import it without importing the __init__ module.
Since I can't figure out a way to do this, I thought I should include a function in the __init__ file that does everything so nothing would be done directly, but in order to do this, I would need to have any variables set to be global. Is there any way to tell Python that all variables are global in a function, or to not run the __init__ module?
| [
"dthat I know of, there is not way to specify that all variables are global but you can import the module while you are in the module. just make sure that you do it in a function that isn't called at the top level, you are playing with infinite recursion here but a simple use should be safe.\n#module.py\n\nfoo = ba... | [
1
] | [] | [] | [
"global_variables",
"import",
"initialization",
"module",
"python"
] | stackoverflow_0003774510_global_variables_import_initialization_module_python.txt |
Q:
Get data from the meta tags using BeautifulSoup
I am trying to read the description from the meta tag and this is what I used
soup.findAll(name="description")
but it does not work, however, the code below works just fine
soup.findAll(align="center")
How do I read the description from the meta tag in the head of a document?
A:
Yep, name can't be used in keyword-argument form to designate an attribute named name because the name name is already used by BeautifulSoup itself. So use instead:
soup.findAll(attrs={"name":"description"})
That's what the attrs argument is for: passing as a dict those attribute constraints for which you can't use keyword-argument form because their names are Python keyword or otherwise taken by BeautifulSoup itself!
| Get data from the meta tags using BeautifulSoup | I am trying to read the description from the meta tag and this is what I used
soup.findAll(name="description")
but it does not work, however, the code below works just fine
soup.findAll(align="center")
How do I read the description from the meta tag in the head of a document?
| [
"Yep, name can't be used in keyword-argument form to designate an attribute named name because the name name is already used by BeautifulSoup itself. So use instead:\nsoup.findAll(attrs={\"name\":\"description\"})\n\nThat's what the attrs argument is for: passing as a dict those attribute constraints for which you... | [
35
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003774571_beautifulsoup_python.txt |
Q:
Implementing use of 'with object() as f' in custom class in python
I have to open a file-like object in python (it's a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in the destructor. I'm getting weird errors though and I think it has to do with the garbage collector and such, I'm still not used to not knowing exactly when my objects are being deleted =\
The reason I was doing this is because I have to use tcsetattr with a bunch of parameters each time I open it and it gets annoying doing all that all over the place. So I want to implement an inner class to handle all that so I can use it doing
with Meter('/dev/ttyS2') as m:
I was looking online and I couldn't find a really good answer on how the with syntax is implemented. I saw that it uses the __enter__(self) and __exit(self)__ methods. But is all I have to do implement those methods and I can use the with syntax? Or is there more to it?
Is there either an example on how to do this or some documentation on how it's implemented on file objects already that I can look at?
A:
Those methods are pretty much all you need for making the object work with with statement.
In __enter__ you have to return the file object after opening it and setting it up.
In __exit__ you have to close the file object. The code for writing to it will be in the with statement body.
class Meter():
def __init__(self, dev):
self.dev = dev
def __enter__(self):
#ttysetattr etc goes here before opening and returning the file object
self.fd = open(self.dev, MODE)
return self
def __exit__(self, type, value, traceback):
#Exception handling here
close(self.fd)
meter = Meter('dev/tty0')
with meter as m:
#here you work with the file object.
m.fd.read()
A:
Easiest may be to use standard Python library module contextlib:
import contextlib
@contextlib.contextmanager
def themeter(name):
theobj = Meter(name)
try:
yield theobj
finally:
theobj.close() # or whatever you need to do at exit
# usage
with themeter('/dev/ttyS2') as m:
# do what you need with m
m.read()
This doesn't make Meter itself a context manager (and therefore is non-invasive to that class), but rather "decorates" it (not in the sense of Python's "decorator syntax", but rather almost, but not quite, in the sense of the decorator design pattern;-) with a factory function themeter which is a context manager (which the contextlib.contextmanager decorator builds from the "single-yield" generator function you write) -- this makes it so much easier to separate the entering and exiting condition, avoids nesting, &c.
| Implementing use of 'with object() as f' in custom class in python | I have to open a file-like object in python (it's a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in the destructor. I'm getting weird errors though and I think it has to do with the garbage collector and such, I'm still not used to not knowing exactly when my objects are being deleted =\
The reason I was doing this is because I have to use tcsetattr with a bunch of parameters each time I open it and it gets annoying doing all that all over the place. So I want to implement an inner class to handle all that so I can use it doing
with Meter('/dev/ttyS2') as m:
I was looking online and I couldn't find a really good answer on how the with syntax is implemented. I saw that it uses the __enter__(self) and __exit(self)__ methods. But is all I have to do implement those methods and I can use the with syntax? Or is there more to it?
Is there either an example on how to do this or some documentation on how it's implemented on file objects already that I can look at?
| [
"Those methods are pretty much all you need for making the object work with with statement.\nIn __enter__ you have to return the file object after opening it and setting it up.\nIn __exit__ you have to close the file object. The code for writing to it will be in the with statement body.\nclass Meter():\n def __i... | [
155,
62
] | [
"The first Google hit (for me) explains it simply enough:\nhttp://effbot.org/zone/python-with-statement.htm\nand the PEP explains it more precisely (but also more verbosely):\nhttp://www.python.org/dev/peps/pep-0343/\n"
] | [
-11
] | [
"file_io",
"python",
"with_statement"
] | stackoverflow_0003774328_file_io_python_with_statement.txt |
Q:
Can't call method in Python C extension
I'm working on making my first Python C extension, which defines a few functions and custom types. The strange thing is that the custom types are working, but not the regular functions. The top-level MyModule.c file looks like this:
static PyMethodDef MyModule_methods[] = {
{"doStuff", MyModule_doStuff, METH_VARARGS, ""},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef MyModule_module = {
PyModuleDef_HEAD_INIT,
"mymodule",
"Documentation",
-1,
MyModule_methods
};
PyMODINIT_FUNC PyInit_audioDevice(void) {
PyObject *object = PyModule_Create(&MyModule_module);
if(object == NULL) {
return NULL;
}
if(PyType_Ready(&MyCustomType_type) < 0) {
return NULL;
}
Py_INCREF(&MyCustomType_type);
PyModule_AddObject(object, "MyCustomType", (PyObject*)&MyCustomType_type);
return object;
}
I'm building the extension with this setup.py file:
from distutils.core import setup, Extension
setup(name = "mymodule",
version = "1.0",
ext_modules = [Extension("mymodule", ["MyModule.c", "MyCustomType.c", "DoStuff.c"])])
The "DoStuff" file defines its function as such:
static PyObject*
AudioOutputOSX_doStuff(PyObject *self, PyObject *args) {
printf("Hello from doStuff\n");
return Py_None;
}
The funny thing is that the MyCustomType type works fine, as I can instantiate it with:
from mymodule.MyCustomType import MyCustomType
foo = MyCustomType()
And I see my printf() statements from the custom type's new and init methods printed out. However, this code fails:
import mymodule
mymodule.doStuff()
I get the following error:
Traceback (most recent call last):
File "MyModuleTest.py", line 9, in
mymodule.doStuff(buffer)
AttributeError: 'module' object has no attribute 'doStuff'
What is going on here? Do I have some error in my module's method declarations somehow?
A:
The fact that this code works:
from mymodule.MyCustomType import MyCustomType
is absolutely astonishing and tells us that mymodule is actually a package, and MyCustomType a module within that package (which contains a type or class by the same name).
Therefore, to call the function, you'll obviously have to do:
from mymodule import MyCustomType as therealmodule
therealmodule.doStuff()
or the like -- assuming the info you give us, particularly that first line of code which I've quoted from code you say works, is indeed exact.
A:
What do you see if you do import mymodule followed by print(dir(mymodule)) ?
Is your module really large enough to be split over 3 files? Splitting does add a whole lot of complexity with the linking ... name-mangling, perhaps?
AudioOutputOSX_doStuff versus MyModule_doStuff ... a real problem, or just a question-editing problem?
What platform, what compiler?
| Can't call method in Python C extension | I'm working on making my first Python C extension, which defines a few functions and custom types. The strange thing is that the custom types are working, but not the regular functions. The top-level MyModule.c file looks like this:
static PyMethodDef MyModule_methods[] = {
{"doStuff", MyModule_doStuff, METH_VARARGS, ""},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef MyModule_module = {
PyModuleDef_HEAD_INIT,
"mymodule",
"Documentation",
-1,
MyModule_methods
};
PyMODINIT_FUNC PyInit_audioDevice(void) {
PyObject *object = PyModule_Create(&MyModule_module);
if(object == NULL) {
return NULL;
}
if(PyType_Ready(&MyCustomType_type) < 0) {
return NULL;
}
Py_INCREF(&MyCustomType_type);
PyModule_AddObject(object, "MyCustomType", (PyObject*)&MyCustomType_type);
return object;
}
I'm building the extension with this setup.py file:
from distutils.core import setup, Extension
setup(name = "mymodule",
version = "1.0",
ext_modules = [Extension("mymodule", ["MyModule.c", "MyCustomType.c", "DoStuff.c"])])
The "DoStuff" file defines its function as such:
static PyObject*
AudioOutputOSX_doStuff(PyObject *self, PyObject *args) {
printf("Hello from doStuff\n");
return Py_None;
}
The funny thing is that the MyCustomType type works fine, as I can instantiate it with:
from mymodule.MyCustomType import MyCustomType
foo = MyCustomType()
And I see my printf() statements from the custom type's new and init methods printed out. However, this code fails:
import mymodule
mymodule.doStuff()
I get the following error:
Traceback (most recent call last):
File "MyModuleTest.py", line 9, in
mymodule.doStuff(buffer)
AttributeError: 'module' object has no attribute 'doStuff'
What is going on here? Do I have some error in my module's method declarations somehow?
| [
"The fact that this code works:\nfrom mymodule.MyCustomType import MyCustomType\n\nis absolutely astonishing and tells us that mymodule is actually a package, and MyCustomType a module within that package (which contains a type or class by the same name). \nTherefore, to call the function, you'll obviously have to... | [
2,
0
] | [] | [] | [
"c",
"python",
"python_extensions"
] | stackoverflow_0003774291_c_python_python_extensions.txt |
Q:
Cycle of multiple iterables?
Given:
x = ['a','b','c','d','e']
y = ['1','2','3']
I'd like iterate resulting in:
a, 1
b, 2
c, 3
d, 1
e, 2
a, 3
b, 1
... where the two iterables cycle independently until a given count.
Python's cycle(iterable) can do this w/ 1 iterable. Functions such as map and itertools.izip_longest can take a function to handle None, but do not provide the built-in auto-repeat.
A not-so-crafty idea is to just concatenate each list to a certain size from which I can iterate evenly. (Boooo!)
Suggestions? Thanks in advance.
A:
The simplest way to do this is in cyclezip1 below. It is fast enough for most purposes.
import itertools
def cyclezip1(it1, it2, count):
pairs = itertools.izip(itertools.cycle(iter1),
itertools.cycle(iter2))
return itertools.islice(pairs, 0, count)
Here is another implementation of it that is about twice as fast when count is significantly larger than the least common multiple of it1 and it2.
import fractions
def cyclezip2(co1, co2, count):
l1 = len(co1)
l2 = len(co2)
lcm = l1 * l2 / float(fractions.gcd(l1, l2))
pairs = itertools.izip(itertools.cycle(co1),
itertools.cycle(co2))
pairs = itertools.islice(pairs, 0, lcm)
pairs = itertools.cycle(pairs)
return itertools.islice(pairs, 0, count)
here we take advantage of the fact that pairs will cycle after the first n of them where n is the least common mutliple of len(it1) and len(it2). This of course assumes that the iterables are collections so that asking for the length of them makes any sense. A further optimization that can be made is to
replace the line
pairs = itertools.islice(pairs, 0, lcm)
with
pairs = list(itertools.islice(pairs, 0, lcm))
This is not nearly as dramatic of an improvement (about 2% in my testing) and not nearly as consistent. it also requires more memory. If it1 and it2 were known in advance to be small enough so that the additional memory was negligible, then you could squeeze that extra performance out of it.
It's interesting to note that the obvious thing to do in the case of a collection is about four times slower than the first option presented.
def cyclezip3(co1, co2, count):
l1 = len(co1)
l2 = len(co2)
return ((co1[i%l1], co2[i%l2]) for i in xrange(count))
A:
import itertools
x = ['a','b','c','d','e']
y = ['1','2','3']
for a, b in itertools.izip(itertools.cycle(x), itertools.cycle(y)):
print a, b
| Cycle of multiple iterables? | Given:
x = ['a','b','c','d','e']
y = ['1','2','3']
I'd like iterate resulting in:
a, 1
b, 2
c, 3
d, 1
e, 2
a, 3
b, 1
... where the two iterables cycle independently until a given count.
Python's cycle(iterable) can do this w/ 1 iterable. Functions such as map and itertools.izip_longest can take a function to handle None, but do not provide the built-in auto-repeat.
A not-so-crafty idea is to just concatenate each list to a certain size from which I can iterate evenly. (Boooo!)
Suggestions? Thanks in advance.
| [
"The simplest way to do this is in cyclezip1 below. It is fast enough for most purposes. \nimport itertools\n\ndef cyclezip1(it1, it2, count):\n pairs = itertools.izip(itertools.cycle(iter1),\n itertools.cycle(iter2))\n return itertools.islice(pairs, 0, count)\n\nHere is another ... | [
10,
7
] | [] | [] | [
"python"
] | stackoverflow_0003775027_python.txt |
Q:
Python multiprocessing Pool.map is calling aquire?
I have a numpy.array of 640x480 images, each of which is 630 images long.
The total array is thus 630x480x640.
I want to generate an average image, as well as compute the standard deviation for
each pixel across all 630 images.
This is easily accomplished by
avg_image = numpy.mean(img_array, axis=0)
std_image = numpy.std(img_array, axis=0)
However, since I'm running this for 50 or so such arrays, and have a
8 core/16 thread workstation, I figured I'd get greedy and parallelize things with
multiprocessing.Pool.
So I did the following:
def chunk_avg_map(chunk):
#do the processing
sig_avg = numpy.mean(chunk, axis=0)
sig_std = numpy.std(chunk, axis=0)
return([sig_avg, sig_std])
def chunk_avg(img_data):
#take each row of the image
chunks = [img_data[:,i,:] for i in range(len(img_data[0]))]
pool = multiprocessing.Pool()
result = pool.map(chunk_avg_map, chunks)
pool.close()
pool.join()
return result
However, I saw only a small speedup. By putting print statements in chunk_avg_map I was able to determine that only one or two processes are being launched at a time, rather than
16 (as I would expect).
I then ran my code through cProfile in iPython:
%prun current_image_anal.main()
The result indicated that by far the most time was spent in calls to acquire:
ncalls tottime percall cumtime percall filename:lineno(function)
1527 309.755 0.203 309.755 0.203 {built-in method acquire}
Which I understand to be something to do with locking, but I don't understand why my code would be doing that. Does anyone have any ideas?
[EDIT] As requested, here is a run-able script which demonstrates the problem.
You can profile it by whatever means you like, but when I did I found that the lions
share of the time was taken up with calls to acquire, rather than mean or std as I would
have expected.
#!/usr/bin/python
import numpy
import multiprocessing
def main():
fake_images = numpy.random.randint(0,2**14,(630,480,640))
chunk_avg(fake_images)
def chunk_avg_map(chunk):
#do the processing
sig_avg = numpy.mean(chunk, axis=0)
sig_std = numpy.std(chunk, axis=0)
return([sig_avg, sig_std])
def chunk_avg(img_data):
#take each row of the image
chunks = [img_data[:,i,:] for i in range(len(img_data[0]))]
pool = multiprocessing.Pool()
result = pool.map(chunk_avg_map, chunks)
pool.close()
pool.join()
return result
if __name__ == "__main__":
main()
A:
I believe the problem is that the amount of CPU time it takes to process each chunk is small relative to the amount of time it takes to copy the input and output to and from the worker processes. I modified your example code to split the output into 16 even chunks and to print out the difference in CPU time (time.clock()) between when a run of chunk_avg_map() begins and ends. On my system each individual run took slightly under a second of CPU time, but the overall CPU time usage for the process group (system + user time) was more than 38 seconds. An apparent 0.75 second copying overhead per chunk leaves your program performing calculations only slightly faster than multiprocessing can deliver the data, leading to only two worker processes ever being utilize at once.
If I modify the code such that the "input data" is just xrange(16) and build the random array within chunk_avg_map() then I see the sysem + user time drop to around 19 seconds and all 16 worker processes executing at the same time.
| Python multiprocessing Pool.map is calling aquire? | I have a numpy.array of 640x480 images, each of which is 630 images long.
The total array is thus 630x480x640.
I want to generate an average image, as well as compute the standard deviation for
each pixel across all 630 images.
This is easily accomplished by
avg_image = numpy.mean(img_array, axis=0)
std_image = numpy.std(img_array, axis=0)
However, since I'm running this for 50 or so such arrays, and have a
8 core/16 thread workstation, I figured I'd get greedy and parallelize things with
multiprocessing.Pool.
So I did the following:
def chunk_avg_map(chunk):
#do the processing
sig_avg = numpy.mean(chunk, axis=0)
sig_std = numpy.std(chunk, axis=0)
return([sig_avg, sig_std])
def chunk_avg(img_data):
#take each row of the image
chunks = [img_data[:,i,:] for i in range(len(img_data[0]))]
pool = multiprocessing.Pool()
result = pool.map(chunk_avg_map, chunks)
pool.close()
pool.join()
return result
However, I saw only a small speedup. By putting print statements in chunk_avg_map I was able to determine that only one or two processes are being launched at a time, rather than
16 (as I would expect).
I then ran my code through cProfile in iPython:
%prun current_image_anal.main()
The result indicated that by far the most time was spent in calls to acquire:
ncalls tottime percall cumtime percall filename:lineno(function)
1527 309.755 0.203 309.755 0.203 {built-in method acquire}
Which I understand to be something to do with locking, but I don't understand why my code would be doing that. Does anyone have any ideas?
[EDIT] As requested, here is a run-able script which demonstrates the problem.
You can profile it by whatever means you like, but when I did I found that the lions
share of the time was taken up with calls to acquire, rather than mean or std as I would
have expected.
#!/usr/bin/python
import numpy
import multiprocessing
def main():
fake_images = numpy.random.randint(0,2**14,(630,480,640))
chunk_avg(fake_images)
def chunk_avg_map(chunk):
#do the processing
sig_avg = numpy.mean(chunk, axis=0)
sig_std = numpy.std(chunk, axis=0)
return([sig_avg, sig_std])
def chunk_avg(img_data):
#take each row of the image
chunks = [img_data[:,i,:] for i in range(len(img_data[0]))]
pool = multiprocessing.Pool()
result = pool.map(chunk_avg_map, chunks)
pool.close()
pool.join()
return result
if __name__ == "__main__":
main()
| [
"I believe the problem is that the amount of CPU time it takes to process each chunk is small relative to the amount of time it takes to copy the input and output to and from the worker processes. I modified your example code to split the output into 16 even chunks and to print out the difference in CPU time (time... | [
7
] | [] | [] | [
"multiprocessing",
"profiling",
"python"
] | stackoverflow_0003771875_multiprocessing_profiling_python.txt |
Q:
Using file descriptors to communicate between processes
I have the following python code:
import pty
import subprocess
os=subprocess.os
from subprocess import PIPE
import time
import resource
pipe=subprocess.Popen(["cat"], stdin=PIPE, stdout=PIPE, stderr=PIPE, \
close_fds=True)
skip=[f.fileno() for f in (pipe.stdin, pipe.stdout, pipe.stderr)]
pid, child_fd = pty.fork()
if(pid==0):
max_fd=resource.getrlimit(resource.RLIMIT_NOFILE)[0]
fd=3
while fd<max_fd:
if(fd not in skip):
try:
os.close(fd)
except OSError:
pass
fd+=1
enviroment=os.environ.copy()
enviroment.update({"FD": str(pipe.stdin.fileno())})
os.execvpe("zsh", ["-i", "-s"], enviroment)
else:
os.write(child_fd, "echo a >&$FD\n")
time.sleep(1)
print pipe.stdout.read(2)
How can I rewrite it so that it will not use Popen and cat? I need a way to pass data from a shell function running in the interactive shell that will not mix with data created by other functions (so I cannot use stdout or stderr).
A:
Ok, I think I've got a handle on your question now, and see two different approaches you could take.
If you absolutely want to provide the shell in the child process with an already-open file descriptor, then you can replace the Popen() of cat with a call to os.pipe(). That will give you a connected pair of real file descriptors (not Python file objects). Anything written to the second file descriptor can be read from the first, replacing your jury-rigged cat-pipe. (Although "cat-pipe" is fun to say...). A socket pair (socket.socketpair()) can also be used to achieve the same end if you need a bidirectional pair.
Alternatively, you could simplify your life even further by using a named pipe (aka FIFO). If you aren't familiar with the facility, a named pipe is a uni-directional pipe located in the filesystem namespace. The os.mkfifo() function will create the pipe on the filesystem. You can then open the pipe for reading in your primary process and open it for writing / direct output to it from your shell child process. This should simplify your code and open the option of using an existing library like Pexpect to interact with the shell.
| Using file descriptors to communicate between processes | I have the following python code:
import pty
import subprocess
os=subprocess.os
from subprocess import PIPE
import time
import resource
pipe=subprocess.Popen(["cat"], stdin=PIPE, stdout=PIPE, stderr=PIPE, \
close_fds=True)
skip=[f.fileno() for f in (pipe.stdin, pipe.stdout, pipe.stderr)]
pid, child_fd = pty.fork()
if(pid==0):
max_fd=resource.getrlimit(resource.RLIMIT_NOFILE)[0]
fd=3
while fd<max_fd:
if(fd not in skip):
try:
os.close(fd)
except OSError:
pass
fd+=1
enviroment=os.environ.copy()
enviroment.update({"FD": str(pipe.stdin.fileno())})
os.execvpe("zsh", ["-i", "-s"], enviroment)
else:
os.write(child_fd, "echo a >&$FD\n")
time.sleep(1)
print pipe.stdout.read(2)
How can I rewrite it so that it will not use Popen and cat? I need a way to pass data from a shell function running in the interactive shell that will not mix with data created by other functions (so I cannot use stdout or stderr).
| [
"Ok, I think I've got a handle on your question now, and see two different approaches you could take.\nIf you absolutely want to provide the shell in the child process with an already-open file descriptor, then you can replace the Popen() of cat with a call to os.pipe(). That will give you a connected pair of real... | [
1
] | [] | [] | [
"file_descriptor",
"ipc",
"python",
"zsh"
] | stackoverflow_0003769048_file_descriptor_ipc_python_zsh.txt |
Q:
Numeric variable scope in Python closure (Python v2.5.2)
I have a nested function where I am trying to access variables assigned in the parent scope. From the first line of the next() function I can see that path, and nodes_done are assigned as expected. distance, current, and probability_left have no value and are causing a NameError to be thrown.
What am I doing wrong here? How can I access and modify the values of current, distance, and probability_left from the next() function?
def cheapest_path(self):
path = []
current = 0
distance = 0
nodes_done = [False for _ in range(len(self.graph.nodes))]
probability_left = sum(self.graph.probabilities)
def next(dest):
log('next: %s -> %s distance(%.2f), nodes_done(%s), probability_left(%.2f)' % (distance,self.graph.nodes[current],self.graph.nodes[dest],str(nodes_done),probability_left))
path.append((current, distance, nodes_done, probability_left))
probability_left -= self.graph.probabilities[current]
nodes_done[current] = True
distance = self.graph.shortest_path[current][dest]
current = dest
def back():
current,nodes_done,probability_left = path.pop()
A:
The way Python's nested scopes work, you can never assign to a variable in the parent scope, unless it's global (via the global keyword). This changes in Python 3 (with the addition of nonlocal), but with 2.x you're stuck.
Instead, you have to sort of work around this by using a datatype which is stored by reference:
def A():
foo = [1]
def B():
foo[0] = 2 # since foo is a list, modifying it here modifies the referenced list
Note that this is why your list variables work - they're stored by reference, and thus modifying the list modifies the original referenced list. If you tried to do something like path = [] inside your nested function, it wouldn't work because that would be actually assigning to path (which Python would interpret as creating a new local variable path inside the nested function that shadows the parent's path).
One option that is sometimes used is to just keep all of the things that you want to persist down into the nested scope in a dict:
def A():
state = {
'path': [],
'current': 0,
# ...
}
def B():
state['current'] = 3
A:
The short answer is that python does not have proper lexical scoping support. If it did, there would have to be more syntax to support the behavior (i.e. a var/def/my keyword to declare the variable scope).
Barring actual lexical scoping, the best you can do is store the data in an environment data structure. One simple example would be a list, e.g.:
def cheapest_path(self):
path = []
path_info = [0, 0]
nodes_done = [False for _ in range(len(self.graph.nodes))]
probability_left = sum(self.graph.probabilities)
def next(dest):
distance, current = path_info
log('next: %s -> %s distance(%.2f), nodes_done(%s), probability_left(%.2f)' % (distance,self.graph.nodes[current],self.graph.nodes[dest],str(nodes_done),probability_left))
path.append((current, distance, nodes_done, probability_left))
probability_left -= self.graph.probabilities[current]
nodes_done[current] = True
path_info[0] = self.graph.shortest_path[current][dest]
path_info[1] = dest
def back():
current,nodes_done,probability_left = path.pop()
You can do this or do inspect magic. For more history on this read this thread.
A:
If you happen to be working with Python 3, you can use the nonlocal statement (documentation) to make those variables exist in the current scope, e.g.:
def next(dest):
nonlocal distance, current, probability_left
...
| Numeric variable scope in Python closure (Python v2.5.2) | I have a nested function where I am trying to access variables assigned in the parent scope. From the first line of the next() function I can see that path, and nodes_done are assigned as expected. distance, current, and probability_left have no value and are causing a NameError to be thrown.
What am I doing wrong here? How can I access and modify the values of current, distance, and probability_left from the next() function?
def cheapest_path(self):
path = []
current = 0
distance = 0
nodes_done = [False for _ in range(len(self.graph.nodes))]
probability_left = sum(self.graph.probabilities)
def next(dest):
log('next: %s -> %s distance(%.2f), nodes_done(%s), probability_left(%.2f)' % (distance,self.graph.nodes[current],self.graph.nodes[dest],str(nodes_done),probability_left))
path.append((current, distance, nodes_done, probability_left))
probability_left -= self.graph.probabilities[current]
nodes_done[current] = True
distance = self.graph.shortest_path[current][dest]
current = dest
def back():
current,nodes_done,probability_left = path.pop()
| [
"The way Python's nested scopes work, you can never assign to a variable in the parent scope, unless it's global (via the global keyword). This changes in Python 3 (with the addition of nonlocal), but with 2.x you're stuck.\nInstead, you have to sort of work around this by using a datatype which is stored by refere... | [
4,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003775213_python.txt |
Q:
How to use Scrapy
I would like to know how can I start a crawler based on Scrapy. I installed the tool via apt-get install and I tried to run an example:
/usr/share/doc/scrapy/examples/googledir/googledir$ scrapy list
directory.google.com
/usr/share/doc/scrapy/examples/googledir/googledir$ scrapy crawl
I hacked the code from spiders/google_directory.py but it seems that it is not executed, because I don't see any prints that I inserted. I read their documentation, but I found nothing related to this; do you have any ideas?
Also, if you think that for crawling a website I should use other tools, please let me know. I'm not experienced with Python tools and Python is a must.
Thanks!
A:
EveryBlock.com released some quality scraping code using lxml, urllib2 and Django as their stack.
Scraperwiki.com is inspirational, full of examples of python scrapers.
Simple example with cssselect:
from lxml.html import fromstring
dom = fromstring('<html... ...')
navigation_links = [a.get('href') for a in htm.cssselect('#navigation a')]
A:
You missed the spider name in the crawl command. Use:
$ scrapy crawl directory.google.com
Also, I suggest you copy the example project to your home, instead of working in the /usr/share/doc/scrapy/examples/ directory, so you can modify it and play with it:
$ cp -r /usr/share/doc/scrapy/examples/googledir ~
$ cd ~/googledir
$ scrapy crawl directory.google.com
| How to use Scrapy | I would like to know how can I start a crawler based on Scrapy. I installed the tool via apt-get install and I tried to run an example:
/usr/share/doc/scrapy/examples/googledir/googledir$ scrapy list
directory.google.com
/usr/share/doc/scrapy/examples/googledir/googledir$ scrapy crawl
I hacked the code from spiders/google_directory.py but it seems that it is not executed, because I don't see any prints that I inserted. I read their documentation, but I found nothing related to this; do you have any ideas?
Also, if you think that for crawling a website I should use other tools, please let me know. I'm not experienced with Python tools and Python is a must.
Thanks!
| [
"EveryBlock.com released some quality scraping code using lxml, urllib2 and Django as their stack.\nScraperwiki.com is inspirational, full of examples of python scrapers.\nSimple example with cssselect:\nfrom lxml.html import fromstring\n\ndom = fromstring('<html... ...')\nnavigation_links = [a.get('href') for a in... | [
7,
7
] | [] | [] | [
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0003773035_python_scrapy_web_crawler.txt |
Q:
Statistical accumulator in Python
An statistical accumulator allows one to perform incremental calculations. For instance, for computing the arithmetic mean of a stream of numbers given at arbitrary times one could make an object which keeps track of the current number of items given, n and their sum, sum. When one requests the mean, the object simply returns sum/n.
An accumulator like this allows you to compute incrementally in the sense that, when given a new number, you don't need to recompute the entire sum and count.
Similar accumulators can be written for other statistics (cf. boost library for a C++ implementation).
How would you implement accumulators in Python? The code I came up with is:
class Accumulator(object):
"""
Used to accumulate the arithmetic mean of a stream of
numbers. This implementation does not allow to remove items
already accumulated, but it could easily be modified to do
so. also, other statistics could be accumulated.
"""
def __init__(self):
# upon initialization, the numnber of items currently
# accumulated (_n) and the total sum of the items acumulated
# (_sum) are set to zero because nothing has been accumulated
# yet.
self._n = 0
self._sum = 0.0
def add(self, item):
# the 'add' is used to add an item to this accumulator
try:
# try to convert the item to a float. If you are
# successful, add the float to the current sum and
# increase the number of accumulated items
self._sum += float(item)
self._n += 1
except ValueError:
# if you fail to convert the item to a float, simply
# ignore the exception (pass on it and do nothing)
pass
@property
def mean(self):
# the property 'mean' returns the current mean accumulated in
# the object
if self._n > 0:
# if you have more than zero items accumulated, then return
# their artithmetic average
return self._sum / self._n
else:
# if you have no items accumulated, return None (you could
# also raise an exception)
return None
# using the object:
# Create an instance of the object "Accumulator"
my_accumulator = Accumulator()
print my_accumulator.mean
# prints None because there are no items accumulated
# add one (a number)
my_accumulator.add(1)
print my_accumulator.mean
# prints 1.0
# add two (a string - it will be converted to a float)
my_accumulator.add('2')
print my_accumulator.mean
# prints 1.5
# add a 'NA' (will be ignored because it cannot be converted to float)
my_accumulator.add('NA')
print my_accumulator.mean
# prints 1.5 (notice that it ignored the 'NA')
Interesting design questions arise:
How to make the accumulator
thread-safe?
How to safely remove
items?
How to architect in a way
that allows other statistics to be
plugged in easily (a factory for statistics)
A:
For a generalized, threadsafe higher-level function, you could use something like the following in combination with the Queue.Queue class and some other bits:
from Queue import Empty
def Accumulator(f, q, storage):
"""Yields successive values of `f` over the accumulation of `q`.
`f` should take a single iterable as its parameter.
`q` is a Queue.Queue or derivative.
`storage` is a persistent sequence that provides an `append` method.
`collections.deque` may be particularly useful, but a `list` is quite acceptable.
>>> from Queue import Queue
>>> from collections import deque
>>> from threading import Thread
>>> def mean(it):
... vals = tuple(it)
... return sum(it) / len(it)
>>> value_queue = Queue()
>>> LastThreeAverage = Accumulator(mean, value_queue, deque((), 3))
>>> def add_to_queue(it, queue):
... for value in it:
... value_queue.put(value)
>>> putting_thread = Thread(target=add_to_queue,
... args=(range(0, 12, 2), value_queue))
>>> putting_thread.start()
>>> list(LastThreeAverage)
[0, 1, 2, 4, 6, 8]
"""
try:
while True:
storage.append(q.get(timeout=0.1))
q.task_done()
yield f(storage)
except Empty:
pass
This generator function evades most of its purported responsibility by delegating it to other entities:
It relies on Queue.Queue to supply its source elements in a thread-safe manner
A collections.deque object can be passed in as the value of the storage parameter; this provides, among other things, a convenient way to only use the last n (in this case 3) values
The function itself (in this case mean) is passed as a parameter. This will result in less-than-optimally efficient code in some cases, but is readily applied to all sorts of situations.
Note that there is a possibility of the accumulator timing out if your producer thread takes longer than 0.1 seconds per value. This is easily remedied by passing a longer timeout or by removing the timeout parameter entirely. In the latter case the function will block indefinitely at the end of the queue; this usage makes more sense in a case where it's being used in a sub thread (usually a daemon thread). Of course you can also parametrize the arguments that are passed to q.get as a fourth argument to Accumulator.
If you want to communicate end of queue, i.e. that there are no more values to come, from the producer thread (here putting_thread), you can pass and check for a sentinel value or use some other method. There is more info in this thread; I opted to write a subclass of Queue.Queue called CloseableQueue that provides a close method.
There are various other ways you could customize the behaviour of such a function, for example by limiting the queue size; this is just an example of usage.
edit
As mentioned above, this loses some efficiency because of the necessity of recalculation and also, I think, doesn't really answer your question.
A generator function can also accept values through its send method. So you can write a mean generator function like
def meangen():
"""Yields the accumulated mean of sent values.
>>> g = meangen()
>>> g.send(None) # Initialize the generator
>>> g.send(4)
4.0
>>> g.send(10)
7.0
>>> g.send(-2)
4.0
"""
sum = yield(None)
count = 1
while True:
sum += yield(sum / float(count))
count += 1
Here the yield expression is both bringing values —the arguments to send— into the function, while simultaneously passing the calculated values out as the return value of send.
You can pass the generator returned by a call to that function to a more optimizable accumulator generator function like this one:
def EfficientAccumulator(g, q):
"""Similar to Accumulator but sends values to a generator `g`.
>>> from Queue import Queue
>>> from threading import Thread
>>> value_queue = Queue()
>>> g = meangen()
>>> g.send(None)
>>> mean_accumulator = EfficientAccumulator(g, value_queue)
>>> def add_to_queue(it, queue):
... for value in it:
... value_queue.put(value)
>>> putting_thread = Thread(target=add_to_queue,
... args=(range(0, 12, 2), value_queue))
>>> putting_thread.start()
>>> list(mean_accumulator)
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
try:
while True:
yield(g.send(q.get(timeout=0.1)))
q.task_done()
except Empty:
pass
A:
If I were doing this in Python, there are two things I would do differently:
Separate out the functionality of each accumulator.
Not use @property in any way you did.
For the first one, I would likely want to come up with an API for performing an accumulation, perhaps something like:
def add(self, num) # add a number
def compute(self) # compute the value of the accumulator
Then I would create a AccumulatorRegistry that holds onto these accumulators, and allows the user to call actions and add to all of them. The code may look like:
class Accumulators(object):
_accumulator_library = {}
def __init__(self):
self.accumulator_library = {}
for key, value in Accumulators._accumulator_library.items():
self.accumulator_library[key] = value()
@staticmethod
def register(name, accumulator):
Accumulators._accumulator_library[name] = accumulator
def add(self, num):
for accumulator in self.accumulator_library.values():
accumulator.add(num)
def compute(self, name):
self.accumulator_library[name].compute()
@staticmethod
def register_decorator(name):
def _inner(cls):
Accumulators.register(name, cls)
return cls
@Accumulators.register_decorator("Mean")
class Mean(object):
def __init__(self):
self.total = 0
self.count = 0
def add(self, num):
self.count += 1
self.total += num
def compute(self):
return self.total / float(self.count)
I should probably speak to your thread-safe question. Python's GIL protects you from a lot of threading issues. There are a few things you may way to do to protect yourself though:
If these objects are localized to one thread, use threading.local
If not, you can wrap the operations in a lock, using the with context syntax to deal with holding the lock for you.
| Statistical accumulator in Python | An statistical accumulator allows one to perform incremental calculations. For instance, for computing the arithmetic mean of a stream of numbers given at arbitrary times one could make an object which keeps track of the current number of items given, n and their sum, sum. When one requests the mean, the object simply returns sum/n.
An accumulator like this allows you to compute incrementally in the sense that, when given a new number, you don't need to recompute the entire sum and count.
Similar accumulators can be written for other statistics (cf. boost library for a C++ implementation).
How would you implement accumulators in Python? The code I came up with is:
class Accumulator(object):
"""
Used to accumulate the arithmetic mean of a stream of
numbers. This implementation does not allow to remove items
already accumulated, but it could easily be modified to do
so. also, other statistics could be accumulated.
"""
def __init__(self):
# upon initialization, the numnber of items currently
# accumulated (_n) and the total sum of the items acumulated
# (_sum) are set to zero because nothing has been accumulated
# yet.
self._n = 0
self._sum = 0.0
def add(self, item):
# the 'add' is used to add an item to this accumulator
try:
# try to convert the item to a float. If you are
# successful, add the float to the current sum and
# increase the number of accumulated items
self._sum += float(item)
self._n += 1
except ValueError:
# if you fail to convert the item to a float, simply
# ignore the exception (pass on it and do nothing)
pass
@property
def mean(self):
# the property 'mean' returns the current mean accumulated in
# the object
if self._n > 0:
# if you have more than zero items accumulated, then return
# their artithmetic average
return self._sum / self._n
else:
# if you have no items accumulated, return None (you could
# also raise an exception)
return None
# using the object:
# Create an instance of the object "Accumulator"
my_accumulator = Accumulator()
print my_accumulator.mean
# prints None because there are no items accumulated
# add one (a number)
my_accumulator.add(1)
print my_accumulator.mean
# prints 1.0
# add two (a string - it will be converted to a float)
my_accumulator.add('2')
print my_accumulator.mean
# prints 1.5
# add a 'NA' (will be ignored because it cannot be converted to float)
my_accumulator.add('NA')
print my_accumulator.mean
# prints 1.5 (notice that it ignored the 'NA')
Interesting design questions arise:
How to make the accumulator
thread-safe?
How to safely remove
items?
How to architect in a way
that allows other statistics to be
plugged in easily (a factory for statistics)
| [
"For a generalized, threadsafe higher-level function, you could use something like the following in combination with the Queue.Queue class and some other bits:\nfrom Queue import Empty\n\ndef Accumulator(f, q, storage):\n \"\"\"Yields successive values of `f` over the accumulation of `q`.\n\n `f` should take ... | [
3,
1
] | [] | [] | [
"accumulator",
"oop",
"python",
"statistics"
] | stackoverflow_0003774315_accumulator_oop_python_statistics.txt |
Q:
Dealing with special floating point values in Python
I am writing a simple app that takes a bunch of numerical inputs and calculates a set of results. (The app is in PyGTK but I don't think that's relevant.)
My problem is that if I want to just have NaN's and Inf's propagated through, then in every calculation I need to do something like:
# At the top of the module
nan = float("nan")
inf = float("inf")
try:
res = (a + b) / (0.1*c + d)
except ZeroDivisionError:
# replicate every little subtlety of IEEE 754 here
except OverflowError:
# replicate every little subtlety of IEEE 754 here again
...or, of course, pre-empt it for every calculation:
numerator = a + b
denominator = 0.1*c + d
if denominator == 0:
# etc
elif math.isnan(numerator):
# *sigh*
How can I deal with this sanely in Python 2.6? Do I really need to install a massive 3rd-party module (numpy, scipy) on every target machine just to do IEEE 754 arithmetic? Or is there a simpler way?
A:
No, Python's built-in math raises exceptions for errors rather than returning them as NaN and INF. You'll need to use a library or your own code if you don't want this behavior.
(Thought I'd give the simple answer, since too many questions where the answer is "sorry, no" simply don't get answered.)
| Dealing with special floating point values in Python | I am writing a simple app that takes a bunch of numerical inputs and calculates a set of results. (The app is in PyGTK but I don't think that's relevant.)
My problem is that if I want to just have NaN's and Inf's propagated through, then in every calculation I need to do something like:
# At the top of the module
nan = float("nan")
inf = float("inf")
try:
res = (a + b) / (0.1*c + d)
except ZeroDivisionError:
# replicate every little subtlety of IEEE 754 here
except OverflowError:
# replicate every little subtlety of IEEE 754 here again
...or, of course, pre-empt it for every calculation:
numerator = a + b
denominator = 0.1*c + d
if denominator == 0:
# etc
elif math.isnan(numerator):
# *sigh*
How can I deal with this sanely in Python 2.6? Do I really need to install a massive 3rd-party module (numpy, scipy) on every target machine just to do IEEE 754 arithmetic? Or is there a simpler way?
| [
"No, Python's built-in math raises exceptions for errors rather than returning them as NaN and INF. You'll need to use a library or your own code if you don't want this behavior.\n(Thought I'd give the simple answer, since too many questions where the answer is \"sorry, no\" simply don't get answered.)\n"
] | [
2
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0003775513_floating_point_python.txt |
Q:
Writing a parser for regular expressions
Even after years of programming, I'm ashamed to say that I've never really fully grasped regular expressions. In general, when a problem calls for a regex, I can usually (after a bunch of referring to syntax) come up with an appropriate one, but it's a technique that I find myself using increasingly often.
So, to teach myself and understand regular expressions properly, I've decided to do what I always do when trying to learn something; i.e., try to write something ambitious that I'll probably abandon as soon as I feel I've learnt enough.
To this end, I want to write a regular expression parser in Python. In this case, "learn enough" means that I want to implement a parser that can understand Perl's extended regex syntax completely. However, it doesn't have to be the most efficient parser or even necessarily usable in the real-world. It merely has to correctly match or fail to match a pattern in a string.
The question is, where do I start? I know almost nothing about how regexes are parsed and interpreted apart from the fact that it involves a finite state automaton in some way. Any suggestions for how to approach this rather daunting problem would be much appreciated.
EDIT: I should clarify that while I'm going to implement the regex parser in Python, I'm not overly fussed about what programming language the examples or articles are written in. As long as it's not in Brainfuck, I will probably understand enough of it to make it worth my while.
A:
Writing an implementation of a regular expression engine is indeed a quite complex task.
But if you are interested in how to do it, even if you can't understand enough of the details to actually implement it, I would recommend that you at least look at this article:
Regular Expression Matching Can Be Simple And Fast
(but is slow in Java, Perl, PHP, Python, Ruby, ...)
It explains how many of the popular programming languages implement regular expressions in a way that can be very slow for some regular expressions, and explains a slightly different method that is faster. The article includes some details of how the proposed implementation works, including some source code in C. It may be a bit heavy reading if you are just starting to learn regular expressions, but I think it is well worth knowing about the difference between the two approaches.
A:
I've already given a +1 to Mark Byers - but as far as I remember the paper doesn't really say that much about how regular expression matching works beyond explaining why one algorithm is bad and another much better. Maybe something in the links?
I'll focus on the good approach - creating finite automata. If you limit yourself to deterministic automata with no minimisation, this isn't really too difficult.
What I'll (very quickly) describe is the approach taken in Modern Compiler Design.
Imagine you have the following regular expression...
a (b c)* d
The letters represent literal characters to match. The * is the usual zero-or-more repetitions match. The basic idea is to derive states based on dotted rules. State zero we'll take as the state where nothing has been matched yet, so the dot goes at the front...
0 : .a (b c)* d
The only possible match is 'a', so the next state we derive is...
1 : a.(b c)* d
We now have two possibilities - match the 'b' (if there's at least one repeat of 'b c') or match the 'd' otherwise. Note - we are basically doing a digraph search here (either depth first or breadth first or whatever) but we are discovering the digraph as we search it. Assuming a breadth-first strategy, we'll need to queue one of our cases for later consideration, but I'll ignore that issue from here on. Anyway, we've discovered two new states...
2 : a (b.c)* d
3 : a (b c)* d.
State 3 is an end state (there may be more than one). For state 2, we can only match the 'c', but we need to be careful with the dot position afterwards. We get "a.(b c)* d" - which is the same as state 1, so we don't need a new state.
IIRC, the approach in Modern Compiler Design is to translate a rule when you hit an operator, in order to simplify the handling of the dot. State 1 would be transformed to...
1 : a.b c (b c)* d
a.d
That is, your next option is either to match the first repetition or to skip the repetition. The next states from this are equivalent to states 2 and 3. An advantage of this approach is that you can discard all your past matches (everything before the '.') as you only care about future matches. This typically gives a smaller state model (but not necessarily a minimal one).
EDIT If you do discard already matched details, your state description is a representation of the set of strings that can occur from this point on.
In terms of abstract algebra, this is a kind of set closure. An algebra is basically a set with one (or more) operators. Our set is of state descriptions, and our operators are our transitions (character matches). A closed set is one where applying any operator to any members in the set always produces another member that is in the set. The closure of a set is the mimimal larger set that is closed. So basically, starting with the obvious start state, we are constructing the minimal set of states that is closed relative to our set of transition operators - the minimal set of reachable states.
Minimal here refers to the closure process - there may be a smaller equivalent automata which is normally referred to as minimal.
With this basic idea in mind, it's not too difficult to say "if I have two state machines representing two sets of strings, how to I derive a third representing the union" (or intersection, or set difference...). Instead of dotted rules, your state representations will a current state (or set of current states) from each input automaton and perhaps additional details.
If your regular grammars are getting complex, you can minimise. The basic idea here is relatively simple. You group all your states into one equivalence class or "block". Then you repeatedly test whether you need to split blocks (the states aren't really equivalent) with respect to a particular transition type. If all states in a particular block can accept a match of the same character and, in doing so, reach the same next-block, they are equivalent.
Hopcrofts algorithm is an efficient way to handle this basic idea.
A particularly interesting thing about minimisation is that every deterministic finite automaton has precisely one minimal form. Furthermore, Hopcrofts algorithm will produce the same representation of that minimal form, no matter what representation of what larger case it started from. That is, this is a "canonical" representation which can be used to derive a hash or for arbitrary-but-consistent orderings. What this means is that you can use minimal automata as keys into containers.
The above is probably a bit sloppy WRT definitions, so make sure you look up any terms yourself before using them yourself, but with a bit of luck this gives a fair quick introduction to the basic ideas.
BTW - have a look around the rest of Dick Grunes site - he has a free PDF book on parsing techniques. The first edition of Modern Compiler Design is pretty good IMO, but as you'll see, there's a second edition imminent.
A:
"A play on regular expressions: functional pearl" takes an interesting approach. The implementation is given in Haskell, but it's been reimplemented in Python at least once.
The developed program is based on an old technique to turn regular expressions into finite automata which makes it efficient both in terms of worst-case time and space bounds and actual performance: despite its simplicity, the Haskell implementation can compete with a recently published professional C++ program for the same problem.
A:
There's an interesting (if slightly short) chapter in Beautiful Code by Brian Kernighan, appropriately called "A Regular Expression Matcher". In it he discusses a simple matcher that can match literal characters, and the .^$* symbols.
A:
I do agree that writing a regex engine will improve understanding but have you taken a look at ANTLR??. It generates the parsers automatically for any kind of language. So maybe you can try your hand by taking one of the language grammars listed at Grammar examples and run through the AST and parser that it generates. It generates a really complicated code but you will have a good understanding on how a parser works.
| Writing a parser for regular expressions | Even after years of programming, I'm ashamed to say that I've never really fully grasped regular expressions. In general, when a problem calls for a regex, I can usually (after a bunch of referring to syntax) come up with an appropriate one, but it's a technique that I find myself using increasingly often.
So, to teach myself and understand regular expressions properly, I've decided to do what I always do when trying to learn something; i.e., try to write something ambitious that I'll probably abandon as soon as I feel I've learnt enough.
To this end, I want to write a regular expression parser in Python. In this case, "learn enough" means that I want to implement a parser that can understand Perl's extended regex syntax completely. However, it doesn't have to be the most efficient parser or even necessarily usable in the real-world. It merely has to correctly match or fail to match a pattern in a string.
The question is, where do I start? I know almost nothing about how regexes are parsed and interpreted apart from the fact that it involves a finite state automaton in some way. Any suggestions for how to approach this rather daunting problem would be much appreciated.
EDIT: I should clarify that while I'm going to implement the regex parser in Python, I'm not overly fussed about what programming language the examples or articles are written in. As long as it's not in Brainfuck, I will probably understand enough of it to make it worth my while.
| [
"Writing an implementation of a regular expression engine is indeed a quite complex task.\nBut if you are interested in how to do it, even if you can't understand enough of the details to actually implement it, I would recommend that you at least look at this article:\nRegular Expression Matching Can Be Simple And ... | [
44,
22,
10,
6,
2
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0003639574_parsing_python_regex.txt |
Q:
Scala or Python to Build a Comet server to support a PHP application?
I have a currently running PHP application that I want to add real-time feed (Google search latest result feeds), I have an implementation in PHP that does the following:
An AJAX request to the server.
The PHP responds.
After 15000ms (15 seconds) using setTimeout(), we repeat the steps.
I knew this have very much overhead on the server and will cause the C10K problems.
After researching I figured out that PHP as an Apache2 module is incompetent to implement the Comet solutions which is unfortunate!
I have two options, to use Scala, or Use Python to implement this part of my website since it's all complete and there is no time for rewriting it.
I don't care for anything as I care for performance since I use VPS200 from ServerGrove, And I'm going to install JVM or Python side-by-side with PHP.
So what you think has less memory/CPU consumption in this case JVM with Scala, Or Python?
Thanks in advance
Update:
I guess I'll use Akka Project, I'm going to test it.
Update 2:
I've done it using Node.js, it's incomparable by any other solution (IMO) in learning curve, community support, and project maturity. And I had an unfortunate experience with Scala since I a gave Scala a very long opportunity before trying Node.js.
A:
Why not node.js? It has a proven reputation of the solution that perfectly handles COMET. Everyone knows Plurk success story - one of the most popular social networking sites in Asia that has 500+mln subscribers, with up to 200k of them working in a parallel (using COMET long-polling connections). node.js memory usage is way better (~10 times less) compared to solutions based on java app server suitable for COMET (Jetty/Netty).
If you finally want to go with Java/Scala, you should first of all have a look at Atmosphere framework. It has the richest feature-set these days (supports all kinds of COMET strategies + web-sockets + servlets 3.0); out-of-the-box REST-support, based on Jersey (implementation of JAX-RS specification); integration with Akka (very powerful implementation of actors, fault-tolerance, STM, remotings etc on Scala).
Choosing a Lift, you'd probably have to re-write your application entirely, though it has a very good COMET support.
A:
Scala with lift (lliftweb.org) will have better opportunity for performance. Comet support in Lift is excellent. You should test them both though with a small prototype and compare.
| Scala or Python to Build a Comet server to support a PHP application? | I have a currently running PHP application that I want to add real-time feed (Google search latest result feeds), I have an implementation in PHP that does the following:
An AJAX request to the server.
The PHP responds.
After 15000ms (15 seconds) using setTimeout(), we repeat the steps.
I knew this have very much overhead on the server and will cause the C10K problems.
After researching I figured out that PHP as an Apache2 module is incompetent to implement the Comet solutions which is unfortunate!
I have two options, to use Scala, or Use Python to implement this part of my website since it's all complete and there is no time for rewriting it.
I don't care for anything as I care for performance since I use VPS200 from ServerGrove, And I'm going to install JVM or Python side-by-side with PHP.
So what you think has less memory/CPU consumption in this case JVM with Scala, Or Python?
Thanks in advance
Update:
I guess I'll use Akka Project, I'm going to test it.
Update 2:
I've done it using Node.js, it's incomparable by any other solution (IMO) in learning curve, community support, and project maturity. And I had an unfortunate experience with Scala since I a gave Scala a very long opportunity before trying Node.js.
| [
"Why not node.js? It has a proven reputation of the solution that perfectly handles COMET. Everyone knows Plurk success story - one of the most popular social networking sites in Asia that has 500+mln subscribers, with up to 200k of them working in a parallel (using COMET long-polling connections). node.js memory u... | [
4,
2
] | [] | [] | [
"comet",
"javascript",
"node.js",
"python",
"scala"
] | stackoverflow_0003770974_comet_javascript_node.js_python_scala.txt |
Q:
Fourier space filtering
I have a real vector time series x of length T and a filter h of length t << T. h is a filter in fourier space, real and symmetric. It is approximately 1/f.
I would like to filter x with h to get y.
Suppose t == T and FFT's of length T could fit into memory (neither of which are true). To get my filtered x in python, I would do:
import numpy as np
from scipy.signal import fft, ifft
y = np.real( np.ifft( np.fft(x) * h ) ) )
Since the conditions don't hold, I tried the following hack:
Select a padding size P < t/2, select a block size B such that B + 2P is a good FFT size
Scale h via spline interpolation to be of size B + 2P > t (h_scaled)
y = []; Loop:
Take block of length B + 2P from x (called x_b)
Perform y_b = ifft(fft( x_b ) * h_scaled)
Drop padding P from either side of y_b and concatenate with y
Select next x_b overlapping with last by P
Is this a good strategy? How do I select the padding P in a good way? What is the proper way to do this? I don't know much signal processing. This is a good chance to learn.
I am using cuFFT to speed things up so it would be great if the bulk of the operations are FFTs. The actual problem is 3D. Also, I am not concerned about artifacts from an acausal filter.
Thanks,
Paul.
A:
You're on the right track. The technique is called overlap-save processing. Is t short enough that FFTs of that length fit in memory? If so, you can pick your block size B such that B > 2*min(length(x),length(h)) and makes for a fast transform. Then when you process, you drop the first half of y_b, rather than dropping from both ends.
To see why you drop the first half, remember that the spectral multiplication is the same as circular convolution in the time domain. Convolving with the zero-padded h creates weird glitchy transients in the first half of the result, but by the second half all the transients are gone because the circular wrap point in x is aligned with the zero part of h. There's a good explanation of this, with pictures, in "Theory and Application of Digital Signal Processing" by Lawrence Rabiner and Bernard Gold.
It's important that your time domain filter taper to 0 at least on one end so that you don't get ringing artifacts. You mention that h is real in the frequency domain, which implies that it has all 0 phase. Usually, such a signal will be continuous only in a circular fashion, and when used as a filter will create distortion all through the frequency band. One easy way to create a reasonable filter is to design it in the frequency domain with 0 phase, inverse transform, and rotate. For instance:
def OneOverF(N):
import numpy as np
N2 = N/2; #N has to be even!
x = np.hstack((1, np.arange(1, N2+1), np.arange(N2-1, 0, -1)))
hf = 1/(2*np.pi*x/N2)
ht = np.real(np.fft.ifft(hf)) # discard tiny imag part from numerical error
htrot = np.roll(ht, N2)
htwin = htrot * np.hamming(N)
return ht, htrot, htwin
(I'm pretty new to Python, please let me know if there's a better way to code this).
If you compare the frequency responses of ht, htrot, and htwin, you see the following (x-axis is normalized frequency up to pi):
ht, at the top, has lots of ripple. This is due to the discontinuity at the edge. htrot, in the middle, is better, but still has ripple. htwin is nice and smooth, at the expense of flattening out at a slightly higher frequency. Note that you can extend the length of the straight-line section by using a bigger value for N.
I wrote about the discontinuity issue, and also wrote a Matlab/Octave example in another SO question if you want to see more detail.
| Fourier space filtering | I have a real vector time series x of length T and a filter h of length t << T. h is a filter in fourier space, real and symmetric. It is approximately 1/f.
I would like to filter x with h to get y.
Suppose t == T and FFT's of length T could fit into memory (neither of which are true). To get my filtered x in python, I would do:
import numpy as np
from scipy.signal import fft, ifft
y = np.real( np.ifft( np.fft(x) * h ) ) )
Since the conditions don't hold, I tried the following hack:
Select a padding size P < t/2, select a block size B such that B + 2P is a good FFT size
Scale h via spline interpolation to be of size B + 2P > t (h_scaled)
y = []; Loop:
Take block of length B + 2P from x (called x_b)
Perform y_b = ifft(fft( x_b ) * h_scaled)
Drop padding P from either side of y_b and concatenate with y
Select next x_b overlapping with last by P
Is this a good strategy? How do I select the padding P in a good way? What is the proper way to do this? I don't know much signal processing. This is a good chance to learn.
I am using cuFFT to speed things up so it would be great if the bulk of the operations are FFTs. The actual problem is 3D. Also, I am not concerned about artifacts from an acausal filter.
Thanks,
Paul.
| [
"You're on the right track. The technique is called overlap-save processing. Is t short enough that FFTs of that length fit in memory? If so, you can pick your block size B such that B > 2*min(length(x),length(h)) and makes for a fast transform. Then when you process, you drop the first half of y_b, rather than... | [
6
] | [] | [] | [
"fft",
"numpy",
"python",
"scipy",
"signal_processing"
] | stackoverflow_0003775912_fft_numpy_python_scipy_signal_processing.txt |
Q:
Python: How use constants for multiple clasess?
I want use a constant in Python for 2 classes.
Which is the better way? Thanks in advance!
MY_COLOR = "#000001" # <-------- Are correct here?
BLACK = "#000000" # <-------- Are correct here?
class One:
MY_FONT = "monospace"
def __init__(self):
if MY_COLOR == BLACK:
print("It's black")
if self.MY_FONT == "monospace":
print("Font equal")
class Two:
def __init__(self):
if MY_COLOR == BLACK:
print("It's black")
A:
The location of the "constant" looks fine to me. As @pyfunc commented you might want to declare other color/font values as "constant"s as well.
If you are expecting a lot of custom colors and/or fonts you might want to think of a separate module or a properties/configuration file.
[pedantic] There is no "constant" in Python the way you seem to imply. You are setting a variable at the module level, that is all. The all caps is a convention used to indicate that the value shouldn't be changed. There is nothing preventing it from being changed. [/pedantic]
A:
Something like this should be better:
BLACK = "#000000"
GREY = "#111111"
MONO = "monospace"
class One:
def __init__(self, color, font ):
if color == GREY:
print("Color not equal")
if font == "MONO:
print("Font equal")
| Python: How use constants for multiple clasess? | I want use a constant in Python for 2 classes.
Which is the better way? Thanks in advance!
MY_COLOR = "#000001" # <-------- Are correct here?
BLACK = "#000000" # <-------- Are correct here?
class One:
MY_FONT = "monospace"
def __init__(self):
if MY_COLOR == BLACK:
print("It's black")
if self.MY_FONT == "monospace":
print("Font equal")
class Two:
def __init__(self):
if MY_COLOR == BLACK:
print("It's black")
| [
"The location of the \"constant\" looks fine to me. As @pyfunc commented you might want to declare other color/font values as \"constant\"s as well. \nIf you are expecting a lot of custom colors and/or fonts you might want to think of a separate module or a properties/configuration file. \n[pedantic] There is no \"... | [
1,
0
] | [] | [] | [
"class",
"constants",
"python"
] | stackoverflow_0003776295_class_constants_python.txt |
Q:
python compare subsection of 2 strings and see if they match
I have 2 strings e.g.
str1 = 'section1.1: this is a heading for section 1'
and
str2 = 'section1.1: this is a heading for section 1.1'
I want to compare the text which comes after 'section1.1:' and return whether it is the same or not. In the example it would return false as the first says section 1 and the second says section 1.1
The first piece of the string can be anything e.g. subsection2.5: but always ends with a :
What is the best way to do this using Python?
A:
Use the split method of the strings to split on only the first ::
>>> str1 = 'section1.1: this is a heading for section 1'
>>> str2 = 'section1.1: this is a heading for section 1.1'
>>> str1.split(':', 1)[1]
' this is a heading for section 1'
>>> str2.split(':', 1)[1]
' this is a heading for section 1.1'
A:
Depending on how well you know what the format will be, you might do something like this.
In [1]: str1 = 'section1.1: this is a heading for section 1'
In [2]: str2 = 'section1.1: this is a heading for section 1.1'
In [3]: if str1.split(":", 1)[1] == str2.split(":", 1)[1]:
...: print "true"
In [4]: str2 = 'section1.1: this is a heading for section 1'
In [7]: if str1.split(":", 1)[1] == str2.split(":", 1)[1]:
...: print "true"
true
You can always strip the responses if you're concerned about trailing or leading whitespace to be different.
(edit: Missing line in IPython session)
A:
You can translate this pretty directly into code:
def compare( str1, str2):
# I want to compare the text which comes after the first ':' (for example)
def find_that_part( s ):
idx = s.find(':') # where is the first ':'?
return s[idx:] # the part after it
# and return whether it is the same or not.
return find_that_part(str1) == find_that_part(str2)
A:
The split(":") solutions in the other answers work fine. If you already parsed the first part (before the colon) in some way, and you know the length, you could do a simple string comparison like this:
parsedUntilColon = "section1.1:" # for example
if str1[len(parsedUntilColon):] == str2[len(parsedUntilColon):]:
print "strings are equal"
A:
A one liner should be cool!!
>>> str1 = 'section1.1: this is a heading for section 1'
>>> str2 = 'section1.1: this is a heading for section 1.1'
>>> cmp = lambda str1, str2: [x_.findall(str1) == x_.findall(str2) for x_ in [re.compile(':[\w*\s*\.*]*')]][0] and True
>>> cmp(str1, str2)
False
| python compare subsection of 2 strings and see if they match | I have 2 strings e.g.
str1 = 'section1.1: this is a heading for section 1'
and
str2 = 'section1.1: this is a heading for section 1.1'
I want to compare the text which comes after 'section1.1:' and return whether it is the same or not. In the example it would return false as the first says section 1 and the second says section 1.1
The first piece of the string can be anything e.g. subsection2.5: but always ends with a :
What is the best way to do this using Python?
| [
"Use the split method of the strings to split on only the first ::\n>>> str1 = 'section1.1: this is a heading for section 1'\n>>> str2 = 'section1.1: this is a heading for section 1.1'\n>>> str1.split(':', 1)[1]\n' this is a heading for section 1'\n>>> str2.split(':', 1)[1]\n' this is a heading for section 1.1'... | [
2,
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003770024_python.txt |
Q:
Is this a memory leak?
I'm using gc module to debug a leak.
It's a gui program and I've hooked this function to a button.
I've set set debug more to gc.SAVE_ALL
> gc.collect()
>
> print gc.garbage
and this is the output
[(<type '_ctypes.Array'>,), {'__module__': 'ctypes._endian', '__dict__': <attribute '__dict__' of 'c_int_Array_3' objects>, '__weakref__': <attribute '__weakref__' of 'c_int_Array_3' objects>, '_length_': 3, '_type_': <class 'ctypes.c_int'>, '__doc__': None}, <class 'ctypes._endian.c_int_Array_3'>, <attribute '__dict__' of 'c_int_Array_3' objects>, <attribute '__weakref__' of 'c_int_Array_3' objects>, (<class 'ctypes._endian.c_int_Array_3'>, <type '_ctypes.Array'>, <type '_ctypes._CData'>, <type 'object'>), (<type '_ctypes.CFuncPtr'>,), {'__module__': 'ctypes', '__dict__': <attribute '__dict__' of '_FuncPtr' objects>, '__weakref__': <attribute '__weakref__' of '_FuncPtr' objects>, '_flags_': 1, '__doc__': None, '_restype_': <class 'ctypes.c_int'>}, <class 'ctypes._FuncPtr'>, <attribute '__dict__' of '_FuncPtr' objects>, <attribute '__weakref__' of '_FuncPtr' objects>, (<class 'ctypes._FuncPtr'>, <type '_ctypes.CFuncPtr'>, <type '_ctypes._CData'>, <type 'object'>), {}, <cell at 0x10a24b0: Resource object at 0x10e6a50>, <cell at 0x10a2478: dict object at 0x11a4440>, <cell at 0x7f1703949f68: function object at 0x10ec7d0>, <cell at 0x10e2f30: NoneType object at 0x826880>, <cell at 0x10e2d70: NoneType object at 0x826880>, <cell at 0x10e2ef8: str object at 0x7f1703dd5e10>, <cell at 0x10e2de0: dict object at 0x118aaa0>, {'Accept': 'application/json', 'User-Agent': 'couchdb-python 0.6'}, (<cell at 0x10e2f30: NoneType object at 0x826880>, <cell at 0x10a24b0: Resource object at 0x10e6a50>, <cell at 0x10e2de0: dict object at 0x118aaa0>, <cell at 0x10a2478: dict object at 0x11a4440>, <cell at 0x10e2d70: NoneType object at 0x826880>, <cell at 0x10e2ef8: str object at 0x7f1703dd5e10>, <cell at 0x7f1703949f68: function object at 0x10ec7d0>), <function _make_request at 0x10ec7d0>, (1,), {}, <cell at 0x10e2bb0: Resource object at 0x10e6a50>, <cell at 0x10e2e88: dict object at 0x119f360>, <cell at 0x10f0130: function object at 0x10ec578>, <cell at 0x10f01d8: NoneType object at 0x826880>, <cell at 0x10f01a0: NoneType object at 0x826880>, <cell at 0x10f00f8: str object at 0x7f170b05d810>, <cell at 0x10f00c0: dict object at 0x11969a0>, {'Accept': 'application/json', 'User-Agent': 'couchdb-python 0.6'}, (<cell at 0x10f01d8: NoneType object at 0x826880>, <cell at 0x10e2bb0: Resource object at 0x10e6a50>, <cell at 0x10f00c0: dict object at 0x11969a0>, <cell at 0x10e2e88: dict object at 0x119f360>, <cell at 0x10f01a0: NoneType object at 0x826880>, <cell at 0x10f00f8: str object at 0x7f170b05d810>, <cell at 0x10f0130: function object at 0x10ec578>), <function _make_request at 0x10ec578>, (1,), {}, <cell at 0x10f0440: Resource object at 0x10e6a50>, <cell at 0x10f02b8: dict object at 0x11b2d70>, <cell at 0x10f0360: function object at 0x10ec6e0>, <cell at 0x10f0280: NoneType object at 0x826880>, <cell at 0x10f02f0: str object at 0x10ca228>, <cell at 0x10f0408: str object at 0x7f170b05d810>, <cell at 0x10f0050: dict object at 0x11b6370>, {'Accept': 'application/json', 'User-Agent': 'couchdb-python 0.6'}, (<cell at 0x10f0280: NoneType object at 0x826880>]
The gc.garbage list has a lot of items. Does this mean the objects in gc.garbage are leaking or have been collected or will be collected?
A:
From the docs:
gc.garbage
A list of objects which the collector found to be unreachable but could not be freed (uncollectable objects).
So it looks like some kind of leak to me. Now the docs go on to explain the conditions under which this could occur:
Objects that have del() methods and are part of a reference cycle cause the entire reference cycle to be uncollectable, including objects not necessarily in the cycle but reachable only from it. Python doesn’t collect such cycles automatically because, in general, it isn’t possible for Python to guess a safe order in which to run the del() methods. If you know a safe order, you can force the issue by examining the garbage list, and explicitly breaking cycles due to your objects within the list. Note that these objects are kept alive even so by virtue of being in the garbage list, so they should be removed from garbage too. For example, after breaking cycles, do del gc.garbage[:] to empty the list. It’s generally better to avoid the issue by not creating cycles containing objects with del() methods, and garbage can be examined in that case to verify that no such cycles are being created.
Now having the DEBUG_SAVEALL flag set makes all of your garbage leak. From the same source:
gc.DEBUG_SAVEALL
When set, all unreachable objects found will be appended to garbage rather than being freed. This can be useful for debugging a leaking program.
So, again, yes, that list is leaked memory. But you told it to leak all that!
A:
In other languages, I've used a heap profiler with great success to track down memory leaks. I've never used one in Python, but Heapy seems like it'd be worth trying.
Under their "Data Processing" section, try this feature out:
Calculation of the 'dominated' set from a set of root objects which yields the set of objects that would be deallocated if the root objects were deallocated.
If it is like other tools, you should be able to drill down. Follow the objects with the biggest 'dominated set' until you find something that seems too big, that's likely a leak.
| Is this a memory leak? | I'm using gc module to debug a leak.
It's a gui program and I've hooked this function to a button.
I've set set debug more to gc.SAVE_ALL
> gc.collect()
>
> print gc.garbage
and this is the output
[(<type '_ctypes.Array'>,), {'__module__': 'ctypes._endian', '__dict__': <attribute '__dict__' of 'c_int_Array_3' objects>, '__weakref__': <attribute '__weakref__' of 'c_int_Array_3' objects>, '_length_': 3, '_type_': <class 'ctypes.c_int'>, '__doc__': None}, <class 'ctypes._endian.c_int_Array_3'>, <attribute '__dict__' of 'c_int_Array_3' objects>, <attribute '__weakref__' of 'c_int_Array_3' objects>, (<class 'ctypes._endian.c_int_Array_3'>, <type '_ctypes.Array'>, <type '_ctypes._CData'>, <type 'object'>), (<type '_ctypes.CFuncPtr'>,), {'__module__': 'ctypes', '__dict__': <attribute '__dict__' of '_FuncPtr' objects>, '__weakref__': <attribute '__weakref__' of '_FuncPtr' objects>, '_flags_': 1, '__doc__': None, '_restype_': <class 'ctypes.c_int'>}, <class 'ctypes._FuncPtr'>, <attribute '__dict__' of '_FuncPtr' objects>, <attribute '__weakref__' of '_FuncPtr' objects>, (<class 'ctypes._FuncPtr'>, <type '_ctypes.CFuncPtr'>, <type '_ctypes._CData'>, <type 'object'>), {}, <cell at 0x10a24b0: Resource object at 0x10e6a50>, <cell at 0x10a2478: dict object at 0x11a4440>, <cell at 0x7f1703949f68: function object at 0x10ec7d0>, <cell at 0x10e2f30: NoneType object at 0x826880>, <cell at 0x10e2d70: NoneType object at 0x826880>, <cell at 0x10e2ef8: str object at 0x7f1703dd5e10>, <cell at 0x10e2de0: dict object at 0x118aaa0>, {'Accept': 'application/json', 'User-Agent': 'couchdb-python 0.6'}, (<cell at 0x10e2f30: NoneType object at 0x826880>, <cell at 0x10a24b0: Resource object at 0x10e6a50>, <cell at 0x10e2de0: dict object at 0x118aaa0>, <cell at 0x10a2478: dict object at 0x11a4440>, <cell at 0x10e2d70: NoneType object at 0x826880>, <cell at 0x10e2ef8: str object at 0x7f1703dd5e10>, <cell at 0x7f1703949f68: function object at 0x10ec7d0>), <function _make_request at 0x10ec7d0>, (1,), {}, <cell at 0x10e2bb0: Resource object at 0x10e6a50>, <cell at 0x10e2e88: dict object at 0x119f360>, <cell at 0x10f0130: function object at 0x10ec578>, <cell at 0x10f01d8: NoneType object at 0x826880>, <cell at 0x10f01a0: NoneType object at 0x826880>, <cell at 0x10f00f8: str object at 0x7f170b05d810>, <cell at 0x10f00c0: dict object at 0x11969a0>, {'Accept': 'application/json', 'User-Agent': 'couchdb-python 0.6'}, (<cell at 0x10f01d8: NoneType object at 0x826880>, <cell at 0x10e2bb0: Resource object at 0x10e6a50>, <cell at 0x10f00c0: dict object at 0x11969a0>, <cell at 0x10e2e88: dict object at 0x119f360>, <cell at 0x10f01a0: NoneType object at 0x826880>, <cell at 0x10f00f8: str object at 0x7f170b05d810>, <cell at 0x10f0130: function object at 0x10ec578>), <function _make_request at 0x10ec578>, (1,), {}, <cell at 0x10f0440: Resource object at 0x10e6a50>, <cell at 0x10f02b8: dict object at 0x11b2d70>, <cell at 0x10f0360: function object at 0x10ec6e0>, <cell at 0x10f0280: NoneType object at 0x826880>, <cell at 0x10f02f0: str object at 0x10ca228>, <cell at 0x10f0408: str object at 0x7f170b05d810>, <cell at 0x10f0050: dict object at 0x11b6370>, {'Accept': 'application/json', 'User-Agent': 'couchdb-python 0.6'}, (<cell at 0x10f0280: NoneType object at 0x826880>]
The gc.garbage list has a lot of items. Does this mean the objects in gc.garbage are leaking or have been collected or will be collected?
| [
"From the docs:\n\ngc.garbage\nA list of objects which the collector found to be unreachable but could not be freed (uncollectable objects).\n\nSo it looks like some kind of leak to me. Now the docs go on to explain the conditions under which this could occur:\n\nObjects that have del() methods and are part of a r... | [
1,
0
] | [] | [] | [
"garbage_collection",
"memory_leaks",
"python"
] | stackoverflow_0003776291_garbage_collection_memory_leaks_python.txt |
Q:
Can Django use "external" python scripts linked to other libraries (NumPy, RPy2...)
I am new to the world of IT business (serious) development but I have in mind a business idea and still trying to vizualize how the overall infrastructure should work.
I have done some few research for a good technology to deliver the solution. I am very inclined to use Python, MySql, Django (Apache) on the server side and some RIA on the client side (probably Flex) as I need some advanced visualization capabilities (especially after seeing the FLARE project).
The application requires some "heaving lifting" on the numerical / statistical side and integrating R with Python (RPy2) + other like NumPy seems to be ideal.
The thing i cannot get so far (certainly because i am a newbie) is the following:
Can Django (one way or the other) execute an (external) python script / program which contain reference to the extra libraries (NumPy ...)?
ex: user triggers an action to perform a statistical analysis, Django receives the request and should run some python code (using R, NumPy...) which uses the data in the database and store the results back in the DB. Django accesses the DB data and send it back to the client app to be displayed.
Is this the right logic or am i completely off path?
Many thanks in advance for your expertise.
A:
Django is a Python program. And like any other Python program it will be able to access other Python scripts/modules. The question then, is how to execute the script. If your script explicitly defines a main (or another starting point) function then you can merely import it as you would a module and call the main.
For instance:
# my custom script. Located in my_script.py
# lots of functions
def main():
# call functions in sequence.
# my django view.
from myscript import main as script_main
script_main()
If you'd rather execute as if from the command line then look at the subprocess module. If you want to run it asynchronously then something like Celery might be what you are looking for.
A:
If you can install it on the server and import it into python, then you can use it in python and hence Django.
That is to say, if
import foo
works, then so does
import foo
foo.bar(fobaz)
assuming that it would work without Django. Also, if you were to try to do something that sent HTTP headers or responses outside of Django, you might run into problems but numerical packages wont do anything like that.
| Can Django use "external" python scripts linked to other libraries (NumPy, RPy2...) | I am new to the world of IT business (serious) development but I have in mind a business idea and still trying to vizualize how the overall infrastructure should work.
I have done some few research for a good technology to deliver the solution. I am very inclined to use Python, MySql, Django (Apache) on the server side and some RIA on the client side (probably Flex) as I need some advanced visualization capabilities (especially after seeing the FLARE project).
The application requires some "heaving lifting" on the numerical / statistical side and integrating R with Python (RPy2) + other like NumPy seems to be ideal.
The thing i cannot get so far (certainly because i am a newbie) is the following:
Can Django (one way or the other) execute an (external) python script / program which contain reference to the extra libraries (NumPy ...)?
ex: user triggers an action to perform a statistical analysis, Django receives the request and should run some python code (using R, NumPy...) which uses the data in the database and store the results back in the DB. Django accesses the DB data and send it back to the client app to be displayed.
Is this the right logic or am i completely off path?
Many thanks in advance for your expertise.
| [
"Django is a Python program. And like any other Python program it will be able to access other Python scripts/modules. The question then, is how to execute the script. If your script explicitly defines a main (or another starting point) function then you can merely import it as you would a module and call the main.... | [
5,
1
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0003776515_django_mysql_python.txt |
Q:
Debug C++ code in visual studio from python code running in eclipse
Does any one know how we can do this?
I have python code in eclipse and whenever it calls c++ functions, i want the break point to go to the visual studio c++ project.
A:
You can use a __debugbreak in visual studio so that every time the code is invoked it triggers the debugger (you may want to search the function in MSDN).
Insert the instruction in the C++ function (or class method) you want to debug, e.g.
void foo()
{
__debugbreak();
[...]
}
at this point compile the library and run the python script, when library loads and the code is executed a messagebox appears telling if you want to attach the visual studio debugger.
It is the replacement of the old __asm { int 3 }.
A:
If the C++ app runs as a separate process then its pretty easy. You can run the process yourself or attach visual studio to existing running process and put break points.
If C++ code is an embedded DLL/LIB then you can use python as debug/launch process. As soon as python will load the DLL/LIB into your python code visual studio will activate your break points.
Alternatively you can also add windows debugger launcher calls to your code. As soon as your code gets executed, you will see a dialog box asking if you want to attach a debugger.
| Debug C++ code in visual studio from python code running in eclipse | Does any one know how we can do this?
I have python code in eclipse and whenever it calls c++ functions, i want the break point to go to the visual studio c++ project.
| [
"You can use a __debugbreak in visual studio so that every time the code is invoked it triggers the debugger (you may want to search the function in MSDN).\nInsert the instruction in the C++ function (or class method) you want to debug, e.g.\nvoid foo()\n{\n __debugbreak();\n [...]\n}\n\nat this point compile the... | [
4,
2
] | [] | [] | [
"c++",
"eclipse",
"python",
"visual_studio"
] | stackoverflow_0003351110_c++_eclipse_python_visual_studio.txt |
Q:
Shortest way to break-up long string (add whitespace) after 60 chars?
I'm processing a bunch of strings and displaying them on a web page.
Unfortunately if a string contains a word that is longer than 60 chars it makes my design implode.
Therefore i'm looking for the easiest, most efficient way to add a whitespace after every 60 chars without whitespaces in a string in python.
I only came up with clunky solutions like using str.find(" ") two times and check if the index difference is > 60.
Any ideas appreciated, thanks.
A:
>>> import textwrap
>>> help(textwrap.wrap)
wrap(text, width=70, **kwargs)
Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour.
>>> s = "a" * 20
>>> s = "\n".join(textwrap.wrap(s, width=10))
>>> print s
aaaaaaaaaa
aaaaaaaaaa
Any extra newlines inserted will be treated as space when the web page is processed by the browser.
Alternatively:
def break_long_words(s, width, fix):
return " ".join(x if len(x) < width else fix(x) for x in s.split())
def handle_long_word(s): # choose a name that describes what action you want
# do something
return s
s = "a" * 20
s = break_long_words(s, 60, handle_long_word)
A:
def make_wrappable(your_string):
new_parts = []
for x in your_string.split():
if len(x)>60:
# do whatever you like to shorten it,
# then append it to new_parts
else:
new_parts.append(x)
return ' '.join(new_parts)
A:
def splitLongWord ( word ):
segments = list()
while len( word ) > 0:
segments.append( a[:60] )
word = a[60:]
return ' '.join( segments )
myString = '...' # a long string with words that are longer than 60 characters
words = list()
for word in myString.split( ' ' ):
if len( word ) <= 60:
words.append( word )
else:
words.extend( splitLongWord( word ) )
myString = ' '.join( words )
| Shortest way to break-up long string (add whitespace) after 60 chars? | I'm processing a bunch of strings and displaying them on a web page.
Unfortunately if a string contains a word that is longer than 60 chars it makes my design implode.
Therefore i'm looking for the easiest, most efficient way to add a whitespace after every 60 chars without whitespaces in a string in python.
I only came up with clunky solutions like using str.find(" ") two times and check if the index difference is > 60.
Any ideas appreciated, thanks.
| [
"\n>>> import textwrap\n>>> help(textwrap.wrap)\nwrap(text, width=70, **kwargs)\n Wrap a single paragraph of text, returning a list of wrapped lines.\n\n Reformat the single paragraph in 'text' so it fits in lines of no\n more than 'width' columns, and return a list of wrapped lines. By\n default, tabs... | [
5,
0,
0
] | [] | [] | [
"python",
"string",
"whitespace"
] | stackoverflow_0003776627_python_string_whitespace.txt |
Q:
free implementation of counting user sessions from a web server log?
Web server log analyzers (e.g. Urchin) often display a number of "sessions". A session is defined as a series of page visits / clicks made by an individual within a limited, continuous time segment. The attempt is made to identify these segments using IP addresses, and often supplementary info like user agent and OS, along with a session timeout threshold such as 15 or 30 minutes.
For certain web sites and applications, a user can be logged in and/or tracked with a cookie, which means the server can precisely know when a session begins. I'm not talking about that, but about inferring sessions heuristically ("session reconstruction") when the web server does not track them.
I could write some code e.g. in Python to try to reconstruct sessions based on the criteria mentioned above, but I'd rather not reinvent the wheel. I'm looking at log files of a size around 400K lines, so I'd have to be careful to use a scalable algorithm.
My goal here is to extract a list of unique IP addresses from a log file, and for each IP address, to have the number of sessions inferred from that log. Absolute precision and accuracy are not necessary... pretty-good estimates are ok.
Based on this description:
a new request is put in an existing
session if two conditions are valid:
the IP address and the user-agent are the same of the requests already
inserted in the session,
the request is done less than fifteen minutes after the last
request inserted.
it would be simple in theory to write a Python program to build up a dictionary (keyed by IP) of dictionaries (keyed by user-agent) whose value is a pair: (number of sessions, latest request of latest session).
But I would rather try to use an existing implementation if one's available, since I might otherwise risk spending a lot of time tuning performance.
FYI lest someone ask for sample input, here is a line of our log file (sanitized):
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status
2010-09-21 23:59:59 215.51.1.119 GET /graphics/foo.gif - 80 - 128.123.114.141 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.9.2)+Gecko/20100115+Firefox/3.6+(.NET+CLR+3.5.30729) http://www.mysite.org/blarg.htm 200 0 0
A:
OK, in the absence of any other answer, here's my Python implementation. I'm not a Python expert. Suggestions for improvement are welcome.
#!/usr/bin/env python
"""Reconstruct sessions: Take a space-delimited web server access log
including IP addresses, timestamps, and User Agent,
and output a list of the IPs, and the number of inferred sessions for each."""
## Input looks like:
# Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status
# 2010-09-21 23:59:59 172.21.1.119 GET /graphics/foo.gif - 80 - 128.123.114.141 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.9.2)+Gecko/20100115+Firefox/3.6+(.NET+CLR+3.5.30729) http://www.site.org//baz.htm 200 0 0
import datetime
import operator
infileName = "ex100922.log"
outfileName = "visitor-ips.csv"
ipDict = {}
def inputRecords():
infile = open(infileName, "r")
recordsRead = 0
progressThreshold = 100
sessionTimeout = datetime.timedelta(minutes=30)
for line in infile:
if (line[0] == '#'):
continue
else:
recordsRead += 1
fields = line.split()
# print "line of %d records: %s\n" % (len(fields), line)
if (recordsRead >= progressThreshold):
print "Read %d records" % recordsRead
progressThreshold *= 2
# http://www.dblab.ntua.gr/persdl2007/papers/72.pdf
# "a new request is put in an existing session if two conditions are valid:
# * the IP address and the user-agent are the same of the requests already
# inserted in the session,
# * the request is done less than fifteen minutes after the last request inserted."
theDate, theTime = fields[0], fields[1]
newRequestTime = datetime.datetime.strptime(theDate + " " + theTime, "%Y-%m-%d %H:%M:%S")
ipAddr, userAgent = fields[8], fields[9]
if ipAddr not in ipDict:
ipDict[ipAddr] = {userAgent: [1, newRequestTime]}
else:
if userAgent not in ipDict[ipAddr]:
ipDict[ipAddr][userAgent] = [1, newRequestTime]
else:
ipdipaua = ipDict[ipAddr][userAgent]
if newRequestTime - ipdipaua[1] >= sessionTimeout:
ipdipaua[0] += 1
ipdipaua[1] = newRequestTime
infile.close()
return recordsRead
def outputSessions():
outfile = open(outfileName, "w")
outfile.write("#Fields: IPAddr Sessions\n")
recordsWritten = len(ipDict)
# ipDict[ip] is { userAgent1: [numSessions, lastTimeStamp], ... }
for ip, val in ipDict.iteritems():
# TODO: sum over on all keys' values [(v, k) for (k, v) in d.iteritems()].
totalSessions = reduce(operator.add, [v2[0] for v2 in val.itervalues()])
outfile.write("%s\t%d\n" % (ip, totalSessions))
outfile.close()
return recordsWritten
recordsRead = inputRecords()
recordsWritten = outputSessions()
print "Finished session reconstruction: read %d records, wrote %d\n" % (recordsRead, recordsWritten)
Update: This took 39 seconds to input and process 342K records and write 21K records. That's good enough speed for my purposes. Apparently 3/4 of that time was spent in strptime()!
| free implementation of counting user sessions from a web server log? | Web server log analyzers (e.g. Urchin) often display a number of "sessions". A session is defined as a series of page visits / clicks made by an individual within a limited, continuous time segment. The attempt is made to identify these segments using IP addresses, and often supplementary info like user agent and OS, along with a session timeout threshold such as 15 or 30 minutes.
For certain web sites and applications, a user can be logged in and/or tracked with a cookie, which means the server can precisely know when a session begins. I'm not talking about that, but about inferring sessions heuristically ("session reconstruction") when the web server does not track them.
I could write some code e.g. in Python to try to reconstruct sessions based on the criteria mentioned above, but I'd rather not reinvent the wheel. I'm looking at log files of a size around 400K lines, so I'd have to be careful to use a scalable algorithm.
My goal here is to extract a list of unique IP addresses from a log file, and for each IP address, to have the number of sessions inferred from that log. Absolute precision and accuracy are not necessary... pretty-good estimates are ok.
Based on this description:
a new request is put in an existing
session if two conditions are valid:
the IP address and the user-agent are the same of the requests already
inserted in the session,
the request is done less than fifteen minutes after the last
request inserted.
it would be simple in theory to write a Python program to build up a dictionary (keyed by IP) of dictionaries (keyed by user-agent) whose value is a pair: (number of sessions, latest request of latest session).
But I would rather try to use an existing implementation if one's available, since I might otherwise risk spending a lot of time tuning performance.
FYI lest someone ask for sample input, here is a line of our log file (sanitized):
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status
2010-09-21 23:59:59 215.51.1.119 GET /graphics/foo.gif - 80 - 128.123.114.141 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.9.2)+Gecko/20100115+Firefox/3.6+(.NET+CLR+3.5.30729) http://www.mysite.org/blarg.htm 200 0 0
| [
"OK, in the absence of any other answer, here's my Python implementation. I'm not a Python expert. Suggestions for improvement are welcome.\n#!/usr/bin/env python\n\n\"\"\"Reconstruct sessions: Take a space-delimited web server access log\nincluding IP addresses, timestamps, and User Agent,\nand output a list of th... | [
2
] | [] | [] | [
"python",
"session",
"web_analytics",
"web_analytics_tools"
] | stackoverflow_0003773840_python_session_web_analytics_web_analytics_tools.txt |
Q:
Writing a module for both Python 2.x and 3.x
I've written a pure-Python module for Python 3.0/3.1 which I'd also like to make it compatible with 2.x (probably just 2.6/2.7) in order to make it available to the widest possible audience.
The module is concerned with reading and writing a set of related file formats, so the differences between 2.x and 3.x versions would be slight — e.g. io.BytesIO instead of StringIO.StringIO — but not all of them are easily handled via try/except blocks, such as setting metaclasses.
What's the correct way to handle this? Two nearly-identical codebases which must be kept in sync or one codebase sprinkled with feature detection? A single, clean codebase plus 2to3 or 3to2?
A:
Write your code entirely against 2.x, targeting the most recent version in the 2.x series. In this case, it's probably going to remain 2.7. Run it through 2to3, and if it doesn't pass all of its unit tests, fix the 2.x version until the generated 3.x version works.
Eventually, when you want to drop 2.x support, you can take the generated 3.x version and start modifying it directly. Until then, only modify the 2.x version.
This is the workflow highly recommended by the people who worked on 2to3. Unfortunately I don't remember offhand the link to the document I gleaned all of this from.
| Writing a module for both Python 2.x and 3.x | I've written a pure-Python module for Python 3.0/3.1 which I'd also like to make it compatible with 2.x (probably just 2.6/2.7) in order to make it available to the widest possible audience.
The module is concerned with reading and writing a set of related file formats, so the differences between 2.x and 3.x versions would be slight — e.g. io.BytesIO instead of StringIO.StringIO — but not all of them are easily handled via try/except blocks, such as setting metaclasses.
What's the correct way to handle this? Two nearly-identical codebases which must be kept in sync or one codebase sprinkled with feature detection? A single, clean codebase plus 2to3 or 3to2?
| [
"Write your code entirely against 2.x, targeting the most recent version in the 2.x series. In this case, it's probably going to remain 2.7. Run it through 2to3, and if it doesn't pass all of its unit tests, fix the 2.x version until the generated 3.x version works.\nEventually, when you want to drop 2.x support, y... | [
11
] | [] | [] | [
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0003776665_python_python_2.x_python_3.x.txt |
Q:
Right alignment for table cell in pyqt
I have QStandardItemModel and QTableView. I want to have the number align to the right. How can i specify this in pyqt?
Now i have it like this (see ID) http://simple-database-explorer.googlecode.com/files/Main2.jpg
Working example:
self.model.setData(self.model.index(i, j, QtCore.QModelIndex()), value, role=0)
if isNumber(value):
self.model.setData(self.model.index(i, j, QtCore.QModelIndex()), QtCore.QVariant(QtCore.Qt.AlignRight), QtCore.Qt.TextAlignmentRole)
A:
Are you using QStandardItems as well? Then you can use setTextAlignment.
Update
Using setData:
model.setData(index, QtCore.QVariant(QtCore.Qt.AlignRight),
QtCore.Qt.TextAlignmentRole)
| Right alignment for table cell in pyqt | I have QStandardItemModel and QTableView. I want to have the number align to the right. How can i specify this in pyqt?
Now i have it like this (see ID) http://simple-database-explorer.googlecode.com/files/Main2.jpg
Working example:
self.model.setData(self.model.index(i, j, QtCore.QModelIndex()), value, role=0)
if isNumber(value):
self.model.setData(self.model.index(i, j, QtCore.QModelIndex()), QtCore.QVariant(QtCore.Qt.AlignRight), QtCore.Qt.TextAlignmentRole)
| [
"Are you using QStandardItems as well? Then you can use setTextAlignment.\nUpdate\nUsing setData:\nmodel.setData(index, QtCore.QVariant(QtCore.Qt.AlignRight),\n QtCore.Qt.TextAlignmentRole)\n\n"
] | [
3
] | [] | [] | [
"datatable",
"pyqt",
"python",
"qt"
] | stackoverflow_0003776533_datatable_pyqt_python_qt.txt |
Q:
Python xlrd data extraction
I am using python xlrd http://scienceoss.com/read-excel-files-from-python/ to read data from an excel sheet
My question is if i read a row with first cell as "Employee name" in the excel sheet
And there is another row named whose first cell is "Employee name"
How can we read the last column starting with the last row which has "Employee name" in the first cell.Ignoring the previous
wb = xlrd.open_workbook(file,encoding_override="cp1252")
wb.sheet_names()
sh = wb.sheet_by_index(0)
num_of_rows = sh.nrows
num_of_cols = sh.ncols
valid_xl_format = 0
invalid_xl_format = 0
if(num_of_rows != 0):
for i in range(num_of_rows):
questions_dict = {}
for j in range(num_of_cols):
xl_data=sh.cell(i,j).value
if ((xl_data == "Employee name")):
# Regardless of how many "Employee name" found in rows first cell,Read only the last "Employee name"
A:
I am using python xlrd http://scienceoss.com/read-excel-files-from-python/ to read data from an excel sheet
You need to think about what you are doing, instead of grabbing some blog code and leaving in totally irrelevant stuff like wb.sheet_names() and omitting parts very relevant to your requirement like first_column = sh.col_values(0).
Here's how to find the row_index of the last "whatever" in column A (the first column) -- untested:
import xlrd
wb = xlrd.open_workbook(file_name)
# Why do you think that you need to use encoding_overide?
sheet0 = wb.sheet_by_index(0)
tag = u"Employee name" # or u"Emp name" or ...
column_0_values = sheet0.col_values(colx=0)
try:
max_tag_row_index = column_0_values.rindex(tag)
print "last tag %r found at row_index %d" % (
tag, max_tag_row_index)
except IndexError:
print "tag %r not found" % tag
Now we need to interpret "How can we read the last column starting with the last row which has "Employee name" in the first cell"
Assuming that "the last column" means the one with column_index == sheet0.ncols - 1, then:
last_colx = sheet0.ncols - 1
required_values = sheet0.col_values(colx=last_colx, start_rowx=max_tag_row_index)
required_cells = sheet0.col_slice(colx=last_colx, start_rowx=max_tag_row_index)
# choose one of the above 2 lines, depending on what you need to do
If that's not what you mean (which is quite possible as it is ignoring a whole bunch of data (why do you want to read only the last column?), please try to explain with examples what you do mean.
Possibly you want to iterate over the remaining cells:
for rowx in xrange(max_tag_row_index, sheet0.nrows): # or max_tag_row_index + 1
for colx in xrange(0, sheet0.ncols):
do_something_with_cell_object(sheet0.cell(rowx, colx))
A:
It's difficult to understand exactly what you're asking.
Posting sample data might help make your intent more clear.
Have you tried iterating over the dataset in reverse?, e.g.:
for i in reversed(range(num_of_rows)):
...
if xl_data == "Employee name":
# do something
# then break since you've found the final "Employee Name"
break
| Python xlrd data extraction | I am using python xlrd http://scienceoss.com/read-excel-files-from-python/ to read data from an excel sheet
My question is if i read a row with first cell as "Employee name" in the excel sheet
And there is another row named whose first cell is "Employee name"
How can we read the last column starting with the last row which has "Employee name" in the first cell.Ignoring the previous
wb = xlrd.open_workbook(file,encoding_override="cp1252")
wb.sheet_names()
sh = wb.sheet_by_index(0)
num_of_rows = sh.nrows
num_of_cols = sh.ncols
valid_xl_format = 0
invalid_xl_format = 0
if(num_of_rows != 0):
for i in range(num_of_rows):
questions_dict = {}
for j in range(num_of_cols):
xl_data=sh.cell(i,j).value
if ((xl_data == "Employee name")):
# Regardless of how many "Employee name" found in rows first cell,Read only the last "Employee name"
| [
"I am using python xlrd http://scienceoss.com/read-excel-files-from-python/ to read data from an excel sheet\nYou need to think about what you are doing, instead of grabbing some blog code and leaving in totally irrelevant stuff like wb.sheet_names() and omitting parts very relevant to your requirement like first_c... | [
5,
0
] | [] | [] | [
"python",
"xlrd"
] | stackoverflow_0003775695_python_xlrd.txt |
Q:
Django and FeinCMS: A way to use the Media Library in other normal models?
I'm using Django and FeinCMS on a project. I'm currently using FeinCMS for all the pages on the site. But I also have another separate model that handles very simple stock for the site too. This stock model has the usual fields (name, description, etc) but I also want it to have photos.
Because FeinCMS has a media library already, I would like to technically use that to have the photos with my stock model. I could just normally do a Photo model and ManyToManyField that, but I'm curious to know if I can ManyToManyField with the FeinCMS media library?
I know with FeinCMS you can use the item editor on any other model, but I'm not sure that's the right way to go about it. If it's the only way to do this, then that will have to be it.
Many thanks
A:
Sure -- there's nothing stopping you from adding a ForeignKey or a ManyToManyField to the MediaFile model to one of your own models. Note that you'll have a hard time limiting the media files to only images. Maybe limit_choices_to will help though.
| Django and FeinCMS: A way to use the Media Library in other normal models? | I'm using Django and FeinCMS on a project. I'm currently using FeinCMS for all the pages on the site. But I also have another separate model that handles very simple stock for the site too. This stock model has the usual fields (name, description, etc) but I also want it to have photos.
Because FeinCMS has a media library already, I would like to technically use that to have the photos with my stock model. I could just normally do a Photo model and ManyToManyField that, but I'm curious to know if I can ManyToManyField with the FeinCMS media library?
I know with FeinCMS you can use the item editor on any other model, but I'm not sure that's the right way to go about it. If it's the only way to do this, then that will have to be it.
Many thanks
| [
"Sure -- there's nothing stopping you from adding a ForeignKey or a ManyToManyField to the MediaFile model to one of your own models. Note that you'll have a hard time limiting the media files to only images. Maybe limit_choices_to will help though.\n"
] | [
1
] | [] | [] | [
"content_management_system",
"django",
"django_admin",
"feincms",
"python"
] | stackoverflow_0003542723_content_management_system_django_django_admin_feincms_python.txt |
Q:
Best way to create Singleton Table in Django/MySQL
I want a table which can only have one record. My current solution is:
class HitchingPost(models.Model):
SINGLETON_CHOICES = (('S', 'Singleton'),)
singleton = models.CharField(max_length=1, choices=SINGLETON_CHOICES, unique=True, null=False, default='S');
value = models.IntegerField()
def __unicode__(self):
return u"HitchingPost" # only ever one record
This is a bit ugly, and doesn't enforce the constraint at the MySQL level.
Is there a better solution?
Is there a MySQL field type which can only have one value (boolean is the smallest I've found, having two possibilities)? A base-0 digit is the nearest I've come to expressing the concept.
Is there a mathematical name for such a thing?
Thanks,
Chris.
P.S. Generated SQL is:
CREATE TABLE `appname_hitchingpost` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`singleton` varchar(1) NOT NULL UNIQUE,
`value` integer NOT NULL
)
;
A:
This is a bit ugly, and doesn't enforce the constraint at the MySQL level.
If you are worried about enforcement you ought to look at Django's model validation methods. You can write a custom validate_unique that will raise a ValidationError if HitchingPost.objects.count() != 0.
class HitchingPost(models.Model):
...
def validate_unique(self, exclude = None):
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
if HitchingPost.objects.count() != 0:
raise ValidationError({NON_FIELD_ERRORS: ["There can be only one!"]})
Is there a better solution?
Hard to say without getting knowing more about your broader requirement.
Is there a MySQL field type which can only have one value (boolean is the smallest I've found, having two possibilities)? A base-0 digit is the nearest I've come to expressing the concept.
You can try a custom single element enum. I've never tried anything like it, so take my advice with a pinch of salt.
Is there a mathematical name for such a thing?
Set-once-constant? I made that up. In truth I have no idea. Better people here will help you out.
| Best way to create Singleton Table in Django/MySQL | I want a table which can only have one record. My current solution is:
class HitchingPost(models.Model):
SINGLETON_CHOICES = (('S', 'Singleton'),)
singleton = models.CharField(max_length=1, choices=SINGLETON_CHOICES, unique=True, null=False, default='S');
value = models.IntegerField()
def __unicode__(self):
return u"HitchingPost" # only ever one record
This is a bit ugly, and doesn't enforce the constraint at the MySQL level.
Is there a better solution?
Is there a MySQL field type which can only have one value (boolean is the smallest I've found, having two possibilities)? A base-0 digit is the nearest I've come to expressing the concept.
Is there a mathematical name for such a thing?
Thanks,
Chris.
P.S. Generated SQL is:
CREATE TABLE `appname_hitchingpost` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`singleton` varchar(1) NOT NULL UNIQUE,
`value` integer NOT NULL
)
;
| [
"\nThis is a bit ugly, and doesn't enforce the constraint at the MySQL level.\n\nIf you are worried about enforcement you ought to look at Django's model validation methods. You can write a custom validate_unique that will raise a ValidationError if HitchingPost.objects.count() != 0.\nclass HitchingPost(models.Mode... | [
2
] | [] | [] | [
"django",
"django_models",
"mysql",
"python"
] | stackoverflow_0003777602_django_django_models_mysql_python.txt |
Q:
Lightweight framework for forms w Ajax in Python
I'm new to Python and would like to know of some good framework / code library out there to help me out with building forms w/ ajax (and fallback to no-js) submits.
Doing it from scratch is possible ofcourse, but since this is such a common task I figured there must be some great stuff out there.
Django could be the way, but seems to big for this.
Thanks!
A:
Are you looking for built-in AJAX support like Ruby on Rails? Or are you looking for a web framework that will work well with AJAX?
If you are looking for the latter, then Flask is a "micro framework" that is considerably smaller than Django. There are others such as web.py (again, very compact), Pylons and Turbogears but I guess you'd have already considered them.
A:
Maybe not a direct answer but something definitely worth a look is the wonderful pyjamas http://pyjs.org/. That's a python to js compiler that lets you build whole browser client apps in python. If used with django as the server side (you only need the model and some views) then you get front-to-back python and a strong webservice model. For something simpler php with phpolait would be fine on the server side.
A:
I personally made good experiences with web.py in conjunction with jQuery.
web.py (Python Webframework) is very lightweight and easy to understand, writing your own Ajax requests with jQuery is not too complicated either. I used these both in my first webproject written in Python and the learning curve was nearly zero. :)
| Lightweight framework for forms w Ajax in Python | I'm new to Python and would like to know of some good framework / code library out there to help me out with building forms w/ ajax (and fallback to no-js) submits.
Doing it from scratch is possible ofcourse, but since this is such a common task I figured there must be some great stuff out there.
Django could be the way, but seems to big for this.
Thanks!
| [
"Are you looking for built-in AJAX support like Ruby on Rails? Or are you looking for a web framework that will work well with AJAX? \nIf you are looking for the latter, then Flask is a \"micro framework\" that is considerably smaller than Django. There are others such as web.py (again, very compact), Pylons and Tu... | [
1,
1,
1
] | [] | [] | [
"ajax",
"forms",
"python"
] | stackoverflow_0003777418_ajax_forms_python.txt |
Q:
how to get the value of the 'class' attribute in a link?
I wrote the sentence as follows:
allLinkValues = ie.getLinksValue('class')
but the return values are all None, don't know why...
A:
should be 'className' in IE...
| how to get the value of the 'class' attribute in a link? | I wrote the sentence as follows:
allLinkValues = ie.getLinksValue('class')
but the return values are all None, don't know why...
| [
"should be 'className' in IE...\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003752154_python.txt |
Q:
Possible to use unittest-like fixtures in py.test?
I really like py.test, but I am having lots of difficulty understanding how funcargs work.
Is it possible to use a command line argument or an extension to enable the use of something that performs a similar role to unittest.TestCase.setUp and unittest.TestCase.tearDown?
A:
py.test supports "normal" xunit method-based fixtures by default, see:
http://codespeak.net/py/dist/test/xunit_setup.html
Alternatively you can subclass from unittest.TestCase and use .setUp/tearDown but the latter may be a bit limited.
| Possible to use unittest-like fixtures in py.test? | I really like py.test, but I am having lots of difficulty understanding how funcargs work.
Is it possible to use a command line argument or an extension to enable the use of something that performs a similar role to unittest.TestCase.setUp and unittest.TestCase.tearDown?
| [
"py.test supports \"normal\" xunit method-based fixtures by default, see:\nhttp://codespeak.net/py/dist/test/xunit_setup.html\nAlternatively you can subclass from unittest.TestCase and use .setUp/tearDown but the latter may be a bit limited.\n"
] | [
1
] | [] | [] | [
"pytest",
"python",
"unit_testing"
] | stackoverflow_0003731768_pytest_python_unit_testing.txt |
Q:
i want a to resize an image but without distortion
I have an image having dimension 1000*500
I want to make it of 400*300
But My image should not looked distorted.
http://www.daniweb.com/forums/thread295652.html - i used this as a reference. But My image get distorted.
A:
Your target image size has a different aspect ratio to that of the original. The original is 2:1 but the target is 4:3.
You can resize preserving the aspect ratio, but depending on which dimension you choose you'll either get an image that's 400 x 200 or 600 x 300.
If you need the image to be 400 x 300 then you'll need to resize to 400 x 200 and then add border to each side or 600 x 300 and add the border to the top and bottom.
| i want a to resize an image but without distortion | I have an image having dimension 1000*500
I want to make it of 400*300
But My image should not looked distorted.
http://www.daniweb.com/forums/thread295652.html - i used this as a reference. But My image get distorted.
| [
"Your target image size has a different aspect ratio to that of the original. The original is 2:1 but the target is 4:3.\nYou can resize preserving the aspect ratio, but depending on which dimension you choose you'll either get an image that's 400 x 200 or 600 x 300.\nIf you need the image to be 400 x 300 then you'... | [
5
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0003778043_image_processing_python.txt |
Q:
Is there a app or python package for managing background python script add,execute,stop?
I want an app or python package that can
1.Dynamically add python script to the background
2.Execute a specified time
3.Check is this python script is running,
4.Also i can kill the current execute script.
Is already has such package,so i needn't care about cron, at, check processing is running etc.
Cron only can provide execute job periodically,AT provide execute job once at future.
They didn't supply well wrapped python package, although there's a python-crontab, but it wasn't work
What I want is a process control management, like start,monitor process current status, I found the supervisor is exactly what I want, also it provide a web gui & xmlprc for intergate it into my app.
I think supervisor is a better choice,and it's provide a high level API, I hope i have explain why I don't use Cron & AT clearly
A:
Take a look at http://supervisord.org/.
| Is there a app or python package for managing background python script add,execute,stop? | I want an app or python package that can
1.Dynamically add python script to the background
2.Execute a specified time
3.Check is this python script is running,
4.Also i can kill the current execute script.
Is already has such package,so i needn't care about cron, at, check processing is running etc.
Cron only can provide execute job periodically,AT provide execute job once at future.
They didn't supply well wrapped python package, although there's a python-crontab, but it wasn't work
What I want is a process control management, like start,monitor process current status, I found the supervisor is exactly what I want, also it provide a web gui & xmlprc for intergate it into my app.
I think supervisor is a better choice,and it's provide a high level API, I hope i have explain why I don't use Cron & AT clearly
| [
"Take a look at http://supervisord.org/.\n"
] | [
0
] | [] | [] | [
"at_job",
"background",
"process",
"python"
] | stackoverflow_0003778106_at_job_background_process_python.txt |
Q:
PySide Error - QPaintDevice: Cannot destroy paint device that is being painted
I'm baffled by this one. I tried moving the QPainter to it's own def as some have suggested, but it gives the exact same error. Here's the def I created.
def PaintButtons(self):
solid = QtGui.QPixmap(200, 32)
paint = QtGui.QPainter()
paint.begin(solid)
paint.setPen(QtGui.Qcolor(255,255,255))
paint.setBrush(QtGui.QColor(255, 0, 0))
paint.drawRect(0, 0, 200, 32)
paint.end()
A:
It was just a typo. You're using Qcolor (the first occurrence).Changing that to QColor will do the trick. :)
| PySide Error - QPaintDevice: Cannot destroy paint device that is being painted | I'm baffled by this one. I tried moving the QPainter to it's own def as some have suggested, but it gives the exact same error. Here's the def I created.
def PaintButtons(self):
solid = QtGui.QPixmap(200, 32)
paint = QtGui.QPainter()
paint.begin(solid)
paint.setPen(QtGui.Qcolor(255,255,255))
paint.setBrush(QtGui.QColor(255, 0, 0))
paint.drawRect(0, 0, 200, 32)
paint.end()
| [
"It was just a typo. You're using Qcolor (the first occurrence).Changing that to QColor will do the trick. :)\n"
] | [
2
] | [] | [] | [
"pyside",
"python"
] | stackoverflow_0003768440_pyside_python.txt |
Q:
how to displace an image in python?
I have an image size 400*200.
I have a frame size 400* 300.
I want to put the image in the center of frame. That is my image cordinate (0,0) starts with the frame cordinates (0,50).
A:
frame= Image.new(image.mode, (400, 300))
frame.paste(image, (0, 50))
(frame.paste(image, (0, 50), image) if the image to be framed has a transparency mask you want to keep. And pass a third parameter to Image.new to set the background colour of the frame if the default isn't what you want.)
| how to displace an image in python? | I have an image size 400*200.
I have a frame size 400* 300.
I want to put the image in the center of frame. That is my image cordinate (0,0) starts with the frame cordinates (0,50).
| [
"frame= Image.new(image.mode, (400, 300))\nframe.paste(image, (0, 50))\n\n(frame.paste(image, (0, 50), image) if the image to be framed has a transparency mask you want to keep. And pass a third parameter to Image.new to set the background colour of the frame if the default isn't what you want.)\n"
] | [
2
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0003778300_python_python_imaging_library.txt |
Q:
Get original row number from .get_model() and .get_path() after TreeView was resorted
So I have this TreeView/TreeStore, which I fill with data from a list. My application uses only said list as reference data. The TreeStore is just constructed for display. And the TreeView can be resorted by tipping the column headers. Because .set_sort_column_id() was used for initialization of each column.
Problem is, following code always returns the clicked row number in the display:
# convert ListStore iter to row number
def rowno(self):
(model, iter) = self.MY_LIST_STORE.get_selection().get_selected()
return model.get_path(iter)[0]
It's supposed to do that. This works fine for me as long as the original unsorted list is displayed. Once the TreeView (and TreeStore?) is resorted, the displayed row numbers (.get_path) no longer correspond to the row numbers in my original data store.
How can I map this? Or how can I find out which selected path number corresponds to which entry in the originally passed TreeView list?
(Of course, I could insert a faux column into the TreeStore to keep my original row number. But there must be some kind of native way to achieve it?)
A:
Congratulations, you have entered just about the most nightmarish thing that PyGTK has to offer. I don't expect any bounty for this, but my solution revolves around wrapping your Model in a Sortable model and also in a Filterable one. This way, you can get the various paths and iters for the 3 nested models depending on what you want. The code is far too extreme for here, but we have generalised it in PyGTKHelpers to use without pain, or to copy for your own implementation. Here is the module.
| Get original row number from .get_model() and .get_path() after TreeView was resorted | So I have this TreeView/TreeStore, which I fill with data from a list. My application uses only said list as reference data. The TreeStore is just constructed for display. And the TreeView can be resorted by tipping the column headers. Because .set_sort_column_id() was used for initialization of each column.
Problem is, following code always returns the clicked row number in the display:
# convert ListStore iter to row number
def rowno(self):
(model, iter) = self.MY_LIST_STORE.get_selection().get_selected()
return model.get_path(iter)[0]
It's supposed to do that. This works fine for me as long as the original unsorted list is displayed. Once the TreeView (and TreeStore?) is resorted, the displayed row numbers (.get_path) no longer correspond to the row numbers in my original data store.
How can I map this? Or how can I find out which selected path number corresponds to which entry in the originally passed TreeView list?
(Of course, I could insert a faux column into the TreeStore to keep my original row number. But there must be some kind of native way to achieve it?)
| [
"Congratulations, you have entered just about the most nightmarish thing that PyGTK has to offer. I don't expect any bounty for this, but my solution revolves around wrapping your Model in a Sortable model and also in a Filterable one. This way, you can get the various paths and iters for the 3 nested models depend... | [
1
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003743756_gtk_gtktreeview_pygtk_python.txt |
Q:
Find all tags with a specific attribute value
How can I iterate over all tags which have a specific attribute with a specific value? For instance, let's say we need the data1, data2 etc... only.
<html>
<body>
<invalid html here/>
<dont care> ... </dont care>
<invalid html here too/>
<interesting attrib1="naah, it is not this"> ... </interesting tag>
<interesting attrib1="yes, this is what we want">
<group>
<line>
data
</line>
</group>
<group>
<line>
data1
<line>
</group>
<group>
<line>
data2
<line>
</group>
</interesting>
</body>
</html>
I tried BeautifulSoup but it can't parse the file. lxml's parser, though, seems to work:
broken_html = get_sanitized_data(SITE)
parser = etree.HTMLParser()
tree = etree.parse(StringIO(broken_html), parser)
result = etree.tostring(tree.getroot(), pretty_print=True, method="html")
print(result)
I am not familiar with its API, and I could not figure out how to use either getiterator or xpath.
A:
Here's one way, using lxml and the XPath 'descendant::*[@attrib1="yes, this is what we want"]'. The XPath tells lxml to look at all the descendants of the current node and return those with an attrib1 attribute equal to "yes, this is what we want".
import lxml.html as lh
import cStringIO
content='''
<html>
<body>
<invalid html here/>
<dont care> ... </dont care>
<invalid html here too/>
<interesting attrib1="naah, it is not this"> ... </interesting tag>
<interesting attrib1="yes, this is what we want">
<group>
<line>
data
</line>
</group>
<group>
<line>
data1
<line>
</group>
<group>
<line>
data2
<line>
</group>
</interesting>
</body>
</html>
'''
doc=lh.parse(cStringIO.StringIO(content))
tags=doc.xpath('descendant::*[@attrib1="yes, this is what we want"]')
print(tags)
# [<Element interesting at b767e14c>]
for tag in tags:
print(lh.tostring(tag))
# <interesting attrib1="yes, this is what we want"><group><line>
# data
# </line></group><group><line>
# data1
# <line></line></line></group><group><line>
# data2
# <line></line></line></group></interesting>
| Find all tags with a specific attribute value | How can I iterate over all tags which have a specific attribute with a specific value? For instance, let's say we need the data1, data2 etc... only.
<html>
<body>
<invalid html here/>
<dont care> ... </dont care>
<invalid html here too/>
<interesting attrib1="naah, it is not this"> ... </interesting tag>
<interesting attrib1="yes, this is what we want">
<group>
<line>
data
</line>
</group>
<group>
<line>
data1
<line>
</group>
<group>
<line>
data2
<line>
</group>
</interesting>
</body>
</html>
I tried BeautifulSoup but it can't parse the file. lxml's parser, though, seems to work:
broken_html = get_sanitized_data(SITE)
parser = etree.HTMLParser()
tree = etree.parse(StringIO(broken_html), parser)
result = etree.tostring(tree.getroot(), pretty_print=True, method="html")
print(result)
I am not familiar with its API, and I could not figure out how to use either getiterator or xpath.
| [
"Here's one way, using lxml and the XPath 'descendant::*[@attrib1=\"yes, this is what we want\"]'. The XPath tells lxml to look at all the descendants of the current node and return those with an attrib1 attribute equal to \"yes, this is what we want\".\nimport lxml.html as lh \nimport cStringIO\n\ncontent='''\n<ht... | [
3
] | [] | [] | [
"html_parsing",
"lxml",
"python"
] | stackoverflow_0003778512_html_parsing_lxml_python.txt |
Q:
why can't I fetch sql statements in python?
I have a very large table (374870 rows) and when I run the following code timestamps just ends up being a long int with the value 374870.... I want to be able to grab all the timestamps in the table... but all I get is a long int :S
import MySQLdb
db = MySQLdb.connect(
host = "Some Host",
user = "SOME USER",
passwd = "SOME PASS",
db = "SOME DB",
port = 3306
)
sql = "SELECT `timestamp` from `table`"
timestamps = db.cursor().execute(sql)
A:
Try this:
cur = db.cursor()
cur.execute(sql)
timestamps = []
for rec in cur:
timestamps.append(rec[0])
A:
You need to call fetchmany() on the cursor to fetch more than one row, or call fetchone() in a loop until it returns None.
A:
Consider the possibility that the not-very-long integer that you are getting is the number of rows in your query result.
Consider reading the docs (PEP 249) ... (1) return value from cursor.execute() is not defined; what you are seeing is particular to your database and for portability sake should not be relied on. (2) you need to do results = cursor.fetch{one|many|all}() or iterate over the cursor ... for row in cursor: do_something(row)
| why can't I fetch sql statements in python? | I have a very large table (374870 rows) and when I run the following code timestamps just ends up being a long int with the value 374870.... I want to be able to grab all the timestamps in the table... but all I get is a long int :S
import MySQLdb
db = MySQLdb.connect(
host = "Some Host",
user = "SOME USER",
passwd = "SOME PASS",
db = "SOME DB",
port = 3306
)
sql = "SELECT `timestamp` from `table`"
timestamps = db.cursor().execute(sql)
| [
"Try this:\ncur = db.cursor()\ncur.execute(sql)\ntimestamps = []\nfor rec in cur:\n timestamps.append(rec[0])\n\n",
"You need to call fetchmany() on the cursor to fetch more than one row, or call fetchone() in a loop until it returns None.\n",
"Consider the possibility that the not-very-long integer that you... | [
2,
1,
0
] | [] | [] | [
"mysql",
"python",
"sql"
] | stackoverflow_0003778935_mysql_python_sql.txt |
Q:
Create Python array.array Object from cStringIO Object
I want to create an array.array object from a cStringIO object:
import cStringIO, array
s = """
<several lines of text>
"""
f = cStringIO.StringIO(s)
a = array.array('c')
a.fromfile(f, len(s))
But I get the following exception:
Traceback (most recent call last):
File "./myfile.py", line 22, in <module>
a.fromfile(f, len(s))
TypeError: arg1 must be open file
It seems like array.array() is checking the type() of the first argument, which makes it incompatible with cStringIO (and StringIO for that matter). Is there any way to make this work?
A:
Why not use a.fromstring()? Since the StringIO buffer is entirely in memory, there is no benefit to trying to use a file api to read the bits from one memory location to another.
a = array.array('c')
a.fromstring(s)
If you are using StringIO for another reason (as a memory buffer, or as a file earlier on), then you can use StringIO's getvalue() function to get the string value.
| Create Python array.array Object from cStringIO Object | I want to create an array.array object from a cStringIO object:
import cStringIO, array
s = """
<several lines of text>
"""
f = cStringIO.StringIO(s)
a = array.array('c')
a.fromfile(f, len(s))
But I get the following exception:
Traceback (most recent call last):
File "./myfile.py", line 22, in <module>
a.fromfile(f, len(s))
TypeError: arg1 must be open file
It seems like array.array() is checking the type() of the first argument, which makes it incompatible with cStringIO (and StringIO for that matter). Is there any way to make this work?
| [
"Why not use a.fromstring()? Since the StringIO buffer is entirely in memory, there is no benefit to trying to use a file api to read the bits from one memory location to another.\na = array.array('c')\na.fromstring(s)\n\nIf you are using StringIO for another reason (as a memory buffer, or as a file earlier on), th... | [
4
] | [] | [] | [
"python",
"stringio"
] | stackoverflow_0003779206_python_stringio.txt |
Q:
Pre-interpret Django site at deployment time
I deploy Django apps using a fabric script that checks out a copy of my project and when everything is in place the source is symlinked and the web server is reloaded (guessing this is a typical approach).
My concern is that the first time the site gets hit after deployment all the python scripts need to be re-interpreted.
I have some bright ideas about how I might force the code to get processed before any clients hit it but I'm looking for any high-level strategies people might use to accomplish this.
Any suggestions are welcome. Thanks in advance for any advice you can offer.
-Mike
A:
python -m compileall /path/to/django/site
Will precompile any .py files under the directory recursively.
How are you running django? If you're using WSGI the interpreter or interpreters are already running and would have already compiled a lot of your django site. What is being dynamically loaded?
| Pre-interpret Django site at deployment time | I deploy Django apps using a fabric script that checks out a copy of my project and when everything is in place the source is symlinked and the web server is reloaded (guessing this is a typical approach).
My concern is that the first time the site gets hit after deployment all the python scripts need to be re-interpreted.
I have some bright ideas about how I might force the code to get processed before any clients hit it but I'm looking for any high-level strategies people might use to accomplish this.
Any suggestions are welcome. Thanks in advance for any advice you can offer.
-Mike
| [
"python -m compileall /path/to/django/site\n\nWill precompile any .py files under the directory recursively.\nHow are you running django? If you're using WSGI the interpreter or interpreters are already running and would have already compiled a lot of your django site. What is being dynamically loaded?\n"
] | [
1
] | [] | [] | [
"django",
"fabric",
"python"
] | stackoverflow_0003779365_django_fabric_python.txt |
Q:
Loop thru a directory and search in all pre-filtered XML files for a word
I would like to loop through a given directory and seach in all pre-filtered files
for a search word. I prepared this code, but it is not looping thru all files, only
the last file which was found is analyzed. Ideally all files should be analyzed and
the output should be saved in a textfile. Could someone help?
import os, glob
for filename in glob.glob("C:\\test*.xml"):
print filename
for line in open(filename):
if "SEARCHWORD" in line:
print line
The OUTPUT is looking like:
C:\test-261.xml
C:\test-262.xml
C:\test-263.xml
C:\test-264.xml
<Area>SEARCHWORD</Area>
A:
Indent the 2nd for-loop one more level to make it loop for every file found.
for filename in glob.glob("C:\\test*.xml"):
print filename
#-->
for line in open(filename):
if "SEARCHWORD" in line:
print line
BTW, since you are just iterating on the globbed result instead of storing it, you should use glob.iglob to save for duplicating the list. Also, it is better to put that open() in a with-statement so that the file can be closed properly even an exception is thrown.
for filename in glob.iglob('C:\\test*.xml'):
print filename
with open(filename) as f:
for line in f:
if 'SEARCHWORD' in line:
print line
A:
You can also put the results in a file:
import os, glob
results = open('results.txt', 'w')
for filename in glob.glob("C:\test*.xml"):
for line in open(filename):
if "SEARCHWORD" in line:
results.write(line)
results.close()
| Loop thru a directory and search in all pre-filtered XML files for a word | I would like to loop through a given directory and seach in all pre-filtered files
for a search word. I prepared this code, but it is not looping thru all files, only
the last file which was found is analyzed. Ideally all files should be analyzed and
the output should be saved in a textfile. Could someone help?
import os, glob
for filename in glob.glob("C:\\test*.xml"):
print filename
for line in open(filename):
if "SEARCHWORD" in line:
print line
The OUTPUT is looking like:
C:\test-261.xml
C:\test-262.xml
C:\test-263.xml
C:\test-264.xml
<Area>SEARCHWORD</Area>
| [
"Indent the 2nd for-loop one more level to make it loop for every file found.\nfor filename in glob.glob(\"C:\\\\test*.xml\"):\n print filename\n\n#-->\n for line in open(filename):\n if \"SEARCHWORD\" in line:\n print line\n\nBTW, since you are just iterating on the globbed result instead o... | [
2,
0
] | [] | [] | [
"indentation",
"python",
"syntax"
] | stackoverflow_0003779632_indentation_python_syntax.txt |
Q:
Best dynamic languages for OpenGL/general graphics
Which are the most mature and well supported solutions for writing graphical programs?
I have been using C++ with OpenGL/GLUT, but would like to try a more flexible and expressive approach.
Ruby and Processing? Python and OGRE? What things have worked well for you?
A:
If you are just interested in experimenting, I'd suggest picking a 3D framework with bindings for a dynamic language you are already familiar with.
I started doing experiments with Ruby/OpenGL a year or three ago and that was easy enough to play around with.
If you seriously want to build a project (for whatever reason), I'd suggest picking a framework based on a combination of
The native language it's implemented in (or runtime it runs on)
The dynamic language bindings available for the engine or runtime
The license of the framework
If you want your project to be fairly easily running across different OS'es, you'll probably want to pick a framework written in Java (because the JVM runs everywhere) with bindings in Ruby (jRuby) or JavaScript (because these languages are well supported there). This would, however, limit the frameworks available to you. (This is my OSS + linux bias showing).
Wikipedia has a list of game engines. Based on several criteria I started a project with jMonkeyEngine (v2) and found it easy to work with and control from Rhino (a JVM JavaScript implementation).
I recently saw a presentation from another Java-based framework with bindings for several languages that looked really cool (inspired by the Ogre engine), but I forget the name and can't find it in the list.
Doing C# at the time I did look at projects/frameworks targeting both dotNet and Mono for running across platforms but it was too much hassle to get the development builds of the (Tao?) framework and the Mono Lua bindings running. Maybe things have changed.
To sum it up, pick a framework that can run on the environment(s) you want with bindings for the dynamic language that you want to use. Even if the framework library code available for the dynamic language you want to use is fairly minimal you can easily extend it if you can work with the underlying language. If you're fluent with C++, Java and C# shouldn't be too much of a stretch.
A:
Given you are familiar with C++, you might give Lua a try. Lua is a dynamic language that can be embedded in any C/C++ program. It is very popular in the game industry.
A:
I would like to mention Python with PyOpenGL as an option to consider.
If you are already familiar with OpenGL, PyOpenGL is basically a API wrapper written in Python. I was surprised at first how similar the code looks in Python and in C++. Like this (note I'm also using Pyglet):
def setup_render(self):
'''First rendering setup'''
glClearColor(0.0, 0.0, 0.0, 1.0)
glClearDepth(1.0)
glEnable(GL_LIGHTING)
glEnable(GL_DEPTH_TEST)
glEnable(GL_ALPHA_TEST)
glEnable(GL_CULL_FACE)
def draw(self, time_passed):
'''Drawing events'''
if self.has_exit:
pyglet.app.exit()
return
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glUseProgram(self.shader.program)
self.set_lights()
# Draw objects here
glTranslate(0, 0, -10)
glScale(5.0, 5.0, 5.0)
glutSolidSphere(1, 16, 16)
See how similar it is to C++ code.
I was able to quickly pick up PyOpenGL in Python, and implemented a Quaternion class under 200 lines. If you're comfortable with Python, I wouldn't hesitate to recommend you to check it out.
By the way, PyOpenGL's API documentation is far more readable than the official one, too.
A:
If you are looking for dynamic languages that support OpenGL out-of-the-box (no external bindings) try these:
PLT Scheme
Spark-Scheme
Factor
A:
My personal suggestion if you are after maturity and support would be Processing - very flexible, open source, well documented and a great community. Syntax is C-like so you should have no difficulty picking it up.
One slightly more cutting edge solution that looks very promising (but I haven't got round to testing yet!) is Penumbra - a Clojure library for OpenGL development in a dynamic functional programming style. Here's a elegant little snippet:
(enable :light0)
(push-matrix
(translate 0 0 -10)
(draw-quads
(vertex 0 0 0)
(vertex 0 1 0)
(vertex 1 1 0)
(vertex 1 0 0)))
Note that thanks to lots of Clojure macro cleverness, it automatically and transparently handles things like popping the transformation matrices at the right time. Other things that look good are things like GPGPU support.
| Best dynamic languages for OpenGL/general graphics | Which are the most mature and well supported solutions for writing graphical programs?
I have been using C++ with OpenGL/GLUT, but would like to try a more flexible and expressive approach.
Ruby and Processing? Python and OGRE? What things have worked well for you?
| [
"If you are just interested in experimenting, I'd suggest picking a 3D framework with bindings for a dynamic language you are already familiar with.\nI started doing experiments with Ruby/OpenGL a year or three ago and that was easy enough to play around with.\nIf you seriously want to build a project (for whatever... | [
8,
5,
4,
2,
2
] | [] | [] | [
"graphics",
"processing",
"python",
"ruby",
"scheme"
] | stackoverflow_0001904454_graphics_processing_python_ruby_scheme.txt |
Q:
Determining a file's path name from different working directories in python
I have a python module that is shared among several of my projects (the projects each have a different working directory). One of the functions in this shared module, executes a script using os.spawn. The problem is, I'm not sure what pathname to give to os.spawn since I don't know what the current working directory will be when the function is called. How can I reference the file in a way that any caller can find it? Thanks!
A:
So I just learned about the __file__ variable, which will provide a solution to my problem. I can use file to get a pathname which will be constant among all projects, and use that to reference the script I need to call, since the script will always be in the same location relative to __file__. However, I'm open to other/better methods if anyone has them.
A:
Put it in a well known directory (/usr/lib/yourproject/ or ~/lib or something similar), or have it in a well known relative path based on the location of your source files that are using it.
A:
The following piece of code will find the location of the calling module, which makes sense from a programmer's point of view:
## some magic to allow paths relative to calling module
if path.startswith('/'):
self.path = path
else:
frame = sys._getframe(1)
base = os.path.dirname(frame.f_globals['__file__'])
self.path = os.path.join(base, path)
I.e. if your project lives in /home/foo/project, and you want to reference a script 'myscript' in scripts/, you can simply pass 'scripts/myscript'. The snippet will figure out the caller is in /home/foo/project and the entire path should be /home/foo/projects/scripts/myscript.
Alternatively, you can always require the programmer to specify a full path, and check using os.path.exists if it exists.
A:
You might find the materials in this PyCon 2010 presentation on cross platform application development and distribution useful. One of the problems they solve is finding data files consistently across platforms and for installed vs development checkouts of the code.
| Determining a file's path name from different working directories in python | I have a python module that is shared among several of my projects (the projects each have a different working directory). One of the functions in this shared module, executes a script using os.spawn. The problem is, I'm not sure what pathname to give to os.spawn since I don't know what the current working directory will be when the function is called. How can I reference the file in a way that any caller can find it? Thanks!
| [
"So I just learned about the __file__ variable, which will provide a solution to my problem. I can use file to get a pathname which will be constant among all projects, and use that to reference the script I need to call, since the script will always be in the same location relative to __file__. However, I'm open t... | [
1,
0,
0,
0
] | [] | [] | [
"file",
"python",
"relative_path"
] | stackoverflow_0003780094_file_python_relative_path.txt |
Q:
How to fix ImportError in matplotlib
I compiled matplotlib on a mac running snow leopard only to find that when I import matplotlib.pyplot I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/pyplot.py", line 6, in <module>
from matplotlib.figure import Figure, figaspect
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/figure.py", line 18, in <module>
from axes import Axes, SubplotBase, subplot_class_factory
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/axes.py", line 12, in <module>
import matplotlib.axis as maxis
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/axis.py", line 10, in <module>
import matplotlib.font_manager as font_manager
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 52, in <module>
from matplotlib import ft2font
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/ft2font.so, 2): Symbol not found: _FT_Attach_File
Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/ft2font.so
Expected in: dynamic lookup
How do I fix this?
A:
Building matplotlib on OS X is notoriously fraught with problems linking to mismatched versions of libraries that can be in the system directories, /usr/local, /opt/local, what have you. That's why there is a README.osx file in the source distribution advising you to use the make.osx file provided in the distribution that fetches and compiles the libraries and builds matplotlib against the fetched copy.
| How to fix ImportError in matplotlib | I compiled matplotlib on a mac running snow leopard only to find that when I import matplotlib.pyplot I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/pyplot.py", line 6, in <module>
from matplotlib.figure import Figure, figaspect
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/figure.py", line 18, in <module>
from axes import Axes, SubplotBase, subplot_class_factory
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/axes.py", line 12, in <module>
import matplotlib.axis as maxis
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/axis.py", line 10, in <module>
import matplotlib.font_manager as font_manager
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 52, in <module>
from matplotlib import ft2font
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/ft2font.so, 2): Symbol not found: _FT_Attach_File
Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/ft2font.so
Expected in: dynamic lookup
How do I fix this?
| [
"Building matplotlib on OS X is notoriously fraught with problems linking to mismatched versions of libraries that can be in the system directories, /usr/local, /opt/local, what have you. That's why there is a README.osx file in the source distribution advising you to use the make.osx file provided in the distribut... | [
0
] | [] | [] | [
"import",
"importerror",
"matplotlib",
"python"
] | stackoverflow_0003120265_import_importerror_matplotlib_python.txt |
Q:
Regex in python to get javadoc-style comments in CSS
I'm writing a python script to loop through a directory of CSS files and save the contents of any which contain a specifically-formatted javadoc style comment.
The comment/CSS looks like this:
/**thirdpartycss
* @description Used for fixing stuff
*/
.class_one {
margin: 10px;
}
#id_two {
padding: 2px;
}
The regex to fetch the entire contents of the file looks like this:
pattern = "/\*\*thirdpartycss(.*?)}$"
matches = re.findall(pattern, css, flags=re.MULTILINE | re.DOTALL)
This gives me the file contents. What I want to do now is write a regex to grab each CSS definition within the class. This is what I tried:
rule_pattern = "(.*){(.*)}?"
rules = re.findall(rule_pattern, matches[0], flags=re.MULTILINE | re.DOTALL)
I'm basically trying to find any text, then an opening {, any text, then a closing } - I want a list of all of the CSS classes, essentially, but this just returns the entire string in one chunk.
Can anybody point me in the right direction?
Thanks.
Matt
A:
{(.*)} is a greedy match -- it will match from the first { to the last }, thus gobble up any {/} pairs that might be inside those. You want non-greedy matching, that is
{(.*?)}
the difference is the question mark after the asterisk, making it non-greedy.
This still won't work if you need to properly match "nested" braces -- but then, nothing in the RE world will: among regular languages many well-known limitations (regular languages are those that regular expressions can match) is that "properly nesting" any kind of open/closed parentheses is impossible (some incredibly-extended so-called-RE manage to, but not Python's, and anybody with CS background will find calling those expression "regular" offensive anyway;-). If you need more general parsing than REs can afford, pyparsing or other full-fledged Python parsers are the right way to go.
A:
@Alex is right (is he ever not? but I digress). You are better off using a custom parser if you need more specific parsing than what regular expressions can offer. Luckily you don't have to reinvent the (CSS parsing) wheel. There is an already existing solution for this.
I faced a similar requirement some time back. The cssutils module came in handy at the time. I just refreshed my cssutils fu to cook up this code snippet for you:
In [16]: import cssutils
In [17]: s = """/**thirdpartycss
* @description Used for fixing stuff
*/
.class_one {
margin: 10px;
}
#id_two {
padding: 2px;
}"""
In [26]: sheet = cssutils.parseString(s)
In [27]: sheet.cssRules
Out[27]:
[cssutils.css.CSSComment(cssText=u'/**thirdpartycss\n* @description Used for fixing stuff\n*/'),
cssutils.css.CSSStyleRule(selectorText=u'.class_one', style=u'margin: 10px'),
cssutils.css.CSSStyleRule(selectorText=u'#id_two', style=u'padding: 2px')]
In [28]: sheet.cssRules[0].cssText
Out[28]: u'/**thirdpartycss\n* @description Used for fixing stuff\n*/'
In [29]: print sheet.cssRules[0].cssText
-------> print(sheet.cssRules[0].cssText)
/**thirdpartycss
* @description Used for fixing stuff
*/
You can parse the CSS and then loop through the sheet object's cssRules to find all CSSComment instances.
| Regex in python to get javadoc-style comments in CSS | I'm writing a python script to loop through a directory of CSS files and save the contents of any which contain a specifically-formatted javadoc style comment.
The comment/CSS looks like this:
/**thirdpartycss
* @description Used for fixing stuff
*/
.class_one {
margin: 10px;
}
#id_two {
padding: 2px;
}
The regex to fetch the entire contents of the file looks like this:
pattern = "/\*\*thirdpartycss(.*?)}$"
matches = re.findall(pattern, css, flags=re.MULTILINE | re.DOTALL)
This gives me the file contents. What I want to do now is write a regex to grab each CSS definition within the class. This is what I tried:
rule_pattern = "(.*){(.*)}?"
rules = re.findall(rule_pattern, matches[0], flags=re.MULTILINE | re.DOTALL)
I'm basically trying to find any text, then an opening {, any text, then a closing } - I want a list of all of the CSS classes, essentially, but this just returns the entire string in one chunk.
Can anybody point me in the right direction?
Thanks.
Matt
| [
"{(.*)} is a greedy match -- it will match from the first { to the last }, thus gobble up any {/} pairs that might be inside those. You want non-greedy matching, that is\n{(.*?)}\n\nthe difference is the question mark after the asterisk, making it non-greedy.\nThis still won't work if you need to properly match \"... | [
2,
1
] | [] | [] | [
"css",
"javadoc",
"python",
"regex"
] | stackoverflow_0003780722_css_javadoc_python_regex.txt |
Q:
Need help with wxPython, NotebookCtrl in particular
I am trying to write a non-webbased client for a chat service on a web site, it connects to it fine via socket and can communicate with it and everything. I am writing a GUI for it (I tried writing it in tkinter but I hit some walls I really wantd to get passed, so I switched to wxPython)
What I'm having a problem with:
This application uses an extended Notebook widget called NotebookCtrl. However the same problem appears with regular Notebook. First it creates a page in which things are logged to, which is successful, and then it connects, and it's supposed to add pages with each chatroom it joins on the service. However, when it adds a tab after it's mainloop has been started (I am communicating with the GUI and the sockets via queues and threading), the tab comes up completely blank. I have been stuck on this for hours and hours and got absolutely nowhere
The example that came with the NotebookCtrl download adds and deletes pages by itself perfectly fine. I am on the edge of completely giving up on this project. Here is what the code looks like (note this is a very small portion of the application, but this covers the wxPython stuff)
class Chatroom(Panel):
''' Frame for the notebook widget to tabulate a chatroom'''
def __init__(self, ns, parent):
Panel.__init__(self, parent, -1)
self.msgs, self.typed, self.pcbuff = [], [], {}
self.members, self._topic, self._title, self.pc = None, None, None, None
self.name, self.tabsign, = ns, 0
self.hSizer1 = wx.BoxSizer(wx.HORIZONTAL)
self.vSizer = wx.BoxSizer(wx.VERTICAL)
self.Grid = wx.GridBagSizer(5, 2)
self.Title = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE | wx.TE_READONLY)
self.Topic = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE | wx.TE_READONLY)
self.Privclasses = TreeCtrl(self, size=(150, -1))
self.Buffer = wx.html.HtmlWindow(self)
self.Buffer.SetStandardFonts(8)
self.templbl = StaticText(self, -1, 'This is where the formatting buttons will go!')
# note to remember: self.templbl.SetLabel('string') sets the label
self.Typer = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE)
self.Grid.Add(self.Title, (0,0), (1,2), wx.EXPAND, 2)
self.Grid.Add(self.Topic, (1,0), (1,1), wx.EXPAND, 2)
self.Grid.Add(self.Privclasses, (1,1), (2,1), wx.EXPAND, 2)
self.Grid.Add(self.Buffer, (2,0), (1,1), wx.EXPAND, 2)
self.Grid.Add(self.templbl, (3,0), (1,1), wx.EXPAND | wx.ALIGN_LEFT, 2)
self.Grid.Add(self.Typer, (4,0), (1,1), wx.EXPAND, 2)
self.Grid.AddGrowableCol(0)
self.Grid.AddGrowableRow(2)
self.SetSizerAndFit(self.Grid)
self.Show(True)
self.Typer.Bind(EVT_CHAR, self.Typer_OnKeyDown)
def Typer_OnKeyDown(self, event):
keycode = event.GetKeyCode()
if event.ShiftDown():
if keycode == WXK_RETURN:
pass
elif keycode == WXK_BACK:
pass
elif keycode == WXK_UP:
pass
elif keycode == WXK_DOWN:
pass
else:
if keycode == WXK_RETURN:
pass
event.Skip()
def Write(self, msg, K):
self.msgs.append(msg)
if len(self.msgs) > 300:
self.msgs = self.msgs[50:]
self.Buffer.SetPage('<br>'.join(self.msgs))
class Application(App):
def __init__(self, K):
self.Queue = Queue.Queue()
self.current = ''
self.chatorder = []
self.Window = App(0)
self.frame = MainFrame(None, 0, "Komodo Dragon")
self.Pages = NC.NotebookCtrl(self.frame, 9000)
self.Channels = {}
self.AddChatroom('~Komodo', K)
self.frame.Show(True)
self.Window.SetTopWindow(self.frame)
self.Timer = _Timer(0.050, self.OnTimer)
self.Timer.start()
self.Pages.Bind(NC.EVT_NOTEBOOKCTRL_PAGE_CHANGED, self.onPageChanged)
self.Pages.Bind(NC.EVT_NOTEBOOKCTRL_PAGE_CHANGING, self.onPageChanging)
self.Pages.Bind(EVT_PAINT, self.onPaint)
self.Pages.Bind(EVT_SIZE, self.onSize)
def onPaint(self, event):
event.Skip()
def onSize(self, event):
event.Skip()
def Run(self):
self.Window.MainLoop()
def onPageChanged(self, event):
event.Skip()
def onPageChanging(self, event):
event.Skip()
# Timer and Queue functions
def OnTimer(self):
self.CheckQueue()
self.Timer = _Timer(0.050, self.OnTimer)
self.Timer.start()
def CheckQueue(self): # the Application needs to use a queue to do things in order to prevent
try: # overlaps from happening, such as runtime errors and widgets changing
while not self.Queue.empty(): # suddenly. The most common error seems to be size
func = self.Queue.get_nowait() # changes during iterations. Everything from
func() # packet processing to adding widgets needs to wait in line this way
except Queue.Empty:
pass
def AddQueue(self, func):
self.Queue.put(func)
# Channel controls
def AddChatroom(self, ns, K):
if ns in self.Channels: return
#self.typedindex = 0
c = K.format_ns(ns)
self.chatorder.append(ns)
self.current = ns
self.Channels[ns] = Chatroom(ns, self.Pages)
self.Pages.AddPage(self.Channels[ns], ns, True)
def DeleteChatroom(self, ns, bot): # Delete a channel, it's properties, and buttons
ind = self.chatorder.index(ns)
del self.chatorder[ind]
for each in self.chatorder[ind:]:
x = self.channels[each].tab.grid_info()
if x['column'] == '0': r, c = int(x['row'])-1, 9
else: r, c = int(x['row']), int(x['column'])-1
self.channels[each].tab.grid_configure(row=r, column=c)
x = self.channels[each].tab.grid_info()
self.channels[ns].Tab.destroy()
self.channels[ns].tab.destroy()
self.channels[self.chatorder[-1]].tab.select()
self.switchtab(bot, self.chatorder[-1])
x = self.tabids_reverse[ns]
del self.tabids_reverse[ns], self.tabids[x], self.channels[ns]
The Chatroom class covers what each tab should have in it. the first tab that is added in class Application's init function is perfectly fine, and even prints messages it receives from the chat service when it attempts to connect. Once the service sends a join packet to me, it calls the same exact function used to add that tab, AddChatroom(), and should create the exact same thing, only printing messages specifically for that chatroom. It creates the tab, but the Chatroom page is completely empty and grey. I am very sad :C
Thanks in advance if you can help me.
EDIT
I have written a working example of this script you can run yourself (if you have wxPython). It uses regular Notebook instead of NotebookCtrl so you don't have to download that widget as well, but the bug happens for both. The example sets up the window, and sets up the main debug tab and then a chatroom tab before entering mainloop. After mainloop, any chatrooms added afterwords are completely blank
from wx import *
import Queue, time
from threading import Timer as _Timer
from threading import Thread
# import System._NotebookCtrl.NotebookCtrl as NC ## Using regular notebook for this example
class MainFrame(Frame):
def __init__(self, parent, ID, title):
ID_FILE_LOGIN = 100
ID_FILE_RESTART = 101
ID_FILE_EXIT = 102
ID_HELP_ABOUT = 200
Frame.__init__(self, parent, ID, title,
DefaultPosition, Size(1000, 600))
self.CreateStatusBar()
self.SetStatusText("This is the statusbar")
menu_File = Menu()
menu_Help = Menu()
menu_Edit = Menu()
menu_Config = Menu()
menu_File.Append(ID_FILE_LOGIN, "&Login Info",
"Enter your deviantArt Login information")
menu_File.AppendSeparator()
menu_File.Append(ID_FILE_RESTART, "&Restart",
"Restart the program")
menu_File.Append(ID_FILE_EXIT, "E&xit",
"Terminate the program")
menu_Help.Append(ID_HELP_ABOUT, "&About",
"More information about this program")
menuBar = MenuBar()
menuBar.Append(menu_File, "&File");
menuBar.Append(menu_Edit, "&Edit");
menuBar.Append(menu_Config, "&Config");
menuBar.Append(menu_Help, "&Help");
self.SetMenuBar(menuBar)
EVT_MENU(self, ID_FILE_LOGIN, self.OnLogin)
EVT_MENU(self, ID_FILE_RESTART, self.OnRestart)
EVT_MENU(self, ID_FILE_EXIT, self.OnQuit)
EVT_MENU(self, ID_HELP_ABOUT, self.OnAbout)
def OnAbout(self, event):
dlg = MessageDialog(self, "Hi! I am Komodo Dragon! I am an application\n"
"that communicates with deviantArt's Messaging Network (dAmn)",
"Komodo", OK | ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def OnQuit(self, event):
self.Close(True)
def OnRestart(self, event):
pass
def OnLogin(self, event):
dlg = MessageDialog(self, "Enter your Login information here:\n"
"Work in progress, LOL",
"Login", OK | ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
class Chatroom(Panel):
''' Frame for the notebook widget to tabulate a chatroom'''
def __init__(self, parent, ns):
Panel.__init__(self, parent, -1)
self.msgs, self.typed, self.pcbuff = [], [], {}
self.members, self._topic, self._title, self.pc = None, None, None, None
self.name, self.tabsign, = ns, 0
self.hSizer1 = wx.BoxSizer(wx.HORIZONTAL)
self.vSizer = wx.BoxSizer(wx.VERTICAL)
self.Grid = wx.GridBagSizer(5, 2)
self.Title = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE | wx.TE_READONLY)
self.Topic = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE | wx.TE_READONLY)
self.Privclasses = TreeCtrl(self, size=(150, -1))
self.Buffer = wx.html.HtmlWindow(self)
self.Buffer.SetStandardFonts(8)
self.templbl = StaticText(self, -1, 'This is where the formatting buttons will go!')
self.Typer = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE)
self.Grid.Add(self.Title, (0,0), (1,2), wx.EXPAND, 2)
self.Grid.Add(self.Topic, (1,0), (1,1), wx.EXPAND, 2)
self.Grid.Add(self.Privclasses, (1,1), (2,1), wx.EXPAND, 2)
self.Grid.Add(self.Buffer, (2,0), (1,1), wx.EXPAND, 2)
self.Grid.Add(self.templbl, (3,0), (1,1), wx.EXPAND | wx.ALIGN_LEFT, 2)
self.Grid.Add(self.Typer, (4,0), (1,1), wx.EXPAND, 2)
self.Grid.AddGrowableCol(0)
self.Grid.AddGrowableRow(2)
self.SetSizerAndFit(self.Grid)
self.Show(True)
self.Typer.Bind(EVT_CHAR, self.Typer_OnKeyDown)
def Typer_OnKeyDown(self, event):
keycode = event.GetKeyCode()
if event.ShiftDown():
if keycode == WXK_RETURN:
pass
elif keycode == WXK_BACK:
pass
elif keycode == WXK_UP:
pass
elif keycode == WXK_DOWN:
pass
else:
if keycode == WXK_RETURN:
pass
event.Skip()
def Write(self, msg):
self.msgs.append(msg)
if len(self.msgs) > 300:
self.msgs = self.msgs[50:]
self.Buffer.SetPage('<br>'.join(self.msgs))
class Application(App):
def __init__(self, K):
self.Queue = Queue.Queue()
self.current = ''
self.chatorder = []
self.Window = App(0)
self.frame = MainFrame(None, 0, "Komodo Dragon")
self.Pages = Notebook(self.frame, 9000)
self.Channels = {}
self.AddChatroom('~Komodo', K)
self.frame.Show(True)
self.Window.SetTopWindow(self.frame)
self.Timer = _Timer(0.050, self.OnTimer)
self.Pages.Bind(EVT_NOTEBOOK_PAGE_CHANGED, self.onPageChanged)
self.Pages.Bind(EVT_NOTEBOOK_PAGE_CHANGING, self.onPageChanging)
self.Pages.Bind(EVT_PAINT, self.onPaint)
self.Pages.Bind(EVT_SIZE, self.onSize)
def onPaint(self, event):
event.Skip()
def onSize(self, event):
event.Skip()
def onPageChanged(self, event):
event.Skip()
def onPageChanging(self, event):
event.Skip()
def Run(self):
self.Window.MainLoop()
# Timer and Queue functions
def OnTimer(self):
self.CheckQueue()
self.Timer = _Timer(0.050, self.OnTimer)
self.Timer.start()
def CheckQueue(self): # the Application needs to use a queue to do things in order to prevent
try: # overlaps from happening, such as runtime errors and widgets changing
while not self.Queue.empty(): # suddenly. The most common error seems to be size
func = self.Queue.get_nowait() # changes during iterations. Everything from
if func is not None:
func() # packet processing to adding widgets needs to wait in line this way
except Queue.Empty:
pass
def AddQueue(self, func):
self.Queue.put(func)
# Channel controls
def AddChatroom(self, ns, K):
if ns in self.Channels: return
self.chatorder.append(ns)
self.current = ns
self.Channels[ns] = Chatroom(self.Pages, ns)
self.Pages.AddPage(self.Channels[ns], ns, True)
class _Thread(Thread):
def __init__(self, K):
Thread.__init__(self)
self.K = K
def run(self):
self.K.Mainloop()
class K:
def __init__(self):
self.App = Application(self)
self.App.AddQueue(self.App.Channels['~Komodo'].Write('>> Welcome!') )
self.App.AddQueue(self.App.Channels['~Komodo'].Write('>> Entering mainloop...') )
self.App.AddChatroom('#TestChatroom1', self)
self.roomcount = 1
self.timer = time.time() + 3
self.thread = _Thread(self)
self.thread.start()
self.App.Timer.start()
self.App.Run()
def Mainloop(self):
while True:
if time.time() > self.timer:
self.App.AddQueue(
lambda: self.App.Channels['~Komodo'].Write('>> Testing') )
if self.roomcount < 5:
self.roomcount += 1
self.App.AddQueue(
lambda: self.App.AddChatroom('#TestChatroom{0}'.format(self.roomcount), self) )
self.timer = time.time() + 3
if __name__ == '__main__':
test = K()
A:
Here is your problem:
lambda: self.App.AddChatroom('#TestChatroom{0}'.format(self.roomcount), self) )
Fixed by using wx.CallAfter (tested on win xp sp3):
lambda: wx.CallAfter(self.App.AddChatroom, '#TestChatroom{0}'.format(self.roomcount), self)
You were probably tying up the GUI by calling wx objects from thread code. See this wxPython wiki article.
A:
It doesn't look like you're creating your Chatroom with its parent as the Notebook. What is "K" in Application.__init__? (you didn't post a fully runnable sample)
A:
When adding or deleting tabs, you probably need to call Layout() right after you're done. One easy way to find out is to grab an edge of the frame and resize it slightly. If you see widgets magically appear, then it's because Layout() was called and your page re-drawn.
| Need help with wxPython, NotebookCtrl in particular | I am trying to write a non-webbased client for a chat service on a web site, it connects to it fine via socket and can communicate with it and everything. I am writing a GUI for it (I tried writing it in tkinter but I hit some walls I really wantd to get passed, so I switched to wxPython)
What I'm having a problem with:
This application uses an extended Notebook widget called NotebookCtrl. However the same problem appears with regular Notebook. First it creates a page in which things are logged to, which is successful, and then it connects, and it's supposed to add pages with each chatroom it joins on the service. However, when it adds a tab after it's mainloop has been started (I am communicating with the GUI and the sockets via queues and threading), the tab comes up completely blank. I have been stuck on this for hours and hours and got absolutely nowhere
The example that came with the NotebookCtrl download adds and deletes pages by itself perfectly fine. I am on the edge of completely giving up on this project. Here is what the code looks like (note this is a very small portion of the application, but this covers the wxPython stuff)
class Chatroom(Panel):
''' Frame for the notebook widget to tabulate a chatroom'''
def __init__(self, ns, parent):
Panel.__init__(self, parent, -1)
self.msgs, self.typed, self.pcbuff = [], [], {}
self.members, self._topic, self._title, self.pc = None, None, None, None
self.name, self.tabsign, = ns, 0
self.hSizer1 = wx.BoxSizer(wx.HORIZONTAL)
self.vSizer = wx.BoxSizer(wx.VERTICAL)
self.Grid = wx.GridBagSizer(5, 2)
self.Title = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE | wx.TE_READONLY)
self.Topic = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE | wx.TE_READONLY)
self.Privclasses = TreeCtrl(self, size=(150, -1))
self.Buffer = wx.html.HtmlWindow(self)
self.Buffer.SetStandardFonts(8)
self.templbl = StaticText(self, -1, 'This is where the formatting buttons will go!')
# note to remember: self.templbl.SetLabel('string') sets the label
self.Typer = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE)
self.Grid.Add(self.Title, (0,0), (1,2), wx.EXPAND, 2)
self.Grid.Add(self.Topic, (1,0), (1,1), wx.EXPAND, 2)
self.Grid.Add(self.Privclasses, (1,1), (2,1), wx.EXPAND, 2)
self.Grid.Add(self.Buffer, (2,0), (1,1), wx.EXPAND, 2)
self.Grid.Add(self.templbl, (3,0), (1,1), wx.EXPAND | wx.ALIGN_LEFT, 2)
self.Grid.Add(self.Typer, (4,0), (1,1), wx.EXPAND, 2)
self.Grid.AddGrowableCol(0)
self.Grid.AddGrowableRow(2)
self.SetSizerAndFit(self.Grid)
self.Show(True)
self.Typer.Bind(EVT_CHAR, self.Typer_OnKeyDown)
def Typer_OnKeyDown(self, event):
keycode = event.GetKeyCode()
if event.ShiftDown():
if keycode == WXK_RETURN:
pass
elif keycode == WXK_BACK:
pass
elif keycode == WXK_UP:
pass
elif keycode == WXK_DOWN:
pass
else:
if keycode == WXK_RETURN:
pass
event.Skip()
def Write(self, msg, K):
self.msgs.append(msg)
if len(self.msgs) > 300:
self.msgs = self.msgs[50:]
self.Buffer.SetPage('<br>'.join(self.msgs))
class Application(App):
def __init__(self, K):
self.Queue = Queue.Queue()
self.current = ''
self.chatorder = []
self.Window = App(0)
self.frame = MainFrame(None, 0, "Komodo Dragon")
self.Pages = NC.NotebookCtrl(self.frame, 9000)
self.Channels = {}
self.AddChatroom('~Komodo', K)
self.frame.Show(True)
self.Window.SetTopWindow(self.frame)
self.Timer = _Timer(0.050, self.OnTimer)
self.Timer.start()
self.Pages.Bind(NC.EVT_NOTEBOOKCTRL_PAGE_CHANGED, self.onPageChanged)
self.Pages.Bind(NC.EVT_NOTEBOOKCTRL_PAGE_CHANGING, self.onPageChanging)
self.Pages.Bind(EVT_PAINT, self.onPaint)
self.Pages.Bind(EVT_SIZE, self.onSize)
def onPaint(self, event):
event.Skip()
def onSize(self, event):
event.Skip()
def Run(self):
self.Window.MainLoop()
def onPageChanged(self, event):
event.Skip()
def onPageChanging(self, event):
event.Skip()
# Timer and Queue functions
def OnTimer(self):
self.CheckQueue()
self.Timer = _Timer(0.050, self.OnTimer)
self.Timer.start()
def CheckQueue(self): # the Application needs to use a queue to do things in order to prevent
try: # overlaps from happening, such as runtime errors and widgets changing
while not self.Queue.empty(): # suddenly. The most common error seems to be size
func = self.Queue.get_nowait() # changes during iterations. Everything from
func() # packet processing to adding widgets needs to wait in line this way
except Queue.Empty:
pass
def AddQueue(self, func):
self.Queue.put(func)
# Channel controls
def AddChatroom(self, ns, K):
if ns in self.Channels: return
#self.typedindex = 0
c = K.format_ns(ns)
self.chatorder.append(ns)
self.current = ns
self.Channels[ns] = Chatroom(ns, self.Pages)
self.Pages.AddPage(self.Channels[ns], ns, True)
def DeleteChatroom(self, ns, bot): # Delete a channel, it's properties, and buttons
ind = self.chatorder.index(ns)
del self.chatorder[ind]
for each in self.chatorder[ind:]:
x = self.channels[each].tab.grid_info()
if x['column'] == '0': r, c = int(x['row'])-1, 9
else: r, c = int(x['row']), int(x['column'])-1
self.channels[each].tab.grid_configure(row=r, column=c)
x = self.channels[each].tab.grid_info()
self.channels[ns].Tab.destroy()
self.channels[ns].tab.destroy()
self.channels[self.chatorder[-1]].tab.select()
self.switchtab(bot, self.chatorder[-1])
x = self.tabids_reverse[ns]
del self.tabids_reverse[ns], self.tabids[x], self.channels[ns]
The Chatroom class covers what each tab should have in it. the first tab that is added in class Application's init function is perfectly fine, and even prints messages it receives from the chat service when it attempts to connect. Once the service sends a join packet to me, it calls the same exact function used to add that tab, AddChatroom(), and should create the exact same thing, only printing messages specifically for that chatroom. It creates the tab, but the Chatroom page is completely empty and grey. I am very sad :C
Thanks in advance if you can help me.
EDIT
I have written a working example of this script you can run yourself (if you have wxPython). It uses regular Notebook instead of NotebookCtrl so you don't have to download that widget as well, but the bug happens for both. The example sets up the window, and sets up the main debug tab and then a chatroom tab before entering mainloop. After mainloop, any chatrooms added afterwords are completely blank
from wx import *
import Queue, time
from threading import Timer as _Timer
from threading import Thread
# import System._NotebookCtrl.NotebookCtrl as NC ## Using regular notebook for this example
class MainFrame(Frame):
def __init__(self, parent, ID, title):
ID_FILE_LOGIN = 100
ID_FILE_RESTART = 101
ID_FILE_EXIT = 102
ID_HELP_ABOUT = 200
Frame.__init__(self, parent, ID, title,
DefaultPosition, Size(1000, 600))
self.CreateStatusBar()
self.SetStatusText("This is the statusbar")
menu_File = Menu()
menu_Help = Menu()
menu_Edit = Menu()
menu_Config = Menu()
menu_File.Append(ID_FILE_LOGIN, "&Login Info",
"Enter your deviantArt Login information")
menu_File.AppendSeparator()
menu_File.Append(ID_FILE_RESTART, "&Restart",
"Restart the program")
menu_File.Append(ID_FILE_EXIT, "E&xit",
"Terminate the program")
menu_Help.Append(ID_HELP_ABOUT, "&About",
"More information about this program")
menuBar = MenuBar()
menuBar.Append(menu_File, "&File");
menuBar.Append(menu_Edit, "&Edit");
menuBar.Append(menu_Config, "&Config");
menuBar.Append(menu_Help, "&Help");
self.SetMenuBar(menuBar)
EVT_MENU(self, ID_FILE_LOGIN, self.OnLogin)
EVT_MENU(self, ID_FILE_RESTART, self.OnRestart)
EVT_MENU(self, ID_FILE_EXIT, self.OnQuit)
EVT_MENU(self, ID_HELP_ABOUT, self.OnAbout)
def OnAbout(self, event):
dlg = MessageDialog(self, "Hi! I am Komodo Dragon! I am an application\n"
"that communicates with deviantArt's Messaging Network (dAmn)",
"Komodo", OK | ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def OnQuit(self, event):
self.Close(True)
def OnRestart(self, event):
pass
def OnLogin(self, event):
dlg = MessageDialog(self, "Enter your Login information here:\n"
"Work in progress, LOL",
"Login", OK | ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
class Chatroom(Panel):
''' Frame for the notebook widget to tabulate a chatroom'''
def __init__(self, parent, ns):
Panel.__init__(self, parent, -1)
self.msgs, self.typed, self.pcbuff = [], [], {}
self.members, self._topic, self._title, self.pc = None, None, None, None
self.name, self.tabsign, = ns, 0
self.hSizer1 = wx.BoxSizer(wx.HORIZONTAL)
self.vSizer = wx.BoxSizer(wx.VERTICAL)
self.Grid = wx.GridBagSizer(5, 2)
self.Title = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE | wx.TE_READONLY)
self.Topic = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE | wx.TE_READONLY)
self.Privclasses = TreeCtrl(self, size=(150, -1))
self.Buffer = wx.html.HtmlWindow(self)
self.Buffer.SetStandardFonts(8)
self.templbl = StaticText(self, -1, 'This is where the formatting buttons will go!')
self.Typer = TextCtrl(self, size=(-1, 50), style=wx.TE_MULTILINE)
self.Grid.Add(self.Title, (0,0), (1,2), wx.EXPAND, 2)
self.Grid.Add(self.Topic, (1,0), (1,1), wx.EXPAND, 2)
self.Grid.Add(self.Privclasses, (1,1), (2,1), wx.EXPAND, 2)
self.Grid.Add(self.Buffer, (2,0), (1,1), wx.EXPAND, 2)
self.Grid.Add(self.templbl, (3,0), (1,1), wx.EXPAND | wx.ALIGN_LEFT, 2)
self.Grid.Add(self.Typer, (4,0), (1,1), wx.EXPAND, 2)
self.Grid.AddGrowableCol(0)
self.Grid.AddGrowableRow(2)
self.SetSizerAndFit(self.Grid)
self.Show(True)
self.Typer.Bind(EVT_CHAR, self.Typer_OnKeyDown)
def Typer_OnKeyDown(self, event):
keycode = event.GetKeyCode()
if event.ShiftDown():
if keycode == WXK_RETURN:
pass
elif keycode == WXK_BACK:
pass
elif keycode == WXK_UP:
pass
elif keycode == WXK_DOWN:
pass
else:
if keycode == WXK_RETURN:
pass
event.Skip()
def Write(self, msg):
self.msgs.append(msg)
if len(self.msgs) > 300:
self.msgs = self.msgs[50:]
self.Buffer.SetPage('<br>'.join(self.msgs))
class Application(App):
def __init__(self, K):
self.Queue = Queue.Queue()
self.current = ''
self.chatorder = []
self.Window = App(0)
self.frame = MainFrame(None, 0, "Komodo Dragon")
self.Pages = Notebook(self.frame, 9000)
self.Channels = {}
self.AddChatroom('~Komodo', K)
self.frame.Show(True)
self.Window.SetTopWindow(self.frame)
self.Timer = _Timer(0.050, self.OnTimer)
self.Pages.Bind(EVT_NOTEBOOK_PAGE_CHANGED, self.onPageChanged)
self.Pages.Bind(EVT_NOTEBOOK_PAGE_CHANGING, self.onPageChanging)
self.Pages.Bind(EVT_PAINT, self.onPaint)
self.Pages.Bind(EVT_SIZE, self.onSize)
def onPaint(self, event):
event.Skip()
def onSize(self, event):
event.Skip()
def onPageChanged(self, event):
event.Skip()
def onPageChanging(self, event):
event.Skip()
def Run(self):
self.Window.MainLoop()
# Timer and Queue functions
def OnTimer(self):
self.CheckQueue()
self.Timer = _Timer(0.050, self.OnTimer)
self.Timer.start()
def CheckQueue(self): # the Application needs to use a queue to do things in order to prevent
try: # overlaps from happening, such as runtime errors and widgets changing
while not self.Queue.empty(): # suddenly. The most common error seems to be size
func = self.Queue.get_nowait() # changes during iterations. Everything from
if func is not None:
func() # packet processing to adding widgets needs to wait in line this way
except Queue.Empty:
pass
def AddQueue(self, func):
self.Queue.put(func)
# Channel controls
def AddChatroom(self, ns, K):
if ns in self.Channels: return
self.chatorder.append(ns)
self.current = ns
self.Channels[ns] = Chatroom(self.Pages, ns)
self.Pages.AddPage(self.Channels[ns], ns, True)
class _Thread(Thread):
def __init__(self, K):
Thread.__init__(self)
self.K = K
def run(self):
self.K.Mainloop()
class K:
def __init__(self):
self.App = Application(self)
self.App.AddQueue(self.App.Channels['~Komodo'].Write('>> Welcome!') )
self.App.AddQueue(self.App.Channels['~Komodo'].Write('>> Entering mainloop...') )
self.App.AddChatroom('#TestChatroom1', self)
self.roomcount = 1
self.timer = time.time() + 3
self.thread = _Thread(self)
self.thread.start()
self.App.Timer.start()
self.App.Run()
def Mainloop(self):
while True:
if time.time() > self.timer:
self.App.AddQueue(
lambda: self.App.Channels['~Komodo'].Write('>> Testing') )
if self.roomcount < 5:
self.roomcount += 1
self.App.AddQueue(
lambda: self.App.AddChatroom('#TestChatroom{0}'.format(self.roomcount), self) )
self.timer = time.time() + 3
if __name__ == '__main__':
test = K()
| [
"Here is your problem:\nlambda: self.App.AddChatroom('#TestChatroom{0}'.format(self.roomcount), self) )\n\nFixed by using wx.CallAfter (tested on win xp sp3):\nlambda: wx.CallAfter(self.App.AddChatroom, '#TestChatroom{0}'.format(self.roomcount), self)\n\nYou were probably tying up the GUI by calling wx objects from... | [
1,
0,
0
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003765852_python_user_interface_wxpython.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.